@hivelore/cli 0.30.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/LICENSE +21 -0
- package/README.md +668 -0
- package/dist/Dashboard-3WMW72XE.js +361 -0
- package/dist/Dashboard-3WMW72XE.js.map +1 -0
- package/dist/index.js +19657 -0
- package/dist/index.js.map +1 -0
- package/package.json +59 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/commands/briefing.ts","../src/utils/ui.ts","../src/utils/briefing-radar.ts","../src/utils/autopilot.ts","../src/commands/memory-lint.ts","../src/commands/tui.ts","../src/commands/embeddings.ts","../src/commands/index-code.ts","../src/commands/init.ts","../src/utils/bridge-files.ts","../src/commands/agent.ts","../src/commands/init-mcp-setup.ts","../src/commands/init-bootstrap.ts","../src/commands/init-stack-packs.ts","../src/commands/install-hooks.ts","../src/utils/claude-hooks.ts","../src/commands/observe.ts","../src/commands/mcp.ts","../../mcp/src/server.ts","../../mcp/src/context.ts","../../mcp/src/tools/bootstrap-project-save.ts","../../mcp/src/tools/get-project-context.ts","../../mcp/src/tools/mem-list.ts","../../mcp/src/tools/mem-save.ts","../../mcp/src/tools/mem-search.ts","../../mcp/src/tools/mem-verify.ts","../../mcp/src/tools/mem-reject.ts","../../mcp/src/tools/mem-feedback.ts","../../mcp/src/tools/mem-for-files.ts","../../mcp/src/tools/mem-get.ts","../../mcp/src/tools/mem-delete.ts","../../mcp/src/tools/mem-update.ts","../../mcp/src/tools/mem-pending.ts","../../mcp/src/tools/mem-approve.ts","../../mcp/src/tools/mem-tried.ts","../../mcp/src/tools/propose-sensor.ts","../../mcp/src/tools/ingest-findings.ts","../../mcp/src/tools/mem-observe.ts","../../mcp/src/tools/mem-session-end.ts","../../mcp/src/session-tracker.ts","../../mcp/src/tools/get-briefing.ts","../../mcp/src/tools/briefing-helpers.ts","../../mcp/src/tools/code-map.ts","../../mcp/src/tools/mem-diff.ts","../../mcp/src/tools/get-recap.ts","../../mcp/src/tools/mem-relevant-to.ts","../../mcp/src/tools/code-search.ts","../../mcp/src/tools/why-this-file.ts","../../mcp/src/tools/anti-patterns-check.ts","../../mcp/src/tools/mem-distill.ts","../../mcp/src/tools/why-this-decision.ts","../../mcp/src/tools/mem-conflicts.ts","../../mcp/src/tools/precommit-check.ts","../../mcp/src/tools/pattern-detect.ts","../../mcp/src/tools/mem-conflict-candidates.ts","../../mcp/src/tools/mem-resolve-project.ts","../../mcp/src/tools/mem-suggest-topic.ts","../../mcp/src/tools/mem-timeline.ts","../../mcp/src/tools/runtime-journal-append.ts","../../mcp/src/tools/runtime-journal-tail.ts","../../mcp/src/prompts/bootstrap-project.ts","../../mcp/src/prompts/bootstrap-repo.ts","../../mcp/src/prompts/post-task.ts","../../mcp/src/prompts/import-docs.ts","../src/commands/sync.ts","../src/commands/memory-add.ts","../src/commands/memory-list.ts","../src/utils/fs.ts","../src/commands/memory-promote.ts","../src/commands/memory-approve.ts","../src/commands/memory-update.ts","../src/commands/memory-auto-promote.ts","../src/commands/memory-edit.ts","../src/commands/memory-for-files.ts","../src/commands/memory-hot.ts","../src/commands/memory-tried.ts","../src/commands/memory-seed.ts","../src/commands/memory-pending.ts","../src/commands/memory-query.ts","../src/commands/memory-reject.ts","../src/commands/memory-rm.ts","../src/commands/memory-show.ts","../src/commands/memory-stats.ts","../src/commands/memory-impact.ts","../src/commands/memory-feedback.ts","../src/commands/memory-verify.ts","../src/commands/memory-import.ts","../src/commands/memory-import-changelog.ts","../src/commands/memory-digest.ts","../src/commands/session-end.ts","../src/commands/snapshot.ts","../src/commands/hub.ts","../src/commands/stats.ts","../src/commands/bench.ts","../src/commands/benchmark.ts","../src/commands/eval.ts","../src/commands/memory-suggest.ts","../src/commands/memory-archive.ts","../src/commands/doctor.ts","../src/commands/playback.ts","../src/commands/precommit.ts","../src/commands/welcome.ts","../src/commands/memory-suggest-topic.ts","../src/commands/resolve-project.ts","../src/commands/runtime-journal.ts","../src/commands/memory-timeline.ts","../src/commands/memory-conflict-candidates.ts","../src/commands/enforce.ts","../src/commands/run.ts","../src/commands/sensors.ts","../src/commands/ingest.ts","../src/commands/dashboard.ts","../src/commands/dev-link.ts","../src/commands/coverage.ts","../src/commands/merge-driver.ts","../src/commands/memory-resolve-conflict.ts","../src/commands/memory-seed-git.ts","../src/commands/bridges.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport { registerBriefing } from \"./commands/briefing.js\";\nimport { registerTui } from \"./commands/tui.js\";\nimport { registerEmbeddings } from \"./commands/embeddings.js\";\nimport { registerIndexCode } from \"./commands/index-code.js\";\nimport { registerInit } from \"./commands/init.js\";\nimport { registerInstallHooks } from \"./commands/install-hooks.js\";\nimport { registerObserve } from \"./commands/observe.js\";\nimport { registerMcp } from \"./commands/mcp.js\";\nimport { registerSync } from \"./commands/sync.js\";\nimport { registerMemoryAdd } from \"./commands/memory-add.js\";\nimport { registerMemoryList } from \"./commands/memory-list.js\";\nimport { registerMemoryPromote } from \"./commands/memory-promote.js\";\nimport { registerMemoryApprove } from \"./commands/memory-approve.js\";\nimport { registerMemoryUpdate } from \"./commands/memory-update.js\";\nimport { registerMemoryAutoPromote } from \"./commands/memory-auto-promote.js\";\nimport { registerMemoryEdit } from \"./commands/memory-edit.js\";\nimport { registerMemoryForFiles } from \"./commands/memory-for-files.js\";\nimport { registerMemoryHot } from \"./commands/memory-hot.js\";\nimport { registerMemoryTried } from \"./commands/memory-tried.js\";\nimport { registerMemorySeed } from \"./commands/memory-seed.js\";\nimport { registerMemoryPending } from \"./commands/memory-pending.js\";\nimport { registerMemoryQuery } from \"./commands/memory-query.js\";\nimport { registerMemoryReject } from \"./commands/memory-reject.js\";\nimport { registerMemoryRm } from \"./commands/memory-rm.js\";\nimport { registerMemoryShow } from \"./commands/memory-show.js\";\nimport { registerMemoryStats } from \"./commands/memory-stats.js\";\nimport { registerMemoryImpact } from \"./commands/memory-impact.js\";\nimport { registerMemoryFeedback } from \"./commands/memory-feedback.js\";\nimport { registerMemoryVerify } from \"./commands/memory-verify.js\";\nimport { registerMemoryImport } from \"./commands/memory-import.js\";\nimport { registerMemoryImportChangelog } from \"./commands/memory-import-changelog.js\";\nimport { registerMemoryDigest } from \"./commands/memory-digest.js\";\nimport { registerSessionEnd } from \"./commands/session-end.js\";\nimport { registerSnapshot } from \"./commands/snapshot.js\";\nimport { registerHub } from \"./commands/hub.js\";\nimport { registerStats } from \"./commands/stats.js\";\nimport { registerBench } from \"./commands/bench.js\";\nimport { registerBenchmark } from \"./commands/benchmark.js\";\nimport { registerEval } from \"./commands/eval.js\";\nimport { registerMemorySuggest } from \"./commands/memory-suggest.js\";\nimport { registerMemoryArchive } from \"./commands/memory-archive.js\";\nimport { registerDoctor } from \"./commands/doctor.js\";\nimport { registerPlayback } from \"./commands/playback.js\";\nimport { registerPrecommit } from \"./commands/precommit.js\";\nimport { registerWelcome } from \"./commands/welcome.js\";\nimport { registerMemoryLint } from \"./commands/memory-lint.js\";\nimport { registerMemorySuggestTopic } from \"./commands/memory-suggest-topic.js\";\nimport { registerResolveProject } from \"./commands/resolve-project.js\";\nimport { registerRuntime } from \"./commands/runtime-journal.js\";\nimport { registerMemoryTimeline } from \"./commands/memory-timeline.js\";\nimport { registerMemoryConflictCandidates } from \"./commands/memory-conflict-candidates.js\";\nimport { registerEnforce } from \"./commands/enforce.js\";\nimport { registerRun } from \"./commands/run.js\";\nimport { registerAgent } from \"./commands/agent.js\";\nimport { registerSensors } from \"./commands/sensors.js\";\nimport { registerIngest } from \"./commands/ingest.js\";\nimport { registerDashboard } from \"./commands/dashboard.js\";\nimport { registerDevLink } from \"./commands/dev-link.js\";\nimport { registerCoverage } from \"./commands/coverage.js\";\nimport { registerMergeDriver } from \"./commands/merge-driver.js\";\nimport { registerMemoryResolveConflict } from \"./commands/memory-resolve-conflict.js\";\nimport { registerMemorySeedGit } from \"./commands/memory-seed-git.js\";\n// --- Lot C ---\nimport { registerBridges } from \"./commands/bridges.js\";\n\nconst program = new Command();\n\ndeclare const __HAIVE_VERSION__: string;\n\nprogram\n .name(\"hivelore\")\n .description(\"Hivelore - repo-native memory and context policy for coding-agent harnesses\")\n .version(__HAIVE_VERSION__)\n .option(\"--advanced\", \"show maintenance and experimental commands in help\")\n // Agents guess flags by analogy (`--content` for `--body`, `--summary` for `--goal`) and a\n // bare \"unknown option\" dead-ends them. Must run BEFORE the register* calls so subcommands\n // created via program.command() inherit the setting.\n .showSuggestionAfterError(true);\n\nregisterInit(program);\nregisterWelcome(program);\nregisterResolveProject(program);\nregisterRuntime(program);\nregisterEnforce(program);\nregisterRun(program);\nregisterAgent(program);\nregisterSensors(program);\nregisterIngest(program);\nregisterDashboard(program);\nregisterCoverage(program);\nregisterMergeDriver(program);\nregisterDevLink(program);\n\nregisterMcp(program);\nregisterBriefing(program);\nregisterTui(program);\nregisterEmbeddings(program);\nregisterSync(program);\nregisterBridges(program); // --- Lot C ---\nregisterInstallHooks(program);\nregisterObserve(program);\nregisterIndexCode(program);\n\nconst memory = program.command(\"memory\").description(\"Manage memory entries\");\nregisterMemoryAdd(memory);\nregisterMemoryList(memory);\nregisterMemoryQuery(memory);\nregisterMemoryPromote(memory);\nregisterMemoryVerify(memory);\nregisterMemoryStats(memory);\nregisterMemoryImpact(memory);\nregisterMemoryFeedback(memory);\nregisterMemoryReject(memory);\nregisterMemoryAutoPromote(memory);\nregisterMemoryForFiles(memory);\nregisterMemoryShow(memory);\nregisterMemoryEdit(memory);\nregisterMemoryRm(memory);\nregisterMemoryPending(memory);\nregisterMemoryApprove(memory);\nregisterMemoryUpdate(memory);\nregisterMemoryHot(memory);\nregisterMemoryTried(memory);\nregisterMemorySeed(memory);\nregisterMemorySeedGit(memory);\nregisterMemoryResolveConflict(memory);\nregisterMemoryImport(memory);\nregisterMemoryImportChangelog(memory);\nregisterMemoryDigest(memory);\nregisterMemorySuggest(memory);\nregisterMemorySuggestTopic(memory);\nregisterMemoryTimeline(memory);\nregisterMemoryConflictCandidates(memory);\nregisterMemoryArchive(memory);\nregisterMemoryLint(memory);\n\nconst session = program.command(\"session\").description(\n \"Manage session lifecycle.\\n\\n\" +\n \" Session start is automatic — Hivelore loads context via `get_briefing` at the start\\n\" +\n \" of each agent session (Claude Code SessionStart hook or MCP first call).\\n\" +\n \" Use `hivelore session end` to save a rich end-of-session recap for the next session.\",\n);\nregisterSessionEnd(session);\n\nregisterSnapshot(program);\nregisterHub(program);\nregisterStats(program);\nregisterBench(program);\nregisterBenchmark(program);\nregisterEval(program);\nregisterDoctor(program);\nregisterPlayback(program);\nregisterPrecommit(program);\n\n// The core harness loop only — what a developer actually types day to day. Everything else\n// (tui dashboard, welcome onboarding, the manual `precommit` variant of `enforce check`, plus the\n// maintenance/experimental families) stays one `--advanced` away. A focused surface is part of the\n// positioning: Hivelore is repo context policy for coding-agent harnesses, not a 54-command Swiss army knife.\nconst CORE_ROOT_COMMANDS = new Set([\n \"init\",\n \"doctor\",\n \"agent\",\n \"briefing\",\n \"bridges\", // --- Lot C ---\n \"enforce\",\n \"run\",\n \"sensors\",\n \"sync\",\n \"mcp\",\n \"memory\",\n \"session\",\n]);\n\n// Canonical verbs mirror the MCP tool names (mem_save / mem_search / mem_get / mem_delete)\n// so an agent learns one vocabulary across both façades. Old verbs (add/query/show/rm) stay\n// as command aliases, so existing scripts keep working.\nconst CORE_MEMORY_COMMANDS = new Set([\n \"save\",\n \"list\",\n \"search\",\n \"get\",\n \"verify\",\n \"lint\",\n \"tried\",\n \"delete\",\n]);\n\nconst CORE_SESSION_COMMANDS = new Set([\"end\"]);\n\napplySurfaceVisibility(program);\n\nprogram.parseAsync(process.argv).catch((err: unknown) => {\n if (isZodError(err)) {\n for (const issue of err.issues) {\n const field = issue.path.length > 0 ? `${String(issue.path.join(\".\"))}: ` : \"\";\n console.error(`\\x1b[31m✗\\x1b[0m ${field}${issue.message}`);\n }\n } else {\n console.error(err instanceof Error ? err.message : err);\n }\n process.exit(1);\n});\n\nfunction applySurfaceVisibility(root: Command): void {\n const showAdvanced =\n process.argv.includes(\"--advanced\") || process.env.HAIVE_SHOW_ADVANCED === \"1\";\n\n if (!showAdvanced) hideNonCoreCommands(root);\n\n // Families block lists advanced command names, so it only shows in advanced help —\n // the default help stays focused on the golden path (those names would otherwise leak\n // into the core surface).\n const familiesBlock = showAdvanced\n ? [\n \"\",\n \"Advanced surface, by family:\",\n \" reports: dashboard · stats · playback eval: eval · benchmark · selftest (alias: bench)\",\n \" index: index · code-search · embeddings runtime: runtime · observe · snapshot\",\n \" ops: memory <sub> · sensors · ingest · hub · sync · install-hooks (= enforce install) · precommit (= enforce check)\",\n ]\n : [];\n root.addHelpText(\n \"after\",\n [\n \"\",\n \"Golden path (what you type day to day):\",\n \" init → doctor → agent setup → briefing → memory save/tried → sensors check → enforce finish → sync → session end\",\n \"\",\n \"Memory verbs mirror the MCP tools: memory save/search/get/delete <-> mem_save/mem_search/mem_get/mem_delete\",\n \"(old verbs add/query/show/rm still work as aliases).\",\n ...familiesBlock,\n \"\",\n \"Run `hivelore --advanced --help` or set HAIVE_SHOW_ADVANCED=1 to show maintenance and experimental commands.\",\n ].join(\"\\n\"),\n );\n const memoryCommand = root.commands.find((cmd) => cmd.name() === \"memory\");\n memoryCommand?.addHelpText(\n \"after\",\n [\n \"\",\n \"Default help shows the memory commands that support the core harness workflow.\",\n \"Run `hivelore --advanced memory --help` or set HAIVE_SHOW_ADVANCED=1 to show review, import, digest, timeline, and conflict tools.\",\n ].join(\"\\n\"),\n );\n}\n\nfunction hideNonCoreCommands(command: Command): void {\n for (const child of command.commands) {\n if (!isCoreCommand(command, child)) {\n (child as unknown as { _hidden: boolean })._hidden = true;\n }\n hideNonCoreCommands(child);\n }\n}\n\nfunction isCoreCommand(parent: Command, child: Command): boolean {\n const parentName = parent.name();\n const childName = child.name();\n if (parentName === \"hivelore\") return CORE_ROOT_COMMANDS.has(childName);\n if (parentName === \"memory\") return CORE_MEMORY_COMMANDS.has(childName);\n if (parentName === \"session\") return CORE_SESSION_COMMANDS.has(childName);\n return true;\n}\n\nfunction isZodError(\n err: unknown,\n): err is { issues: Array<{ path: unknown[]; message: string }> } {\n return (\n err !== null &&\n typeof err === \"object\" &&\n \"issues\" in err &&\n Array.isArray((err as Record<string, unknown>).issues)\n );\n}\n","import { existsSync } from \"node:fs\";\nimport { mkdir, readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n classifyMemoryPriority,\n compactAutoRecapBody,\n extractActionsBriefBody,\n findProjectRoot,\n literalMatchesAllTokens,\n literalMatchesAnyToken,\n loadCodeMap,\n loadConfig,\n loadMemoriesFromDir,\n loadUsageIndex,\n memoryHasExcludedTag,\n memoryMatchesAnchorPaths,\n queryCodeMap,\n resolveBriefingBudget,\n resolveHaivePaths,\n tokenizeQuery,\n trackReads,\n writeBriefingMarker,\n} from \"@hivelore/core\";\nimport { ui } from \"../utils/ui.js\";\nimport { buildRadar, radarHasContent, type RadarReport } from \"../utils/briefing-radar.js\";\nimport { applyAutopilotRepairs } from \"../utils/autopilot.js\";\n\ninterface BriefingOptions {\n task?: string;\n files?: string;\n symbols?: string;\n maxMemories?: string;\n maxTokens?: string;\n explainSource?: boolean;\n scope?: string;\n includeDraft?: boolean;\n includeStale?: boolean;\n dir?: string;\n include?: string[];\n radar?: boolean;\n /** quick | balanced | deep — aligns with get_briefing budget_preset */\n budget?: string;\n /** full | actions — mimic get_briefing format for printed bodies */\n memoryFormat?: string;\n /** Back-compat alias for users who know the MCP get_briefing format option. */\n format?: string;\n /** Emit the ranked briefing as JSON (parity with the MCP get_briefing tool) instead of text. */\n json?: boolean;\n}\n\nconst RADAR_AUTO_THRESHOLD = 3;\n\nconst CHARS_PER_TOKEN = 4;\n\nfunction printRadar(\n radar: RadarReport,\n out: (text: string) => boolean,\n reason: \"low-memory-signal\" | \"forced\",\n): void {\n if (!radar.insideGitRepo) return;\n if (!radarHasContent(radar)) return;\n const header = reason === \"low-memory-signal\"\n ? \"=== Project Radar (few relevant memories — surfacing live signals) ===\"\n : \"=== Project Radar ===\";\n out(`${ui.bold(header)}\\n`);\n\n if (radar.recentCommits.length > 0) {\n out(ui.bold(\"Recent commits:\"));\n for (const c of radar.recentCommits) {\n const filesBlurb = c.files.slice(0, 3).join(\", \");\n const more = c.files.length > 3 ? ` (+${c.files.length - 3})` : \"\";\n out(` ${ui.dim(c.date)} ${c.sha} ${c.subject}`);\n if (filesBlurb) out(ui.dim(` ${filesBlurb}${more}`));\n }\n out(\"\");\n }\n if (radar.openTodos.length > 0) {\n out(ui.bold(\"Open TODOs/FIXMEs:\"));\n for (const t of radar.openTodos) {\n out(` ${ui.dim(t.file + \":\" + t.line)} ${t.text}`);\n }\n out(\"\");\n }\n if (radar.hotFiles.length > 0) {\n out(ui.bold(\"Hot files (most modified recently):\"));\n for (const f of radar.hotFiles) {\n out(` ${f.changes}× ${ui.dim(f.path)}`);\n }\n out(\"\");\n }\n}\n\nclass TokenBudgetWriter {\n private used = 0;\n private truncated = false;\n constructor(private readonly budgetChars: number) {}\n write(text: string): boolean {\n if (this.truncated) return false;\n const next = this.used + text.length + 1;\n if (next > this.budgetChars) {\n console.log(ui.dim(`... [briefing truncated to fit --max-tokens budget · ${Math.round(this.used / CHARS_PER_TOKEN)} tokens used]`));\n this.truncated = true;\n return false;\n }\n console.log(text);\n this.used = next;\n return true;\n }\n isTruncated(): boolean { return this.truncated; }\n remainingChars(): number { return Math.max(0, this.budgetChars - this.used); }\n}\n\nexport function registerBriefing(program: Command): void {\n program\n .command(\"briefing\")\n .description(\n \"Print the full project briefing: last session recap + project context + relevant memories.\\n\" +\n \" Equivalent to calling get_briefing via MCP. Run before starting any task.\\n\\n\" +\n \" Examples:\\n\" +\n \" hivelore briefing\\n\" +\n \" hivelore briefing --task \\\"add Stripe payment\\\" --files src/payments/PaymentService.ts\\n\" +\n \" hivelore briefing --budget quick --task \\\"tiny fix\\\"\\n\",\n )\n .option(\"--task <text>\", \"what you are about to do — filters memories by relevance\")\n .option(\"--files <csv>\", \"comma-separated file paths being worked on (surfaces anchored memories)\")\n .option(\"--symbols <csv>\", \"symbol names to look up in the code-map (e.g. PaymentService,TenantFilter) — requires hivelore index code\")\n .option(\"--max-memories <n>\", \"cap on memories surfaced\", \"8\")\n .option(\"--max-tokens <n>\", \"approximate token budget for the entire briefing (truncates if exceeded)\")\n .option(\"--explain-source\", \"annotate each memory with [source: <relative-path> · anchors: <files>] for traceable citations\")\n .option(\"--radar\", \"force project radar (recent commits, open TODOs, hot files) even when memories are plentiful\")\n .option(\"--no-radar\", \"disable the project radar even when memories are scarce\")\n .option(\"--json\", \"emit the ranked briefing as JSON (memories + scores + priority), like the MCP get_briefing tool\", false)\n .option(\n \"--budget <preset>\",\n \"align with MCP get_briefing budget_preset: quick | balanced | deep — sets cap + truncation budget (overrides --max-memories / replaces default open-ended output)\",\n undefined,\n )\n .option(\n \"--memory-format <mode>\",\n \"printed memory bodies: full (default) | actions (cheap bullet-focused excerpt)\",\n \"full\",\n )\n .option(\n \"--format <mode>\",\n \"alias for --memory-format; accepts full | actions | compact\",\n )\n .option(\n \"--scope <scope>\",\n \"personal | team | shared | all (default: all — includes team + shared cross-repo memories)\",\n \"all\",\n )\n .option(\"--include-draft\", \"include draft memories (excluded by default)\")\n .option(\"--include-stale\", \"include stale memories (excluded by default — may be outdated)\")\n .option(\n \"--include <path>\",\n \"merge memories from another Hivelore-initialized project (repeatable). \" +\n \"Useful for teams with multiple coordinated repos (e.g. backend + frontend).\",\n collectInclude,\n [] as string[],\n )\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: BriefingOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n const requestedFormat = (opts.format ?? opts.memoryFormat ?? \"full\").toLowerCase();\n opts.memoryFormat = requestedFormat === \"compact\" ? \"actions\" : requestedFormat;\n const markerFiles = parseCsv(opts.files);\n if (existsSync(paths.haiveDir)) {\n await applyAutopilotRepairs(root, paths, {\n applyConfig: false,\n applyContext: true,\n applyCorpus: true,\n applyCodeMap: false,\n applyCodeSearch: true,\n }).catch(() => { /* briefing should still work if repair fails */ });\n }\n if (existsSync(paths.haiveDir)) {\n await mkdir(paths.runtimeDir, { recursive: true });\n await writeBriefingMarker(paths, {\n task: opts.task ?? \"CLI briefing\",\n source: \"haive-briefing-cli\",\n sessionId: process.env.HAIVE_SESSION_ID,\n files: markerFiles,\n }).catch(() => { /* marker is best-effort */ });\n }\n\n type BB = \"quick\" | \"balanced\" | \"deep\";\n let budgetPreset: BB | null = null;\n if (opts.budget) {\n const b = opts.budget.trim().toLowerCase();\n if (b === \"quick\" || b === \"balanced\" || b === \"deep\") budgetPreset = b;\n else ui.warn(`Unknown --budget '${opts.budget}' — ignoring (use quick|balanced|deep).`);\n }\n\n let maxMemories = Math.max(1, Number(opts.maxMemories ?? 8));\n let budgetTokensCap: number | null = opts.maxTokens ? Math.max(100, Number(opts.maxTokens)) : null;\n\n if (budgetPreset !== null) {\n const presetNums = resolveBriefingBudget(budgetPreset, {\n max_tokens: 8000,\n max_memories: 8,\n include_module_contexts: true,\n });\n budgetTokensCap = presetNums.max_tokens;\n maxMemories = presetNums.max_memories;\n }\n\n const json = opts.json === true;\n const writer = budgetTokensCap !== null ? new TokenBudgetWriter(budgetTokensCap * CHARS_PER_TOKEN) : null;\n const out = (text: string): boolean => {\n if (json) return true; // JSON mode: suppress all formatted text; structured payload emitted below\n if (writer) return writer.write(text);\n console.log(text);\n return true;\n };\n const stopped = (): boolean => writer?.isTruncated() ?? false;\n\n if (!existsSync(paths.memoriesDir)) {\n // No memories yet — print project context (if any) + radar fallback\n if (existsSync(paths.projectContext)) {\n out(`${ui.bold(\"=== Project Context ===\")}\\n`);\n out((await readFile(paths.projectContext, \"utf8\")).trim());\n out(\"\");\n } else {\n ui.warn(\"No project-context.md found. Run `hivelore init` and the `bootstrap_project` MCP prompt to set it up.\");\n }\n if (opts.radar !== false && !stopped()) {\n const filePathsEarly = parseCsv(opts.files);\n const tokensEarly = opts.task ? tokenizeQuery(opts.task) : null;\n const radar = await buildRadar({ root, taskTokens: tokensEarly, filePaths: filePathsEarly });\n printRadar(radar, out, \"low-memory-signal\");\n }\n return;\n }\n\n type LoadedWithOrigin = Awaited<ReturnType<typeof loadMemoriesFromDir>>[number] & { origin?: string };\n const ownMemories: LoadedWithOrigin[] = await loadMemoriesFromDir(paths.memoriesDir);\n\n // Make the gate's fix hint actually unblock — and independently of --budget / ranking.\n // The decision-coverage gate checks that the validated policy memories\n // (decision/gotcha/architecture/convention) anchored to the changed files are present in the\n // marker's memory_ids. The displayed (\"surfaced\") set is budget-limited and can omit some of\n // them, so we compute the FULL anchored-policy set here with the SAME match function the gate\n // uses and UNION it into the final marker write below. Then `hivelore briefing --files <changed>`\n // (the command the gate suggests) satisfies the gate regardless of --budget.\n const POLICY_TYPES = new Set([\"decision\", \"gotcha\", \"architecture\", \"convention\"]);\n const anchoredPolicyIds =\n markerFiles.length > 0\n ? ownMemories\n .map((m) => m.memory)\n .filter(\n (mem) =>\n POLICY_TYPES.has(mem.frontmatter.type) &&\n mem.frontmatter.status === \"validated\" &&\n memoryMatchesAnchorPaths(mem, markerFiles),\n )\n .map((mem) => mem.frontmatter.id)\n : [];\n\n // Multi-project aggregation: merge memories from --include <path> projects.\n const externalRoots: string[] = [];\n if (opts.include && opts.include.length > 0) {\n for (const includePath of opts.include) {\n try {\n const otherRoot = findProjectRoot(includePath);\n if (otherRoot === root) continue; // skip self\n const otherPaths = resolveHaivePaths(otherRoot);\n if (!existsSync(otherPaths.memoriesDir)) {\n ui.warn(`--include ${includePath}: no .ai/memories at ${otherRoot} — skipping`);\n continue;\n }\n const otherMemories = await loadMemoriesFromDir(otherPaths.memoriesDir);\n const tag = path.basename(otherRoot);\n for (const m of otherMemories) {\n ownMemories.push({ ...m, origin: tag });\n }\n externalRoots.push(`${tag} (${otherMemories.length})`);\n } catch (err) {\n ui.warn(`--include ${includePath}: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n if (externalRoots.length > 0) {\n ui.info(`merged from: ${externalRoots.join(\", \")}`);\n console.log();\n }\n }\n\n const all = ownMemories;\n const filePaths = markerFiles;\n const tokens = opts.task ? tokenizeQuery(opts.task) : null;\n const scopeFilter = opts.scope ?? \"all\";\n\n // ── 1. Session recap — always shown first so agents start with fresh context ──\n const recaps = all\n .filter(({ memory: mem }) => mem.frontmatter.type === \"session_recap\")\n .sort((a, b) =>\n new Date(b.memory.frontmatter.created_at).getTime() -\n new Date(a.memory.frontmatter.created_at).getTime(),\n );\n if (recaps.length > 0 && !stopped()) {\n const recap = recaps[0]!;\n const fm = recap.memory.frontmatter;\n const rev = fm.revision_count ? ` · revision #${fm.revision_count}` : \"\";\n out(`${ui.bold(\"=== Last Session Recap ===\")}\\n`);\n out(ui.dim(`${fm.id} (${fm.scope}${rev})`));\n // Auto-generated recaps are low-signal tool dumps — compact them so they don't dominate.\n out(compactAutoRecapBody(recap.memory.body).trim());\n out(\"\");\n }\n\n // ── 2. Project context ─────────────────────────────────────────────────────\n if (existsSync(paths.projectContext) && !stopped()) {\n const ctx = await readFile(paths.projectContext, \"utf8\");\n const isTemplate = ctx.includes(\"TODO — high-level overview\") || ctx.includes(\"Generated by `hivelore init`\");\n // Adaptive: an init-bootstrapped context that is still mostly \"TODO —\" scaffolding is\n // inferable noise — don't dump it. Mirrors the MCP get_briefing adaptive trim.\n const bootstrapUnfilled =\n /Auto-generated by `hivelore init/i.test(ctx) && (ctx.match(/TODO —/g)?.length ?? 0) >= 2;\n if (isTemplate || bootstrapUnfilled) {\n // In --json mode, stdout MUST stay pure JSON — route the advisory to stderr instead.\n const msg =\n \"project-context.md is still auto-generated/unfilled — skipping it (low value). \" +\n \"Fill it in, or invoke the bootstrap_project MCP prompt for real context.\";\n if (json) console.error(msg); else ui.warn(msg);\n out(\"\");\n } else {\n out(`${ui.bold(\"=== Project Context ===\")}\\n`);\n out(ctx.trim());\n out(\"\");\n }\n } else if (!existsSync(paths.projectContext)) {\n ui.warn(\n \"No project-context.md found. Run `hivelore init` then invoke the bootstrap_project MCP prompt.\",\n );\n }\n\n // Strategy/positioning memories are excluded from automatic surfacing (still searchable via\n // `memory search`) — mirrors the MCP get_briefing filter so both façades behave identically.\n const briefingConfig = await loadConfig(paths);\n const excludeTags = briefingConfig.briefingExcludeTags;\n\n // Filter: exclude noise, drafts, stale, and session_recap (shown above) by default\n const candidates = all.filter(({ memory: mem }) => {\n const fm = mem.frontmatter;\n if (fm.status === \"rejected\" || fm.status === \"deprecated\") return false;\n if (!opts.includeDraft && fm.status === \"draft\") return false;\n if (!opts.includeStale && fm.status === \"stale\") return false;\n if (scopeFilter !== \"all\" && fm.scope !== scopeFilter && !(scopeFilter === \"team\" && fm.scope === \"shared\")) return false;\n if (fm.type === \"session_recap\") return false; // shown separately above\n if (memoryHasExcludedTag(fm, excludeTags)) return false;\n return true;\n });\n\n // Score by relevance (AND on task tokens; OR fallback if AND produces no task hits)\n const andTaskHits = tokens\n ? new Set(candidates.filter(({ memory: mem }) => literalMatchesAllTokens(mem, tokens)).map(({ memory: mem }) => mem.frontmatter.id))\n : null;\n const useOrFallback = andTaskHits !== null && andTaskHits.size === 0 && (tokens?.length ?? 0) > 1;\n\n const scored = candidates.map(({ memory: mem, filePath }) => {\n const fm = mem.frontmatter;\n let score = 0;\n if (fm.status === \"validated\") score += 3;\n else if (fm.status === \"proposed\") score += 1;\n if (filePaths.length > 0 && memoryMatchesAnchorPaths(mem, filePaths)) score += 4;\n if (tokens) {\n if (andTaskHits?.has(fm.id)) score += 3;\n else if (useOrFallback && literalMatchesAnyToken(mem, tokens)) score += 1;\n }\n return { memory: mem, filePath, score };\n });\n\n scored.sort((a, b) => b.score - a.score);\n const top = scored.slice(0, maxMemories);\n\n if (top.length === 0) {\n if (json) { console.log(JSON.stringify({ task: opts.task ?? null, memories: [], briefing_quality: \"thin\" }, null, 2)); return; }\n ui.info(\"No relevant memories found.\");\n const draftCount = all.filter(\n (m) =>\n m.memory.frontmatter.status === \"draft\" &&\n (scopeFilter === \"all\" || m.memory.frontmatter.scope === scopeFilter),\n ).length;\n if (draftCount > 0) {\n ui.info(`(${draftCount} draft memories excluded — use --include-draft to show)`);\n }\n if (opts.radar !== false && !stopped()) {\n const radar = await buildRadar({ root, taskTokens: tokens, filePaths });\n out(\"\");\n printRadar(radar, out, \"low-memory-signal\");\n }\n return;\n }\n\n if (stopped()) return;\n const usageIndex = await loadUsageIndex(paths).catch(() => null);\n out(`${ui.bold(\"=== Relevant Memories ===\")}\\n`);\n const priorities = top.map((item) =>\n classifyCliPriority(\n item,\n filePaths,\n tokens,\n Boolean(andTaskHits?.has(item.memory.frontmatter.id)),\n Boolean(useOrFallback && tokens && literalMatchesAnyToken(item.memory, tokens)),\n ),\n );\n const mustReadCount = priorities.filter((p) => p === \"must_read\").length;\n const usefulCount = priorities.filter((p) => p === \"useful\").length;\n const backgroundCount = priorities.filter((p) => p === \"background\").length;\n // Mirrors classifyBriefingQuality (briefing-helpers.ts): a must_read hit is actionable,\n // so \"noisy\" only applies to useful-only briefings dominated by background seeds.\n const quality = mustReadCount > 0 || usefulCount > 0\n ? mustReadCount === 0 && backgroundCount > usefulCount && backgroundCount > 2 ? \"noisy\" : \"strong\"\n : \"thin\";\n\n // JSON mode: emit the structured ranked briefing (parity with the MCP get_briefing tool) and stop.\n if (json) {\n console.log(JSON.stringify({\n task: opts.task ?? null,\n files: filePaths,\n briefing_quality: quality,\n counts: { must_read: mustReadCount, useful: usefulCount, background: backgroundCount },\n recap_id: recaps[0]?.memory.frontmatter.id ?? null,\n memories: top.map((item, i) => ({\n id: item.memory.frontmatter.id,\n scope: item.memory.frontmatter.scope,\n type: item.memory.frontmatter.type,\n status: item.memory.frontmatter.status,\n priority: priorities[i],\n score: item.score,\n file: path.relative(root, item.filePath),\n summary: (item.memory.body.split(\"\\n\").map((l) => l.replace(/^#+\\s*/, \"\").trim()).find((l) => l.length > 0) ?? \"\").slice(0, 140),\n })),\n }, null, 2));\n return;\n }\n out(ui.dim(`briefing_quality: ${quality} · must_read=${mustReadCount} useful=${usefulCount} background=${backgroundCount}`));\n out(\"\");\n printCliBreadcrumbs({\n top,\n priorities,\n task: opts.task,\n files: filePaths,\n symbols: parseCsv(opts.symbols),\n out,\n stopped,\n });\n for (const [idx, item] of top.entries()) {\n if (stopped()) break;\n const fm = item.memory.frontmatter;\n const badge = ui.statusBadge(fm.status);\n const draftMarker = fm.status === \"draft\" ? ui.yellow(\" [DRAFT]\") : \"\";\n const unverifiedMarker = fm.status === \"proposed\" ? ui.yellow(\" [UNVERIFIED]\") : \"\";\n const originMarker = (item as LoadedWithOrigin).origin\n ? ` ${ui.yellow(\"[from \" + (item as LoadedWithOrigin).origin + \"]\")}`\n : \"\";\n const reads = usageIndex?.by_id[fm.id]?.read_count ?? 0;\n const hitMarker = reads > 0 ? ` ${ui.dim(\"· \" + reads + \"× read\")}` : \"\";\n const priority = priorities[idx] ?? \"background\";\n out(\n `${ui.bold(fm.id)} ${priorityBadge(priority)} ${ui.dim(fm.scope + \"/\" + fm.type)} ${badge}${draftMarker}${unverifiedMarker}${originMarker}${hitMarker}`,\n );\n if (opts.explainSource) {\n const relPath = path.relative(root, item.filePath);\n const anchorPaths = fm.anchor?.paths ?? [];\n const anchorSymbols = fm.anchor?.symbols ?? [];\n const parts: string[] = [`source: ${relPath}`];\n if (anchorPaths.length > 0) parts.push(`paths: ${anchorPaths.join(\", \")}`);\n if (anchorSymbols.length > 0) parts.push(`symbols: ${anchorSymbols.join(\", \")}`);\n out(ui.dim(` [${parts.join(\" · \")}]`));\n }\n const memBody =\n opts.memoryFormat?.toLowerCase() === \"actions\"\n ? extractActionsBriefBody(item.memory.body)\n : item.memory.body.trim();\n out(memBody);\n out(\"\");\n }\n if (!stopped()) out(ui.dim(`${top.length} memor${top.length === 1 ? \"y\" : \"ies\"} surfaced`));\n\n // Track reads so usage stats, decay, and hot-memory detection work via CLI too\n const ids = top.map(({ memory: mem }) => mem.frontmatter.id);\n if (ids.length > 0) {\n await trackReads(paths, ids).catch(() => { /* non-fatal */ });\n }\n // Union the surfaced ids with the anchored-policy ids so the marker always covers what the\n // decision-coverage gate checks, even when --budget trimmed the surfaced set.\n const markerIds = [...new Set([...ids, ...anchoredPolicyIds])];\n if (markerIds.length > 0) {\n await writeBriefingMarker(paths, {\n task: opts.task ?? \"CLI briefing\",\n source: \"haive-briefing-cli\",\n sessionId: process.env.HAIVE_SESSION_ID,\n memoryIds: markerIds,\n files: filePaths,\n }).catch(() => { /* marker is best-effort */ });\n }\n\n // ── Project radar — surface git/TODO/hot-file signals when memories are scarce ──\n const radarForced = opts.radar === true;\n const radarAuto = opts.radar !== false && top.length < RADAR_AUTO_THRESHOLD;\n if ((radarForced || radarAuto) && !stopped()) {\n const radar = await buildRadar({ root, taskTokens: tokens, filePaths });\n if (radarHasContent(radar)) {\n out(\"\");\n printRadar(radar, out, radarForced ? \"forced\" : \"low-memory-signal\");\n }\n }\n\n // ── Code-map symbol lookup ──────────────────────────────────────────\n const requestedSymbols = (opts.symbols ?? \"\")\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n if (requestedSymbols.length > 0 && !stopped()) {\n const codeMap = await loadCodeMap(paths);\n if (!codeMap) {\n ui.warn(\"No code-map found. Run `hivelore index code` first to enable symbol lookup.\");\n } else {\n out(`\\n${ui.bold(\"=== Symbol Locations ===\")}\\n`);\n for (const sym of requestedSymbols) {\n if (stopped()) break;\n const { files } = queryCodeMap(codeMap, { symbol: sym });\n if (files.length === 0) {\n out(`${ui.dim(sym)} (not found in code-map)`);\n } else {\n for (const f of files) {\n if (stopped()) break;\n const exports = f.entry.exports.filter((e) =>\n e.name.toLowerCase().includes(sym.toLowerCase()),\n );\n for (const e of exports) {\n if (stopped()) break;\n const desc = e.description ? ` — ${e.description}` : \"\";\n out(`${ui.bold(e.name)} ${ui.dim(f.path + \":\" + e.line)} [${e.kind}]${desc}`);\n }\n }\n }\n }\n out(\"\");\n }\n }\n });\n}\n\ntype CliMemoryPriority = \"must_read\" | \"useful\" | \"background\";\n\n/**\n * Map the CLI briefing's lexical evidence into the SHARED core classifier, so `hivelore briefing` and\n * the MCP `get_briefing` can never disagree on priority (the drift that bit us twice). The CLI has no\n * embeddings, so `strongSemantic` is false and `usefulSemantic` is derived from the lexical score.\n */\nfunction classifyCliPriority(\n item: { memory: Awaited<ReturnType<typeof loadMemoriesFromDir>>[number][\"memory\"]; score: number },\n filePaths: string[],\n tokens: string[] | null,\n exactTaskHit: boolean,\n partialTaskHit: boolean,\n): CliMemoryPriority {\n const fm = item.memory.frontmatter;\n const anchored = filePaths.length > 0 && memoryMatchesAnchorPaths(item.memory, filePaths);\n return classifyMemoryPriority({\n type: fm.type,\n tags: fm.tags,\n requiresHumanApproval: Boolean(fm.requires_human_approval),\n directAnchor: anchored,\n directSymbol: false, // symbol lookup is rendered separately in the CLI, not via anchor priority\n exactTaskMatch: exactTaskHit,\n strongSemantic: false,\n usefulSemantic: partialTaskHit || item.score >= 4,\n moduleOrDomainMatch: false,\n tagTaskMatch: Boolean(tokens && fm.tags.some((tag) => tokens.includes(tag))),\n });\n}\n\nfunction priorityBadge(priority: CliMemoryPriority): string {\n if (priority === \"must_read\") return ui.red(\"[must_read]\");\n if (priority === \"useful\") return ui.yellow(\"[useful]\");\n return ui.dim(\"[background]\");\n}\n\nfunction printCliBreadcrumbs(input: {\n top: Array<{ memory: Awaited<ReturnType<typeof loadMemoriesFromDir>>[number][\"memory\"]; filePath: string; score: number }>;\n priorities: CliMemoryPriority[];\n task?: string;\n files: string[];\n symbols: string[];\n out: (text: string) => boolean;\n stopped: () => boolean;\n}): void {\n if (input.stopped()) return;\n // A terse pointer map only — the full body for each memory is printed right below, so re-summarizing\n // it here would just duplicate the payload. Keep breadcrumbs small (\"map, not manual\").\n const startHere = input.top.slice(0, 4).map((item, idx) => {\n const fm = item.memory.frontmatter;\n const priority = input.priorities[idx] ?? \"background\";\n const anchor = fm.anchor.paths[0] ? ` · applies to ${fm.anchor.paths[0]}` : \"\";\n return ` - ${priority}: ${fm.id} (${fm.scope}/${fm.type})${anchor}`;\n });\n\n const drillDown: string[] = [];\n for (const item of input.top.slice(0, 3)) {\n drillDown.push(` - mem_get(\"${item.memory.frontmatter.id}\")`);\n }\n if (input.task && input.files.length > 0) {\n drillDown.push(\n ` - mem_relevant_to(task:\"${cliOneLine(input.task)}\", files:[${input.files.map((f) => `\"${f}\"`).join(\", \")}], format:\"actions\")`,\n );\n }\n if (input.task) drillDown.push(` - code_search(query:\"${cliOneLine(input.task)}\", k:5)`);\n for (const symbol of input.symbols.slice(0, 3)) {\n drillDown.push(` - code_map(symbol:\"${cliOneLine(symbol)}\")`);\n }\n\n if (startHere.length === 0 && drillDown.length === 0) return;\n\n input.out(`${ui.bold(\"=== Breadcrumbs ===\")}\\n`);\n if (startHere.length > 0) {\n input.out(ui.bold(\"Start here:\"));\n for (const line of startHere) {\n if (input.stopped()) return;\n input.out(line);\n }\n input.out(\"\");\n }\n const uniqueDrillDown = [...new Set(drillDown)].slice(0, 6);\n if (uniqueDrillDown.length > 0) {\n input.out(ui.bold(\"Drill down only if needed:\"));\n for (const line of uniqueDrillDown) {\n if (input.stopped()) return;\n input.out(line);\n }\n input.out(\"\");\n }\n}\n\nfunction cliOneLine(value: string): string {\n return value.replace(/\\s+/g, \" \").replace(/\"/g, '\\\\\"').trim().slice(0, 120);\n}\n\nfunction parseCsv(value: string | undefined): string[] {\n if (!value) return [];\n return value.split(\",\").map((s) => s.trim()).filter(Boolean);\n}\n\nfunction collectInclude(value: string, previous: string[]): string[] {\n return [...previous, value];\n}\n","import pc from \"picocolors\";\n\n// When a command emits machine-readable JSON on stdout, human log lines must not pollute it.\n// `setUiJsonMode(true)` routes info/success/warn to stderr so stdout stays a clean JSON channel.\nlet jsonMode = false;\nexport function setUiJsonMode(on: boolean): void {\n jsonMode = on;\n}\nconst logHuman = (icon: string, msg: string): void => {\n if (jsonMode) console.error(icon, msg);\n else console.log(icon, msg);\n};\n\nexport const ui = {\n info: (msg: string) => logHuman(pc.cyan(\"ℹ\"), msg),\n success: (msg: string) => logHuman(pc.green(\"✓\"), msg),\n warn: (msg: string) => logHuman(pc.yellow(\"⚠\"), msg),\n error: (msg: string) => console.error(pc.red(\"✗\"), msg),\n dim: (msg: string) => pc.dim(msg),\n bold: (msg: string) => pc.bold(msg),\n green: (msg: string) => pc.green(msg),\n yellow: (msg: string) => pc.yellow(msg),\n red: (msg: string) => pc.red(msg),\n statusBadge: (status: string): string => {\n switch (status) {\n case \"validated\": return pc.green(status);\n case \"proposed\": return pc.yellow(status);\n case \"stale\": return pc.yellow(status);\n case \"rejected\": return pc.red(status);\n case \"deprecated\": return pc.dim(status);\n default: return pc.dim(status); // draft\n }\n },\n};\n","import { execFile } from \"node:child_process\";\nimport path from \"node:path\";\nimport { promisify } from \"node:util\";\n\nconst exec = promisify(execFile);\n\nexport interface RadarOptions {\n root: string;\n taskTokens: string[] | null;\n filePaths: string[];\n daysBack?: number;\n maxCommits?: number;\n maxTodos?: number;\n maxHotFiles?: number;\n}\n\nexport interface RadarReport {\n recentCommits: { sha: string; date: string; subject: string; files: string[] }[];\n openTodos: { file: string; line: number; text: string }[];\n hotFiles: { path: string; changes: number }[];\n insideGitRepo: boolean;\n}\n\nconst DEFAULT_DAYS_BACK = 14;\nconst DEFAULT_MAX_COMMITS = 5;\nconst DEFAULT_MAX_TODOS = 8;\nconst DEFAULT_MAX_HOT_FILES = 5;\n\nconst TODO_RE = /\\b(?:TODO|FIXME|HACK|XXX)\\b[: ]?(.{0,120})/i;\n\nconst SOURCE_GLOBS = [\n \"*.ts\", \"*.tsx\", \"*.js\", \"*.jsx\", \"*.py\", \"*.go\", \"*.rs\",\n \"*.java\", \"*.kt\", \"*.swift\", \"*.rb\", \"*.php\", \"*.cs\", \"*.cpp\", \"*.c\", \"*.h\",\n];\n\n/**\n * True only when `root` is the git repo root, or sits ABOVE it — NOT when `root` is a subdirectory of\n * a larger repo. Otherwise the radar surfaces the PARENT repo's commits/churn as if they were this\n * project's (a real leak: a fixture with a local `.ai/` but no `.git` walked up to the parent repo's\n * history). When the git toplevel is an ancestor of `root`, the parent's history is not \"this project's\".\n */\nasync function isGitRepo(root: string): Promise<boolean> {\n try {\n const { stdout } = await exec(\"git\", [\"rev-parse\", \"--show-toplevel\"], { cwd: root });\n const toplevel = path.resolve(stdout.trim());\n const resolvedRoot = path.resolve(root);\n if (toplevel === resolvedRoot) return true;\n // Allow the toplevel being INSIDE root (root contains the repo); reject it being an ANCESTOR.\n return toplevel.startsWith(resolvedRoot + path.sep);\n } catch {\n return false;\n }\n}\n\nasync function getRecentCommits(\n root: string,\n daysBack: number,\n maxCommits: number,\n taskTokens: string[] | null,\n filePaths: string[],\n): Promise<RadarReport[\"recentCommits\"]> {\n try {\n const { stdout } = await exec(\n \"git\",\n [\n \"log\",\n `--since=${daysBack}.days.ago`,\n \"--name-only\",\n \"--pretty=format:%x1f%h%x1f%ad%x1f%s\",\n \"--date=short\",\n \"-n\", \"60\",\n ],\n { cwd: root, maxBuffer: 4 * 1024 * 1024 },\n );\n\n const blocks = stdout.split(\"\\x1f\").filter((b) => b.trim().length > 0);\n const commits: RadarReport[\"recentCommits\"] = [];\n for (let i = 0; i + 2 < blocks.length; i += 3) {\n const sha = blocks[i]!.trim();\n const date = blocks[i + 1]!.trim();\n const tail = blocks[i + 2]!;\n const lines = tail.split(\"\\n\").map((l) => l.trim()).filter(Boolean);\n const subject = lines.shift() ?? \"\";\n const files = lines;\n commits.push({ sha, date, subject, files });\n }\n\n const lowerTokens = taskTokens?.map((t) => t.toLowerCase()) ?? [];\n const lowerPaths = filePaths.map((p) => p.toLowerCase());\n const scored = commits.map((c) => {\n let score = 0;\n const haystack = (c.subject + \" \" + c.files.join(\" \")).toLowerCase();\n for (const t of lowerTokens) if (haystack.includes(t)) score += 2;\n for (const p of lowerPaths) if (c.files.some((f) => f.toLowerCase().includes(p))) score += 3;\n return { c, score };\n });\n\n if (lowerTokens.length === 0 && lowerPaths.length === 0) {\n return commits.slice(0, maxCommits);\n }\n return scored\n .filter((s) => s.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, maxCommits)\n .map((s) => s.c);\n } catch {\n return [];\n }\n}\n\nasync function getOpenTodos(\n root: string,\n maxTodos: number,\n taskTokens: string[] | null,\n filePaths: string[],\n): Promise<RadarReport[\"openTodos\"]> {\n try {\n const includeArgs = SOURCE_GLOBS.flatMap((g) => [\"--include\", g]);\n const { stdout } = await exec(\n \"grep\",\n [\n \"-rnE\",\n \"--exclude-dir=node_modules\",\n \"--exclude-dir=.git\",\n \"--exclude-dir=dist\",\n \"--exclude-dir=build\",\n \"--exclude-dir=.next\",\n \"--exclude-dir=coverage\",\n ...includeArgs,\n \"\\\\b(TODO|FIXME|HACK|XXX)\\\\b\",\n \".\",\n ],\n { cwd: root, maxBuffer: 4 * 1024 * 1024 },\n ).catch((err: { stdout?: string }) => ({ stdout: err.stdout ?? \"\" }));\n\n const lines = stdout.split(\"\\n\").filter(Boolean);\n const parsed: RadarReport[\"openTodos\"] = [];\n for (const line of lines) {\n const m = line.match(/^([^:]+):(\\d+):(.*)$/);\n if (!m) continue;\n const [, file, lineNoStr, rest] = m;\n const todoMatch = rest!.match(TODO_RE);\n if (!todoMatch) continue;\n const text = (todoMatch[1] ?? \"\").trim() || rest!.trim().slice(0, 120);\n parsed.push({ file: file!.replace(/^\\.\\//, \"\"), line: Number(lineNoStr), text });\n }\n\n const lowerTokens = taskTokens?.map((t) => t.toLowerCase()) ?? [];\n const lowerPaths = filePaths.map((p) => p.toLowerCase());\n if (lowerTokens.length === 0 && lowerPaths.length === 0) {\n return parsed.slice(0, maxTodos);\n }\n const scored = parsed.map((t) => {\n let score = 0;\n const hay = (t.file + \" \" + t.text).toLowerCase();\n for (const tok of lowerTokens) if (hay.includes(tok)) score += 1;\n for (const p of lowerPaths) if (t.file.toLowerCase().includes(p)) score += 2;\n return { t, score };\n });\n return scored\n .filter((s) => s.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, maxTodos)\n .map((s) => s.t);\n } catch {\n return [];\n }\n}\n\nasync function getHotFiles(\n root: string,\n daysBack: number,\n maxHotFiles: number,\n filePaths: string[],\n): Promise<RadarReport[\"hotFiles\"]> {\n try {\n const { stdout } = await exec(\n \"git\",\n [\n \"log\",\n `--since=${daysBack * 6}.days.ago`,\n \"--name-only\",\n \"--pretty=format:\",\n ],\n { cwd: root, maxBuffer: 4 * 1024 * 1024 },\n );\n const counts = new Map<string, number>();\n for (const raw of stdout.split(\"\\n\")) {\n const f = raw.trim();\n if (!f) continue;\n counts.set(f, (counts.get(f) ?? 0) + 1);\n }\n let entries = [...counts.entries()].map(([path, changes]) => ({ path, changes }));\n\n const lowerPaths = filePaths.map((p) => p.toLowerCase());\n if (lowerPaths.length > 0) {\n entries = entries.filter((e) => lowerPaths.some((p) => e.path.toLowerCase().includes(p)));\n }\n\n return entries.sort((a, b) => b.changes - a.changes).slice(0, maxHotFiles);\n } catch {\n return [];\n }\n}\n\nexport async function buildRadar(opts: RadarOptions): Promise<RadarReport> {\n const inside = await isGitRepo(opts.root);\n if (!inside) {\n return { recentCommits: [], openTodos: [], hotFiles: [], insideGitRepo: false };\n }\n const daysBack = opts.daysBack ?? DEFAULT_DAYS_BACK;\n const [recentCommits, openTodos, hotFiles] = await Promise.all([\n getRecentCommits(opts.root, daysBack, opts.maxCommits ?? DEFAULT_MAX_COMMITS, opts.taskTokens, opts.filePaths),\n getOpenTodos(opts.root, opts.maxTodos ?? DEFAULT_MAX_TODOS, opts.taskTokens, opts.filePaths),\n getHotFiles(opts.root, daysBack, opts.maxHotFiles ?? DEFAULT_MAX_HOT_FILES, opts.filePaths),\n ]);\n return { recentCommits, openTodos, hotFiles, insideGitRepo: true };\n}\n\nexport function radarHasContent(r: RadarReport): boolean {\n return r.recentCommits.length > 0 || r.openTodos.length > 0 || r.hotFiles.length > 0;\n}\n","import { existsSync } from \"node:fs\";\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n AUTOPILOT_DEFAULTS,\n buildCodeMap,\n loadCodeMap,\n loadConfig,\n loadMemoriesFromDir,\n saveCodeMap,\n saveConfig,\n type HaiveConfig,\n type HaivePaths,\n} from \"@hivelore/core\";\nimport { lintMemoriesAsync } from \"../commands/memory-lint.js\";\n\nexport interface AutopilotRepair {\n code: string;\n message: string;\n}\n\nexport interface AutopilotRepairOptions {\n applyConfig?: boolean;\n applyCorpus?: boolean;\n applyContext?: boolean;\n applyCodeMap?: boolean;\n applyCodeSearch?: boolean;\n forceCodeMap?: boolean;\n}\n\nexport interface ProjectContextVersionStatus {\n expectedVersion?: string;\n currentVersion?: string;\n mismatch: boolean;\n canSync: boolean;\n}\n\nexport async function applyAutopilotRepairs(\n root: string,\n paths: HaivePaths,\n options: AutopilotRepairOptions = {},\n): Promise<AutopilotRepair[]> {\n const repairs: AutopilotRepair[] = [];\n const config = await loadConfig(paths);\n\n if (options.applyConfig) {\n const changed = await ensureAutopilotConfig(paths, config);\n if (changed) {\n repairs.push({\n code: \"autopilot-config\",\n message: \"Enabled autopilot defaults in .ai/haive.config.json.\",\n });\n }\n }\n\n const current = await loadConfig(paths);\n const autoRepair = current.autoRepair ?? {};\n\n if (options.applyContext ?? autoRepair.context ?? current.autopilot) {\n const changed = await syncProjectContextVersion(root, paths);\n if (changed) {\n repairs.push({\n code: \"project-context-version\",\n message: \"Updated .ai/project-context.md version metadata from package.json.\",\n });\n }\n }\n\n if (options.applyCorpus ?? autoRepair.corpus ?? current.autopilot) {\n const report = await lintMemoriesAsync(root, { fix: true, apply: true });\n const applied = report.fixes.filter((fix) => fix.applied);\n if (applied.length > 0) {\n repairs.push({\n code: \"memory-lint-fix\",\n message: `Applied ${applied.length} safe memory lint fix${applied.length === 1 ? \"\" : \"es\"}.`,\n });\n }\n\n const indexed = await refreshMemorySemanticIndex(paths);\n if (indexed) {\n repairs.push({\n code: \"memory-embeddings-index\",\n message: \"Refreshed memory embeddings index.\",\n });\n }\n }\n\n if (options.applyCodeMap ?? autoRepair.codeMap ?? current.autopilot) {\n const refreshed = await refreshCodeMap(root, paths, Boolean(options.forceCodeMap));\n if (refreshed) {\n repairs.push({\n code: \"code-map-refresh\",\n message: \"Refreshed .ai/code-map.json.\",\n });\n }\n }\n\n if (options.applyCodeSearch ?? autoRepair.codeSearch ?? current.autopilot) {\n const indexed = await refreshCodeSearchIndex(paths);\n if (indexed) {\n repairs.push({\n code: \"code-search-index\",\n message: \"Refreshed code-search embeddings index.\",\n });\n }\n }\n\n return repairs;\n}\n\nexport async function ensureAutopilotConfig(\n paths: HaivePaths,\n currentConfig?: HaiveConfig,\n): Promise<boolean> {\n const current = currentConfig ?? await loadConfig(paths);\n const next: HaiveConfig = {\n ...current,\n autopilot: true,\n defaultScope: \"team\",\n defaultStatus: \"validated\",\n autoApproveDelayHours: current.autoApproveDelayHours ?? AUTOPILOT_DEFAULTS.autoApproveDelayHours,\n autoPromoteMinReads: current.autoPromoteMinReads ?? AUTOPILOT_DEFAULTS.autoPromoteMinReads,\n autoSessionEnd: true,\n autoContext: true,\n autoRepair: {\n context: true,\n corpus: true,\n codeMap: true,\n codeSearch: current.autoRepair?.codeSearch ?? true,\n },\n enforcement: {\n ...AUTOPILOT_DEFAULTS.enforcement,\n ...current.enforcement,\n mode: \"strict\",\n requireBriefingFirst: true,\n requireSessionRecap: true,\n requireMemoryVerify: true,\n blockStaleDecisionChanges: true,\n requireDecisionCoverage: true,\n cleanupGeneratedArtifacts: true,\n toolProfile: current.enforcement?.toolProfile ?? \"enforcement\",\n },\n };\n\n if (JSON.stringify(current) === JSON.stringify(next)) return false;\n await saveConfig(paths, next);\n return true;\n}\n\nexport async function syncProjectContextVersion(\n root: string,\n paths: HaivePaths,\n): Promise<boolean> {\n const status = await projectContextVersionStatus(root, paths);\n if (!status.canSync || !status.expectedVersion) return false;\n\n const original = await readFile(paths.projectContext, \"utf8\");\n let updated = original\n .replace(\n /^# Project context — Hivelore \\(v[^)]+\\)$/m,\n `# Project context — Hivelore (v${status.expectedVersion})`,\n )\n .replace(\n /> \\*\\*Current version\\*\\*: [^—\\n]+—/m,\n `> **Current version**: ${status.expectedVersion} —`,\n );\n\n if (updated === original && !original.includes(\"Current version\")) {\n updated = original.replace(\n /^(> Repo-native context enforcement[^\\n]*\\n)/m,\n `$1> **Current version**: ${status.expectedVersion} — @hivelore/core, cli, mcp, embeddings are versioned together.\\n`,\n );\n }\n\n if (updated === original && !original.includes(\"Current version\")) {\n updated = original.replace(\n /^(# Project context[^\\n]*\\n)/m,\n `$1\\n> **Current version**: ${status.expectedVersion}\\n`,\n );\n }\n\n if (updated === original) return false;\n await writeFile(paths.projectContext, updated, \"utf8\");\n return true;\n}\n\nexport async function projectContextVersionStatus(\n root: string,\n paths: HaivePaths,\n): Promise<ProjectContextVersionStatus> {\n if (!existsSync(paths.projectContext)) {\n return { mismatch: false, canSync: false };\n }\n const packagePath = path.join(root, \"package.json\");\n if (!existsSync(packagePath)) {\n return { mismatch: false, canSync: false };\n }\n\n const packageJson = JSON.parse(await readFile(packagePath, \"utf8\")) as { version?: string };\n const expectedVersion = packageJson.version;\n if (!expectedVersion) {\n return { mismatch: false, canSync: false };\n }\n\n const content = await readFile(paths.projectContext, \"utf8\");\n const headingVersion = content.match(/^# Project context — Hivelore \\(v([^)]+)\\)$/m)?.[1];\n const currentLineVersion = content.match(/^> \\*\\*Current version\\*\\*: ([^—\\n]+)/m)?.[1]?.trim();\n const currentVersion = currentLineVersion ?? headingVersion;\n\n return {\n expectedVersion,\n currentVersion,\n mismatch: currentVersion !== expectedVersion,\n canSync: true,\n };\n}\n\nasync function refreshCodeMap(\n root: string,\n paths: HaivePaths,\n force: boolean,\n): Promise<boolean> {\n const existing = await loadCodeMap(paths);\n if (existing && !force) return false;\n\n const map = await buildCodeMap(root, {\n includeUntracked: true,\n excludeDirs: [\n \"node_modules\",\n \"dist\",\n \"build\",\n \"out\",\n \".git\",\n \".next\",\n \".turbo\",\n \".vitest-cache\",\n \"coverage\",\n ],\n });\n if (\n existing &&\n existing.root === map.root &&\n JSON.stringify(existing.files) === JSON.stringify(map.files)\n ) {\n return false;\n }\n await saveCodeMap(paths, map);\n return true;\n}\n\nasync function refreshCodeSearchIndex(paths: HaivePaths): Promise<boolean> {\n try {\n const mod = await import(\"@hivelore/embeddings\");\n const embedder = await mod.Embedder.create();\n const { report } = await mod.rebuildCodeIndex(paths, embedder);\n return report.added > 0 || report.updated > 0 || report.removed > 0;\n } catch {\n return false;\n }\n}\n\nasync function refreshMemorySemanticIndex(paths: HaivePaths): Promise<boolean> {\n try {\n if (!existsSync(paths.memoriesDir)) return false;\n const memories = await loadMemoriesFromDir(paths.memoriesDir);\n if (memories.length === 0) return false;\n const mod = await import(\"@hivelore/embeddings\");\n const embedder = await mod.Embedder.create();\n const { report } = await mod.rebuildIndex(paths, embedder);\n return report.added > 0 || report.updated > 0 || report.removed > 0;\n } catch {\n return false;\n }\n}\n","/**\n * Lightweight quality checks — no ML, safe to run on CI alongside tests.\n */\nimport { existsSync } from \"node:fs\";\nimport { writeFile } from \"node:fs/promises\";\nimport { spawnSync } from \"node:child_process\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n findProjectRoot,\n getUsage,\n retirementSignal,\n loadCodeMap,\n loadMemoriesFromDir,\n loadUsageIndex,\n looksLikeGenericAdvice,\n resolveHaivePaths,\n serializeMemory,\n specificityScore,\n type LoadedMemory,\n} from \"@hivelore/core\";\nimport { ui } from \"../utils/ui.js\";\n\nexport type LintSeverity = \"error\" | \"warn\" | \"info\";\n\nexport interface MemoryLintFinding {\n file: string;\n id: string;\n severity: LintSeverity;\n code: string;\n message: string;\n suggested_anchors?: {\n paths: string[];\n symbols: string[];\n };\n}\n\ninterface LintOpts {\n json?: boolean;\n dir?: string;\n fix?: boolean;\n dryRun?: boolean;\n apply?: boolean;\n}\n\nexport interface MemoryLintFix {\n file: string;\n id: string;\n actions: string[];\n applied: boolean;\n}\n\nexport interface MemoryLintReport {\n findings: MemoryLintFinding[];\n fixes: MemoryLintFix[];\n}\n\nexport async function lintMemoriesAsync(\n root: string,\n options: { fix?: boolean; apply?: boolean } = {},\n): Promise<MemoryLintReport> {\n const paths = resolveHaivePaths(root);\n const out: MemoryLintFinding[] = [];\n const fixes: MemoryLintFix[] = [];\n if (!existsSync(paths.memoriesDir)) return { findings: out, fixes };\n\n const loaded = await loadMemoriesFromDir(paths.memoriesDir);\n const usage = await loadUsageIndex(paths);\n const codeMap = await loadCodeMap(paths);\n const trackedFiles = gitTrackedFiles(root);\n\n const ANCHOR_TYPES = new Set([\"decision\", \"architecture\", \"gotcha\"]);\n const actionableWords =\n /\\b(always|never|prefer|use|run|avoid|because|instead|why|rationale|do not|must|should|require|required|requires|fix|fail|failed|fails|prevent|prevents|allow|allows|lets|ensure|ensures|catch|catches)\\b/i;\n\n for (const { filePath, memory } of loaded) {\n const fm = memory.frontmatter;\n if (fm.type === \"session_recap\") continue;\n\n const body = memory.body.trim();\n const naked = body.replace(/^#.*$/gm, \"\").replace(/```[\\s\\S]*?```/g, \"\").trim();\n const retired = retirementSignal(fm, memory.body);\n\n if (retired.retired && fm.status !== \"deprecated\" && fm.status !== \"rejected\" && fm.status !== \"stale\") {\n out.push({\n file: filePath,\n id: fm.id,\n severity: \"warn\",\n code: \"RETIRED_ACTIVE_MEMORY\",\n message:\n `Record is still active but lifecycle metadata says it should be retired (${retired.reason}). ` +\n \"Mark it deprecated or remove the fixed/superseded marker if it still applies.\",\n });\n }\n\n if (naked.length < 40 && fm.status !== \"rejected\") {\n out.push({\n file: filePath,\n id: fm.id,\n severity: \"warn\",\n code: \"SHORT_BODY\",\n message: \"Body looks very short (< ~40 chars of prose after headings). Prefer actionable detail.\",\n });\n }\n\n if (\n [\"decision\", \"gotcha\", \"convention\", \"architecture\", \"attempt\"].includes(fm.type) &&\n fm.status !== \"rejected\" &&\n !actionableWords.test(naked)\n ) {\n out.push({\n file: filePath,\n id: fm.id,\n severity: \"info\",\n code: \"LOW_ACTIONABILITY\",\n message:\n \"Record does not contain obvious action/rationale words. Add the concrete rule, why it exists, and what to do instead.\",\n });\n }\n\n // Low-value / likely-guessable: Hivelore earns its keep on UNGUESSABLE team knowledge. A memory\n // that reads like generic best practice (no concrete literals/identifiers/values) is something\n // a capable model already does by default — surfacing it is mostly token overhead.\n if (\n [\"decision\", \"gotcha\", \"convention\", \"architecture\"].includes(fm.type) &&\n fm.status !== \"rejected\" &&\n naked.length >= 40 &&\n specificityScore(naked) < 0.2 &&\n // High-precision gate: only flag when there is positive evidence of generic advice.\n // A low-density but arbitrary team policy (unguessable prose) must not be flagged.\n looksLikeGenericAdvice(naked)\n ) {\n out.push({\n file: filePath,\n id: fm.id,\n severity: \"info\",\n code: \"LOW_VALUE_GUESSABLE\",\n message:\n \"Reads like generic best practice a capable model already follows. Hivelore's value is \" +\n \"UNGUESSABLE team knowledge — add the concrete, arbitrary specifics (exact names, values, \" +\n \"formats, magic numbers) or consider removing it to keep briefings high-signal.\",\n });\n }\n\n const suggestedAnchors = suggestAnchors(root, { filePath, memory }, codeMap, trackedFiles);\n // Stack-pack seeds are framework-level guidance with no natural file anchor; they already\n // carry `needs_anchor` and their bodies say to anchor-or-replace when they become repo policy.\n // Flagging them on the very first `hivelore memory lint` run buries real findings in seed noise.\n const isUnanchoredSeed = fm.tags.includes(\"stack-pack\") && fm.tags.includes(\"needs_anchor\");\n if (ANCHOR_TYPES.has(fm.type) && fm.anchor.paths.length === 0 && fm.status === \"validated\" && !isUnanchoredSeed) {\n out.push({\n file: filePath,\n id: fm.id,\n severity: \"warn\",\n code: \"MISSING_ANCHOR\",\n message:\n `${fm.type} is validated without anchor paths — add anchor.paths so hivelore sync can flag staleness.`,\n ...(suggestedAnchors.paths.length > 0 || suggestedAnchors.symbols.length > 0\n ? { suggested_anchors: suggestedAnchors }\n : {}),\n });\n }\n\n if (fm.status === \"stale\" && !fm.stale_reason) {\n out.push({\n file: filePath,\n id: fm.id,\n severity: \"info\",\n code: \"STALE_NO_REASON\",\n message: \"Status is stale but stale_reason is empty — document why when possible.\",\n });\n }\n\n if (fm.type === \"glossary\" && naked.length > 6000) {\n out.push({\n file: filePath,\n id: fm.id,\n severity: \"info\",\n code: \"LONG_GLOSSARY\",\n message: \"Very long glossary — consider splitting concepts for tighter briefings.\",\n });\n }\n\n const hasMarkdownHeading = /^#{1,3}\\s+\\S/m.test(memory.body.trim());\n if (!hasMarkdownHeading) {\n out.push({\n file: filePath,\n id: fm.id,\n severity: \"warn\",\n code: \"NO_MD_HEADING\",\n message:\n \"No Markdown heading (#/##/###) — add one so humans and auditors can skim the memo quickly.\",\n });\n }\n\n const u = getUsage(usage, fm.id);\n const createdAt = Date.parse(fm.created_at);\n const ageDays = Number.isFinite(createdAt)\n ? (Date.now() - createdAt) / (24 * 60 * 60 * 1000)\n : 0;\n if (fm.status === \"validated\" && u.read_count === 0 && ageDays >= 7) {\n out.push({\n file: filePath,\n id: fm.id,\n severity: \"info\",\n code: \"NEVER_READ\",\n message:\n \"Validated record has never been surfaced/read. Consider improving tags/anchors or archiving it if it is not useful.\",\n });\n }\n\n if (options.fix) {\n const actions: string[] = [];\n let nextBody = memory.body;\n let nextFrontmatter = memory.frontmatter;\n\n if (!hasMarkdownHeading) {\n nextBody = `# ${titleFromId(fm.id)}\\n\\n${nextBody.trim()}`;\n actions.push(\"add missing Markdown heading\");\n }\n\n if (\n ANCHOR_TYPES.has(fm.type) &&\n fm.anchor.paths.length === 0 &&\n fm.status === \"validated\" &&\n suggestedAnchors.paths.length > 0\n ) {\n nextFrontmatter = {\n ...nextFrontmatter,\n anchor: {\n ...nextFrontmatter.anchor,\n paths: [...new Set([...nextFrontmatter.anchor.paths, ...suggestedAnchors.paths])],\n symbols: [\n ...new Set([...nextFrontmatter.anchor.symbols, ...suggestedAnchors.symbols]),\n ],\n },\n tags: nextFrontmatter.tags.filter((tag) => tag !== \"needs_anchor\"),\n };\n actions.push(\"add suggested tracked anchor paths\");\n if (suggestedAnchors.symbols.length > 0) {\n actions.push(\"add suggested anchor symbols\");\n }\n }\n\n if (\n ANCHOR_TYPES.has(fm.type) &&\n fm.anchor.paths.length === 0 &&\n fm.anchor.symbols.length === 0 &&\n suggestedAnchors.paths.length === 0 &&\n fm.status === \"validated\" &&\n !fm.tags.includes(\"needs_anchor\")\n ) {\n nextFrontmatter = {\n ...nextFrontmatter,\n tags: [...nextFrontmatter.tags, \"needs_anchor\"],\n };\n actions.push(\"tag validated anchorless record with needs_anchor\");\n }\n\n if (actions.length > 0) {\n fixes.push({ file: filePath, id: fm.id, actions, applied: Boolean(options.apply) });\n if (options.apply) {\n await writeFile(\n filePath,\n serializeMemory({ frontmatter: nextFrontmatter, body: nextBody }),\n \"utf8\",\n );\n }\n }\n }\n }\n\n for (const dup of nearDuplicatePairs(loaded)) {\n out.push({\n file: dup.file,\n id: dup.id,\n severity: \"warn\",\n code: \"NEAR_DUPLICATE\",\n message:\n `Body overlaps ~${Math.round(dup.score * 100)}% with ${dup.otherId}. Merge or deprecate one record to reduce briefing noise.`,\n });\n }\n\n return { findings: out, fixes };\n}\n\nfunction titleFromId(id: string): string {\n const withoutDate = id.replace(/^\\d{4}-\\d{2}-\\d{2}-/, \"\");\n return withoutDate\n .split(\"-\")\n .filter(Boolean)\n .map((part) => part.slice(0, 1).toUpperCase() + part.slice(1))\n .join(\" \");\n}\n\nfunction suggestAnchors(\n root: string,\n loaded: LoadedMemory,\n codeMap: Awaited<ReturnType<typeof loadCodeMap>>,\n trackedFiles: ReadonlySet<string> | null,\n): { paths: string[]; symbols: string[] } {\n const body = loaded.memory.body;\n const paths = new Set<string>();\n const symbols = new Set<string>();\n\n for (const match of body.matchAll(/`([^`\\n]+\\.[A-Za-z0-9]+)`|(?:^|\\s)([A-Za-z0-9_./-]+\\.[A-Za-z0-9]+)/gm)) {\n const candidate = (match[1] ?? match[2] ?? \"\").replace(/^\\.?\\//, \"\");\n if (!candidate || candidate.startsWith(\"http\")) continue;\n if (existsSync(path.join(root, candidate)) && isSafeAnchorPath(candidate, trackedFiles)) {\n paths.add(candidate);\n }\n }\n\n if (codeMap) {\n const lowered = body.toLowerCase();\n for (const [file, entry] of Object.entries(codeMap.files)) {\n for (const exp of entry.exports) {\n if (!exp.name || exp.name.length < 4) continue;\n if (lowered.includes(exp.name.toLowerCase())) {\n if (isSafeAnchorPath(file, trackedFiles)) {\n paths.add(file);\n symbols.add(exp.name);\n }\n }\n if (paths.size >= 5 && symbols.size >= 5) break;\n }\n if (paths.size >= 5 && symbols.size >= 5) break;\n }\n }\n\n return {\n paths: [...paths].slice(0, 5),\n symbols: [...symbols].slice(0, 5),\n };\n}\n\nfunction gitTrackedFiles(root: string): ReadonlySet<string> | null {\n const result = spawnSync(\"git\", [\"ls-files\"], {\n cwd: root,\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n });\n if (result.status !== 0) return null;\n const files = result.stdout\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter(Boolean);\n return new Set(files);\n}\n\nfunction isSafeAnchorPath(file: string, trackedFiles: ReadonlySet<string> | null): boolean {\n const normalized = file.replace(/\\\\/g, \"/\").replace(/^\\.?\\//, \"\");\n if (normalized.startsWith(\".ai/.cache/\") || normalized.startsWith(\".ai/.runtime/\")) return false;\n if (normalized.includes(\"/node_modules/\") || normalized.startsWith(\"node_modules/\")) return false;\n if (normalized.includes(\"/dist/\") || normalized.startsWith(\"dist/\")) return false;\n if (trackedFiles && !trackedFiles.has(normalized)) return false;\n return true;\n}\n\nfunction nearDuplicatePairs(\n loaded: Awaited<ReturnType<typeof loadMemoriesFromDir>>,\n): Array<{ id: string; otherId: string; file: string; score: number }> {\n const out: Array<{ id: string; otherId: string; file: string; score: number }> = [];\n const candidates = loaded.filter(({ memory }) => {\n const fm = memory.frontmatter;\n return fm.type !== \"session_recap\" && fm.status !== \"rejected\" && fm.status !== \"deprecated\";\n });\n for (let i = 0; i < candidates.length; i++) {\n for (let j = i + 1; j < candidates.length; j++) {\n const a = candidates[i]!;\n const b = candidates[j]!;\n if (a.memory.frontmatter.scope !== b.memory.frontmatter.scope) continue;\n if (a.memory.frontmatter.type !== b.memory.frontmatter.type) continue;\n const score = jaccard(tokenSet(a.memory.body), tokenSet(b.memory.body));\n if (score >= 0.72) {\n out.push({\n id: a.memory.frontmatter.id,\n otherId: b.memory.frontmatter.id,\n file: a.filePath,\n score,\n });\n }\n }\n }\n return out;\n}\n\nfunction tokenSet(body: string): Set<string> {\n return new Set(\n (body.toLowerCase().match(/\\b[a-z0-9]{4,}\\b/g) ?? [])\n .filter((word) => ![\"this\", \"that\", \"with\", \"from\", \"have\"].includes(word)),\n );\n}\n\nfunction jaccard(a: Set<string>, b: Set<string>): number {\n if (a.size === 0 || b.size === 0) return 0;\n let inter = 0;\n for (const item of a) if (b.has(item)) inter++;\n return inter / (a.size + b.size - inter);\n}\n\nexport function registerMemoryLint(parent: Command): void {\n parent\n .command(\"lint\")\n .description(\n \"Heuristic corpus checks (anchors on key types, headings, verbosity). Static analysis only.\",\n )\n .option(\"--json\", \"emit findings as JSON\", false)\n .option(\"--fix\", \"prepare simple automatic fixes (use with --dry-run or --apply)\", false)\n .option(\"--dry-run\", \"with --fix, show files that would change without writing\", false)\n .option(\"--apply\", \"with --fix, write simple fixes to disk\", false)\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: LintOpts) => {\n const root = findProjectRoot(opts.dir);\n const apply = Boolean(opts.fix && opts.apply);\n const dryRun = Boolean(opts.fix && (opts.dryRun || !opts.apply));\n const report = await lintMemoriesAsync(root, { fix: Boolean(opts.fix), apply });\n const findings = report.findings;\n\n if (opts.json) {\n console.log(JSON.stringify({\n findings_count: findings.length,\n findings,\n fixes_count: report.fixes.length,\n fixes: report.fixes,\n fix_mode: opts.fix ? apply ? \"apply\" : \"dry-run\" : \"off\",\n }, null, 2));\n process.exitCode = findings.some((f) => f.severity === \"error\") ? 1 : 0;\n return;\n }\n\n if (findings.length === 0) {\n ui.success(`memory lint OK — ${root}`);\n return;\n }\n\n console.log(ui.bold(`memory lint (${findings.length} finding${findings.length === 1 ? \"\" : \"s\"})`) + `\\n`);\n if (opts.fix) {\n const mode = apply ? \"apply\" : dryRun ? \"dry-run\" : \"dry-run\";\n const verb = apply ? \"changed\" : \"would change\";\n console.log(ui.bold(`fix ${mode}: ${report.fixes.length} file${report.fixes.length === 1 ? \"\" : \"s\"} ${verb}`));\n for (const fix of report.fixes) {\n console.log(` ${ui.dim(fix.id)} ${fix.actions.join(\"; \")}`);\n console.log(ui.dim(` → ${fix.file}`));\n }\n console.log();\n }\n\n const order: Record<LintSeverity, number> = { error: 0, warn: 1, info: 2 };\n findings.sort((a, b) => order[a.severity] - order[b.severity] || a.id.localeCompare(b.id));\n\n for (const f of findings) {\n const color =\n f.severity === \"error\" ? ui.red : f.severity === \"warn\" ? ui.yellow : ui.dim;\n console.log(\n `${color(f.severity.padEnd(5))} ${ui.dim(f.code)} ${f.id}`,\n );\n console.log(` ${f.message}`);\n if (f.suggested_anchors) {\n const pathHints = f.suggested_anchors.paths.length > 0\n ? `paths: ${f.suggested_anchors.paths.join(\", \")}`\n : \"\";\n const symbolHints = f.suggested_anchors.symbols.length > 0\n ? `symbols: ${f.suggested_anchors.symbols.join(\", \")}`\n : \"\";\n console.log(ui.dim(` suggested anchors: ${[pathHints, symbolHints].filter(Boolean).join(\" · \")}`));\n }\n console.log(ui.dim(` → ${f.file}`));\n }\n\n process.exitCode = findings.some((x) => x.severity === \"error\") ? 1 : 0;\n });\n}\n","import { Command } from \"commander\";\nimport { findProjectRoot } from \"@hivelore/core\";\n\nexport function registerTui(program: Command): void {\n program\n .command(\"tui\")\n .description(\n \"Interactive terminal dashboard for browsing and managing memories.\\n\\n\" +\n \" Screens (switch with 1 / 2 / 3):\\n\" +\n \" 1 — Memories: list + preview, filter by status (Tab), actions (a/r/p/d)\\n\" +\n \" 2 — Health: stale, pending review, anchorless memories\\n\" +\n \" 3 — Stats: most-read, decaying, total counts\\n\\n\" +\n \" Key bindings:\\n\" +\n \" ↑ ↓ navigate list\\n\" +\n \" Tab cycle status filter (all → proposed → validated → stale)\\n\" +\n \" a approve selected memory\\n\" +\n \" r reject selected memory\\n\" +\n \" p promote personal → team (proposed)\\n\" +\n \" d delete selected memory\\n\" +\n \" q / Esc exit\\n\",\n )\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: { dir?: string }) => {\n if (!process.stdout.isTTY) {\n console.error(\"hivelore tui requires an interactive terminal (TTY).\");\n process.exitCode = 1;\n return;\n }\n const root = findProjectRoot(opts.dir);\n const { render } = await import(\"ink\");\n const { createElement } = await import(\"react\");\n const { Dashboard } = await import(\"../tui/Dashboard.js\");\n const { waitUntilExit } = render(createElement(Dashboard, { root }));\n await waitUntilExit();\n });\n}\n","import { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport { findProjectRoot, resolveHaivePaths } from \"@hivelore/core\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface EmbeddingsOptions {\n dir?: string;\n}\n\ninterface EmbeddingsQueryOptions extends EmbeddingsOptions {\n limit?: string;\n minScore?: string;\n}\n\nexport function registerEmbeddings(program: Command): void {\n const embeddings = program\n .command(\"embeddings\")\n .description(\"Manage local embeddings index for semantic search\");\n\n embeddings\n .command(\"index\")\n .description(\"Generate or refresh the embeddings index for all memories\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: EmbeddingsOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.memoriesDir)) {\n ui.error(`No .ai/memories at ${root}. Run \\`hivelore init\\` first.`);\n process.exitCode = 1;\n return;\n }\n const { Embedder, rebuildIndex } = await loadEmbeddings();\n ui.info(\"Loading embedding model (first run downloads ~110MB)…\");\n const embedder = await Embedder.create();\n ui.info(`Model ready: ${embedder.model} (dim=${embedder.dimension}). Indexing memories…`);\n const { report } = await rebuildIndex(paths, embedder);\n ui.success(\n `Indexed ${report.total} memories — added=${report.added} updated=${report.updated} unchanged=${report.unchanged} removed=${report.removed}`,\n );\n });\n\n embeddings\n .command(\"query <text>\")\n .description(\"Run a semantic search against the local embeddings index\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .option(\"--limit <n>\", \"max results\", \"10\")\n .option(\"--min-score <n>\", \"minimum cosine similarity (0-1)\", \"0\")\n .action(async (text: string, opts: EmbeddingsQueryOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n const { semanticSearch } = await loadEmbeddings();\n const result = await semanticSearch(paths, text, {\n limit: Number(opts.limit ?? 10),\n minScore: Number(opts.minScore ?? 0),\n });\n if (!result) {\n ui.error(\"No embeddings index found. Run `hivelore embeddings index` first.\");\n process.exitCode = 1;\n return;\n }\n if (result.hits.length === 0) {\n ui.info(\"No semantic matches above the threshold.\");\n return;\n }\n for (const hit of result.hits) {\n const score = hit.score.toFixed(3);\n console.log(`${ui.bold(score)} ${hit.id}`);\n console.log(` ${ui.dim(path.relative(root, hit.file_path))}`);\n }\n });\n\n embeddings\n .command(\"status\")\n .description(\"Show the embeddings index status\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: EmbeddingsOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n const { indexStat } = await loadEmbeddings();\n const stat = await indexStat(paths);\n if (!stat.exists) {\n ui.warn(\"No embeddings index. Run `hivelore embeddings index` to create one.\");\n return;\n }\n console.log(`${ui.bold(\"entries:\")} ${stat.count}`);\n console.log(`${ui.bold(\"model:\")} ${stat.model}`);\n console.log(`${ui.bold(\"updated_at:\")} ${stat.updatedAt}`);\n console.log(`${ui.bold(\"size:\")} ${(stat.sizeBytes / 1024).toFixed(1)} KB`);\n });\n}\n\nasync function loadEmbeddings() {\n try {\n return await import(\"@hivelore/embeddings\");\n } catch {\n ui.error(\n \"Could not load @hivelore/embeddings. Run: npm install -g @hivelore/embeddings (or `pnpm build` in the monorepo)\",\n );\n process.exit(1);\n }\n}\n","import { existsSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n buildCodeMap,\n codeMapPath,\n findProjectRoot,\n loadCodeMap,\n resolveHaivePaths,\n saveCodeMap,\n} from \"@hivelore/core\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface IndexCodeOptions {\n dir?: string;\n exclude?: string;\n status?: boolean;\n json?: boolean;\n}\n\nexport function registerIndexCode(program: Command): void {\n const idx = program\n .command(\"index\")\n .description(\n \"Build local indexes that let AIs look up symbols instead of grepping.\\n\\n\" +\n \" Run once after init, then hivelore sync refreshes it automatically when source changes.\",\n );\n idx.action(() => idx.help());\n idx\n .command(\"code\")\n .description(\n \"Scan source files and write .ai/code-map.json (file → exports + 1-line description).\\n\\n\" +\n \" Supported languages: TypeScript, JavaScript, Java, Python, Go, Rust, C#, PHP.\\n\" +\n \" The map is used by:\\n\" +\n \" • get_briefing (symbol_locations) — look up where a class/function lives\\n\" +\n \" • code_map MCP tool — browse exports without grepping\\n\" +\n \" • hivelore briefing --symbols — look up symbols from the CLI\\n\\n\" +\n \" Run automatically by hivelore init (autopilot mode) and hivelore sync (if source changed).\\n\\n\" +\n \" Example:\\n\" +\n \" hivelore index code\\n\" +\n \" hivelore index code --status # report freshness without rebuilding\\n\" +\n \" hivelore index code --exclude generated,proto\\n\",\n )\n .option(\"-d, --dir <dir>\", \"project root\")\n .option(\n \"--exclude <csv>\",\n \"extra directory names to skip (comma-separated)\",\n \"\",\n )\n .option(\"--status\", \"report code-map / code-search index freshness without rebuilding\")\n .option(\"--json\", \"with --status, emit machine-readable JSON (for CI / agents)\")\n .action(async (opts: IndexCodeOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n\n if (opts.status) {\n await reportIndexStatus(root, paths, opts.json === true);\n return;\n }\n\n const extraExcludes = (opts.exclude ?? \"\")\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n\n ui.info(`Indexing source files in ${root}…`);\n const map = await buildCodeMap(root, {\n includeUntracked: true,\n excludeDirs: [\n \"node_modules\",\n \"dist\",\n \"build\",\n \"out\",\n \".git\",\n \".next\",\n \".turbo\",\n \".vitest-cache\",\n \"coverage\",\n ...extraExcludes,\n ],\n });\n\n await saveCodeMap(paths, map);\n const fileCount = Object.keys(map.files).length;\n const exportCount = Object.values(map.files).reduce((s, f) => s + f.exports.length, 0);\n ui.success(\n `Indexed ${fileCount} file(s) with ${exportCount} export(s) → ${path.relative(root, codeMapPath(paths))}`,\n );\n });\n\n idx\n .command(\"code-search\")\n .description(\n \"Build the semantic-search embeddings index for code (powers the code_search MCP tool).\\n\\n\" +\n \" Reads .ai/code-map.json (run `hivelore index code` first) and embeds each exported\\n\" +\n \" symbol's metadata (filename + name + kind + description).\\n\\n\" +\n \" Re-runs are incremental: unchanged entries keep their cached vectors, only the\\n\" +\n \" diff is re-embedded. First run downloads the bge-small-en-v1.5 model (~110MB).\\n\",\n )\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: IndexCodeOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n\n let mod: typeof import(\"@hivelore/embeddings\");\n try {\n mod = await import(\"@hivelore/embeddings\");\n } catch {\n ui.error(\n \"@hivelore/embeddings is not installed. Install it (`pnpm add @hivelore/embeddings`) \" +\n \"or run `hivelore embeddings install`.\",\n );\n process.exit(1);\n }\n\n ui.info(\"Loading embedder (first run downloads ~110MB)…\");\n const embedder = await mod.Embedder.create();\n ui.info(`Embedding code-map symbols…`);\n try {\n const { report } = await mod.rebuildCodeIndex(paths, embedder);\n ui.success(\n `Code-search index ready: ${report.total} symbols ` +\n `(+${report.added} new, ~${report.updated} updated, =${report.unchanged} cached, -${report.removed} removed)`,\n );\n } catch (err) {\n ui.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n });\n}\n\nasync function reportIndexStatus(\n root: string,\n paths: ReturnType<typeof resolveHaivePaths>,\n asJson: boolean,\n): Promise<void> {\n const mapFile = codeMapPath(paths);\n const map = existsSync(mapFile) ? await loadCodeMap(paths) : null;\n const fileCount = map ? Object.keys(map.files).length : 0;\n const exportCount = map\n ? Object.values(map.files).reduce((s, f) => s + f.exports.length, 0)\n : 0;\n const mapMtime = existsSync(mapFile) ? statSync(mapFile).mtime.toISOString() : null;\n\n // Code-search embeddings index lives under .ai/.cache/embeddings/ (built by `index code-search`).\n const searchIndexFile = path.join(paths.haiveDir, \".cache\", \"embeddings\", \"code-embeddings-index.json\");\n const searchIndexPresent = existsSync(searchIndexFile);\n\n // Freshness verdicts (cheap — no re-walk, no embedding):\n // • code-map is stale if any file it lists was modified after the map was generated.\n // • the search index is stale if it was built from a different (older) code-map generation.\n const codeMapStale = map ? isCodeMapStale(root, map.generated_at, Object.keys(map.files)) : false;\n let searchIndexStale: boolean | null = null;\n if (searchIndexPresent && map) {\n try {\n const mod = await import(\"@hivelore/embeddings\");\n const idx = await mod.loadCodeIndex(paths);\n if (idx) searchIndexStale = mod.isCodeIndexStale(idx.source_generated_at, map.generated_at);\n } catch {\n // embeddings not installed — report presence without a freshness verdict\n }\n }\n\n const status = {\n code_map: {\n present: map !== null,\n path: path.relative(root, mapFile),\n files: fileCount,\n exports: exportCount,\n generated_at: map?.generated_at ?? null,\n file_mtime: mapMtime,\n stale: codeMapStale,\n },\n code_search_index: {\n present: searchIndexPresent,\n path: path.relative(root, searchIndexFile),\n stale: searchIndexStale,\n },\n };\n\n if (asJson) {\n console.log(JSON.stringify(status, null, 2));\n if (!status.code_map.present) process.exitCode = 1;\n return;\n }\n\n if (!status.code_map.present) {\n ui.warn(`No code-map at ${status.code_map.path}. Run \\`hivelore index code\\`.`);\n process.exitCode = 1;\n return;\n }\n ui.info(\n `code-map: ${fileCount} file(s), ${exportCount} export(s) · generated ${status.code_map.generated_at ?? \"?\"}` +\n (codeMapStale ? \" · ⚠ STALE — source changed since generation; run `hivelore index code`\" : \" · fresh\"),\n );\n if (!searchIndexPresent) {\n ui.info(\"code-search index: missing — run `hivelore index code-search` for semantic code lookup.\");\n } else if (searchIndexStale) {\n ui.info(\n `code-search index: present (${status.code_search_index.path}) · ⚠ STALE — built from an older ` +\n \"code-map; run `hivelore index code-search`\",\n );\n } else {\n ui.info(`code-search index: present (${status.code_search_index.path})` + (searchIndexStale === false ? \" · fresh\" : \"\"));\n }\n}\n\n/** True if any file the code-map lists has an mtime newer than the map's generation time. Cheap (stat only). */\nfunction isCodeMapStale(root: string, generatedAt: string, files: string[]): boolean {\n const gen = Date.parse(generatedAt);\n if (Number.isNaN(gen)) return false;\n for (const file of files) {\n try {\n if (statSync(path.join(root, file)).mtimeMs > gen) return true;\n } catch {\n // file moved/deleted since generation — also a form of drift, but stat errors are ignored here\n }\n }\n return false;\n}\n","import { execFile } from \"node:child_process\";\nimport { mkdir, readFile, readdir, writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { spawnSync } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { Command } from \"commander\";\nimport {\n AUTOPILOT_DEFAULTS,\n BRIDGE_TARGETS,\n buildCodeMap,\n buildFrontmatter,\n detectStacksFromManifests,\n findProjectRoot,\n memoryFilePath,\n proposeSeedsFromCommits,\n resolveHaivePaths,\n saveCodeMap,\n saveConfig,\n serializeMemory,\n type BridgeTarget,\n type GitCommit,\n} from \"@hivelore/core\";\nimport { setUiJsonMode, ui } from \"../utils/ui.js\";\nimport { writeBridgeFiles } from \"../utils/bridge-files.js\";\nimport { setupAgentMode } from \"./agent.js\";\nimport { applyAutopilotRepairs } from \"../utils/autopilot.js\";\nimport { generateBootstrapContext } from \"./init-bootstrap.js\";\nimport {\n isValidStack,\n seedStackPack,\n SUPPORTED_STACKS,\n type StackName,\n} from \"./init-stack-packs.js\";\n\nconst execFileAsync = promisify(execFile);\n\ndeclare const __HAIVE_VERSION__: string;\nconst HAIVE_GITHUB_ACTION_REF = `v${__HAIVE_VERSION__}`;\n\nconst PROJECT_CONTEXT_TEMPLATE = `# Project context\n\n> Generated by \\`hivelore init\\`. Run \\`hivelore init --bootstrap\\` to auto-fill from your codebase,\n> or invoke the MCP prompt \\`bootstrap_project\\` in your AI client for a richer AI-generated version.\n> **AI agents**: use the **hivelore** MCP (\\`get_briefing\\` / \\`mem_relevant_to\\`) before substantive edits — see bridge files and \\`.cursor/rules/haive-mcp-required.mdc\\`.\n\n## Architecture\nTODO — high-level overview of the codebase.\n\n## Key modules\nTODO — list main modules and their purpose.\n\n## Conventions\nTODO — coding conventions, naming, patterns the team follows.\n\n## Glossary\nTODO — domain terms and what they mean here.\n\n## Gotchas\nTODO — known traps, surprising behavior, things newcomers stub their toes on.\n`;\n\n// Bridge files are a table of contents, not a manual: a short, stable entry\n// point that tells the agent where the real context lives. Kept deliberately\n// under ~30 lines so it never crowds out the task in the agent's context window.\n/** Cursor \\`.cursor/rules/*.mdc\\` — alwaysApply so agents see it even if bridge files are thin. */\nconst CURSOR_HAIVE_RULE_MDC = `---\ndescription: Require Hivelore MCP (get_briefing / mem_relevant_to) before substantive repo edits\nalwaysApply: true\n---\n\n# Hivelore — required for agents\n\nThis repository uses **Hivelore**. Running \\`hivelore init\\` means the team expects agents to **use the hivelore MCP server by default**, not skip it.\n\n## Before you change the repo\n\n1. Call **\\`get_briefing\\`** with \\`task\\` (and \\`files\\` / \\`symbols\\` when known), **or** \\`mem_relevant_to\\` if full project context is already loaded and you only need ranked memories.\n2. Then read/search the codebase as needed. Do not invert this order for non-trivial work.\n\n## During / after the task\n\n- On failure: **\\`mem_tried\\`** immediately.\n- Before closing a substantive session: MCP prompt **\\`post_task\\`** when there is something worth capturing.\n- Before final response: **\\`hivelore enforce finish\\`** must pass; it checks commit/push, release version/tag protocol, and GitHub Actions success for pushed HEAD when the repo has a GitHub remote.\n\n## If hivelore MCP is missing\n\nTell the developer to enable the **hivelore** server (e.g. \\`hivelore mcp --stdio\\` in client config) and restart the client. Do not silently ignore Hivelore.\n`;\n\nconst CI_WORKFLOW = `name: haive-sync\n\non:\n push:\n branches: [main, master]\n pull_request:\n branches: [main, master]\n\njobs:\n # On push to main/master: sync anchors + auto-promote + commit changes\n sync-on-merge:\n if: github.event_name == 'push'\n runs-on: ubuntu-latest\n permissions:\n contents: write\n steps:\n - uses: actions/checkout@v4\n with:\n fetch-depth: 0\n\n - uses: actions/setup-node@v4\n with:\n node-version: '20'\n\n - name: install hivelore\n run: npm install -g @hivelore/cli\n\n - name: refresh memory anchors + auto-promote\n run: hivelore sync --since HEAD~1 || true\n\n - name: commit updated memories (if any)\n run: |\n git config user.name \"github-actions[bot]\"\n git config user.email \"github-actions[bot]@users.noreply.github.com\"\n git add .ai/\n git diff --cached --quiet || git commit -m \"chore: hivelore sync [skip ci]\"\n git push\n\n # On pull request: warn if PR touches files that would invalidate memories\n pr-stale-check:\n if: github.event_name == 'pull_request'\n runs-on: ubuntu-latest\n permissions:\n pull-requests: write\n steps:\n - uses: actions/checkout@v4\n with:\n fetch-depth: 0\n\n - uses: actions/setup-node@v4\n with:\n node-version: '20'\n\n - name: install hivelore\n run: npm install -g @hivelore/cli\n\n - name: verify memory anchors touched by this PR\n id: verify\n run: |\n hivelore memory verify 2>&1 | tee /tmp/haive-verify.txt || true\n STALE=$(grep -c 'stale' /tmp/haive-verify.txt || echo 0)\n echo \"stale_count=$STALE\" >> \"$GITHUB_OUTPUT\"\n\n - name: comment on PR if stale memories detected\n if: steps.verify.outputs.stale_count != '0'\n uses: actions/github-script@v7\n with:\n script: |\n const fs = require('fs');\n const report = fs.readFileSync('/tmp/haive-verify.txt', 'utf8').trim();\n await github.rest.issues.createComment({\n owner: context.repo.owner,\n repo: context.repo.repo,\n issue_number: context.issue.number,\n body: \\`### hivelore — Stale memories detected\\\\n\\\\nSome memories anchored to code modified in this PR may be outdated:\\\\n\\\\n\\\\\\`\\\\\\`\\\\\\`\\\\n\\${report}\\\\n\\\\\\`\\\\\\`\\\\\\`\\\\n\\\\nRun \\\\\\`hivelore memory verify --update\\\\\\` locally to refresh them before merging.\\`\n });\n\n # ── Hivelore PR Memory Check ─────────────────────────────────────────────────\n # Posts a comment on every PR surfacing memories relevant to the changed files.\n # Reviewers and AI agents see gotchas, conventions, and action_required items\n # before they start coding.\n pr-memory-check:\n if: github.event_name == 'pull_request'\n runs-on: ubuntu-latest\n permissions:\n pull-requests: write\n contents: read\n steps:\n - uses: actions/checkout@v4\n\n - uses: Doucs91/hivelore/packages/github-action@${HAIVE_GITHUB_ACTION_REF}\n with:\n github-token: \\${{ secrets.GITHUB_TOKEN }}\n # post-if-empty: 'true' # uncomment to always post (even when no memories found)\n # max-memories: '5' # limit memories per file in the comment\n\n # On pull request: fail if the harness quality score regressed vs the committed baseline.\n # Measures whether the right memories still surface and the right sensors still fire.\n # No-op (passes) when no .ai/eval/baseline.json exists — safe to keep enabled before you\n # ever create one. To turn the gate on: run \\`hivelore eval --baseline\\` locally and commit\n # .ai/eval/baseline.json. Needs nothing external — no secrets, no services.\n pr-eval-gate:\n if: github.event_name == 'pull_request'\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n\n - uses: actions/setup-node@v4\n with:\n node-version: '20'\n\n - name: install hivelore\n run: npm install -g @hivelore/cli\n\n - name: harness quality regression gate\n run: hivelore eval --regression-gate --record --ref \"\\${{ github.sha }}\"\n\n - name: harness quality trend\n if: always()\n run: hivelore eval --trend || true\n\n # On push to main: push shared memories to the hub (if hubPath is configured)\n # Uncomment and configure hubPath in .ai/haive.config.json to enable.\n # hub-push:\n # if: github.event_name == 'push'\n # needs: sync-on-merge\n # runs-on: ubuntu-latest\n # permissions:\n # contents: write\n # steps:\n # - uses: actions/checkout@v4\n # with:\n # fetch-depth: 0\n # - uses: actions/setup-node@v4\n # with:\n # node-version: '20'\n # - name: install hivelore\n # run: npm install -g @hivelore/cli\n # - name: push shared memories to hub\n # run: hivelore hub push --commit\n # # Requires hubPath in .ai/haive.config.json pointing to a cloned hub repo.\n`;\n\nexport function registerInit(program: Command): void {\n program\n .command(\"init\")\n .description(\n \"Initialize a Hivelore project — autopilot mode ON by default (zero human intervention).\\n\" +\n \" Auto-bootstraps project-context.md from local files and seeds detected stack packs.\\n\" +\n \" Seeds draft memories from git revert/hotfix history (--seed, on by default).\\n\" +\n \" Add --manual to control memory approval and session recaps yourself.\\n\" +\n \" Add --no-bootstrap and --stack none to disable the auto-features.\",\n )\n .option(\"-d, --dir <dir>\", \"project root\", process.cwd())\n .option(\"--no-bridges\", \"do not generate any native agent bridge files\")\n .option(\n \"--bridge-targets <list>\",\n `which agent bridges to generate: 'all' (default) | comma-list.\\n` +\n ` Available: ${BRIDGE_TARGETS.join(\", \")}. Each carries top memories + block sensors.`,\n \"all\",\n )\n .option(\"--with-ci\", \"write a GitHub Actions workflow (.github/workflows/haive-sync.yml) — included automatically in autopilot mode\")\n .option(\n \"--manual\",\n \"opt out of autopilot: memories require manual approval, no auto-session recap, no auto-context\",\n )\n .option(\n \"--bootstrap\",\n \"auto-generate .ai/project-context.md from package.json, README, and directory structure (ON by default in autopilot)\",\n )\n .option(\n \"--no-bootstrap\",\n \"skip the project-context auto-generation (only the default template is written)\",\n )\n .option(\n \"--stack <stacks>\",\n `pre-seed validated memory packs for the given stacks (comma-separated).\\n` +\n ` Supported: ${SUPPORTED_STACKS.join(\", \")}.\\n` +\n ` Defaults to 'auto' in autopilot mode (detects from package.json/requirements.txt/go.mod/pom.xml). Pass 'none' to disable.`,\n )\n .option(\n \"--seed\",\n \"seed draft memories from git revert/hotfix history (ON by default in autopilot)\",\n )\n .option(\n \"--no-seed\",\n \"skip git-history seeding\",\n )\n .option(\n \"--seed-limit <n>\",\n \"max git seeds to propose\",\n \"20\",\n )\n .option(\n \"--no-mcp-setup\",\n \"skip auto-configuring hivelore MCP (hivelore mcp --stdio) in Cursor / VS Code / Claude Code\",\n )\n .option(\n \"-y, --yes\",\n \"approve user-level AI client configuration prompts during agent setup\",\n false,\n )\n .option(\"--json\", \"emit a machine-readable summary on stdout (human logs go to stderr)\", false)\n .action(async (opts: {\n dir: string;\n bridges: boolean;\n bridgeTargets?: string;\n withCi?: boolean;\n manual?: boolean;\n bootstrap?: boolean;\n stack?: string;\n seed?: boolean;\n seedLimit?: string;\n mcpSetup: boolean;\n yes?: boolean;\n json?: boolean;\n }) => {\n const root = path.resolve(opts.dir);\n const paths = resolveHaivePaths(root);\n const autopilot = opts.manual !== true; // autopilot is ON by default\n const json = opts.json === true;\n if (json) setUiJsonMode(true); // keep stdout a clean JSON channel\n\n // In autopilot mode, default-on the value-from-day-zero auto-features\n // unless the user explicitly opted out. opts.bootstrap is `false` only\n // when the user passed --no-bootstrap; it's `undefined` when neither flag\n // was given, which we resolve to autopilot's default.\n const wantBootstrap = opts.bootstrap === undefined ? autopilot : opts.bootstrap;\n const wantStack =\n opts.stack === undefined\n ? autopilot ? \"auto\" : undefined\n : opts.stack === \"none\" ? undefined : opts.stack;\n const wantSeed = opts.seed === undefined ? autopilot : opts.seed;\n const seedLimit = Math.max(1, parseInt(opts.seedLimit ?? \"20\", 10) || 20);\n\n // Accumulate stats for the first-session report\n const report = {\n stacksLoaded: [] as string[],\n totalMemories: 0,\n totalSensors: 0,\n gitSeedsWritten: 0,\n gitCommitsScanned: 0,\n gitRevertsFound: 0,\n gitRecurring: 0,\n bridgesWritten: 0,\n };\n\n if (existsSync(paths.haiveDir)) {\n ui.warn(`.ai/ already exists at ${paths.haiveDir} — leaving existing files in place.`);\n }\n\n await mkdir(paths.personalDir, { recursive: true });\n await mkdir(paths.teamDir, { recursive: true });\n await mkdir(paths.moduleDir, { recursive: true });\n await mkdir(paths.modulesContextDir, { recursive: true });\n await ensureAiRuntimeLayout(paths.runtimeDir);\n await ensureAiCacheLayout(path.join(paths.haiveDir, \".cache\"));\n\n // ── project-context.md ───────────────────────────────────────────────\n if (!existsSync(paths.projectContext)) {\n if (wantBootstrap) {\n ui.info(\"Bootstrapping project context from local files…\");\n try {\n const context = await generateBootstrapContext(root);\n await writeFile(paths.projectContext, context, \"utf8\");\n ui.success(\"Created .ai/project-context.md (auto-bootstrapped from local files)\");\n } catch (err) {\n ui.warn(`Bootstrap failed (${String(err)}) — writing default template instead`);\n await writeFile(paths.projectContext, PROJECT_CONTEXT_TEMPLATE, \"utf8\");\n }\n } else {\n await writeFile(paths.projectContext, PROJECT_CONTEXT_TEMPLATE, \"utf8\");\n ui.success(`Created ${path.relative(root, paths.projectContext)}`);\n }\n }\n\n // Write config (autopilot or default)\n const configExists = existsSync(\n path.join(paths.haiveDir, \"haive.config.json\"),\n );\n if (!configExists) {\n await saveConfig(paths, autopilot ? AUTOPILOT_DEFAULTS : { autopilot: false });\n ui.success(\n `Created .ai/haive.config.json (mode: ${autopilot ? \"autopilot\" : \"standard\"})`,\n );\n }\n\n // Native agent bridges are generated AFTER seeding (below) so they carry the\n // seeded memories + sensors, not an empty template.\n\n // ── Stack memory packs ───────────────────────────────────────────────\n const stacksToSeed = await resolveStacksToSeed(root, wantStack);\n if (stacksToSeed.length > 0) {\n let totalSeeded = 0;\n let totalSensors = 0;\n for (const stack of stacksToSeed) {\n const result = await seedStackPack(paths, stack);\n if (result.memories > 0) {\n ui.success(`Seeded ${result.memories} memories for stack: ${stack} (${result.sensors} sensors)`);\n totalSeeded += result.memories;\n totalSensors += result.sensors;\n report.stacksLoaded.push(stack);\n } else {\n ui.info(`Stack pack '${stack}': all memories already exist — skipped`);\n }\n }\n report.totalMemories += totalSeeded;\n report.totalSensors += totalSensors;\n if (totalSeeded > 0) {\n ui.success(\n `${totalSeeded} starter memories seeded (generic stack guidance, kept at background priority)`,\n );\n ui.info(\n \"Anchor them to real files or replace them with repo-specific notes to make them high-signal.\",\n );\n }\n }\n\n // ── Git-history seeding (cold-start) ────────────────────────────────\n if (wantSeed) {\n const gitStats = await seedFromGitHistory(root, paths, seedLimit);\n report.gitCommitsScanned = gitStats.scanned;\n report.gitRevertsFound = gitStats.found;\n report.gitRecurring = gitStats.recurring;\n report.gitSeedsWritten = gitStats.written;\n report.totalMemories += gitStats.written;\n if (gitStats.found > 0) {\n ui.success(\n `Git seeding: ${gitStats.found} revert/hotfix signal(s) found → ${gitStats.written} draft(s) written` +\n (gitStats.recurring > 0 ? ` (${gitStats.recurring} recurring theme(s))` : \"\"),\n );\n } else {\n ui.info(\"Git seeding: no revert/hotfix signals found — run `hivelore memory seed-git` later.\");\n }\n }\n\n // ── Native agent bridges (reach) ─────────────────────────────────────\n // Generated here, after seeding, so each bridge carries the freshly-seeded\n // memories + block sensors — not an empty template. Idempotent: existing\n // files keep their manual content, only the hivelore marker blocks refresh.\n if (opts.bridges) {\n const targets = resolveBridgeTargets(opts.bridgeTargets);\n const res = await writeBridgeFiles(root, paths, { targets });\n // The \"always use the MCP\" Cursor nudge is complementary to the memories bridge.\n await writeCursorHaiveRule(root);\n const made = res.created.length + res.updated.length;\n report.bridgesWritten = made;\n if (res.created.length > 0) {\n ui.success(`Generated ${res.created.length} agent bridge(s): ${res.created.join(\", \")}`);\n }\n if (res.updated.length > 0) {\n ui.info(`Refreshed ${res.updated.length} existing bridge(s): ${res.updated.join(\", \")}`);\n }\n if (made === 0) {\n ui.info(\"Bridges already up to date.\");\n }\n }\n\n // autopilot: CI + enforcement hooks + code-map included automatically\n const wantCi = opts.withCi || autopilot;\n if (wantCi) {\n const ciPath = path.join(root, \".github\", \"workflows\", \"haive-sync.yml\");\n if (existsSync(ciPath)) {\n ui.info(\"CI workflow already exists — skipped\");\n } else {\n await mkdir(path.dirname(ciPath), { recursive: true });\n await writeFile(ciPath, CI_WORKFLOW, \"utf8\");\n ui.success(`Created ${path.relative(root, ciPath)}`);\n }\n }\n\n if (autopilot) {\n // Install agent-agnostic enforcement gates (MCP policy config, git hooks,\n // CI workflow, and supported client hooks such as Claude Code).\n const haiveBin = process.argv[1]!;\n const enforcementResult = spawnSync(\n process.execPath,\n [haiveBin, \"enforce\", \"install\", \"--dir\", root],\n { encoding: \"utf8\" },\n );\n if (enforcementResult.status === 0) {\n ui.success(\"Hivelore enforcement installed (MCP, git, CI, client hooks where available)\");\n } else {\n ui.warn(\"Hivelore enforcement not fully installed — run `hivelore enforce install` manually\");\n }\n\n // Build initial code-map\n try {\n ui.info(\"Building code-map…\");\n const map = await buildCodeMap(root, { includeUntracked: true });\n await saveCodeMap(paths, map);\n ui.success(`Code-map built (${Object.keys(map.files).length} files)`);\n } catch {\n ui.warn(\"Code-map build failed — run `hivelore index code` manually\");\n }\n\n const repairs = await applyAutopilotRepairs(root, paths, {\n applyContext: true,\n applyCorpus: true,\n applyCodeMap: false,\n applyCodeSearch: true,\n });\n for (const repair of repairs) {\n ui.info(repair.message);\n }\n }\n\n // ── Auto-configure MCP in AI clients ────────────────────────────────\n if (opts.mcpSetup !== false) {\n const agentSetup = await setupAgentMode(root, {\n yes: opts.yes === true,\n global: true,\n interactive: process.stdin.isTTY,\n });\n for (const r of agentSetup.project_results) {\n if (r.status === \"configured\" && r.path) ui.success(`hivelore MCP project config written (${path.relative(root, r.path)})`);\n else if (r.status === \"error\") ui.warn(`${r.client}: ${r.error}`);\n }\n for (const r of agentSetup.global_results) {\n if (r.status === \"configured\") ui.success(`hivelore MCP configured in ${r.client} user-level config${r.path ? ` (${r.path})` : \"\"}`);\n else if (r.status === \"already_configured\") ui.info(`hivelore MCP already present in ${r.client} user-level config — left unchanged (this project's config was written above)`);\n }\n if (agentSetup.global_skipped_reason) ui.warn(agentSetup.global_skipped_reason);\n ui.info(`Recommended agent mode: ${agentSetup.detection.recommended_mode}`);\n ui.info(agentSetup.detection.recommended_command);\n await ensureGitignoreEntries(root, [\n \".cursor/mcp.json\",\n \".vscode/mcp.json\",\n \".mcp.json\",\n ]);\n ui.info(ui.dim(\" → Restart your AI client for MCP changes to take effect.\"));\n }\n\n await ensureGitignoreEntries(root, [\n \".ai/.cache/*\",\n \"!.ai/.cache/.gitignore\",\n \".ai/.runtime/*\",\n \"!.ai/.runtime/.gitignore\",\n \"!.ai/.runtime/README.md\",\n ]);\n\n ui.success(`Hivelore initialized at ${root}${autopilot ? \" (autopilot mode)\" : \"\"}`);\n\n if (json) {\n console.log(JSON.stringify({\n root,\n mode: autopilot ? \"autopilot\" : \"manual\",\n stacks_loaded: report.stacksLoaded,\n memories_seeded: report.totalMemories,\n sensors_active: report.totalSensors,\n git_commits_scanned: report.gitCommitsScanned,\n git_signals_found: report.gitRevertsFound,\n git_seeds_written: report.gitSeedsWritten,\n git_recurring: report.gitRecurring,\n bridges: opts.bridges !== false,\n bridges_written: report.bridgesWritten,\n ci: opts.withCi || autopilot,\n }, null, 2));\n return;\n }\n\n console.log();\n\n // ── First-session report ─────────────────────────────────────────────\n printInitReport(report);\n console.log();\n\n if (autopilot) {\n console.log(ui.bold(\"Autopilot mode is ON — Hivelore runs itself:\"));\n console.log(ui.dim(\" ✓ Memories go directly to validated (no approval needed)\"));\n console.log(ui.dim(\" ✓ Proposed memories auto-approve after 72h without rejection\"));\n console.log(ui.dim(\" ✓ Session recap saved automatically when the AI session closes\"));\n console.log(ui.dim(\" ✓ Code-map refreshes automatically after every pull\"));\n console.log(ui.dim(\" ✓ Agent-agnostic enforcement gates installed (MCP, git, CI, wrapper-ready)\"));\n console.log(ui.dim(\" ✓ CI workflows created (sync + enforcement)\"));\n if (stacksToSeed.length > 0) {\n console.log(ui.dim(` ✓ Stack memory packs pre-seeded (${stacksToSeed.join(\", \")})`));\n }\n console.log();\n\n if (!wantBootstrap) {\n console.log(ui.bold(\"One remaining step (optional but recommended):\"));\n console.log(\" \" + ui.bold(\"hivelore init --bootstrap\") + ui.dim(\" ← fill project-context.md without AI\"));\n console.log(\" \" + ui.dim(\"Or in your AI client: invoke the MCP prompt \") + ui.bold(\"bootstrap_project\"));\n } else {\n console.log(ui.bold(\"Project context bootstrapped from local files.\"));\n console.log(ui.dim(\" Review .ai/project-context.md and fill in the TODO sections.\"));\n console.log(ui.dim(\" Or invoke the MCP prompt `bootstrap_project` for a richer AI-generated version.\"));\n }\n console.log();\n console.log(ui.dim(\" Seed more memories instantly:\"));\n console.log(ui.dim(\" hivelore memory import-changelog — from CHANGELOG.md\"));\n console.log(ui.dim(\" hivelore memory import README.md — from README / docs\"));\n } else {\n console.log(ui.bold(\"Next steps:\"));\n if (!wantBootstrap) {\n console.log(ui.dim(\" 1. Fill project context (pick one):\"));\n console.log(\" \" + ui.bold(\"hivelore init --bootstrap\") + ui.dim(\" ← instant, no AI needed\"));\n console.log(\" or invoke the MCP prompt \" + ui.bold(\"bootstrap_project\") + ui.dim(\" in your AI client\"));\n } else {\n console.log(ui.dim(\" 1. Review .ai/project-context.md and fill in the TODO sections.\"));\n }\n console.log();\n console.log(ui.dim(\" 2. Start every AI session with:\"));\n console.log(\" \" + ui.bold(\"get_briefing({ task: '…what you are about to do…' })\"));\n console.log();\n console.log(ui.dim(\" Tip: run `hivelore init` (without --manual) for zero-friction autopilot mode.\"));\n }\n });\n}\n\nasync function resolveStacksToSeed(\n root: string,\n stackOpt: string | undefined,\n): Promise<StackName[]> {\n if (!stackOpt) return [];\n if (stackOpt === \"auto\") {\n return autoDetectStacksFromRoot(root);\n }\n // Comma-separated stack names\n return stackOpt\n .split(\",\")\n .map((s) => s.trim().toLowerCase())\n .filter(isValidStack);\n}\n\n/**\n * Merge dependencies from package.json files in immediate sub-packages (depth ≤ 2), skipping\n * node_modules/build/hidden dirs. Lets stack detection see frameworks that live in monorepo\n * sub-packages or nested repos rather than the root manifest. Best-effort; returns undefined if none.\n */\nasync function collectNestedPackageDeps(root: string): Promise<Record<string, string> | undefined> {\n const SKIP = new Set([\"node_modules\", \"dist\", \"build\", \"out\", \".git\", \".next\", \"coverage\", \"vendor\"]);\n const merged: Record<string, string> = {};\n let found = false;\n async function scan(dir: string, depth: number): Promise<void> {\n if (depth > 2) return;\n let entries;\n try { entries = await readdir(dir, { withFileTypes: true }); } catch { return; }\n for (const entry of entries) {\n if (!entry.isDirectory() || entry.name.startsWith(\".\") || SKIP.has(entry.name)) continue;\n const sub = path.join(dir, entry.name);\n const pkgPath = path.join(sub, \"package.json\");\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(await readFile(pkgPath, \"utf8\")) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n Object.assign(merged, pkg.dependencies ?? {}, pkg.devDependencies ?? {});\n found = true;\n } catch { /* ignore */ }\n }\n await scan(sub, depth + 1);\n }\n }\n await scan(root, 0);\n return found ? merged : undefined;\n}\n\n/** Read all manifest files at root and return detected valid stacks. */\nasync function autoDetectStacksFromRoot(root: string): Promise<StackName[]> {\n let packageJsonDeps: Record<string, string> | undefined;\n let requirementsTxt: string | undefined;\n let goMod: string | undefined;\n let pomXml: string | undefined;\n\n const pkgPath = path.join(root, \"package.json\");\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(await readFile(pkgPath, \"utf8\")) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n packageJsonDeps = { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) };\n } catch { /* ignore parse errors */ }\n }\n\n // Monorepos keep the real frameworks in sub-packages / nested repos (e.g. a Next.js frontend and a\n // NestJS backend), not the root package.json. Merge nested deps so stack detection isn't blind to\n // them — on a real marketplace monorepo the root-only scan saw \"react\" but missed next + nest.\n const nestedDeps = await collectNestedPackageDeps(root);\n if (nestedDeps) packageJsonDeps = { ...(packageJsonDeps ?? {}), ...nestedDeps };\n\n for (const name of [\"requirements.txt\", \"requirements/base.txt\", \"requirements/prod.txt\"]) {\n const reqPath = path.join(root, name);\n if (existsSync(reqPath)) {\n try { requirementsTxt = await readFile(reqPath, \"utf8\"); break; } catch { /* ignore */ }\n }\n }\n\n const goModPath = path.join(root, \"go.mod\");\n if (existsSync(goModPath)) {\n try { goMod = await readFile(goModPath, \"utf8\"); } catch { /* ignore */ }\n }\n\n const pomPath = path.join(root, \"pom.xml\");\n if (existsSync(pomPath)) {\n try { pomXml = await readFile(pomPath, \"utf8\"); } catch { /* ignore */ }\n }\n\n let composerJson: string | undefined;\n const composerPath = path.join(root, \"composer.json\");\n if (existsSync(composerPath)) {\n try { composerJson = await readFile(composerPath, \"utf8\"); } catch { /* ignore */ }\n }\n\n let gemfile: string | undefined;\n const gemfilePath = path.join(root, \"Gemfile\");\n if (existsSync(gemfilePath)) {\n try { gemfile = await readFile(gemfilePath, \"utf8\"); } catch { /* ignore */ }\n }\n\n // .NET / Docker / monorepo are detected by file presence (no content needed).\n const hasDockerfile = existsSync(path.join(root, \"Dockerfile\"));\n const hasTurboJson = existsSync(path.join(root, \"turbo.json\"));\n const hasNxJson = existsSync(path.join(root, \"nx.json\"));\n let hasCsproj = false;\n try {\n const entries = await readdir(root);\n hasCsproj = entries.some((e) => e.endsWith(\".csproj\") || e.endsWith(\".sln\"));\n } catch { /* ignore */ }\n\n const detected = detectStacksFromManifests({\n packageJsonDeps,\n requirementsTxt,\n goMod,\n pomXml,\n composerJson,\n gemfile,\n hasCsproj,\n hasDockerfile,\n hasTurboJson,\n hasNxJson,\n });\n return detected.filter((s): s is StackName => isValidStack(s));\n}\n\ninterface GitSeedStats {\n scanned: number;\n found: number;\n recurring: number;\n written: number;\n}\n\n/** Seed draft memories from git revert/hotfix history. Returns stats. */\nasync function seedFromGitHistory(\n root: string,\n paths: ReturnType<typeof resolveHaivePaths>,\n limit: number,\n): Promise<GitSeedStats> {\n const commits = await readGitCommits(root);\n if (commits.length === 0) return { scanned: 0, found: 0, recurring: 0, written: 0 };\n\n const proposals = proposeSeedsFromCommits(commits, limit);\n\n // Detect recurring: same slug appearing in multiple distinct commits (re-run proposals shows them)\n // proposeSeedsFromCommits already dedupes by slug, so \"recurring\" = proposals whose slug\n // appears in more than one source commit (we re-scan to count)\n const slugCounts = new Map<string, number>();\n for (const c of commits) {\n const sub = c.subject.trim();\n const revertMatch = sub.match(/^Revert\\s+\"(.+)\"\\s*$/i);\n const slug = revertMatch\n ? revertMatch[1]!.toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 60)\n : null;\n if (slug) slugCounts.set(slug, (slugCounts.get(slug) ?? 0) + 1);\n }\n const recurring = proposals.filter((p) => (slugCounts.get(p.slug) ?? 0) > 1).length;\n\n let written = 0;\n for (const p of proposals) {\n const fm = {\n ...buildFrontmatter({\n type: \"attempt\",\n slug: p.slug,\n scope: \"team\",\n tags: [\"seed\", \"git-history\", p.kind],\n paths: p.paths,\n }),\n status: \"draft\" as const,\n };\n const body = `# ${p.what}\\n\\n**Why it failed / do NOT use:** ${p.why_failed}\\n\\n_Seeded from git ${p.kind} commit ${p.source_sha}. Review and validate (or delete) — not yet authoritative._\\n`;\n const file = memoryFilePath(paths, fm.scope, fm.id, fm.module);\n if (existsSync(file)) continue; // idempotent\n await mkdir(path.dirname(file), { recursive: true });\n await writeFile(file, serializeMemory({ frontmatter: fm, body }), \"utf8\");\n written++;\n }\n\n return { scanned: commits.length, found: proposals.length, recurring, written };\n}\n\n/** Read recent git commits with touched files. Returns [] off-git or on error. */\nasync function readGitCommits(root: string): Promise<GitCommit[]> {\n try {\n const { stdout } = await execFileAsync(\n \"git\",\n [\"log\", \"--since=365.days.ago\", \"--name-only\", \"--pretty=format:%x1f%h%x1f%s\", \"-n\", \"500\"],\n { cwd: root, maxBuffer: 8 * 1024 * 1024 },\n );\n const blocks = stdout.split(\"\\x1f\").filter((b) => b.length > 0);\n const commits: GitCommit[] = [];\n for (let i = 0; i + 1 < blocks.length; i += 2) {\n const sha = blocks[i]!.trim();\n const tail = blocks[i + 1]!;\n const lines = tail.split(\"\\n\").map((l) => l.trim()).filter(Boolean);\n const subject = lines.shift() ?? \"\";\n commits.push({ sha, subject, files: lines });\n }\n return commits;\n } catch {\n return [];\n }\n}\n\ninterface InitReport {\n stacksLoaded: string[];\n totalMemories: number;\n totalSensors: number;\n gitSeedsWritten: number;\n gitCommitsScanned: number;\n gitRevertsFound: number;\n gitRecurring: number;\n bridgesWritten: number;\n}\n\nfunction printInitReport(r: InitReport): void {\n const lines: string[] = [];\n\n if (r.gitRevertsFound > 0) {\n const recurring = r.gitRecurring > 0 ? ` (${r.gitRecurring} recurring)` : \"\";\n lines.push(` Git signals : ${r.gitCommitsScanned} commits → ${r.gitRevertsFound} revert/hotfix${recurring}`);\n lines.push(` Drafts ready: ${r.gitSeedsWritten} draft lesson(s) from real past mistakes`);\n }\n if (r.stacksLoaded.length > 0) {\n lines.push(` Stack packs : ${r.stacksLoaded.join(\", \")} — ${r.totalSensors} sensor(s) active`);\n }\n if (r.totalMemories > 0) {\n lines.push(` Total ready : ${r.totalMemories} lesson(s), ${r.totalSensors} sensor(s) — 0 written by hand`);\n }\n if (r.bridgesWritten > 0) {\n lines.push(` Reach : ${r.bridgesWritten} agent bridge(s) generated (Cursor, Cline, Copilot, Roo, Gemini, …)`);\n }\n\n if (lines.length === 0) return;\n\n const width = Math.max(...lines.map((l) => l.length), 44);\n const bar = \"─\".repeat(width + 2);\n console.log(ui.bold(`┌${bar}┐`));\n console.log(ui.bold(`│`) + ` Hivelore — first-session report`.padEnd(width + 1) + ui.bold(`│`));\n console.log(ui.bold(`├${bar}┤`));\n for (const line of lines) {\n console.log(ui.bold(`│`) + line.padEnd(width + 2) + ui.bold(`│`));\n }\n console.log(ui.bold(`└${bar}┘`));\n if (r.gitSeedsWritten > 0) {\n console.log(ui.dim(\" Review draft seeds: hivelore memory pending (validate or delete each one)\"));\n }\n console.log(\n ui.dim(\" Reach: bridges auto-refresh on `hivelore sync`; regenerate any time with `hivelore bridges sync --all`.\"),\n );\n}\n\nasync function writeCursorHaiveRule(root: string): Promise<void> {\n const relPath = \".cursor/rules/haive-mcp-required.mdc\";\n const target = path.join(root, relPath);\n if (existsSync(target)) {\n ui.info(`Cursor rule ${relPath} already exists — skipped`);\n return;\n }\n await mkdir(path.dirname(target), { recursive: true });\n await writeFile(target, CURSOR_HAIVE_RULE_MDC, \"utf8\");\n ui.success(`Created Cursor rule ${relPath}`);\n}\n\n/** Resolve the `--bridge-targets` option ('all' | comma-list) into concrete targets. */\nfunction resolveBridgeTargets(opt: string | undefined): BridgeTarget[] {\n const raw = (opt ?? \"all\").trim().toLowerCase();\n if (raw === \"\" || raw === \"all\") return [...BRIDGE_TARGETS];\n const requested = raw.split(\",\").map((t) => t.trim()).filter(Boolean);\n const valid = requested.filter((t): t is BridgeTarget => (BRIDGE_TARGETS as string[]).includes(t));\n const invalid = requested.filter((t) => !(BRIDGE_TARGETS as string[]).includes(t));\n if (invalid.length > 0) {\n ui.warn(`Ignoring unknown bridge target(s): ${invalid.join(\", \")}. Valid: ${BRIDGE_TARGETS.join(\", \")}`);\n }\n return valid.length > 0 ? valid : [...BRIDGE_TARGETS];\n}\n\nconst RUNTIME_README_BODY = `# .ai/.runtime — disposable local layer\n\nNot team truth. Use for machine-local session notes or tooling scratch files.\nOfficial memories belong in .ai/memories/ (versioned in Git).\nOnly .gitignore and this README are meant to commit; everything else stays untracked.\n\nSession continuity (local): agents may append \\`session-journal.ndjson\\` via MCP \\`runtime_journal_append\\` or \\`hivelore runtime journal append\\`.\n`;\n\nconst RUNTIME_GITIGNORE_BODY = `*\n!.gitignore\n!README.md\n`;\n\nasync function ensureAiRuntimeLayout(runtimeDir: string): Promise<void> {\n await mkdir(runtimeDir, { recursive: true });\n const gi = path.join(runtimeDir, \".gitignore\");\n if (!existsSync(gi)) {\n await writeFile(gi, RUNTIME_GITIGNORE_BODY, \"utf8\");\n }\n const readme = path.join(runtimeDir, \"README.md\");\n if (!existsSync(readme)) {\n await writeFile(readme, RUNTIME_README_BODY, \"utf8\");\n }\n}\n\nasync function ensureAiCacheLayout(cacheDir: string): Promise<void> {\n await mkdir(cacheDir, { recursive: true });\n const gi = path.join(cacheDir, \".gitignore\");\n if (!existsSync(gi)) {\n await writeFile(gi, \"*\\n!.gitignore\\n\", \"utf8\");\n }\n}\n\n/**\n * Append gitignore entries if they aren't already present.\n * Creates .gitignore if it doesn't exist.\n * Silently no-ops on any filesystem error (non-blocking).\n */\nasync function ensureGitignoreEntries(root: string, patterns: string[]): Promise<void> {\n try {\n const gitignorePath = path.join(root, \".gitignore\");\n let existing = \"\";\n if (existsSync(gitignorePath)) {\n existing = await readFile(gitignorePath, \"utf8\");\n }\n const lines = existing.split(\"\\n\");\n const missing = patterns.filter((p) => !lines.some((l) => l.trim() === p));\n if (missing.length === 0) return;\n const toAppend = (existing.endsWith(\"\\n\") || existing === \"\" ? \"\" : \"\\n\") +\n \"# Hivelore project-level MCP configs (machine-specific absolute paths)\\n\" +\n missing.join(\"\\n\") + \"\\n\";\n await writeFile(gitignorePath, existing + toAppend, \"utf8\");\n } catch {\n // non-fatal\n }\n}\n","/**\n * Shared bridge-file writer — used by both `hivelore bridges sync` (explicit) and\n * `hivelore sync` (auto-refresh of bridges that already exist on disk, so native\n * agent configs never go stale after a pull/merge).\n *\n * Loads the corpus, extracts block sensors from memory frontmatter, generates\n * per-target content, and writes it idempotently: a brand-new file is created\n * whole; an existing file only has its `<!-- haive:* -->` marker blocks replaced,\n * preserving any manual content (and, for Cursor `.mdc`, the YAML frontmatter).\n */\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n BRIDGE_MARKERS,\n BRIDGE_TARGET_PATH,\n generateBridges,\n isRetiredMemory,\n loadMemoriesFromDir,\n type BridgeSensor,\n type BridgeTarget,\n type HaivePaths,\n} from \"@hivelore/core\";\n\nexport interface WriteBridgesResult {\n created: string[];\n updated: string[];\n unchanged: string[];\n skipped: string[];\n warnings: string[];\n}\n\nexport interface WriteBridgesOptions {\n targets: BridgeTarget[];\n maxMemories?: number;\n dryRun?: boolean;\n /** When true, skip targets whose file does not already exist (used by `hivelore sync`). */\n onlyExisting?: boolean;\n}\n\nexport type BridgeFileState =\n | \"missing\"\n | \"managed\"\n | \"legacy-managed\"\n | \"unmanaged\"\n | \"invalid\";\n\nexport interface BridgeFileStatus {\n target: BridgeTarget;\n path: string;\n exists: boolean;\n state: BridgeFileState;\n wouldChange: boolean;\n issues: string[];\n}\n\n/** Load corpus + sensors and write/refresh the requested bridge files idempotently. */\nexport async function writeBridgeFiles(\n root: string,\n paths: HaivePaths,\n opts: WriteBridgesOptions,\n): Promise<WriteBridgesResult> {\n const result: WriteBridgesResult = { created: [], updated: [], unchanged: [], skipped: [], warnings: [] };\n if (!existsSync(paths.memoriesDir)) return result;\n\n const allLoaded = await loadMemoriesFromDir(paths.memoriesDir);\n const memories = allLoaded\n .map((l) => l.memory)\n .filter((m) => !isRetiredMemory(m.frontmatter, m.body));\n\n const sensors: BridgeSensor[] = [];\n for (const m of memories) {\n const sensor = m.frontmatter.sensor;\n if (!sensor || sensor.severity !== \"block\") continue;\n sensors.push({\n id: m.frontmatter.id,\n severity: \"block\",\n message: sensor.message,\n ...(sensor.pattern ? { pattern: sensor.pattern } : {}),\n paths: sensor.paths.length > 0 ? sensor.paths : m.frontmatter.anchor.paths,\n });\n }\n\n const maxMemories = Math.max(1, opts.maxMemories ?? 8);\n const outputs = generateBridges(memories, sensors, { maxMemories, targets: opts.targets });\n\n for (const output of outputs) {\n const targetFile = path.join(root, output.path);\n const fileExists = existsSync(targetFile);\n\n if (opts.onlyExisting && !fileExists) continue;\n\n if (opts.dryRun) {\n if (!fileExists) {\n result.created.push(output.path);\n } else {\n const existing = (await readFile(targetFile, \"utf8\")).replace(/\\r\\n/g, \"\\n\");\n const merged = mergeBridgeContent(existing, output.content);\n if (merged.issues.length > 0) {\n result.skipped.push(output.path);\n result.warnings.push(...merged.issues.map((issue) => `${output.path}: ${issue}`));\n } else if (merged.content !== existing) {\n result.updated.push(output.path);\n } else {\n result.unchanged.push(output.path);\n }\n }\n continue;\n }\n\n await mkdir(path.dirname(targetFile), { recursive: true });\n\n if (!fileExists) {\n await writeFile(targetFile, output.content, \"utf8\");\n result.created.push(output.path);\n continue;\n }\n\n const existing = (await readFile(targetFile, \"utf8\")).replace(/\\r\\n/g, \"\\n\");\n const merged = mergeBridgeContent(existing, output.content);\n\n if (merged.issues.length > 0) {\n result.skipped.push(output.path);\n result.warnings.push(...merged.issues.map((issue) => `${output.path}: ${issue}`));\n continue;\n }\n\n if (merged.content === existing) {\n result.unchanged.push(output.path);\n continue;\n }\n\n await writeFile(targetFile, merged.content, \"utf8\");\n result.updated.push(output.path);\n }\n\n return result;\n}\n\n/** Build per-target status for `hivelore bridges status` without writing files. */\nexport async function getBridgeFileStatuses(\n root: string,\n paths: HaivePaths,\n opts: Pick<WriteBridgesOptions, \"targets\" | \"maxMemories\">,\n): Promise<BridgeFileStatus[]> {\n if (!existsSync(paths.memoriesDir)) {\n return opts.targets.map((target) => ({\n target,\n path: BRIDGE_TARGET_PATH[target],\n exists: false,\n state: \"missing\",\n wouldChange: false,\n issues: [\"No .ai/memories directory found.\"],\n }));\n }\n\n const allLoaded = await loadMemoriesFromDir(paths.memoriesDir);\n const memories = allLoaded\n .map((l) => l.memory)\n .filter((m) => !isRetiredMemory(m.frontmatter, m.body));\n const sensors: BridgeSensor[] = [];\n for (const m of memories) {\n const sensor = m.frontmatter.sensor;\n if (!sensor || sensor.severity !== \"block\") continue;\n sensors.push({\n id: m.frontmatter.id,\n severity: \"block\",\n message: sensor.message,\n ...(sensor.pattern ? { pattern: sensor.pattern } : {}),\n paths: sensor.paths.length > 0 ? sensor.paths : m.frontmatter.anchor.paths,\n });\n }\n\n const outputs = generateBridges(memories, sensors, {\n maxMemories: Math.max(1, opts.maxMemories ?? 8),\n targets: opts.targets,\n });\n\n const statuses: BridgeFileStatus[] = [];\n for (const output of outputs) {\n const targetFile = path.join(root, output.path);\n const exists = existsSync(targetFile);\n if (!exists) {\n statuses.push({\n target: output.target,\n path: output.path,\n exists: false,\n state: \"missing\",\n wouldChange: true,\n issues: [],\n });\n continue;\n }\n\n const existing = (await readFile(targetFile, \"utf8\")).replace(/\\r\\n/g, \"\\n\");\n const merged = mergeBridgeContent(existing, output.content);\n statuses.push({\n target: output.target,\n path: output.path,\n exists: true,\n state: classifyBridgeFile(existing, merged.issues),\n wouldChange: merged.issues.length === 0 && merged.content !== existing,\n issues: merged.issues,\n });\n }\n return statuses;\n}\n\n// ── Marker helpers ───────────────────────────────────────────────────────────\n\nexport function extractMarkerBlock(text: string, startMarker: string, endMarker: string): string | null {\n const startIdx = text.indexOf(startMarker);\n const endIdx = text.indexOf(endMarker);\n if (startIdx === -1 || endIdx === -1 || endIdx <= startIdx) return null;\n return text.slice(startIdx, endIdx + endMarker.length);\n}\n\nexport function replaceMarkerBlock(\n existing: string,\n startMarker: string,\n endMarker: string,\n replacement: string | null,\n): string {\n if (!replacement) return existing;\n const startIdx = existing.indexOf(startMarker);\n const endIdx = existing.indexOf(endMarker);\n if (startIdx === -1 || endIdx === -1 || endIdx <= startIdx) {\n return existing + (existing.endsWith(\"\\n\") ? \"\" : \"\\n\") + \"\\n\" + replacement + \"\\n\";\n }\n return existing.slice(0, startIdx) + replacement + existing.slice(endIdx + endMarker.length);\n}\n\ninterface MergeResult {\n content: string;\n issues: string[];\n}\n\nfunction mergeBridgeContent(existing: string, generated: string): MergeResult {\n const issues = validateKnownMarkers(existing);\n if (issues.length > 0) return { content: existing, issues };\n\n const generatedBridge =\n extractMarkerBlock(generated, BRIDGE_MARKERS.bridgeStart, BRIDGE_MARKERS.bridgeEnd) ?? generated.trimEnd();\n const replacement = hasExternalHaiveInstructions(existing)\n ? renderCompactManagedBridge(generated)\n : generatedBridge;\n\n if (hasMarkerPair(existing, BRIDGE_MARKERS.bridgeStart, BRIDGE_MARKERS.bridgeEnd)) {\n return {\n content: replaceMarkerBlock(\n existing,\n BRIDGE_MARKERS.bridgeStart,\n BRIDGE_MARKERS.bridgeEnd,\n replacement,\n ),\n issues,\n };\n }\n\n if (hasAnyHaiveManagedMarker(existing)) {\n const range = legacyManagedRange(existing);\n if (range) {\n return {\n content: existing.slice(0, range.start) + replacement + existing.slice(range.end),\n issues,\n };\n }\n }\n\n return {\n content: existing + (existing.endsWith(\"\\n\") ? \"\" : \"\\n\") + \"\\n\" + generatedBridge + \"\\n\",\n issues,\n };\n}\n\nfunction renderCompactManagedBridge(generated: string): string {\n const memories = extractMarkerBlock(generated, BRIDGE_MARKERS.memoriesStart, BRIDGE_MARKERS.memoriesEnd);\n const sensors = extractMarkerBlock(generated, BRIDGE_MARKERS.sensorsStart, BRIDGE_MARKERS.sensorsEnd);\n const parts = [\n BRIDGE_MARKERS.bridgeStart,\n \"<!-- AUTO-GENERATED by hivelore bridges sync — do not edit between these markers -->\",\n \"\",\n memories,\n ].filter((part): part is string => Boolean(part));\n if (sensors) parts.push(\"\", sensors);\n parts.push(\"\", BRIDGE_MARKERS.bridgeEnd);\n return parts.join(\"\\n\");\n}\n\nfunction classifyBridgeFile(existing: string, issues: string[]): BridgeFileState {\n if (issues.length > 0) return \"invalid\";\n if (hasMarkerPair(existing, BRIDGE_MARKERS.bridgeStart, BRIDGE_MARKERS.bridgeEnd)) return \"managed\";\n if (isLegacyWholeFileBridge(existing) || hasAnyHaiveManagedMarker(existing)) return \"legacy-managed\";\n return \"unmanaged\";\n}\n\nfunction validateKnownMarkers(text: string): string[] {\n return [\n ...validateMarkerPair(text, BRIDGE_MARKERS.bridgeStart, BRIDGE_MARKERS.bridgeEnd),\n ...validateMarkerPair(text, BRIDGE_MARKERS.memoriesStart, BRIDGE_MARKERS.memoriesEnd),\n ...validateMarkerPair(text, BRIDGE_MARKERS.sensorsStart, BRIDGE_MARKERS.sensorsEnd),\n ];\n}\n\nfunction validateMarkerPair(text: string, startMarker: string, endMarker: string): string[] {\n const starts = countOccurrences(text, startMarker);\n const ends = countOccurrences(text, endMarker);\n const issues: string[] = [];\n if (starts !== ends) {\n issues.push(`marker mismatch: ${startMarker} (${starts}) vs ${endMarker} (${ends})`);\n }\n if (starts > 1 || ends > 1) {\n issues.push(`multiple marker blocks are not supported for ${startMarker}`);\n }\n if (starts === 1 && ends === 1 && text.indexOf(endMarker) <= text.indexOf(startMarker)) {\n issues.push(`marker order is invalid for ${startMarker}`);\n }\n return issues;\n}\n\nfunction countOccurrences(text: string, needle: string): number {\n if (needle.length === 0) return 0;\n let count = 0;\n let idx = text.indexOf(needle);\n while (idx !== -1) {\n count++;\n idx = text.indexOf(needle, idx + needle.length);\n }\n return count;\n}\n\nfunction hasMarkerPair(text: string, startMarker: string, endMarker: string): boolean {\n return countOccurrences(text, startMarker) === 1 && countOccurrences(text, endMarker) === 1;\n}\n\nfunction hasAnyHaiveManagedMarker(text: string): boolean {\n return (\n text.includes(BRIDGE_MARKERS.memoriesStart) ||\n text.includes(BRIDGE_MARKERS.sensorsStart)\n );\n}\n\nfunction isLegacyWholeFileBridge(text: string): boolean {\n return text.trimStart().startsWith(\"<!-- Hivelore bridge file\") || text.includes(\"<!-- Managed by Hivelore.\");\n}\n\nfunction hasExternalHaiveInstructions(text: string): boolean {\n const startIdx = text.indexOf(BRIDGE_MARKERS.bridgeStart);\n const beforeManagedBlock = startIdx === -1 ? text : text.slice(0, startIdx);\n return (\n beforeManagedBlock.includes(\"Working through Hivelore\") ||\n beforeManagedBlock.includes(\"Hivelore — mandatory rules\") ||\n beforeManagedBlock.includes(\"Hivelore bridge file\")\n );\n}\n\nfunction legacyManagedRange(text: string): { start: number; end: number } | null {\n const ranges: Array<{ start: number; end: number }> = [];\n for (const [startMarker, endMarker] of [\n [BRIDGE_MARKERS.memoriesStart, BRIDGE_MARKERS.memoriesEnd],\n [BRIDGE_MARKERS.sensorsStart, BRIDGE_MARKERS.sensorsEnd],\n ] as const) {\n const start = text.indexOf(startMarker);\n const end = text.indexOf(endMarker);\n if (start !== -1 && end !== -1 && end > start) {\n ranges.push({ start, end: end + endMarker.length });\n }\n }\n if (ranges.length === 0) return null;\n return {\n start: Math.min(...ranges.map((r) => r.start)),\n end: Math.max(...ranges.map((r) => r.end)),\n };\n}\n","import { spawnSync } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { createInterface } from \"node:readline/promises\";\nimport { Command } from \"commander\";\nimport { findProjectRoot, resolveHaivePaths } from \"@hivelore/core\";\nimport { autoConfigureMcpClients, configureProjectMcpClients, type ConfigureResult } from \"./init-mcp-setup.js\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface AgentOptions {\n dir?: string;\n json?: boolean;\n yes?: boolean;\n global?: boolean;\n noGlobal?: boolean;\n}\n\ninterface AgentDetection {\n root: string;\n initialized: boolean;\n project_mcp: Array<{ client: string; path: string; present: boolean }>;\n installed_agents: Array<{ agent: string; command: string; installed: boolean; mcp_configured?: boolean }>;\n recommended_mode: \"mcp\" | \"wrapped\" | \"fallback\";\n recommended_command: string;\n}\n\ninterface AgentModeRecord {\n selected_mode: AgentDetection[\"recommended_mode\"];\n recommended_command: string;\n configured_at: string;\n project_root: string;\n notes: string[];\n}\n\nexport function registerAgent(program: Command): void {\n const agent = program\n .command(\"agent\")\n .description(\"Detect, configure, and report the best Hivelore mode for AI coding agents.\");\n\n agent\n .command(\"detect\")\n .description(\"Detect available AI agents and Hivelore MCP/wrapper readiness.\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .option(\"--json\", \"emit JSON\", false)\n .action(async (opts: AgentOptions) => {\n const detection = await detectAgentMode(opts.dir);\n printDetection(detection, Boolean(opts.json));\n });\n\n agent\n .command(\"status\")\n .description(\"Alias for agent detect.\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .option(\"--json\", \"emit JSON\", false)\n .action(async (opts: AgentOptions) => {\n const detection = await detectAgentMode(opts.dir);\n printDetection(detection, Boolean(opts.json));\n });\n\n agent\n .command(\"setup\")\n .description(\"Configure Hivelore project MCP, optional global MCP clients, and wrapper fallback metadata.\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .option(\"-y, --yes\", \"approve user-level/global MCP configuration without prompting\", false)\n .option(\"--no-global\", \"skip user-level/global MCP configuration\")\n .option(\"--json\", \"emit JSON\", false)\n .action(async (opts: AgentOptions) => {\n const result = await setupAgentMode(opts.dir, {\n yes: Boolean(opts.yes),\n global: opts.global !== false && opts.noGlobal !== true,\n interactive: process.stdin.isTTY,\n });\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n printSetupResult(result);\n });\n}\n\nexport async function setupAgentMode(\n dir: string | undefined,\n opts: { yes?: boolean; global?: boolean; interactive?: boolean } = {},\n): Promise<{\n detection: AgentDetection;\n project_results: ConfigureResult[];\n global_results: ConfigureResult[];\n mode_file: string;\n global_skipped_reason?: string;\n}> {\n const root = findProjectRoot(dir);\n const paths = resolveHaivePaths(root);\n const projectResults = await configureProjectMcpClients(root);\n const detectionBeforeGlobal = await detectAgentMode(root);\n\n let globalResults: ConfigureResult[] = [];\n let globalSkippedReason: string | undefined;\n const shouldConsiderGlobal = opts.global !== false;\n if (shouldConsiderGlobal) {\n const approved = opts.yes === true || (opts.interactive ? await confirmGlobalSetup() : false);\n if (approved) {\n globalResults = await autoConfigureMcpClients();\n const codex = await configureCodexIfAvailable(root);\n if (codex) globalResults.push(codex);\n } else {\n globalSkippedReason = opts.interactive\n ? \"User declined user-level/global MCP configuration.\"\n : \"Non-interactive shell; skipped user-level/global MCP configuration. Re-run `hivelore agent setup --yes` to apply it.\";\n }\n } else {\n globalSkippedReason = \"User-level/global MCP configuration disabled.\";\n }\n\n const detection = await detectAgentMode(root);\n const modeFile = await writeAgentModeRecord(paths, detection, globalSkippedReason);\n return {\n detection,\n project_results: projectResults,\n global_results: globalResults,\n mode_file: modeFile,\n ...(globalSkippedReason ? { global_skipped_reason: globalSkippedReason } : {}),\n };\n}\n\nexport async function detectAgentMode(dir?: string): Promise<AgentDetection> {\n const root = findProjectRoot(dir);\n const paths = resolveHaivePaths(root);\n const projectMcp = [\n { client: \"Claude Code\", path: path.join(root, \".mcp.json\"), present: existsSync(path.join(root, \".mcp.json\")) },\n { client: \"Cursor\", path: path.join(root, \".cursor\", \"mcp.json\"), present: existsSync(path.join(root, \".cursor\", \"mcp.json\")) },\n { client: \"VS Code\", path: path.join(root, \".vscode\", \"mcp.json\"), present: existsSync(path.join(root, \".vscode\", \"mcp.json\")) },\n ];\n const installedAgents = [\n { agent: \"Codex\", command: \"codex\", installed: commandExists(\"codex\"), mcp_configured: codexMcpConfigured() },\n { agent: \"Claude\", command: \"claude\", installed: commandExists(\"claude\") },\n { agent: \"Aider\", command: \"aider\", installed: commandExists(\"aider\") },\n { agent: \"Cursor\", command: \"cursor\", installed: commandExists(\"cursor\") },\n ];\n const hasProjectMcp = projectMcp.some((item) => item.present);\n const hasNativeMcp = hasProjectMcp || installedAgents.some((a) => a.mcp_configured);\n const wrapperAgent = installedAgents.find((a) => a.installed && [\"codex\", \"claude\", \"aider\"].includes(a.command));\n const recommendedMode: AgentDetection[\"recommended_mode\"] = hasNativeMcp ? \"mcp\" : wrapperAgent ? \"wrapped\" : \"fallback\";\n const recommendedCommand =\n recommendedMode === \"mcp\"\n ? \"Restart your AI client, then call get_briefing before editing.\"\n : recommendedMode === \"wrapped\" && wrapperAgent\n ? `hivelore run -- ${wrapperAgent.command}`\n : 'hivelore briefing --task \"...\" --files \"...\"';\n\n return {\n root,\n initialized: existsSync(paths.haiveDir),\n project_mcp: projectMcp,\n installed_agents: installedAgents,\n recommended_mode: recommendedMode,\n recommended_command: recommendedCommand,\n };\n}\n\nasync function writeAgentModeRecord(\n paths: ReturnType<typeof resolveHaivePaths>,\n detection: AgentDetection,\n skippedReason?: string,\n): Promise<string> {\n const dir = path.join(paths.runtimeDir, \"enforcement\");\n await mkdir(dir, { recursive: true });\n const file = path.join(dir, \"agent-mode.json\");\n const record: AgentModeRecord = {\n selected_mode: detection.recommended_mode,\n recommended_command: detection.recommended_command,\n configured_at: new Date().toISOString(),\n project_root: detection.root,\n notes: [\n \"mcp = native Hivelore MCP tools are available or project MCP config exists.\",\n \"wrapped = use hivelore run when native MCP is unavailable.\",\n \"fallback = use hivelore briefing/enforce manually.\",\n ...(skippedReason ? [skippedReason] : []),\n ],\n };\n await writeFile(file, JSON.stringify(record, null, 2) + \"\\n\", \"utf8\");\n return file;\n}\n\nasync function confirmGlobalSetup(): Promise<boolean> {\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n try {\n const answer = await rl.question(\n \"Configure Hivelore in user-level AI client configs (Cursor/VS Code/Claude/Codex when detected)? [y/N] \",\n );\n return /^y(es)?$/i.test(answer.trim());\n } finally {\n rl.close();\n }\n}\n\nasync function configureCodexIfAvailable(root: string): Promise<ConfigureResult | null> {\n if (!commandExists(\"codex\")) return { client: \"Codex\", status: \"not_installed\" };\n if (codexMcpConfigured()) return { client: \"Codex\", status: \"already_configured\" };\n const result = spawnSync(\"codex\", [\n \"mcp\",\n \"add\",\n \"haive\",\n \"--env\",\n `HAIVE_PROJECT_ROOT=${root}`,\n \"--\",\n \"haive\",\n \"mcp\",\n \"--stdio\",\n ], { encoding: \"utf8\" });\n if (result.status === 0) return { client: \"Codex\", status: \"configured\", path: path.join(os.homedir(), \".codex\", \"config.toml\") };\n return { client: \"Codex\", status: \"error\", error: result.stderr || result.stdout || \"codex mcp add failed\" };\n}\n\nfunction commandExists(command: string): boolean {\n const result = spawnSync(process.platform === \"win32\" ? \"where\" : \"which\", [command], {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n });\n return result.status === 0;\n}\n\nfunction codexMcpConfigured(): boolean {\n if (!commandExists(\"codex\")) return false;\n const result = spawnSync(\"codex\", [\"mcp\", \"get\", \"haive\"], {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n });\n return result.status === 0;\n}\n\nfunction printDetection(detection: AgentDetection, json: boolean): void {\n if (json) {\n console.log(JSON.stringify(detection, null, 2));\n return;\n }\n console.log(ui.bold(\"Hivelore agent status\"));\n console.log(ui.dim(` root: ${detection.root}`));\n console.log(`${detection.initialized ? ui.green(\"✓\") : ui.red(\"✗\")} project initialized`);\n for (const cfg of detection.project_mcp) {\n console.log(`${cfg.present ? ui.green(\"✓\") : ui.yellow(\"•\")} ${cfg.client} project MCP ${ui.dim(path.relative(detection.root, cfg.path))}`);\n }\n for (const agent of detection.installed_agents) {\n const marker = agent.installed ? ui.green(\"✓\") : ui.dim(\"•\");\n const mcp = agent.mcp_configured === true ? \" + Hivelore MCP\" : \"\";\n console.log(`${marker} ${agent.agent} (${agent.command})${mcp}`);\n }\n console.log(ui.bold(`Recommended mode: ${detection.recommended_mode}`));\n console.log(` ${detection.recommended_command}`);\n}\n\nfunction printSetupResult(result: Awaited<ReturnType<typeof setupAgentMode>>): void {\n for (const item of result.project_results) {\n if (item.status === \"configured\") ui.success(`${item.client} project MCP config written (${item.path})`);\n else if (item.status === \"already_configured\") ui.info(`${item.client} already configured`);\n else if (item.status === \"error\") ui.warn(`${item.client}: ${item.error}`);\n }\n for (const item of result.global_results) {\n if (item.status === \"configured\") ui.success(`${item.client} user-level MCP configured${item.path ? ` (${item.path})` : \"\"}`);\n else if (item.status === \"already_configured\") ui.info(`${item.client} user-level MCP already configured`);\n else if (item.status === \"not_installed\") ui.info(`${item.client} not detected`);\n else if (item.status === \"error\") ui.warn(`${item.client}: ${item.error}`);\n }\n if (result.global_skipped_reason) ui.warn(result.global_skipped_reason);\n ui.success(`Agent mode recorded at ${result.mode_file}`);\n printDetection(result.detection, false);\n}\n","/**\n * Auto-configure haive-mcp in supported AI clients.\n *\n * Two layers:\n * User-level (global, written once):\n * - Cursor (~/.cursor/mcp.json)\n * - VS Code (~/.config/Code/User/mcp.json or ~/Library/Application Support/Code/User/mcp.json)\n * - Claude Code (~/.claude.json mcpServers field)\n * - Windsurf (~/.codeium/windsurf/mcp_config.json)\n *\n * Project-level (per project, written at hivelore init, includes HAIVE_PROJECT_ROOT):\n * - Cursor (<root>/.cursor/mcp.json)\n * - VS Code (<root>/.vscode/mcp.json)\n * - Claude Code (<root>/.mcp.json)\n *\n * Project-level configs take precedence over user-level when the client opens that\n * workspace, ensuring the MCP server always resolves the correct project root even\n * when the same haive process serves multiple projects.\n */\nimport { readFile, writeFile, mkdir } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\n\nconst HOME = os.homedir();\nconst HAIVE_MCP_ENTRY = {\n command: \"hivelore\",\n args: [\"mcp\", \"--stdio\"],\n};\n\nfunction projectMcpEntry(root: string) {\n return {\n command: \"hivelore\",\n args: [\"mcp\", \"--stdio\"],\n env: { HAIVE_PROJECT_ROOT: root },\n };\n}\n\n// ── Cursor ────────────────────────────────────────────────────────────────────\n\nfunction cursorMcpPath(): string {\n return path.join(HOME, \".cursor\", \"mcp.json\");\n}\n\nasync function configureCursor(): Promise<ConfigureResult> {\n const mcpPath = cursorMcpPath();\n const cursorDir = path.join(HOME, \".cursor\");\n if (!existsSync(cursorDir)) return { client: \"Cursor\", status: \"not_installed\" };\n\n let config: { mcpServers?: Record<string, unknown> } = {};\n if (existsSync(mcpPath)) {\n try { config = JSON.parse(await readFile(mcpPath, \"utf8\")); } catch { /* ignore malformed */ }\n }\n config.mcpServers ??= {};\n if (config.mcpServers[\"hivelore\"] || config.mcpServers[\"haive\"]) return { client: \"Cursor\", status: \"already_configured\" };\n\n config.mcpServers[\"hivelore\"] = HAIVE_MCP_ENTRY;\n await mkdir(cursorDir, { recursive: true });\n await writeFile(mcpPath, JSON.stringify(config, null, 2), \"utf8\");\n return { client: \"Cursor\", status: \"configured\", path: mcpPath };\n}\n\n// ── VS Code ───────────────────────────────────────────────────────────────────\n\nfunction vscodeMcpPath(): string | null {\n const candidates = [\n path.join(HOME, \".config\", \"Code\", \"User\", \"mcp.json\"), // Linux\n path.join(HOME, \"Library\", \"Application Support\", \"Code\", \"User\", \"mcp.json\"), // macOS\n path.join(HOME, \"AppData\", \"Roaming\", \"Code\", \"User\", \"mcp.json\"), // Windows\n path.join(HOME, \".config\", \"Code - Insiders\", \"User\", \"mcp.json\"),\n ];\n // Return the first one whose *parent directory* exists\n for (const c of candidates) {\n if (existsSync(path.dirname(c))) return c;\n }\n return null;\n}\n\nasync function configureVSCode(): Promise<ConfigureResult> {\n const mcpPath = vscodeMcpPath();\n if (!mcpPath) return { client: \"VS Code\", status: \"not_installed\" };\n\n let config: { servers?: Record<string, unknown> } = {};\n if (existsSync(mcpPath)) {\n try { config = JSON.parse(await readFile(mcpPath, \"utf8\")); } catch { /* ignore */ }\n }\n config.servers ??= {};\n if (config.servers[\"hivelore\"] || config.servers[\"haive\"]) return { client: \"VS Code\", status: \"already_configured\" };\n\n config.servers[\"hivelore\"] = { ...HAIVE_MCP_ENTRY, type: \"stdio\" };\n await mkdir(path.dirname(mcpPath), { recursive: true });\n await writeFile(mcpPath, JSON.stringify(config, null, 2), \"utf8\");\n return { client: \"VS Code\", status: \"configured\", path: mcpPath };\n}\n\n// ── Claude Code ───────────────────────────────────────────────────────────────\n\nfunction claudeConfigPath(): string | null {\n const p = path.join(HOME, \".claude.json\");\n if (existsSync(p)) return p;\n // Some versions put it here\n const p2 = path.join(HOME, \".config\", \"claude\", \"claude.json\");\n if (existsSync(path.dirname(p2))) return p2;\n return null;\n}\n\nasync function configureClaude(): Promise<ConfigureResult> {\n // Claude Code stores MCP servers in ~/.claude.json under mcpServers key\n const cfgPath = claudeConfigPath() ?? path.join(HOME, \".claude.json\");\n if (!existsSync(cfgPath) && !existsSync(path.join(HOME, \".claude\"))) {\n return { client: \"Claude Code\", status: \"not_installed\" };\n }\n\n let config: { mcpServers?: Record<string, unknown> } = {};\n if (existsSync(cfgPath)) {\n try { config = JSON.parse(await readFile(cfgPath, \"utf8\")); } catch { /* ignore */ }\n }\n config.mcpServers ??= {};\n if (config.mcpServers[\"hivelore\"] || config.mcpServers[\"haive\"]) return { client: \"Claude Code\", status: \"already_configured\" };\n\n config.mcpServers[\"hivelore\"] = { ...HAIVE_MCP_ENTRY, type: \"stdio\" };\n await writeFile(cfgPath, JSON.stringify(config, null, 2), \"utf8\");\n return { client: \"Claude Code\", status: \"configured\", path: cfgPath };\n}\n\n// ── Windsurf ─────────────────────────────────────────────────────────────────\n\nfunction windsurfMcpPath(): string | null {\n const candidates = [\n path.join(HOME, \".codeium\", \"windsurf\", \"mcp_config.json\"),\n path.join(HOME, \".windsurf\", \"mcp.json\"),\n ];\n for (const c of candidates) {\n if (existsSync(path.dirname(c))) return c;\n }\n return null;\n}\n\nasync function configureWindsurf(): Promise<ConfigureResult> {\n const mcpPath = windsurfMcpPath();\n if (!mcpPath) return { client: \"Windsurf\", status: \"not_installed\" };\n\n let config: { mcpServers?: Record<string, unknown> } = {};\n if (existsSync(mcpPath)) {\n try { config = JSON.parse(await readFile(mcpPath, \"utf8\")); } catch { /* ignore */ }\n }\n config.mcpServers ??= {};\n if (config.mcpServers[\"hivelore\"] || config.mcpServers[\"haive\"]) return { client: \"Windsurf\", status: \"already_configured\" };\n\n config.mcpServers[\"hivelore\"] = HAIVE_MCP_ENTRY;\n await mkdir(path.dirname(mcpPath), { recursive: true });\n await writeFile(mcpPath, JSON.stringify(config, null, 2), \"utf8\");\n return { client: \"Windsurf\", status: \"configured\", path: mcpPath };\n}\n\n// ── Public API ────────────────────────────────────────────────────────────────\n\nexport interface ConfigureResult {\n client: string;\n status: \"configured\" | \"already_configured\" | \"not_installed\" | \"error\";\n path?: string;\n error?: string;\n}\n\nexport async function autoConfigureMcpClients(): Promise<ConfigureResult[]> {\n const results: ConfigureResult[] = [];\n const configurators = [configureCursor, configureVSCode, configureClaude, configureWindsurf];\n for (const fn of configurators) {\n try {\n results.push(await fn());\n } catch (err) {\n const name = fn.name.replace(\"configure\", \"\");\n results.push({ client: name, status: \"error\", error: String(err) });\n }\n }\n return results;\n}\n\n/**\n * Write project-level MCP configs that include HAIVE_PROJECT_ROOT so that\n * each AI client uses the correct project root regardless of the server's CWD.\n *\n * These files are machine-specific (absolute paths) and should be gitignored.\n * hivelore init appends them to .gitignore automatically.\n *\n * Project-level configs take precedence over user-level configs in Cursor and\n * VS Code when the workspace is opened. This is the canonical fix for the\n * \"MCP server uses wrong project root in multi-project setups\" bug.\n */\nexport async function configureProjectMcpClients(root: string): Promise<ConfigureResult[]> {\n const entry = projectMcpEntry(root);\n const results: ConfigureResult[] = [];\n\n // ── Cursor: <root>/.cursor/mcp.json ──────────────────────────────────────\n try {\n const cursorPath = path.join(root, \".cursor\", \"mcp.json\");\n let config: { mcpServers?: Record<string, unknown> } = {};\n if (existsSync(cursorPath)) {\n try { config = JSON.parse(await readFile(cursorPath, \"utf8\")); } catch { /* keep empty */ }\n }\n config.mcpServers ??= {};\n delete config.mcpServers[\"haive\"]; // legacy key superseded by \"hivelore\"\n config.mcpServers[\"hivelore\"] = entry;\n await mkdir(path.dirname(cursorPath), { recursive: true });\n await writeFile(cursorPath, JSON.stringify(config, null, 2) + \"\\n\", \"utf8\");\n results.push({ client: \"Cursor (project)\", status: \"configured\", path: cursorPath });\n } catch (err) {\n results.push({ client: \"Cursor (project)\", status: \"error\", error: String(err) });\n }\n\n // ── VS Code: <root>/.vscode/mcp.json ─────────────────────────────────────\n try {\n const vscodePath = path.join(root, \".vscode\", \"mcp.json\");\n let config: { servers?: Record<string, unknown> } = {};\n if (existsSync(vscodePath)) {\n try { config = JSON.parse(await readFile(vscodePath, \"utf8\")); } catch { /* keep empty */ }\n }\n config.servers ??= {};\n delete config.servers[\"haive\"]; // legacy key superseded by \"hivelore\"\n config.servers[\"hivelore\"] = { ...entry, type: \"stdio\" };\n await mkdir(path.dirname(vscodePath), { recursive: true });\n await writeFile(vscodePath, JSON.stringify(config, null, 2) + \"\\n\", \"utf8\");\n results.push({ client: \"VS Code (workspace)\", status: \"configured\", path: vscodePath });\n } catch (err) {\n results.push({ client: \"VS Code (workspace)\", status: \"error\", error: String(err) });\n }\n\n // ── Claude Code: <root>/.mcp.json ────────────────────────────────────────\n try {\n const mcpPath = path.join(root, \".mcp.json\");\n let config: { mcpServers?: Record<string, unknown> } = {};\n if (existsSync(mcpPath)) {\n try { config = JSON.parse(await readFile(mcpPath, \"utf8\")); } catch { /* keep empty */ }\n }\n config.mcpServers ??= {};\n delete config.mcpServers[\"haive\"]; // legacy key superseded by \"hivelore\"\n config.mcpServers[\"hivelore\"] = { ...entry, type: \"stdio\" };\n await writeFile(mcpPath, JSON.stringify(config, null, 2) + \"\\n\", \"utf8\");\n results.push({ client: \"Claude Code (project)\", status: \"configured\", path: mcpPath });\n } catch (err) {\n results.push({ client: \"Claude Code (project)\", status: \"error\", error: String(err) });\n }\n\n return results;\n}\n","/**\n * Bootstrap: auto-generate .ai/project-context.md from local filesystem signals.\n *\n * Reads: package.json, README.md, directory structure (top 2 levels).\n * No AI call, no network — pure static analysis.\n */\nimport { readdir, readFile } from \"node:fs/promises\";\nimport type { Dirent } from \"node:fs\";\nimport { existsSync, readdirSync } from \"node:fs\";\nimport path from \"node:path\";\n\nconst IGNORE_DIRS = new Set([\n \"node_modules\", \"dist\", \"build\", \".next\", \".nuxt\", \".svelte-kit\",\n \".git\", \"coverage\", \".turbo\", \"out\", \".cache\", \"tmp\", \"temp\",\n \"__pycache__\", \".venv\", \"venv\", \"target\", \".gradle\",\n]);\n\nconst FRAMEWORK_SIGNALS: Record<string, string[]> = {\n \"NestJS\": [\"@nestjs/core\", \"@nestjs/common\"],\n \"Next.js\": [\"next\"],\n \"Remix\": [\"@remix-run/react\", \"@remix-run/node\"],\n \"React\": [\"react\", \"react-dom\"],\n \"Vue\": [\"vue\"],\n \"Svelte\": [\"svelte\"],\n \"SvelteKit\": [\"@sveltejs/kit\"],\n \"Astro\": [\"astro\"],\n \"Express\": [\"express\"],\n \"Fastify\": [\"fastify\"],\n \"Hono\": [\"hono\"],\n \"tRPC\": [\"@trpc/server\", \"@trpc/client\"],\n \"Prisma\": [\"@prisma/client\"],\n \"Drizzle\": [\"drizzle-orm\"],\n \"Redux Toolkit\": [\"@reduxjs/toolkit\"],\n \"Zustand\": [\"zustand\"],\n \"TanStack Query\": [\"@tanstack/react-query\", \"react-query\"],\n \"Mongoose\": [\"mongoose\"],\n \"Apollo\": [\"@apollo/client\", \"@apollo/server\", \"apollo-server\"],\n \"GraphQL\": [\"graphql\"],\n \"Vite\": [\"vite\"],\n \"Vitest\": [\"vitest\"],\n \"Jest\": [\"jest\"],\n};\n\nconst KEY_DEPS = [\n \"@nestjs/jwt\", \"@nestjs/passport\", \"passport-jwt\",\n \"jsonwebtoken\", \"bcrypt\", \"bcryptjs\",\n \"stripe\", \"axios\", \"socket.io\", \"ws\",\n \"redis\", \"ioredis\", \"pg\", \"mysql2\", \"mongodb\", \"mongoose\",\n \"zod\", \"yup\", \"class-validator\",\n \"tailwindcss\", \"shadcn\", \"@radix-ui\",\n \"@vercel/ai\", \"ai\", \"openai\", \"@anthropic-ai/sdk\",\n \"typescript\",\n];\n\ninterface PackageJson {\n name?: string;\n description?: string;\n version?: string;\n scripts?: Record<string, string>;\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n workspaces?: string[] | { packages: string[] };\n}\n\nfunction detectFrameworks(allDeps: Record<string, string>): string[] {\n const found: string[] = [];\n for (const [fw, signals] of Object.entries(FRAMEWORK_SIGNALS)) {\n if (signals.some((s) => allDeps[s] !== undefined)) found.push(fw);\n }\n return found;\n}\n\nfunction detectKeyDeps(allDeps: Record<string, string>): string[] {\n return KEY_DEPS.filter((d) => allDeps[d] !== undefined);\n}\n\nfunction detectLanguage(root: string): string {\n if (existsSync(path.join(root, \"tsconfig.json\"))) return \"TypeScript\";\n if (existsSync(path.join(root, \"pyproject.toml\")) || existsSync(path.join(root, \"setup.py\"))) return \"Python\";\n if (existsSync(path.join(root, \"go.mod\"))) return \"Go\";\n if (existsSync(path.join(root, \"pom.xml\")) || existsSync(path.join(root, \"build.gradle\"))) return \"Java/Kotlin\";\n if (existsSync(path.join(root, \"Cargo.toml\"))) return \"Rust\";\n if (existsSync(path.join(root, \"package.json\"))) {\n // A Node project without a root tsconfig.json can still be TypeScript (tsconfig in a\n // sub-package, or a loose .ts project). Distinguish TS from JS by scanning source files\n // rather than assuming JavaScript whenever tsconfig.json is absent.\n return hasSourceWithExt(root, [\".ts\", \".tsx\", \".mts\", \".cts\"]) ? \"TypeScript\" : \"JavaScript\";\n }\n return \"Unknown\";\n}\n\n/**\n * Bounded, synchronous scan for source files with any of the given extensions.\n * Looks at the project root and the immediate children of common source dirs\n * (top 2 levels), skipping IGNORE_DIRS and declaration files (`.d.ts`).\n */\nfunction hasSourceWithExt(root: string, exts: string[]): boolean {\n const matches = (name: string): boolean =>\n !name.endsWith(\".d.ts\") && exts.some((ext) => name.endsWith(ext));\n const scanDir = (dir: string, depth: number): boolean => {\n let entries: Dirent[];\n try {\n entries = readdirSync(dir, { withFileTypes: true });\n } catch {\n return false;\n }\n for (const entry of entries) {\n if (entry.isFile() && matches(entry.name)) return true;\n }\n if (depth <= 0) return false;\n for (const entry of entries) {\n if (entry.isDirectory() && !IGNORE_DIRS.has(entry.name) && !entry.name.startsWith(\".\")) {\n if (scanDir(path.join(dir, entry.name), depth - 1)) return true;\n }\n }\n return false;\n };\n return scanDir(root, 2);\n}\n\nfunction detectProjectType(frameworks: string[], scripts: Record<string, string>, isMonorepo: boolean): string {\n if (isMonorepo) {\n if (frameworks.includes(\"NestJS\")) return \"Monorepo (NestJS backend)\";\n if (frameworks.includes(\"Next.js\")) return \"Monorepo (Next.js)\";\n if (frameworks.includes(\"React\")) return \"Multi-package monorepo (React)\";\n if (frameworks.length > 0) return `Multi-package monorepo (${frameworks.slice(0, 2).join(\", \")})`;\n return \"Multi-package monorepo\";\n }\n if (frameworks.includes(\"NestJS\")) return \"Backend API (NestJS)\";\n if (frameworks.includes(\"Next.js\")) return \"Full-stack web app (Next.js)\";\n if (frameworks.includes(\"Remix\")) return \"Full-stack web app (Remix)\";\n if (frameworks.includes(\"Express\") || frameworks.includes(\"Fastify\") || frameworks.includes(\"Hono\")) return \"Backend API\";\n if (frameworks.includes(\"React\") || frameworks.includes(\"Vue\") || frameworks.includes(\"Svelte\")) return \"Frontend SPA\";\n if (scripts[\"build\"] && !scripts[\"dev\"]) return \"CLI tool / library\";\n if (existsSync(\"pom.xml\")) return \"Java backend\";\n return \"Application\";\n}\n\nasync function scanDirs(root: string, maxDepth = 2): Promise<string[]> {\n const results: string[] = [];\n async function walk(dir: string, depth: number): Promise<void> {\n if (depth > maxDepth) return;\n let entries: Dirent<string>[];\n try {\n entries = await readdir(dir, { withFileTypes: true, encoding: \"utf8\" });\n } catch {\n return;\n }\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n if (IGNORE_DIRS.has(entry.name) || entry.name.startsWith(\".\")) continue;\n const rel = path.relative(root, path.join(dir, entry.name));\n results.push(rel);\n await walk(path.join(dir, entry.name), depth + 1);\n }\n }\n await walk(root, 0);\n return results;\n}\n\nfunction inferModuleDescriptions(dirs: string[], frameworks: string[] = []): string[] {\n const known: Record<string, string> = {\n \"src\": \"main source directory\",\n \"app\": \"application entrypoint / routes (Next.js App Router or similar)\",\n \"pages\": \"file-based routing pages\",\n \"components\": \"reusable UI components\",\n \"lib\": \"shared utilities and helpers\",\n \"utils\": \"utility functions\",\n \"hooks\": \"React hooks\",\n \"services\": \"business logic services\",\n \"controllers\": \"HTTP controllers / route handlers\",\n \"modules\": \"feature modules\",\n \"middleware\": \"HTTP or business middleware\",\n \"guards\": \"auth / access guards\",\n \"decorators\": \"custom decorators\",\n \"interceptors\": \"NestJS interceptors\",\n \"filters\": \"exception filters\",\n \"pipes\": \"validation / transformation pipes\",\n \"dto\": \"Data Transfer Objects\",\n \"entities\": \"ORM entities / database models\",\n \"prisma\": \"Prisma schema and migrations\",\n \"migrations\": \"database migrations\",\n \"config\": \"configuration files\",\n \"types\": \"TypeScript type definitions\",\n \"schemas\": \"validation schemas (Zod / class-validator)\",\n \"test\": \"tests\",\n \"tests\": \"tests\",\n \"__tests__\": \"tests\",\n \"e2e\": \"end-to-end tests\",\n \"public\": \"static public assets\",\n \"assets\": \"static assets\",\n \"styles\": \"global CSS / style files\",\n \"scripts\": \"build or utility scripts\",\n \"docs\": \"documentation\",\n \"docker\": \"Docker configuration\",\n \"infra\": \"infrastructure / IaC\",\n \"packages\": \"monorepo sub-packages\",\n \"functions\": \"serverless / edge functions\",\n \"api\": \"API routes or client\",\n \"store\": \"state management (Redux / Zustand / Pinia)\",\n \"context\": \"React contexts\",\n \"server\": \"server-side code\",\n \"client\": \"client-side code\",\n \"features\": \"feature-based modules\",\n \"routes\": \"route definitions\",\n \"workers\": \"background workers / queues\",\n \"auth\": \"authentication / authorization\",\n \"users\": \"user management\",\n \"products\": \"product catalog\",\n \"orders\": \"order management\",\n \"common\": \"shared / common utilities\",\n \"shared\": \"shared code across modules\",\n };\n\n const isNestJS = frameworks.includes(\"NestJS\");\n\n // When src/ has meaningful subdirectories, list them for any backend/API project\n // (NestJS, Express, Fastify, Hono, tRPC, GraphQL…) — not just NestJS\n const isSrcBased = isNestJS ||\n frameworks.some((f) => [\"Express\", \"Fastify\", \"Hono\", \"tRPC\", \"Apollo\", \"GraphQL\"].includes(f));\n const isFrontend = frameworks.some((f) => [\"React\", \"Vue\", \"Svelte\", \"SvelteKit\", \"Astro\"].includes(f));\n const srcSubdirs = dirs.filter((d) => d.startsWith(\"src/\") && d.split(\"/\").length === 2);\n\n // Expand src/ for: all backend stacks AND frontend projects with ≥3 src/ subdirs\n // (shallow frontends like CRA only have src/components + src/index → skip)\n if ((isSrcBased && srcSubdirs.length >= 2) || (isFrontend && srcSubdirs.length >= 3)) {\n const label = isNestJS ? \"main source (NestJS feature modules)\" : \"main source\";\n const result: string[] = [`- \\`src/\\` — ${label}`];\n for (const d of srcSubdirs.slice(0, 12)) {\n const name = d.split(\"/\")[1]!;\n const desc = known[name.toLowerCase()] ?? \"module\";\n result.push(` - \\`${name}/\\` — ${desc}`);\n }\n // Also list other top-level dirs (prisma/, docker/, etc.)\n const otherTopLevel = dirs\n .filter((d) => !d.includes(\"/\") && d !== \"src\")\n .slice(0, 6);\n for (const d of otherTopLevel) {\n const desc = known[d.toLowerCase()] ?? \"module\";\n result.push(`- \\`${d}/\\` — ${desc}`);\n }\n return result;\n }\n\n // Monorepo pattern: packages/ contains workspace sub-packages\n const isMonorepo = dirs.some((d) => d === \"packages\") &&\n dirs.some((d) => d.startsWith(\"packages/\") && d.split(\"/\").length === 2);\n if (isMonorepo) {\n const packageSubdirs = dirs.filter((d) => d.startsWith(\"packages/\") && d.split(\"/\").length === 2);\n const result: string[] = [`- \\`packages/\\` — monorepo sub-packages`];\n for (const d of packageSubdirs.slice(0, 10)) {\n const name = d.split(\"/\")[1]!;\n const desc = known[name.toLowerCase()] ?? \"sub-package\";\n result.push(` - \\`${name}/\\` — ${desc}`);\n }\n const otherTopLevel = dirs\n .filter((d) => !d.includes(\"/\") && d !== \"packages\")\n .slice(0, 5);\n for (const d of otherTopLevel) {\n const desc = known[d.toLowerCase()] ?? \"module\";\n result.push(`- \\`${d}/\\` — ${desc}`);\n }\n return result;\n }\n\n // Default: top-level dirs\n const top = dirs.filter((d) => !d.includes(\"/\")).slice(0, 12);\n return top.map((d) => {\n const desc = known[d.toLowerCase()] ?? \"module\";\n return `- \\`${d}/\\` — ${desc}`;\n });\n}\n\nfunction readmeExcerpt(readme: string): string {\n const lines = readme.split(\"\\n\");\n // Skip the first h1, grab description paragraph\n let inContent = false;\n const kept: string[] = [];\n for (const line of lines) {\n if (!inContent && line.trim().startsWith(\"#\")) { inContent = true; continue; }\n if (!inContent) continue;\n if (kept.length >= 6) break;\n if (line.trim()) kept.push(line.trim());\n }\n return kept.join(\" \").slice(0, 400);\n}\n\nexport async function generateBootstrapContext(root: string): Promise<string> {\n // 1. package.json\n let pkg: PackageJson = {};\n const pkgPath = path.join(root, \"package.json\");\n if (existsSync(pkgPath)) {\n try { pkg = JSON.parse(await readFile(pkgPath, \"utf8\")) as PackageJson; } catch { /* ignore */ }\n }\n\n const allDeps = { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) };\n const frameworks = detectFrameworks(allDeps);\n const keyDeps = detectKeyDeps(allDeps);\n const language = detectLanguage(root);\n const isMonorepo = pkg.workspaces !== undefined &&\n (Array.isArray(pkg.workspaces) ? pkg.workspaces.length > 0 : true);\n const projectType = detectProjectType(frameworks, pkg.scripts ?? {}, isMonorepo);\n const projectName = pkg.name ?? path.basename(root);\n const projectDesc = pkg.description ?? \"\";\n\n // 2. README excerpt\n let readmeSummary = \"\";\n for (const name of [\"README.md\", \"readme.md\", \"README\"]) {\n const p = path.join(root, name);\n if (existsSync(p)) {\n try {\n const content = await readFile(p, \"utf8\");\n readmeSummary = readmeExcerpt(content);\n break;\n } catch { /* ignore */ }\n }\n }\n\n // 3. Directory structure\n const dirs = await scanDirs(root, 2);\n const moduleLines = inferModuleDescriptions(dirs, frameworks);\n\n // 4. Scripts analysis\n const scripts = pkg.scripts ?? {};\n const scriptLines = Object.entries(scripts)\n .filter(([k]) => [\"build\", \"dev\", \"start\", \"test\", \"lint\", \"deploy\"].includes(k))\n .map(([k, v]) => `- \\`${k}\\`: ${v}`)\n .slice(0, 6);\n\n // 5. Tech stack summary\n const stackParts: string[] = [language];\n if (frameworks.length) stackParts.push(...frameworks);\n const techStack = stackParts.join(\", \");\n\n // 6. Key dependencies (notable ones)\n const notableDeps = Object.keys(allDeps)\n .filter((d) => !d.startsWith(\"@types/\") && ![\"typescript\", \"eslint\", \"prettier\", \"jest\"].includes(d))\n .filter((d) => ![\"react\", \"react-dom\", \"next\", \"vue\", \"express\"].includes(d)) // already in frameworks\n .slice(0, 10)\n .map((d) => `\\`${d}\\``);\n\n const lines: string[] = [\n `# Project context — ${projectName}`,\n \"\",\n `> Auto-generated by \\`hivelore init --bootstrap\\`. Review and refine — especially the Architecture and Gotchas sections.`,\n ...(pkg.version ? [`> **Current version**: ${pkg.version}`] : []),\n \"\",\n `## Overview`,\n `**Type:** ${projectType}`,\n `**Tech stack:** ${techStack}`,\n ...(projectDesc ? [`**Description:** ${projectDesc}`] : []),\n ...(readmeSummary ? [`**From README:** ${readmeSummary}`] : []),\n \"\",\n `## Architecture`,\n `TODO — fill in the high-level architecture (inferred structure below, verify manually):`,\n \"\",\n ...(moduleLines.length ? moduleLines : [\"TODO — no clear structure detected.\"]),\n \"\",\n `## Key modules`,\n `TODO — describe the purpose of the main modules. The directory scan found:`,\n ...dirs.filter((d) => !d.includes(\"/\")).slice(0, 8).map((d) => `- \\`${d}/\\``),\n \"\",\n `## Conventions`,\n `TODO — fill in coding conventions (naming, patterns, file layout).`,\n \"\",\n ...(scriptLines.length ? [\n `**Available scripts:**`,\n ...scriptLines,\n \"\",\n ] : []),\n ...(keyDeps.length ? [\n `**Key dependencies in use:** ${keyDeps.map((d) => `\\`${d}\\``).join(\", \")}`,\n \"\",\n ] : []),\n ...(notableDeps.length ? [\n `**Other notable packages:** ${notableDeps.join(\", \")}`,\n \"\",\n ] : []),\n `## Glossary`,\n `TODO — domain terms and what they mean here.`,\n \"\",\n `## Gotchas`,\n `TODO — known traps, surprising behavior, things newcomers stub their toes on.`,\n `(Run \\`hivelore memory import-changelog\\` or \\`hivelore memory import README.md\\` to seed these automatically.)`,\n \"\",\n ];\n\n return lines.join(\"\\n\");\n}\n","/**\n * Stack memory packs — pre-seeded validated memories for common stacks.\n *\n * Each pack contains 4-8 high-value gotchas/conventions that every team\n * using that stack rediscovers. Pre-seeding them means haive is useful\n * from J+0, not J+30.\n */\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n buildFrontmatter,\n loadMemoriesFromDir,\n meetsSeedQualityFloor,\n memoryFilePath,\n serializeMemory,\n STACK_PACK_TAG,\n type HaivePaths,\n type Sensor,\n} from \"@hivelore/core\";\n\n/**\n * A curated, hand-authored regex sensor for a stack-pack memory. Turns generic\n * framework guidance into a deterministic feedforward+feedback guardrail: the\n * lesson fires on the user's own diff, not just when the briefing surfaces it.\n * Seed sensors are always `warn` (never auto-block) and `autogen: false` (vetted).\n */\ninterface PackSensor {\n pattern: string;\n flags?: string;\n message: string;\n /** Optional exact-file/dir-prefix scoping. Empty = applies to all added diff lines. */\n paths?: string[];\n}\n\ninterface PackMemory {\n slug: string;\n type: \"gotcha\" | \"convention\" | \"decision\" | \"architecture\";\n tags: string[];\n body: string;\n /** Optional executable guardrail derived from this lesson. */\n sensor?: PackSensor;\n}\n\nexport type StackName = \"nestjs\" | \"nextjs\" | \"remix\" | \"react\" | \"express\" | \"fastify\" | \"prisma\" | \"drizzle\"\n | \"zustand\" | \"redux\" | \"reactquery\" | \"trpc\" | \"mongoose\" | \"graphql\"\n | \"fastapi\" | \"django\" | \"go\" | \"flask\" | \"vue\" | \"spring\"\n | \"tailwind\" | \"vite\" | \"sveltekit\" | \"astro\" | \"typescript\" | \"monorepo\"\n | \"laravel\" | \"rails\" | \"dotnet\" | \"docker\";\n\nexport const PACKS: Record<StackName, PackMemory[]> = {\n nestjs: [\n {\n slug: \"jwtmodule-requires-secret\",\n type: \"gotcha\",\n tags: [\"auth\", \"jwt\", \"nestjs\"],\n body: `JwtModule must be registered with an explicit secret — there is no default.\n\n\\`\\`\\`ts\nJwtModule.register({ secret: process.env.JWT_SECRET, signOptions: { expiresIn: '7d' } })\n\\`\\`\\`\n\nWithout a secret, tokens are signed with an empty string and any client can forge them.\nAlways load the secret from env and validate it is defined at startup.`,\n },\n {\n slug: \"global-validation-pipe\",\n type: \"convention\",\n tags: [\"validation\", \"nestjs\", \"security\"],\n body: `Register ValidationPipe globally in main.ts, not per-controller.\n\n\\`\\`\\`ts\napp.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true }));\n\\`\\`\\`\n\n- \\`whitelist: true\\` strips unknown properties silently\n- \\`forbidNonWhitelisted: true\\` throws 400 on unknown fields (safer)\n- Without this, NestJS passes unvalidated payloads to handlers.`,\n },\n {\n slug: \"nestjs-no-direct-orm-in-controller\",\n type: \"convention\",\n tags: [\"architecture\", \"nestjs\"],\n body: `Controllers must never import Prisma/TypeORM directly — that belongs in Services.\n\nController → Service → Repository (or direct ORM) is the required layering.\nDirect ORM usage in controllers makes testing impossible and couples transport to persistence.`,\n sensor: {\n pattern: \"@prisma/client|PrismaClient|getRepository\\\\(|createQueryBuilder\\\\(\",\n paths: [\"**/*.controller.ts\"],\n message: \"ORM/Prisma used directly in a controller — move persistence into a Service (Controller → Service → Repository).\",\n },\n },\n {\n slug: \"nestjs-exception-filter-for-prisma\",\n type: \"gotcha\",\n tags: [\"error-handling\", \"nestjs\", \"prisma\"],\n body: `Prisma errors bubble up as unhandled 500s without a custom exception filter.\n\nCreate an \\`AllExceptionsFilter\\` or a specific \\`PrismaClientExceptionFilter\\` that maps:\n- P2002 (unique constraint) → 409 Conflict\n- P2025 (record not found) → 404 Not Found\n- P2003 (foreign key) → 422 Unprocessable\n\nWithout this, clients receive raw Prisma error messages which may leak schema info.`,\n },\n ],\n\n nextjs: [\n {\n slug: \"server-components-no-client-hooks\",\n type: \"gotcha\",\n tags: [\"nextjs\", \"react\", \"server-components\"],\n body: `Server Components cannot use useState, useEffect, or any browser APIs.\n\nAdd \\`\"use client\"\\` at the top of any component that needs hooks or event handlers.\nThe boundary propagates down — children of a client component don't need the directive.\n\nCommon mistake: importing a client-only library (e.g. framer-motion) in a server component\ncauses a cryptic runtime error. Check for browser globals (window, document, localStorage).`,\n },\n {\n slug: \"nextjs-env-client-exposure\",\n type: \"gotcha\",\n tags: [\"security\", \"nextjs\", \"env\"],\n body: `Only environment variables prefixed with NEXT_PUBLIC_ are exposed to the browser.\n\nNever put secrets in NEXT_PUBLIC_* variables — they are bundled into the client JS.\nVariables without the prefix are server-only and safe for API keys, database URLs, etc.`,\n sensor: {\n pattern: \"NEXT_PUBLIC_[A-Z0-9_]*(SECRET|PRIVATE|TOKEN|PASSWORD|API_?KEY)\",\n message: \"A NEXT_PUBLIC_ env var with a secret-looking name is bundled into client JS — move the secret to a server-only (non-NEXT_PUBLIC_) variable.\",\n },\n },\n {\n slug: \"nextjs-fetch-cache-defaults\",\n type: \"gotcha\",\n tags: [\"nextjs\", \"caching\", \"fetch\"],\n body: `In Next.js App Router, \\`fetch()\\` is cached indefinitely by default in Server Components.\n\nAdd \\`{ cache: 'no-store' }\\` for dynamic data, or \\`{ next: { revalidate: 60 } }\\` for ISR.\nForgetting this means stale data is returned after a deploy until the cache expires.`,\n },\n {\n slug: \"nextjs-metadata-api\",\n type: \"convention\",\n tags: [\"nextjs\", \"seo\"],\n body: `Use the Metadata API (export const metadata / generateMetadata) instead of <Head>.\n\n\\`<Head>\\` from next/head still works in pages/ but is not supported in the App Router.\nUse \\`generateMetadata\\` for dynamic titles/descriptions based on route params.`,\n },\n ],\n\n remix: [\n {\n slug: \"remix-loader-vs-action\",\n type: \"convention\",\n tags: [\"remix\", \"architecture\"],\n body: `loader = GET data for rendering. action = handle form submissions / mutations.\n\n- \\`loader\\` runs on every GET request (server-side, returns data for the component)\n- \\`action\\` runs on POST/PUT/DELETE (mutations — redirect after success)\n- Never fetch inside the component itself for route data — use the loader instead.`,\n },\n {\n slug: \"remix-error-boundaries\",\n type: \"gotcha\",\n tags: [\"remix\", \"error-handling\"],\n body: `Each route should export an ErrorBoundary to catch loader/action errors gracefully.\n\nWithout it, errors bubble to the root boundary and replace the entire page.\nExport \\`export function ErrorBoundary() { ... }\\` to scope errors to the route.`,\n },\n ],\n\n react: [\n {\n slug: \"useeffect-cleanup\",\n type: \"gotcha\",\n tags: [\"react\", \"memory-leak\"],\n body: `useEffect subscriptions, timers, and async operations need cleanup to avoid memory leaks.\n\n\\`\\`\\`ts\nuseEffect(() => {\n const controller = new AbortController();\n fetchData({ signal: controller.signal });\n return () => controller.abort(); // cleanup\n}, [dep]);\n\\`\\`\\`\n\nMissing cleanup causes: state updates on unmounted components, duplicate subscriptions,\nand event listeners that accumulate across re-renders.`,\n },\n {\n slug: \"react-key-prop-in-lists\",\n type: \"gotcha\",\n tags: [\"react\", \"performance\"],\n body: `Keys must be stable, unique IDs — never use array index as key.\n\nUsing index as key causes React to re-render wrong items on reorder/filter,\ncorrupts form state, and triggers avoidable DOM mutations.\nUse item.id or a stable hash — never Math.random().`,\n sensor: {\n pattern: \"key=\\\\{\\\\s*index\\\\s*\\\\}\",\n message: \"Array index used as a React key — switch to a stable unique id to avoid state corruption on reorder.\",\n },\n },\n {\n slug: \"react-avoid-use-effect-for-derived-state\",\n type: \"convention\",\n tags: [\"react\", \"state\"],\n body: `Don't use useEffect to sync state from props — compute it during render instead.\n\n\\`\\`\\`ts\n// ❌ Bad\nconst [fullName, setFullName] = useState('');\nuseEffect(() => { setFullName(first + ' ' + last); }, [first, last]);\n\n// ✅ Good\nconst fullName = first + ' ' + last; // derived during render\n\\`\\`\\``,\n },\n ],\n\n express: [\n {\n slug: \"express-missing-validation\",\n type: \"gotcha\",\n tags: [\"security\", \"express\", \"validation\"],\n body: `Express does not validate request bodies by default — always validate with zod, joi, or express-validator.\n\nWithout validation:\n- req.body fields are \\`any\\` and may be missing, wrong type, or injected\n- Downstream code crashes or processes malicious data\nAdd a validation middleware for every route that accepts user input.`,\n },\n {\n slug: \"express-async-error-propagation\",\n type: \"gotcha\",\n tags: [\"express\", \"error-handling\"],\n body: `Async route handlers don't propagate errors to error middleware without explicit next(err).\n\n\\`\\`\\`ts\n// ❌ Unhandled — Express never sees the rejection\napp.get('/', async (req, res) => { throw new Error('oops'); });\n\n// ✅ Correct\napp.get('/', async (req, res, next) => {\n try { await doWork(); }\n catch (err) { next(err); }\n});\n\\`\\`\\`\nOr use express-async-errors / wrap helper.`,\n },\n ],\n\n fastify: [\n {\n slug: \"fastify-schema-validation-required\",\n type: \"convention\",\n tags: [\"fastify\", \"validation\", \"security\"],\n body: `Always define a JSON schema on routes — Fastify validates and coerces automatically.\n\n\\`\\`\\`ts\nfastify.post('/users', {\n schema: { body: { type: 'object', required: ['email'], properties: { email: { type: 'string', format: 'email' } } } }\n}, handler)\n\\`\\`\\`\nRoutes without schema accept any body and bypass Fastify's fast-json-stringify serialization.`,\n },\n ],\n\n prisma: [\n {\n slug: \"prisma-no-disconnect-in-lambda\",\n type: \"gotcha\",\n tags: [\"prisma\", \"serverless\"],\n body: `Do NOT call prisma.$disconnect() inside Lambda/Edge function handlers.\n\nCalling $disconnect() after each request wastes the warm connection pool.\nCreate one PrismaClient per process (module-level singleton), not per request.\nDisconnecting is only needed when the process is shutting down.`,\n sensor: {\n pattern: \"\\\\$disconnect\\\\(\\\\)\",\n message: \"prisma.$disconnect() per request drains the warm connection pool in serverless — use a module-level PrismaClient singleton and only disconnect on shutdown.\",\n },\n },\n {\n slug: \"prisma-migrations-never-modify\",\n type: \"convention\",\n tags: [\"prisma\", \"database\", \"migrations\"],\n body: `Never modify an existing migration file — create a new one instead.\n\nPrisma tracks migration history by file hash. Editing a deployed migration\ncauses \\`migrate deploy\\` to fail with a checksum mismatch in production.\nAlways use \\`npx prisma migrate dev --name <description>\\` to create incremental migrations.`,\n },\n ],\n\n drizzle: [\n {\n slug: \"drizzle-always-await-queries\",\n type: \"gotcha\",\n tags: [\"drizzle\", \"async\"],\n body: `Drizzle queries are thenable but not auto-executed — always await them.\n\n\\`\\`\\`ts\n// ❌ Silently returns a query builder, never executes\nconst rows = db.select().from(users).where(eq(users.id, id));\n\n// ✅ Correct\nconst rows = await db.select().from(users).where(eq(users.id, id));\n\\`\\`\\``,\n },\n {\n slug: \"drizzle-schema-must-match-db\",\n type: \"gotcha\",\n tags: [\"drizzle\", \"migrations\"],\n body: `Drizzle does NOT auto-sync the schema to the database — you must run migrations explicitly.\n\nAfter changing schema.ts:\n1. \\`npx drizzle-kit generate\\` — creates migration SQL\n2. \\`npx drizzle-kit migrate\\` (or push in dev) — applies it\n\nWithout this, queries silently operate on stale column definitions and may return wrong data.`,\n },\n ],\n\n zustand: [\n {\n slug: \"zustand-select-slices-not-whole-store\",\n type: \"convention\",\n tags: [\"zustand\", \"performance\", \"react\"],\n body: `Always select specific slices — never subscribe to the whole store.\n\n\\`\\`\\`ts\n// ❌ Re-renders on any store change (even unrelated fields)\nconst store = useStore();\n\n// ✅ Re-renders only when count changes\nconst count = useStore((s) => s.count);\n\\`\\`\\`\n\nSubscribing to the whole store is the single most common Zustand performance mistake.`,\n sensor: {\n pattern: \"use[A-Z]\\\\w*Store\\\\(\\\\s*\\\\)\",\n message: \"A Zustand store hook called with no selector subscribes to the WHOLE store (re-renders on any change) — pass a slice selector: useStore(s => s.field).\",\n },\n },\n {\n slug: \"zustand-devtools-wrap-dev-only\",\n type: \"convention\",\n tags: [\"zustand\", \"devtools\", \"performance\"],\n body: `Wrap Zustand devtools middleware in a dev-only condition.\n\n\\`\\`\\`ts\nimport { devtools } from 'zustand/middleware';\n\nconst useStore = create(\n process.env.NODE_ENV === 'development'\n ? devtools(storeImpl, { name: 'AppStore' })\n : storeImpl,\n);\n\\`\\`\\`\n\nShipping devtools to production adds overhead and exposes store internals in bundle.`,\n },\n {\n slug: \"zustand-persist-hydration-ssr\",\n type: \"gotcha\",\n tags: [\"zustand\", \"ssr\", \"nextjs\", \"hydration\"],\n body: `Zustand persist middleware causes hydration mismatch in SSR (Next.js / Remix).\n\nThe server renders with empty state; the client rehydrates from localStorage.\nFix: use \\`skipHydration: true\\` and manually call \\`rehydrate()\\` after mount.\n\n\\`\\`\\`ts\n// In a useEffect or useLayoutEffect on the client:\nuseEffect(() => { useStore.persist.rehydrate(); }, []);\n\\`\\`\\``,\n },\n ],\n\n redux: [\n {\n slug: \"redux-toolkit-immer-mutate-or-return\",\n type: \"gotcha\",\n tags: [\"redux\", \"redux-toolkit\", \"immer\"],\n body: `In RTK createSlice reducers (Immer), you must EITHER mutate the draft OR return a new value — never both.\n\n\\`\\`\\`ts\n// ✅ Mutate draft (Immer converts to immutable update)\nstate.count += 1;\n\n// ✅ Return new value\nreturn { ...state, count: state.count + 1 };\n\n// ❌ Both — causes undefined state\nstate.count += 1;\nreturn state; // DON'T — Immer sees both a mutation and a return\n\\`\\`\\``,\n },\n {\n slug: \"redux-toolkit-rtk-query-over-thunk\",\n type: \"decision\",\n tags: [\"redux\", \"redux-toolkit\", \"data-fetching\"],\n body: `Use RTK Query for server data, not createAsyncThunk.\n\nRTK Query automatically handles: caching, loading/error states, cache invalidation, polling, optimistic updates.\ncreateAsyncThunk is for one-off side effects that don't fit the query/mutation model (e.g. file upload with progress).`,\n },\n {\n slug: \"redux-toolkit-normalize-nested-data\",\n type: \"convention\",\n tags: [\"redux\", \"redux-toolkit\", \"normalization\"],\n body: `Normalize nested API responses before storing in Redux — use createEntityAdapter.\n\nStoring deeply nested objects causes:\n- Redundant re-renders when any deeply nested field changes\n- Difficult update logic (deep merge)\n\n\\`\\`\\`ts\nconst usersAdapter = createEntityAdapter<User>();\nconst usersSlice = createSlice({\n name: 'users',\n initialState: usersAdapter.getInitialState(),\n reducers: { usersReceived: usersAdapter.setAll },\n});\n\\`\\`\\``,\n },\n ],\n\n reactquery: [\n {\n slug: \"tanstack-query-stale-time-default\",\n type: \"gotcha\",\n tags: [\"react-query\", \"tanstack-query\", \"caching\"],\n body: `By default, TanStack Query marks data as stale immediately (staleTime: 0) and refetches on every window focus.\n\nSet a reasonable staleTime to avoid unnecessary network requests:\n\n\\`\\`\\`ts\nuseQuery({\n queryKey: ['user', id],\n queryFn: () => getUser(id),\n staleTime: 5 * 60 * 1000, // 5 minutes\n})\n\\`\\`\\`\n\nSet globally via QueryClient defaultOptions for consistency.`,\n },\n {\n slug: \"tanstack-query-invalidate-after-mutation\",\n type: \"convention\",\n tags: [\"react-query\", \"tanstack-query\", \"mutations\"],\n body: `Always invalidate related queries after a mutation to keep the cache fresh.\n\n\\`\\`\\`ts\nuseMutation({\n mutationFn: createUser,\n onSuccess: () => queryClient.invalidateQueries({ queryKey: ['users'] }),\n})\n\\`\\`\\`\n\nSkipping invalidation causes the UI to show stale data after a write until the next background refetch.`,\n },\n {\n slug: \"tanstack-query-querykey-as-dependency\",\n type: \"convention\",\n tags: [\"react-query\", \"tanstack-query\"],\n body: `Treat the queryKey array as a dependency array — include all variables the queryFn depends on.\n\n\\`\\`\\`ts\n// ❌ Won't refetch when userId changes\nuseQuery({ queryKey: ['user'], queryFn: () => getUser(userId) });\n\n// ✅ Refetches automatically when userId changes\nuseQuery({ queryKey: ['user', userId], queryFn: () => getUser(userId) });\n\\`\\`\\``,\n },\n ],\n\n trpc: [\n {\n slug: \"trpc-always-validate-input-with-zod\",\n type: \"convention\",\n tags: [\"trpc\", \"validation\", \"security\"],\n body: `Always validate procedure inputs with Zod — tRPC infers types but doesn't enforce them at runtime without a schema.\n\n\\`\\`\\`ts\n// ❌ No runtime validation — input is 'unknown'\nt.procedure.query(({ input }) => getUser(input as string));\n\n// ✅ Validated and typed end-to-end\nt.procedure\n .input(z.object({ id: z.string().uuid() }))\n .query(({ input }) => getUser(input.id));\n\\`\\`\\``,\n },\n {\n slug: \"trpc-server-side-caller-for-ssr\",\n type: \"convention\",\n tags: [\"trpc\", \"nextjs\", \"ssr\"],\n body: `Use the server-side caller in Server Components / SSR — don't call tRPC over HTTP from the server.\n\n\\`\\`\\`ts\n// In Next.js App Router server component\nconst caller = appRouter.createCaller(await createContext());\nconst data = await caller.users.getAll(); // Direct function call, no HTTP\n\\`\\`\\`\n\nHTTP round-trips from server → server add latency and bypass auth context.`,\n },\n {\n slug: \"trpc-context-for-auth\",\n type: \"architecture\",\n tags: [\"trpc\", \"auth\"],\n body: `Put auth session on the tRPC context, not in individual procedures.\n\n\\`\\`\\`ts\n// createContext(): resolve session once, share across all procedures\nexport async function createContext({ req }: CreateNextContextOptions) {\n const session = await getServerSession(req);\n return { session, db };\n}\n\n// In procedure: ctx.session.user is always typed\nconst protectedProcedure = t.procedure.use(({ ctx, next }) => {\n if (!ctx.session?.user) throw new TRPCError({ code: 'UNAUTHORIZED' });\n return next({ ctx: { ...ctx, user: ctx.session.user } });\n});\n\\`\\`\\``,\n },\n ],\n\n mongoose: [\n {\n slug: \"mongoose-connection-singleton\",\n type: \"convention\",\n tags: [\"mongoose\", \"mongodb\", \"connection\", \"serverless\"],\n body: `Create one Mongoose connection at startup — never connect inside route handlers.\n\nIn serverless (Next.js, Vercel), cache the connection to reuse across warm invocations:\n\n\\`\\`\\`ts\nlet cached = (global as any).__mongoose ?? { conn: null, promise: null };\n\nexport async function dbConnect() {\n if (cached.conn) return cached.conn;\n if (!cached.promise) {\n cached.promise = mongoose.connect(process.env.MONGODB_URI!);\n }\n cached.conn = await cached.promise;\n (global as any).__mongoose = cached;\n return cached.conn;\n}\n\\`\\`\\``,\n },\n {\n slug: \"mongoose-lean-for-read-only\",\n type: \"convention\",\n tags: [\"mongoose\", \"performance\"],\n body: `Add .lean() to read-only queries to get plain JS objects instead of full Mongoose documents.\n\n\\`\\`\\`ts\n// ❌ Full Mongoose document — slow, heavy, has virtuals/methods\nconst users = await User.find({});\n\n// ✅ Plain JS object — 2-5x faster on large result sets\nconst users = await User.find({}).lean();\n\\`\\`\\`\n\n\\`.lean()\\` skips hydration into a Mongoose \\`Document\\`, so getters, virtuals, \\`toObject()\\` and\ninstance methods are gone. Never use \\`.lean()\\` when you then call \\`.save()\\` or instance methods.`,\n },\n {\n slug: \"mongoose-index-frequently-queried-fields\",\n type: \"gotcha\",\n tags: [\"mongoose\", \"mongodb\", \"performance\"],\n body: `Mongoose does NOT create indexes automatically unless you call syncIndexes() or ensureIndexes().\n\nDeclare indexes in the schema and sync them at startup:\n\n\\`\\`\\`ts\nUserSchema.index({ email: 1 }, { unique: true });\nUserSchema.index({ createdAt: -1 });\n\n// At startup (not per-request):\nawait User.syncIndexes();\n\\`\\`\\`\n\nMissing indexes cause full collection scans and timeouts at scale.`,\n },\n ],\n\n graphql: [\n {\n slug: \"graphql-n-plus-one-dataloader\",\n type: \"gotcha\",\n tags: [\"graphql\", \"performance\", \"n+1\"],\n body: `GraphQL resolvers cause N+1 database queries without DataLoader batching.\n\nEvery field resolver runs independently — fetching related data naively causes N queries for N items.\n\n\\`\\`\\`ts\n// In context, create one DataLoader per request (NOT per resolver call)\nconst userLoader = new DataLoader(async (ids: readonly string[]) =>\n User.findByIds(ids as string[])\n);\n\n// In resolver:\nauthor: (post) => userLoader.load(post.authorId),\n\\`\\`\\`\n\nA list of 100 posts with authors = 101 queries without DataLoader, 2 queries with it.`,\n },\n {\n slug: \"graphql-mask-internal-errors-in-production\",\n type: \"gotcha\",\n tags: [\"graphql\", \"security\", \"apollo\"],\n body: `Apollo Server exposes full error details (including stack traces) in development.\n\nIn production, mask internal errors to prevent leaking implementation details:\n\n\\`\\`\\`ts\nnew ApolloServer({\n formatError: (formattedError) => {\n if (formattedError.extensions?.code === 'INTERNAL_SERVER_ERROR') {\n return { message: 'Internal server error', extensions: { code: 'INTERNAL_SERVER_ERROR' } };\n }\n return formattedError;\n },\n});\n\\`\\`\\``,\n },\n {\n slug: \"graphql-depth-limit-and-complexity\",\n type: \"convention\",\n tags: [\"graphql\", \"security\", \"dos\"],\n body: `Add query depth and complexity limits to prevent DoS via deeply nested queries.\n\nWithout limits, a single query can request exponentially nested data and exhaust the server.\n\n\\`\\`\\`ts\nimport depthLimit from 'graphql-depth-limit';\nimport { createComplexityLimitRule } from 'graphql-validation-complexity';\n\nnew ApolloServer({\n validationRules: [\n depthLimit(7),\n createComplexityLimitRule(1000),\n ],\n});\n\\`\\`\\``,\n },\n ],\n\n fastapi: [\n {\n slug: \"fastapi-validate-with-pydantic\",\n type: \"convention\",\n tags: [\"fastapi\", \"python\", \"validation\"],\n body: `Declare request/response models with Pydantic — never read raw dict bodies.\n\n\\`\\`\\`py\nclass CreateUser(BaseModel):\n email: EmailStr\n age: int = Field(ge=0)\n\n@app.post(\"/users\")\ndef create(user: CreateUser): ...\n\\`\\`\\`\n\nPydantic validates and coerces at the boundary; raw \\`dict\\` bodies bypass validation and typing.`,\n },\n {\n slug: \"fastapi-no-blocking-io-in-async\",\n type: \"gotcha\",\n tags: [\"fastapi\", \"python\", \"async\", \"performance\"],\n body: `Never call blocking I/O (requests, time.sleep, sync DB drivers) inside an \\`async def\\` route.\n\nA blocking call inside the event loop freezes the whole worker for every concurrent request.\nUse an async client (httpx.AsyncClient, asyncpg) or run blocking work in a threadpool\n(\\`await run_in_threadpool(...)\\` / \\`def\\` route, which FastAPI runs in a threadpool).`,\n },\n {\n slug: \"fastapi-uvicorn-reload-not-in-prod\",\n type: \"gotcha\",\n tags: [\"fastapi\", \"python\", \"deployment\"],\n body: `\\`uvicorn.run(..., reload=True)\\` is a dev-only feature — never ship it to production.\n\nReload spawns a file-watcher process and disables multi-worker scaling.\nIn production run \\`uvicorn app:app --workers N\\` (no reload) behind a process manager.`,\n sensor: {\n pattern: \"uvicorn\\\\.run\\\\([^)]*reload\\\\s*=\\\\s*True\",\n message: \"uvicorn reload=True is dev-only — remove it from production entrypoints.\",\n },\n },\n {\n slug: \"fastapi-no-bare-except\",\n type: \"convention\",\n tags: [\"fastapi\", \"python\", \"error-handling\"],\n body: `Never use a bare \\`except:\\` — it swallows KeyboardInterrupt/SystemExit and hides real bugs.\n\nCatch the specific exception you expect, or \\`except Exception as e:\\` at most, and log it.`,\n sensor: {\n pattern: \"except\\\\s*:\",\n message: \"Bare `except:` swallows everything (incl. KeyboardInterrupt) — catch a specific exception type.\",\n },\n },\n ],\n\n django: [\n {\n slug: \"django-debug-false-in-prod\",\n type: \"gotcha\",\n tags: [\"django\", \"python\", \"security\", \"deployment\"],\n body: `\\`DEBUG = True\\` in production leaks stack traces, settings, and SQL to any visitor.\n\nDrive it from the environment and default to safe:\n\n\\`\\`\\`py\nDEBUG = os.environ.get(\"DJANGO_DEBUG\", \"0\") == \"1\"\n\\`\\`\\``,\n sensor: {\n pattern: \"DEBUG\\\\s*=\\\\s*True\",\n message: \"DEBUG = True leaks internals in production — read it from the environment and default to False.\",\n },\n },\n {\n slug: \"django-secret-key-from-env\",\n type: \"gotcha\",\n tags: [\"django\", \"python\", \"security\"],\n body: `Never hardcode SECRET_KEY in settings — load it from the environment.\n\nA committed SECRET_KEY lets anyone forge sessions and signed tokens.\n\n\\`\\`\\`py\nSECRET_KEY = os.environ[\"DJANGO_SECRET_KEY\"]\n\\`\\`\\``,\n sensor: {\n pattern: \"SECRET_KEY\\\\s*=\\\\s*[\\\"'][^\\\"']+[\\\"']\",\n message: \"Hardcoded SECRET_KEY — load it from os.environ instead of committing a literal.\",\n },\n },\n {\n slug: \"django-select-related-n-plus-one\",\n type: \"gotcha\",\n tags: [\"django\", \"python\", \"orm\", \"performance\"],\n body: `Accessing a ForeignKey in a loop triggers one query per row (N+1).\n\nUse \\`select_related\\` (FK / one-to-one, SQL JOIN) and \\`prefetch_related\\` (M2M / reverse FK):\n\n\\`\\`\\`py\nfor order in Order.objects.select_related(\"customer\").all():\n order.customer.name # no extra query\n\\`\\`\\``,\n },\n ],\n\n flask: [\n {\n slug: \"flask-no-debug-in-prod\",\n type: \"gotcha\",\n tags: [\"flask\", \"python\", \"security\", \"deployment\"],\n body: `\\`app.run(debug=True)\\` enables the Werkzeug debugger — remote code execution if exposed.\n\nNever ship debug mode. Run behind a real WSGI server (gunicorn/uwsgi) in production and\ndrive debug from the environment for local dev only.`,\n sensor: {\n pattern: \"app\\\\.run\\\\([^)]*debug\\\\s*=\\\\s*True\",\n message: \"Flask debug=True exposes the Werkzeug console (RCE) — never run it in production.\",\n },\n },\n {\n slug: \"flask-secret-key-from-env\",\n type: \"convention\",\n tags: [\"flask\", \"python\", \"security\"],\n body: `Load \\`SECRET_KEY\\` from the environment — never commit a literal.\n\n\\`\\`\\`py\napp.config[\"SECRET_KEY\"] = os.environ[\"SECRET_KEY\"]\n\\`\\`\\`\nA committed key lets anyone forge sessions and CSRF tokens.`,\n },\n {\n slug: \"flask-no-sql-string-interpolation\",\n type: \"gotcha\",\n tags: [\"flask\", \"python\", \"security\", \"sql-injection\"],\n body: `Never build SQL with f-strings/%-formatting — use parameterized queries.\n\n\\`\\`\\`py\n# ❌ SQL injection\ndb.execute(f\"SELECT * FROM users WHERE id = {uid}\")\n# ✅\ndb.execute(\"SELECT * FROM users WHERE id = %s\", (uid,))\n\\`\\`\\``,\n sensor: {\n pattern: \"execute\\\\(\\\\s*f[\\\"']\",\n message: \"SQL built with an f-string inside execute() — SQL injection risk; use a parameterized query: execute(\\\"… %s …\\\", (params,)).\",\n },\n },\n ],\n\n vue: [\n {\n slug: \"vue-v-html-xss\",\n type: \"gotcha\",\n tags: [\"vue\", \"security\", \"xss\"],\n body: `\\`v-html\\` renders raw HTML and bypasses Vue's escaping — an XSS sink for user content.\n\nOnly use it on trusted/sanitized content. Prefer text interpolation ({{ }}) or sanitize\nwith DOMPurify before binding.`,\n sensor: {\n pattern: \"v-html\",\n message: \"v-html renders unescaped HTML (XSS risk) — sanitize the value or use text interpolation.\",\n },\n },\n {\n slug: \"vue-key-in-v-for\",\n type: \"convention\",\n tags: [\"vue\", \"performance\"],\n body: `Always bind a stable \\`:key\\` on \\`v-for\\` — and never the loop index.\n\nIndex keys corrupt component state on reorder/insert, exactly like React. Use a stable id.`,\n },\n {\n slug: \"vue-props-are-readonly\",\n type: \"gotcha\",\n tags: [\"vue\", \"reactivity\"],\n body: `Never mutate a prop inside a child component — props are one-way (parent → child).\n\nMutating a prop breaks the data flow and warns in dev. Emit an event (\\`update:modelValue\\`)\nor copy the prop into local state, depending on intent.`,\n },\n ],\n\n spring: [\n {\n slug: \"spring-constructor-injection\",\n type: \"convention\",\n tags: [\"spring\", \"java\", \"di\", \"testing\"],\n body: `Prefer constructor injection over \\`@Autowired\\` field injection.\n\nConstructor injection makes dependencies explicit, allows \\`final\\` fields, and lets you\ninstantiate the class in tests without a Spring context. Field injection hides dependencies\nand forces reflection-based test setup.`,\n },\n {\n slug: \"spring-no-cors-wildcard\",\n type: \"gotcha\",\n tags: [\"spring\", \"java\", \"security\", \"cors\"],\n body: `\\`@CrossOrigin(origins = \"*\")\\` (or wildcard CORS config) allows any site to call your API.\n\nCombined with credentials it leaks authenticated data cross-origin. Whitelist explicit origins.`,\n sensor: {\n pattern: \"@CrossOrigin\\\\([^)]*\\\\*\",\n message: \"Wildcard CORS (@CrossOrigin origins=\\\"*\\\") lets any site call your API — whitelist explicit origins.\",\n },\n },\n {\n slug: \"spring-no-field-secrets\",\n type: \"convention\",\n tags: [\"spring\", \"java\", \"security\", \"config\"],\n body: `Keep secrets in externalized config (env / vault / application.yml placeholders), not in source.\n\n\\`\\`\\`java\n@Value(\"\\${app.api-key}\") private String apiKey; // resolved from env, not hardcoded\n\\`\\`\\``,\n },\n ],\n\n go: [\n {\n slug: \"go-check-every-error\",\n type: \"convention\",\n tags: [\"go\", \"error-handling\"],\n body: `Check every returned error — never discard it with \\`_\\`.\n\n\\`\\`\\`go\n// ❌ silently ignores failure\nval, _ := doThing()\n\n// ✅\nval, err := doThing()\nif err != nil {\n return fmt.Errorf(\"doThing: %w\", err)\n}\n\\`\\`\\`\nWrap with \\`%w\\` to preserve the chain for errors.Is/As.`,\n },\n {\n slug: \"go-defer-close-after-error-check\",\n type: \"gotcha\",\n tags: [\"go\", \"resources\"],\n body: `Place \\`defer rows.Close()\\` (or file/body Close) AFTER checking the open error, not before.\n\n\\`\\`\\`go\nrows, err := db.Query(q)\nif err != nil { return err }\ndefer rows.Close() // only reached when rows is non-nil\n\\`\\`\\`\nDeferring before the error check can call Close on a nil resource and panic.`,\n },\n {\n slug: \"go-context-first-param\",\n type: \"convention\",\n tags: [\"go\", \"context\", \"api-design\"],\n body: `context.Context is always the FIRST parameter and is never stored in a struct.\n\n\\`\\`\\`go\nfunc Fetch(ctx context.Context, id string) (*User, error)\n\\`\\`\\`\nPass it explicitly down the call chain so cancellation and deadlines propagate.`,\n },\n ],\n\n tailwind: [\n {\n slug: \"tailwind-content-paths-required\",\n type: \"gotcha\",\n tags: [\"tailwind\", \"css\", \"build\"],\n body: `Classes only ship if their files are listed in \\`content\\` (tailwind.config). Miss a path and the styles silently vanish in production.\n\n\\`\\`\\`js\ncontent: [\"./src/**/*.{js,ts,jsx,tsx,mdx}\"]\n\\`\\`\\`\nNever build class names dynamically by string concatenation (\\`\\`text-\\${color}-500\\`\\`) — Tailwind's scanner can't see them and they get purged. Use full literal class names or a safelist.`,\n },\n {\n slug: \"tailwind-no-apply-everywhere\",\n type: \"convention\",\n tags: [\"tailwind\", \"css\", \"maintainability\"],\n body: `Don't recreate component CSS with \\`@apply\\` for everything — it defeats the utility-first model and grows the bundle.\n\nPrefer utility classes in markup; reach for \\`@apply\\` only for small, truly repeated primitives (e.g. \\`.btn\\`). For real components, extract a React/Vue component, not a CSS class.`,\n },\n ],\n\n vite: [\n {\n slug: \"vite-env-prefix-client-exposure\",\n type: \"gotcha\",\n tags: [\"vite\", \"security\", \"env\"],\n body: `Only \\`import.meta.env.VITE_*\\` variables are exposed to client code — and they are bundled into the shipped JS.\n\nNever give a secret a \\`VITE_\\` prefix: it ends up readable in the browser. Keep server secrets unprefixed and read them server-side only.`,\n sensor: {\n pattern: \"VITE_[A-Z0-9_]*(SECRET|PRIVATE|TOKEN|PASSWORD|API_?KEY)\",\n message: \"A VITE_ env var with a secret-looking name is bundled into client JS — drop the VITE_ prefix and read it server-side.\",\n },\n },\n {\n slug: \"vite-no-process-env\",\n type: \"gotcha\",\n tags: [\"vite\", \"env\"],\n body: `\\`process.env\\` is not available in Vite client code — use \\`import.meta.env\\`.\n\nReferencing \\`process.env.FOO\\` in browser code throws \\`process is not defined\\` at runtime (or is statically undefined). Vite only replaces \\`import.meta.env.*\\`.`,\n },\n ],\n\n sveltekit: [\n {\n slug: \"sveltekit-env-static-private-vs-public\",\n type: \"gotcha\",\n tags: [\"sveltekit\", \"security\", \"env\"],\n body: `Import secrets from \\`$env/static/private\\` (or \\`$env/dynamic/private\\`) — never \\`$env/static/public\\`.\n\n\\`$env/*/public\\` (and any \\`PUBLIC_\\`-prefixed var) is shipped to the browser. SvelteKit refuses to import a private module into client code, but a value moved to a PUBLIC_ name is silently exposed.`,\n },\n {\n slug: \"sveltekit-load-runs-on-server-and-client\",\n type: \"gotcha\",\n tags: [\"sveltekit\", \"load\", \"ssr\"],\n body: `A universal \\`load\\` (in \\`+page.js\\`) runs on BOTH server and client. Only \\`+page.server.js\\` / \\`+layout.server.js\\` loads are server-only.\n\nPut DB access, secrets, and private fetches in \\`.server\\` load functions. Universal loads must be safe to run in the browser.`,\n },\n ],\n\n astro: [\n {\n slug: \"astro-islands-need-client-directive\",\n type: \"gotcha\",\n tags: [\"astro\", \"hydration\", \"islands\"],\n body: `Components are server-rendered to static HTML by default — interactivity requires a \\`client:*\\` directive.\n\n\\`\\`\\`astro\n<Counter client:load />\n<Counter client:visible />\n\\`\\`\\`\nWithout a \\`client:\\` directive, event handlers and hooks simply don't run in the browser.`,\n },\n {\n slug: \"astro-frontmatter-runs-on-server\",\n type: \"convention\",\n tags: [\"astro\", \"ssr\"],\n body: `The component frontmatter (the code fence \\`---\\`) runs on the server at build/request time, not in the browser.\n\nFetch data and read secrets there freely — it never ships to the client. Don't expect \\`window\\`/\\`document\\` in the frontmatter; guard browser APIs inside \\`client:\\`-hydrated components or \\`<script>\\` tags.`,\n },\n ],\n\n typescript: [\n {\n slug: \"typescript-no-any-prefer-unknown\",\n type: \"convention\",\n tags: [\"typescript\", \"types\"],\n body: `Avoid \\`any\\` — it disables type-checking for everything it touches and spreads silently. Use \\`unknown\\` and narrow, or a precise type.\n\nEnable \\`\"strict\": true\\` (and \\`noImplicitAny\\`) in tsconfig. \\`unknown\\` forces a check before use; \\`any\\` forces nothing.`,\n sensor: {\n pattern: \":\\\\s*any\\\\b\",\n message: \"Explicit `any` disables type-checking — use `unknown` + narrowing or a precise type.\",\n },\n },\n {\n slug: \"typescript-no-non-null-assertion-on-untrusted\",\n type: \"gotcha\",\n tags: [\"typescript\", \"types\", \"safety\"],\n body: `The non-null assertion (\\`value!\\`) silences the compiler but does NOT check at runtime — it just crashes later if the value is actually null/undefined.\n\nPrefer a real guard (\\`if (!value) throw…\\`) or optional chaining. Reserve \\`!\\` for cases the compiler can't see but you can prove (e.g. just-initialized fields).`,\n },\n ],\n\n monorepo: [\n {\n slug: \"monorepo-pin-internal-deps-workspace-protocol\",\n type: \"convention\",\n tags: [\"monorepo\", \"turborepo\", \"nx\", \"pnpm\"],\n body: `Reference internal packages with the workspace protocol (\\`\"@scope/pkg\": \"workspace:*\"\\`), not a version range.\n\nA real version range makes the package manager fetch the published version from the registry instead of linking the local source — you end up testing stale code.`,\n },\n {\n slug: \"monorepo-declare-task-inputs-outputs\",\n type: \"gotcha\",\n tags: [\"monorepo\", \"turborepo\", \"nx\", \"caching\"],\n body: `Task caching is only correct if inputs/outputs are declared. An undeclared output (e.g. a \\`dist/\\` folder) means a cache hit restores nothing and downstream tasks break.\n\nIn Turborepo declare \\`outputs\\` per task in \\`turbo.json\\`; in Nx declare \\`outputs\\` in target options. Missing/incorrect \\`outputs\\` is the #1 cause of \"works locally, broken in CI\" cache bugs.`,\n },\n ],\n\n laravel: [\n {\n slug: \"laravel-eloquent-n-plus-one\",\n type: \"gotcha\",\n tags: [\"laravel\", \"php\", \"eloquent\", \"performance\"],\n body: `Accessing a relationship in a loop triggers one query per row (N+1). Eager-load with \\`with()\\`.\n\n\\`\\`\\`php\nforeach (Post::with('author')->get() as $post) { echo $post->author->name; }\n\\`\\`\\`\nEnable \\`Model::preventLazyLoading()\\` in dev to catch these.`,\n },\n {\n slug: \"laravel-mass-assignment-fillable\",\n type: \"gotcha\",\n tags: [\"laravel\", \"php\", \"security\"],\n body: `\\`Model::create($request->all())\\` is a mass-assignment hole unless \\`$fillable\\` is set — a user can set columns you never intended (e.g. \\`is_admin\\`).\n\nDefine \\`$fillable\\` (allow-list) on every model and validate the request before creating.`,\n },\n ],\n\n rails: [\n {\n slug: \"rails-n-plus-one-includes\",\n type: \"gotcha\",\n tags: [\"rails\", \"ruby\", \"activerecord\", \"performance\"],\n body: `Calling an association inside a loop triggers N+1 queries. Use \\`includes\\` to eager-load.\n\n\\`\\`\\`ruby\nPost.includes(:author).each { |p| puts p.author.name }\n\\`\\`\\`\nAdd the \\`bullet\\` gem in development to detect them automatically.`,\n },\n {\n slug: \"rails-strong-parameters\",\n type: \"convention\",\n tags: [\"rails\", \"ruby\", \"security\"],\n body: `Never pass \\`params\\` straight to \\`update\\`/\\`create\\` — always go through strong parameters (\\`params.require(:user).permit(:name, :email)\\`).\n\nPermitting everything (or skipping it) lets a request set protected attributes like \\`admin\\`/\\`role\\`.`,\n },\n ],\n\n dotnet: [\n {\n slug: \"dotnet-async-no-blocking-result-wait\",\n type: \"gotcha\",\n tags: [\"dotnet\", \"csharp\", \"async\", \"deadlock\"],\n body: `Never block on async with \\`.Result\\` or \\`.Wait()\\` — it deadlocks under a synchronization context (ASP.NET classic, UI).\n\nMake the call chain async all the way up; use \\`ConfigureAwait(false)\\` in library code.`,\n },\n {\n slug: \"dotnet-httpclient-reuse\",\n type: \"convention\",\n tags: [\"dotnet\", \"csharp\", \"resources\"],\n body: `Don't create a new \\`HttpClient\\` per request — reuse one (or use \\`IHttpClientFactory\\`). Creating + disposing per call exhausts sockets (\\`SocketException\\` under load).\n\nWrap other \\`IDisposable\\` resources (DbConnection, streams) in \\`using\\` so they're released deterministically.`,\n },\n ],\n\n docker: [\n {\n slug: \"docker-no-secrets-in-image-layers\",\n type: \"gotcha\",\n tags: [\"docker\", \"security\", \"secrets\"],\n body: `\\`ENV\\`/\\`ARG\\` secrets and \\`COPY .env\\` are baked into image layers — anyone with the image can read them via \\`docker history\\`, even if a later layer deletes the file.\n\nUse build secrets (\\`RUN --mount=type=secret\\`) or inject at runtime. Add \\`.env\\` to \\`.dockerignore\\`.`,\n },\n {\n slug: \"docker-pin-base-image-and-nonroot\",\n type: \"convention\",\n tags: [\"docker\", \"kubernetes\", \"security\"],\n body: `Pin a specific base image tag (not \\`:latest\\`) for reproducible builds, and run as a non-root user (\\`USER app\\`).\n\nContainers default to root; a container escape then runs as host root. In Kubernetes set \\`securityContext.runAsNonRoot: true\\`. Use multi-stage builds to keep build tooling out of the runtime image.`,\n },\n ],\n\n};\n\n/**\n * Footer appended to every seeded pack memory. Keeps the corpus honest: this is\n * generic framework guidance, not repo-specific knowledge. Anchoring it to a real\n * file (or replacing it) is what turns it into high-signal context.\n */\nconst SEED_FOOTER = (stack: string): string =>\n `> _Seeded by \\`hivelore init\\` from the **${stack}** stack pack — generic guidance, not repo-specific. ` +\n `Anchor it to a real file or replace it with a repo-specific note to raise it above background priority._`;\n\nexport const SUPPORTED_STACKS = Object.keys(PACKS) as StackName[];\n\nexport function isValidStack(name: string): name is StackName {\n return name in PACKS;\n}\n\n/** Auto-detect which stacks are present from a package.json dep map. */\nexport function autoDetectStacks(deps: Record<string, string>): StackName[] {\n const detected: StackName[] = [];\n const stackDetectors: [StackName, string[]][] = [\n [\"nestjs\", [\"@nestjs/core\"]],\n [\"nextjs\", [\"next\"]],\n [\"remix\", [\"@remix-run/react\", \"@remix-run/node\"]],\n [\"react\", [\"react\"]],\n [\"express\", [\"express\"]],\n [\"fastify\", [\"fastify\"]],\n [\"prisma\", [\"@prisma/client\", \"prisma\"]],\n [\"drizzle\", [\"drizzle-orm\"]],\n [\"zustand\", [\"zustand\"]],\n [\"redux\", [\"@reduxjs/toolkit\", \"redux\"]],\n [\"reactquery\", [\"@tanstack/react-query\", \"react-query\"]],\n [\"trpc\", [\"@trpc/server\", \"@trpc/client\"]],\n [\"mongoose\", [\"mongoose\"]],\n [\"graphql\", [\"@apollo/client\", \"@apollo/server\", \"apollo-server\", \"graphql\"]],\n [\"tailwind\", [\"tailwindcss\"]],\n [\"vite\", [\"vite\"]],\n [\"sveltekit\", [\"@sveltejs/kit\"]],\n [\"astro\", [\"astro\"]],\n [\"typescript\", [\"typescript\"]],\n [\"monorepo\", [\"turbo\", \"nx\", \"@nrwl/workspace\", \"@nx/workspace\"]],\n ];\n for (const [stack, signals] of stackDetectors) {\n if (signals.some((s) => s in deps)) detected.push(stack);\n }\n // Deduplicate: avoid react when next/remix already detected\n if (detected.includes(\"nextjs\") || detected.includes(\"remix\")) {\n return detected.filter((s) => s !== \"react\");\n }\n return detected;\n}\n\nexport interface SeedPackResult {\n memories: number;\n sensors: number;\n}\n\n/** Seed memory pack files on disk. Returns counts of memories and sensors written. */\nexport async function seedStackPack(\n haivePaths: HaivePaths,\n stack: StackName,\n): Promise<SeedPackResult> {\n const memories = PACKS[stack];\n if (!memories) return { memories: 0, sensors: 0 };\n\n await mkdir(haivePaths.teamDir, { recursive: true });\n\n // Dedup by a STABLE signature, not the filename. `buildFrontmatter` stamps today's date into\n // the id, so a cross-day re-seed used to produce a duplicate (e.g. the typescript pack appeared\n // twice after a slug change). We skip a pack memory if the corpus already contains one with the\n // same `topic` OR the same date-insensitive id signature (`type-slug`), so re-seeding is idempotent.\n const DATE_PREFIX = /^\\d{4}-\\d{2}-\\d{2}-/;\n const existingTopics = new Set<string>();\n const existingSignatures = new Set<string>();\n if (existsSync(haivePaths.memoriesDir)) {\n for (const { memory } of await loadMemoriesFromDir(haivePaths.memoriesDir)) {\n if (memory.frontmatter.topic) existingTopics.add(memory.frontmatter.topic);\n existingSignatures.add(memory.frontmatter.id.replace(DATE_PREFIX, \"\"));\n }\n }\n\n let memCount = 0;\n let sensorCount = 0;\n for (const mem of memories) {\n // Quality floor: never seed low-value starter content. A pack memory earns its place only if it\n // carries a sensor (enforceable) or is a concrete, non-generic trap. Guards against the corpus\n // being polluted with guessable \"best practice\" an agent already knows.\n if (!meetsSeedQualityFloor(mem.body, Boolean(mem.sensor))) continue;\n const sensor: Sensor | undefined = mem.sensor\n ? {\n kind: \"regex\",\n pattern: mem.sensor.pattern,\n ...(mem.sensor.flags ? { flags: mem.sensor.flags } : {}),\n paths: mem.sensor.paths ?? [],\n message: mem.sensor.message,\n severity: \"warn\",\n autogen: false,\n last_fired: null,\n }\n : undefined;\n // Avoid doubling the stack word in the generated name/slug (e.g. a pack slug already\n // prefixed with the stack → \"typescript-typescript-no-any\" → \"Typescript Typescript …\").\n const combinedSlug = mem.slug === stack || mem.slug.startsWith(`${stack}-`)\n ? mem.slug\n : `${stack}-${mem.slug}`;\n // Stable upsert key: survives date and slug-formatting changes across versions.\n const topic = `stack-pack:${stack}:${mem.slug}`;\n const signature = `${mem.type}-${combinedSlug}`;\n if (existingTopics.has(topic) || existingSignatures.has(signature)) continue; // already seeded\n const fm = buildFrontmatter({\n type: mem.type,\n slug: combinedSlug,\n scope: \"team\",\n status: \"validated\",\n // STACK_PACK_TAG marks this as generic seed knowledge so briefing ranking\n // keeps it at `background` priority until it earns a repo-specific anchor.\n tags: [...mem.tags, STACK_PACK_TAG],\n topic,\n ...(sensor ? { sensor } : {}),\n });\n const filePath = memoryFilePath(haivePaths, \"team\", fm.id);\n if (existsSync(filePath)) continue; // belt-and-suspenders for same-day re-runs\n // Give the seed a clean, human title up front so the corpus normalizer doesn't synthesize an\n // ugly one from the id (e.g. \"Convention Typescript No Any Prefer Unknown\"). Pre-empting it with\n // a real \"<Stack>: <Rule>\" H1 keeps briefings readable.\n const ruleSlug = combinedSlug.startsWith(`${stack}-`) ? combinedSlug.slice(stack.length + 1) : combinedSlug;\n const titleCase = (s: string): string =>\n s.split(\"-\").filter(Boolean).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(\" \");\n const heading = `${titleCase(stack)}: ${titleCase(ruleSlug)}`;\n const titledBody = /^#{1,3}\\s+\\S/m.test(mem.body.trim()) ? mem.body : `# ${heading}\\n\\n${mem.body}`;\n const content = serializeMemory({ frontmatter: fm, body: `${titledBody}\\n\\n${SEED_FOOTER(stack)}` });\n await mkdir(path.dirname(filePath), { recursive: true });\n await writeFile(filePath, content, \"utf8\");\n existingTopics.add(topic);\n existingSignatures.add(signature);\n memCount++;\n if (sensor) sensorCount++;\n }\n return { memories: memCount, sensors: sensorCount };\n}\n","import { mkdir, writeFile, chmod, readFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport { findProjectRoot } from \"@hivelore/core\";\nimport { ui } from \"../utils/ui.js\";\nimport {\n defaultClaudeSettingsPath,\n installClaudeHooksAtPath,\n uninstallClaudeHooksAtPath,\n} from \"../utils/claude-hooks.js\";\n\ninterface InstallHooksOptions {\n dir?: string;\n force?: boolean;\n scope?: \"user\" | \"project\";\n uninstall?: boolean;\n settings?: string;\n}\n\ntype Target = \"git\" | \"claude\";\n\nconst HOOK_MARKER = \"# Hivelore auto-generated\";\n\n// Every generated hook resolves the CLI through the same probe: the new `hivelore` binary\n// first, the legacy `haive` alias next (older global installs), then local node_modules bins.\nconst RESOLVE_CLI = `_hivelore() {\n if command -v hivelore >/dev/null 2>&1; then hivelore \"$@\"\n elif command -v haive >/dev/null 2>&1; then haive \"$@\"\n elif [ -x ./node_modules/.bin/hivelore ]; then ./node_modules/.bin/hivelore \"$@\"\n elif [ -x ./node_modules/.bin/haive ]; then ./node_modules/.bin/haive \"$@\"\n else return 0\n fi\n}`;\n\nconst POST_MERGE_BODY = `#!/bin/sh\n${HOOK_MARKER} — keep this block to allow upgrades. Hand-edit anything outside it.\n\n# After a merge or pull, refresh memory anchors and auto-promote eligible\n# memories so that everyone on this branch sees consistent confidence levels.\n${RESOLVE_CLI}\n\n_hivelore sync --quiet --since ORIG_HEAD || true\n`;\n\nconst PRE_PUSH_BODY = `#!/bin/sh\n${HOOK_MARKER} — keep this block to allow upgrades. Hand-edit anything outside it.\n\n# Before pushing, run the Hivelore workflow policy gate. This is blocking by default:\n# initialized projects should not accept AI changes that bypass Hivelore.\n${RESOLVE_CLI}\n\n_hivelore enforce check --stage pre-push --dir . || exit $?\n\n# Remind agent to save session recap if env var is set\nif [ \"\\$HAIVE_SESSION_REMINDER\" = \"1\" ]; then\n echo \"hivelore: session active — remember to call mem_session_end before closing.\" >&2\nfi\n\nexit 0\n`;\n\nconst HOOKS: { name: string; body: string }[] = [\n { name: \"post-merge\", body: POST_MERGE_BODY },\n { name: \"post-rewrite\", body: POST_MERGE_BODY },\n { name: \"pre-push\", body: PRE_PUSH_BODY },\n {\n name: \"pre-commit\",\n body: `#!/bin/sh\n${HOOK_MARKER} — keep this block to allow upgrades. Hand-edit anything outside it.\n${RESOLVE_CLI}\n\n_hivelore enforce check --stage pre-commit --dir . || exit $?\n`,\n },\n];\n\nasync function installGitHooks(opts: InstallHooksOptions): Promise<void> {\n const root = findProjectRoot(opts.dir);\n const gitDir = path.join(root, \".git\");\n if (!existsSync(gitDir)) {\n ui.error(`No .git directory at ${root}.`);\n process.exitCode = 1;\n return;\n }\n const hooksDir = path.join(gitDir, \"hooks\");\n await mkdir(hooksDir, { recursive: true });\n\n let installed = 0;\n let skipped = 0;\n for (const { name, body } of HOOKS) {\n const file = path.join(hooksDir, name);\n if (existsSync(file) && !opts.force) {\n const existing = await readFile(file, \"utf8\");\n if (!existing.includes(HOOK_MARKER)) {\n ui.warn(`${name} already exists and was not written by Hivelore. Re-run with --force to overwrite.`);\n skipped++;\n continue;\n }\n }\n await writeFile(file, body, \"utf8\");\n await chmod(file, 0o755);\n installed++;\n }\n ui.success(`Installed ${installed} git hook(s) in .git/hooks/${skipped ? `, skipped ${skipped}` : \"\"}`);\n ui.info(\"post-merge: hivelore sync runs after every pull/merge.\");\n ui.info(\"pre-commit: hivelore enforce check blocks unsafe staged changes.\");\n ui.info(\"pre-push: hivelore enforce check blocks pushes that bypass briefing/session recap policy.\");\n}\n\nasync function installClaudeHooks(opts: InstallHooksOptions): Promise<void> {\n const root = findProjectRoot(opts.dir);\n const scope = opts.scope ?? \"user\";\n const settingsPath = opts.settings ?? defaultClaudeSettingsPath(scope, root);\n\n if (opts.uninstall) {\n const result = await uninstallClaudeHooksAtPath(settingsPath);\n ui.success(`Removed Hivelore hooks from ${result.settingsPath}`);\n return;\n }\n\n try {\n const result = await installClaudeHooksAtPath(settingsPath);\n if (result.created) {\n ui.success(`Created ${result.settingsPath} with Hivelore enforcement hooks`);\n } else {\n ui.success(`Patched ${result.settingsPath} (existing user hooks preserved)`);\n }\n } catch (err) {\n ui.error(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n return;\n }\n\n ui.info(\"SessionStart hook: `hivelore enforce session-start` injects briefing context\");\n ui.info(\"PreToolUse hook: blocks Edit/Write/dangerous Bash until briefing is loaded\");\n ui.info(\"PostToolUse hook: `hivelore observe` captures Edit/Write/Bash activity\");\n ui.info(\"SessionEnd hook: `hivelore session end --auto --quiet` distills observations\");\n ui.info(\" into a session_recap memory at session close\");\n ui.info(\"Restart Claude Code (or open a new conversation) for the hooks to take effect.\");\n ui.info(`Run \\`hivelore install-hooks claude --uninstall\\` to remove.`);\n}\n\nexport function registerInstallHooks(program: Command): void {\n program\n .command(\"install-hooks [target]\")\n .description(\n \"Install Hivelore hooks (same effect as `hivelore enforce install`, kept for back-compat). Targets:\\n\\n\" +\n \" git (default) post-merge / post-rewrite / pre-push for hivelore sync + precommit\\n\" +\n \" claude SessionStart + PreToolUse + PostToolUse + SessionEnd hooks\\n\" +\n \" for briefing injection, pre-edit blocking, and capture (Claude Code only)\\n\\n\" +\n \" Examples:\\n\" +\n \" hivelore install-hooks # git hooks (legacy default)\\n\" +\n \" hivelore install-hooks git\\n\" +\n \" hivelore install-hooks claude\\n\" +\n \" hivelore install-hooks claude --scope project\\n\" +\n \" hivelore install-hooks claude --uninstall\\n\",\n )\n .option(\"-d, --dir <dir>\", \"project root\")\n .option(\"--force\", \"overwrite existing hooks (git target only)\")\n .option(\"--scope <scope>\", \"claude target: 'user' (~/.claude) or 'project' (.claude/)\", \"user\")\n .option(\"--uninstall\", \"remove previously installed Hivelore hooks (claude target only)\")\n .option(\"--settings <path>\", \"explicit path to settings.json (claude target only)\")\n .action(async (target: string | undefined, opts: InstallHooksOptions) => {\n const t = (target ?? \"git\").toLowerCase() as Target | string;\n if (t === \"git\") {\n await installGitHooks(opts);\n } else if (t === \"claude\") {\n await installClaudeHooks(opts);\n } else {\n ui.error(`Unknown target: ${target}. Available: git, claude`);\n process.exitCode = 1;\n }\n });\n}\n","/**\n * Patch a Claude Code settings.json file with Hivelore enforcement hooks.\n *\n * Claude Code's hook format:\n * { \"hooks\": { \"PostToolUse\": [{ \"matcher\": \"...\", \"hooks\": [{ \"type\":\"command\", \"command\":\"...\" }] }] } }\n *\n * We add Hivelore-marked entries so we can find and replace them on re-runs:\n * - SessionStart → `hivelore enforce session-start`\n * - PreToolUse → `hivelore enforce pre-tool-use` (matcher: Edit|Write|Bash)\n * - PostToolUse → `hivelore observe` (passive capture)\n * - SessionEnd → `hivelore session end --quiet --auto`\n *\n * Existing user-defined hooks are preserved untouched.\n */\nimport { existsSync } from \"node:fs\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nexport const HAIVE_HOOK_TAG = \"haive-enforcement\";\n\ninterface ClaudeHookEntry {\n type: \"command\";\n command: string;\n /** Hivelore marker so we can identify our own entries on re-runs. */\n haive_tag?: string;\n}\n\ninterface ClaudeHookGroup {\n matcher?: string;\n hooks: ClaudeHookEntry[];\n}\n\ninterface ClaudeSettings {\n hooks?: Record<string, ClaudeHookGroup[]>;\n [key: string]: unknown;\n}\n\nconst POST_TOOL_USE_GROUP: ClaudeHookGroup = {\n matcher: \"Edit|Write|Bash\",\n hooks: [\n {\n type: \"command\",\n command: \"hivelore observe\",\n haive_tag: HAIVE_HOOK_TAG,\n },\n ],\n};\n\nconst PRE_TOOL_USE_GROUP: ClaudeHookGroup = {\n matcher: \"Edit|Write|MultiEdit|NotebookEdit|Bash\",\n hooks: [\n {\n type: \"command\",\n command: \"hivelore enforce pre-tool-use\",\n haive_tag: HAIVE_HOOK_TAG,\n },\n ],\n};\n\nconst SESSION_START_GROUP: ClaudeHookGroup = {\n hooks: [\n {\n type: \"command\",\n command: \"hivelore enforce session-start\",\n haive_tag: HAIVE_HOOK_TAG,\n },\n ],\n};\n\nconst SESSION_END_GROUP: ClaudeHookGroup = {\n hooks: [\n {\n type: \"command\",\n command: \"hivelore session end --quiet --auto\",\n haive_tag: HAIVE_HOOK_TAG,\n },\n ],\n};\n\nfunction dropHaiveGroups(groups: ClaudeHookGroup[]): ClaudeHookGroup[] {\n return groups.filter(\n (g) => !g.hooks.some((h) => h.haive_tag === HAIVE_HOOK_TAG),\n );\n}\n\nexport function patchClaudeSettings(input: ClaudeSettings | null): ClaudeSettings {\n const settings: ClaudeSettings = input ? { ...input } : {};\n const hooks = settings.hooks ? { ...settings.hooks } : {};\n hooks.SessionStart = [\n ...dropHaiveGroups(hooks.SessionStart ?? []),\n SESSION_START_GROUP,\n ];\n hooks.PreToolUse = [\n ...dropHaiveGroups(hooks.PreToolUse ?? []),\n PRE_TOOL_USE_GROUP,\n ];\n hooks.PostToolUse = [\n ...dropHaiveGroups(hooks.PostToolUse ?? []),\n POST_TOOL_USE_GROUP,\n ];\n hooks.SessionEnd = [\n ...dropHaiveGroups(hooks.SessionEnd ?? []),\n SESSION_END_GROUP,\n ];\n settings.hooks = hooks;\n return settings;\n}\n\nexport function unpatchClaudeSettings(input: ClaudeSettings | null): ClaudeSettings {\n const settings: ClaudeSettings = input ? { ...input } : {};\n if (!settings.hooks) return settings;\n const hooks = { ...settings.hooks };\n for (const [event, groups] of Object.entries(hooks)) {\n const cleaned = dropHaiveGroups(groups);\n if (cleaned.length === 0) {\n delete hooks[event];\n } else {\n hooks[event] = cleaned;\n }\n }\n settings.hooks = hooks;\n if (Object.keys(hooks).length === 0) delete settings.hooks;\n return settings;\n}\n\nexport interface ClaudeHooksInstallResult {\n settingsPath: string;\n created: boolean;\n}\n\nexport async function installClaudeHooksAtPath(\n settingsPath: string,\n): Promise<ClaudeHooksInstallResult> {\n let raw: ClaudeSettings | null = null;\n let created = false;\n if (existsSync(settingsPath)) {\n try {\n raw = JSON.parse(await readFile(settingsPath, \"utf8\")) as ClaudeSettings;\n } catch {\n throw new Error(`${settingsPath} exists but is not valid JSON. Fix it manually first.`);\n }\n } else {\n created = true;\n }\n const patched = patchClaudeSettings(raw);\n await mkdir(path.dirname(settingsPath), { recursive: true });\n await writeFile(settingsPath, JSON.stringify(patched, null, 2) + \"\\n\", \"utf8\");\n return { settingsPath, created };\n}\n\nexport async function uninstallClaudeHooksAtPath(\n settingsPath: string,\n): Promise<ClaudeHooksInstallResult> {\n if (!existsSync(settingsPath)) {\n return { settingsPath, created: false };\n }\n const raw = JSON.parse(await readFile(settingsPath, \"utf8\")) as ClaudeSettings;\n const cleaned = unpatchClaudeSettings(raw);\n await writeFile(settingsPath, JSON.stringify(cleaned, null, 2) + \"\\n\", \"utf8\");\n return { settingsPath, created: false };\n}\n\nexport function defaultClaudeSettingsPath(scope: \"user\" | \"project\", projectRoot: string): string {\n if (scope === \"user\") {\n const home = process.env.HOME ?? process.env.USERPROFILE ?? \"\";\n return path.join(home, \".claude\", \"settings.json\");\n }\n return path.join(projectRoot, \".claude\", \"settings.local.json\");\n}\n","/**\n * `hivelore observe` — passive-capture endpoint for Claude Code's PostToolUse hook.\n *\n * Reads a single JSON payload on stdin (Claude Code's hook protocol) and appends\n * a compact observation record to `.ai/.cache/observations.jsonl`. The session-end\n * step later distills these records into proposed memories.\n *\n * Critical properties:\n * - exit 0 ALWAYS (a hook that errors interrupts the user's flow)\n * - bounded I/O (caps stdin read; no LLM call; no network)\n * - tolerant to missing .ai/ (silently no-op if haive isn't initialized here)\n */\nimport { appendFile, mkdir } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport { findProjectRoot, resolveHaivePaths } from \"@hivelore/core\";\n\nconst MAX_STDIN_BYTES = 256 * 1024; // 256 KB cap\nconst TRUNCATE_FIELD = 800;\n\ninterface HookPayload {\n tool_name?: string;\n tool_input?: Record<string, unknown>;\n tool_response?: Record<string, unknown> | string;\n cwd?: string;\n session_id?: string;\n}\n\ninterface Observation {\n ts: string;\n session_id?: string;\n cwd?: string;\n tool: string;\n summary: string;\n files?: string[];\n /** True when the tool response signals a failure — candidate for mem_tried. */\n failure_hint?: true;\n}\n\nfunction truncate(s: unknown, max = TRUNCATE_FIELD): string {\n if (s == null) return \"\";\n const str = typeof s === \"string\" ? s : JSON.stringify(s);\n return str.length > max ? str.slice(0, max) + \"…\" : str;\n}\n\nfunction extractFiles(payload: HookPayload): string[] {\n const files = new Set<string>();\n const input = payload.tool_input ?? {};\n for (const k of [\"file_path\", \"path\", \"notebook_path\"]) {\n const v = input[k];\n if (typeof v === \"string\") files.add(v);\n }\n // Bash tool: try to spot file-ish args\n const cmd = input[\"command\"];\n if (typeof cmd === \"string\") {\n const matches = cmd.match(/[\\w./-]+\\.(?:ts|tsx|js|jsx|py|go|rs|java|kt|swift|rb|php|cs|cpp|c|h|md|json|yml|yaml)\\b/g);\n if (matches) for (const m of matches) files.add(m);\n }\n return [...files].slice(0, 8);\n}\n\nfunction buildSummary(payload: HookPayload): string {\n const tool = payload.tool_name ?? \"?\";\n const input = payload.tool_input ?? {};\n if (tool === \"Bash\") return `Bash: ${truncate(input[\"command\"], 200)}`;\n if (tool === \"Edit\") return `Edit ${truncate(input[\"file_path\"], 200)}`;\n if (tool === \"Write\") return `Write ${truncate(input[\"file_path\"], 200)}`;\n return `${tool}: ${truncate(input, 200)}`;\n}\n\nasync function readStdin(maxBytes: number): Promise<string> {\n if (process.stdin.isTTY) return \"\";\n return await new Promise((resolve) => {\n const chunks: Buffer[] = [];\n let total = 0;\n let done = false;\n const finish = (): void => {\n if (done) return;\n done = true;\n resolve(Buffer.concat(chunks).toString(\"utf8\"));\n };\n process.stdin.on(\"data\", (c: Buffer) => {\n total += c.length;\n if (total > maxBytes) {\n process.stdin.destroy();\n finish();\n return;\n }\n chunks.push(c);\n });\n process.stdin.on(\"end\", finish);\n process.stdin.on(\"error\", finish);\n setTimeout(finish, 2000); // hard cap so a stuck hook never blocks Claude\n });\n}\n\n/**\n * Commands that routinely exit non-zero WITHOUT a real failure, so a bare exit code is not a\n * failure signal for them: `grep`/`rg` (exit 1 = no match), `find`, `test`/`[`/`[[`, `diff`\n * (exit 1 = differs), and ANY pipeline (the last stage — often `head` — sets the exit code, and\n * SIGPIPE/`head` closing a pipe makes earlier stages \"fail\"). These were the false positives that\n * trained agents to ignore the \"N failures detected\" nudge — don't flag them on exit code alone.\n */\nexport function isExpectedNonzeroExit(command: string): boolean {\n if (!command) return false;\n if (command.includes(\"|\")) return true; // pipeline — exit code is the last stage's, not meaningful\n if (/\\|\\|\\s*true\\b/.test(command)) return true; // explicitly tolerated\n return /(^|\\s|;|&&)(grep|egrep|fgrep|rg|ag|find|test|diff|\\[\\[?)\\b/.test(command);\n}\n\n/**\n * Detect whether the tool response signals a failure worth capturing as mem_tried.\n * Checks exit codes for Bash and error patterns in all tool responses.\n * Best-effort — false negatives are acceptable; false positives create noise (and noise that gets\n * ignored is worse than silence), so bare non-zero exits from grep/pipes/etc. are NOT flagged.\n */\nexport function detectFailure(payload: HookPayload): boolean {\n const response = payload.tool_response;\n if (!response) return false;\n\n const responseText = typeof response === \"string\" ? response : JSON.stringify(response);\n\n // Bash: a non-zero exit is a failure signal ONLY when the command isn't one that routinely\n // exits non-zero (grep no-match, a pipeline's last stage, etc.). Real build/test/runtime errors\n // still get caught by the reliable text signatures below regardless of the command shape.\n if (payload.tool_name === \"Bash\") {\n const command = typeof payload.tool_input?.[\"command\"] === \"string\"\n ? (payload.tool_input[\"command\"] as string)\n : \"\";\n if (typeof response === \"object\") {\n const code = (response as Record<string, unknown>)[\"exit_code\"] ??\n (response as Record<string, unknown>)[\"exitCode\"];\n if (typeof code === \"number\" && code !== 0 && !isExpectedNonzeroExit(command)) return true;\n }\n // Text patterns that reliably indicate a hard failure in Bash output\n if (/\\b(command not found|No such file or directory|ERR_MODULE_NOT_FOUND|ENOENT|EACCES)\\b/.test(responseText)) return true;\n if (/\\berror TS\\d+:/i.test(responseText)) return true; // TypeScript compile error\n }\n\n // Edit/Write/Read: tool-level error (file not found, permission denied)\n if ([\"Edit\", \"Write\", \"Read\"].includes(payload.tool_name ?? \"\")) {\n if (typeof response === \"object\") {\n const err = (response as Record<string, unknown>)[\"error\"] ??\n (response as Record<string, unknown>)[\"message\"];\n if (typeof err === \"string\" && err.length > 0) return true;\n }\n }\n\n // Generic: error messages that suggest something went wrong\n if (/^\\s*(Error|FAILED|ENOENT|EACCES|unknown option|Cannot find module)\\b/m.test(responseText)) return true;\n\n return false;\n}\n\nexport function registerObserve(program: Command): void {\n program\n .command(\"observe\")\n .description(\n \"Passive-capture endpoint for Claude Code PostToolUse hooks.\\n\\n\" +\n \" Reads a JSON payload on stdin and appends an observation record to\\n\" +\n \" .ai/.cache/observations.jsonl. Always exits 0; never blocks the agent.\\n\" +\n \" Wired up automatically by `hivelore install-hooks claude`.\",\n )\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: { dir?: string }) => {\n try {\n const raw = await readStdin(MAX_STDIN_BYTES);\n if (!raw.trim()) return;\n\n let payload: HookPayload;\n try {\n payload = JSON.parse(raw) as HookPayload;\n } catch {\n return; // malformed payload — silently no-op\n }\n\n const root = (() => {\n try { return findProjectRoot(opts.dir ?? payload.cwd); } catch { return null; }\n })();\n if (!root) return;\n\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.haiveDir)) return; // not a haive project\n\n const failureHint = detectFailure(payload);\n const observation: Observation = {\n ts: new Date().toISOString(),\n session_id: payload.session_id,\n cwd: payload.cwd,\n tool: payload.tool_name ?? \"?\",\n summary: buildSummary(payload),\n files: extractFiles(payload),\n ...(failureHint ? { failure_hint: true as const } : {}),\n };\n\n const cacheDir = path.join(paths.haiveDir, \".cache\");\n await mkdir(cacheDir, { recursive: true });\n await appendFile(\n path.join(cacheDir, \"observations.jsonl\"),\n JSON.stringify(observation) + \"\\n\",\n \"utf8\",\n );\n } catch {\n // Hooks must never break the user's flow — swallow everything.\n }\n });\n}\n","import { Command } from \"commander\";\nimport { findProjectRoot } from \"@hivelore/core\";\nimport { runHaiveMcpStdio } from \"@hivelore/mcp\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface McpOptions {\n dir?: string;\n root?: string;\n /** Recognized so JSON configs may pass `[\\\"mcp\\\", \\\"--stdio\\\"]` — MCP always uses stdio. */\n stdio?: boolean;\n}\n\nexport function registerMcp(program: Command): void {\n program\n .command(\"mcp\")\n .description(\n \"Run the Hivelore MCP server over stdio (bundled — same tools as legacy haive-mcp).\\n\\n\" +\n \" Configure via hivelore init (project-level), or manually:\\n\" +\n ' \\\"command\\\": \\\"hivelore\\\",\\n' +\n ' \\\"args\\\": [\\\"mcp\\\", \\\"--stdio\\\"],\\n' +\n \" optional env: HAIVE_PROJECT_ROOT (absolute project root).\\n\\n\" +\n \" Updating @hivelore/cli updates MCP; standalone haive-mcp is optional legacy.\",\n )\n .option(\"-d, --dir <dir>\", \"project root (walks up from here for .ai/ / .git/)\")\n .option(\"-r, --root <dir>\", \"same as --dir (parity with legacy haive-mcp --root)\")\n .option(\"--stdio\", \"optional marker for client configs — transport is always stdio\", false)\n .action(async (opts: McpOptions) => {\n void opts.stdio;\n const raw = opts.root ?? opts.dir;\n const root = raw ? findProjectRoot(raw) : findProjectRoot();\n try {\n await runHaiveMcpStdio({ root });\n } catch (err) {\n ui.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n });\n}\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { createContext, type CreateContextOptions, type HaiveContext } from \"./context.js\";\nimport {\n BootstrapProjectSaveInputSchema,\n bootstrapProjectSave,\n type BootstrapProjectSaveInput,\n} from \"./tools/bootstrap-project-save.js\";\nimport {\n GetProjectContextInputSchema,\n getProjectContext,\n type GetProjectContextInput,\n} from \"./tools/get-project-context.js\";\nimport { MemListInputSchema, memList, type MemListInput } from \"./tools/mem-list.js\";\nimport { MemSaveInputSchema, memSave, type MemSaveInput } from \"./tools/mem-save.js\";\nimport {\n MemSearchInputSchema,\n memSearch,\n type MemSearchInput,\n} from \"./tools/mem-search.js\";\nimport {\n MemVerifyInputSchema,\n memVerify,\n type MemVerifyInput,\n} from \"./tools/mem-verify.js\";\nimport {\n MemRejectInputSchema,\n memReject,\n type MemRejectInput,\n} from \"./tools/mem-reject.js\";\nimport {\n MemFeedbackInputSchema,\n memFeedback,\n type MemFeedbackInput,\n} from \"./tools/mem-feedback.js\";\nimport {\n MemForFilesInputSchema,\n memForFiles,\n type MemForFilesInput,\n} from \"./tools/mem-for-files.js\";\nimport { MemGetInputSchema, memGet, type MemGetInput } from \"./tools/mem-get.js\";\nimport {\n MemDeleteInputSchema,\n memDelete,\n type MemDeleteInput,\n} from \"./tools/mem-delete.js\";\nimport {\n MemUpdateInputSchema,\n memUpdate,\n type MemUpdateInput,\n} from \"./tools/mem-update.js\";\nimport {\n MemPendingInputSchema,\n memPending,\n type MemPendingInput,\n} from \"./tools/mem-pending.js\";\nimport {\n MemApproveInputSchema,\n memApprove,\n type MemApproveInput,\n} from \"./tools/mem-approve.js\";\nimport {\n MemTriedInputSchema,\n memTried,\n type MemTriedInput,\n} from \"./tools/mem-tried.js\";\nimport {\n ProposeSensorInputSchema,\n proposeSensor,\n type ProposeSensorInput,\n} from \"./tools/propose-sensor.js\";\nimport {\n IngestFindingsInputSchema,\n ingestFindings,\n type IngestFindingsInput,\n} from \"./tools/ingest-findings.js\";\nimport {\n MemObserveInputSchema,\n memObserve,\n type MemObserveInput,\n} from \"./tools/mem-observe.js\";\nimport {\n MemSessionEndInputSchema,\n memSessionEnd,\n type MemSessionEndInput,\n} from \"./tools/mem-session-end.js\";\nimport {\n GetBriefingInputSchema,\n getBriefing,\n type GetBriefingInput,\n} from \"./tools/get-briefing.js\";\nimport {\n CodeMapInputSchema,\n codeMapTool,\n type CodeMapInput,\n} from \"./tools/code-map.js\";\nimport {\n MemDiffInputSchema,\n memDiff,\n type MemDiffInput,\n} from \"./tools/mem-diff.js\";\nimport {\n GetRecapInputSchema,\n getRecap,\n type GetRecapInput,\n} from \"./tools/get-recap.js\";\nimport {\n MemRelevantToInputSchema,\n memRelevantTo,\n type MemRelevantToInput,\n} from \"./tools/mem-relevant-to.js\";\nimport {\n CodeSearchInputSchema,\n codeSearch,\n type CodeSearchInput,\n} from \"./tools/code-search.js\";\nimport {\n WhyThisFileInputSchema,\n whyThisFile,\n type WhyThisFileInput,\n} from \"./tools/why-this-file.js\";\nimport {\n AntiPatternsCheckInputSchema,\n antiPatternsCheck,\n type AntiPatternsCheckInput,\n} from \"./tools/anti-patterns-check.js\";\nimport {\n MemDistillInputSchema,\n memDistill,\n type MemDistillInput,\n} from \"./tools/mem-distill.js\";\nimport {\n WhyThisDecisionInputSchema,\n whyThisDecision,\n type WhyThisDecisionInput,\n} from \"./tools/why-this-decision.js\";\nimport {\n MemConflictsInputSchema,\n memConflicts,\n type MemConflictsInput,\n} from \"./tools/mem-conflicts.js\";\nimport {\n PreCommitCheckInputSchema,\n preCommitCheck,\n type PreCommitCheckInput,\n} from \"./tools/precommit-check.js\";\nimport {\n PatternDetectInputSchema,\n patternDetect,\n type PatternDetectInput,\n} from \"./tools/pattern-detect.js\";\nimport {\n MemConflictCandidatesInputSchema,\n memConflictCandidates,\n type MemConflictCandidatesInput,\n} from \"./tools/mem-conflict-candidates.js\";\nimport {\n MemResolveProjectInputSchema,\n memResolveProject,\n type MemResolveProjectInput,\n} from \"./tools/mem-resolve-project.js\";\nimport {\n MemSuggestTopicInputSchema,\n memSuggestTopic,\n type MemSuggestTopicInput,\n} from \"./tools/mem-suggest-topic.js\";\nimport {\n MemTimelineInputSchema,\n memTimeline,\n type MemTimelineInput,\n} from \"./tools/mem-timeline.js\";\nimport {\n RuntimeJournalAppendInputSchema,\n runtimeJournalAppend,\n type RuntimeJournalAppendInput,\n} from \"./tools/runtime-journal-append.js\";\nimport {\n RuntimeJournalTailInputSchema,\n runtimeJournalTail,\n type RuntimeJournalTailInput,\n} from \"./tools/runtime-journal-tail.js\";\nimport {\n BootstrapProjectArgsSchema,\n bootstrapProjectPrompt,\n type BootstrapProjectArgs,\n} from \"./prompts/bootstrap-project.js\";\nimport {\n BootstrapRepoArgsSchema,\n bootstrapRepoPrompt,\n type BootstrapRepoArgs,\n} from \"./prompts/bootstrap-repo.js\";\nimport {\n PostTaskArgsSchema,\n postTaskPrompt,\n type PostTaskArgs,\n} from \"./prompts/post-task.js\";\nimport {\n ImportDocsArgsSchema,\n importDocsPrompt,\n type ImportDocsArgs,\n} from \"./prompts/import-docs.js\";\nimport { SessionTracker } from \"./session-tracker.js\";\nimport { hasRecentBriefingMarker, loadConfigSync } from \"@hivelore/core\";\n\n// Re-export tool implementations so `@hivelore/cli` (and integrators) can call\n// them programmatically without going through the MCP stdio transport.\n// These are the same handlers the MCP server registers below.\nexport {\n getBriefing,\n type GetBriefingInput,\n type BriefingOutput,\n} from \"./tools/get-briefing.js\";\nexport {\n codeMapTool,\n type CodeMapInput,\n type CodeMapToolOutput,\n} from \"./tools/code-map.js\";\nexport {\n getRecap,\n type GetRecapInput,\n type GetRecapOutput,\n} from \"./tools/get-recap.js\";\nexport {\n memRelevantTo,\n type MemRelevantToInput,\n type MemRelevantToOutput,\n} from \"./tools/mem-relevant-to.js\";\nexport {\n codeSearch,\n type CodeSearchInput,\n type CodeSearchOutput,\n} from \"./tools/code-search.js\";\nexport {\n whyThisFile,\n type WhyThisFileInput,\n type WhyThisFileOutput,\n} from \"./tools/why-this-file.js\";\nexport {\n antiPatternsCheck,\n type AntiPatternsCheckInput,\n type AntiPatternsCheckOutput,\n} from \"./tools/anti-patterns-check.js\";\nexport {\n memDistill,\n type MemDistillInput,\n type MemDistillOutput,\n} from \"./tools/mem-distill.js\";\nexport {\n whyThisDecision,\n type WhyThisDecisionInput,\n type WhyThisDecisionOutput,\n} from \"./tools/why-this-decision.js\";\nexport {\n memConflicts,\n type MemConflictsInput,\n type MemConflictsOutput,\n} from \"./tools/mem-conflicts.js\";\nexport {\n preCommitCheck,\n type PreCommitCheckInput,\n type PreCommitCheckOutput,\n} from \"./tools/precommit-check.js\";\nexport { readPresumedCorrectTargets } from \"./tools/propose-sensor.js\";\nexport {\n patternDetect,\n type PatternDetectInput,\n type PatternDetectOutput,\n} from \"./tools/pattern-detect.js\";\nexport {\n memResolveProject,\n type MemResolveProjectInput,\n} from \"./tools/mem-resolve-project.js\";\nexport {\n memSuggestTopic,\n type MemSuggestTopicInput,\n} from \"./tools/mem-suggest-topic.js\";\nexport {\n memTimeline,\n type MemTimelineInput,\n} from \"./tools/mem-timeline.js\";\nexport {\n memConflictCandidates,\n type MemConflictCandidatesInput,\n} from \"./tools/mem-conflict-candidates.js\";\nexport {\n runtimeJournalAppend,\n type RuntimeJournalAppendInput,\n} from \"./tools/runtime-journal-append.js\";\nexport {\n runtimeJournalTail,\n type RuntimeJournalTailInput,\n} from \"./tools/runtime-journal-tail.js\";\n\ndeclare const __HAIVE_VERSION__: string;\n\nexport const SERVER_NAME = \"hivelore\";\nexport const SERVER_VERSION = __HAIVE_VERSION__;\nexport type ToolProfile = \"enforcement\" | \"maintenance\" | \"experimental\" | \"full\";\n\nfunction jsonResult(data: unknown) {\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(data, null, 2),\n },\n ],\n };\n}\n\nexport const ENFORCEMENT_PROFILE_TOOLS = [\n \"get_briefing\",\n \"mem_save\",\n \"mem_tried\",\n \"mem_search\",\n \"mem_get\",\n \"mem_verify\",\n \"mem_relevant_to\",\n \"code_map\",\n \"code_search\",\n \"pre_commit_check\",\n \"mem_session_end\",\n \"propose_sensor\",\n] as const;\n\nexport const MAINTENANCE_PROFILE_TOOLS = [\n ...ENFORCEMENT_PROFILE_TOOLS,\n \"mem_suggest_topic\",\n \"mem_for_files\",\n \"mem_list\",\n \"get_project_context\",\n \"bootstrap_project_save\",\n \"mem_resolve_project\",\n \"mem_update\",\n \"mem_approve\",\n \"mem_reject\",\n \"mem_pending\",\n \"mem_delete\",\n \"mem_diff\",\n \"get_recap\",\n \"anti_patterns_check\",\n \"mem_distill\",\n \"mem_timeline\",\n \"mem_conflict_candidates\",\n \"mem_feedback\",\n \"ingest_findings\",\n] as const;\n\nexport const EXPERIMENTAL_PROFILE_TOOLS = [\n ...MAINTENANCE_PROFILE_TOOLS,\n \"mem_observe\",\n \"why_this_file\",\n \"why_this_decision\",\n \"mem_conflicts_with\",\n \"pattern_detect\",\n \"runtime_journal_append\",\n \"runtime_journal_tail\",\n] as const;\n\nexport const TOOL_PROFILES: Record<Exclude<ToolProfile, \"full\">, ReadonlySet<string>> = {\n enforcement: new Set(ENFORCEMENT_PROFILE_TOOLS),\n maintenance: new Set(MAINTENANCE_PROFILE_TOOLS),\n experimental: new Set(EXPERIMENTAL_PROFILE_TOOLS),\n};\n\nexport function getAllowedToolsForProfile(profile: ToolProfile): ReadonlySet<string> {\n if (profile === \"full\") return TOOL_PROFILES.experimental;\n return TOOL_PROFILES[profile] ?? TOOL_PROFILES.enforcement;\n}\n\nconst BRIEFING_TOOLS = new Set([\"get_briefing\", \"mem_relevant_to\"]);\n\nconst MUTATING_TOOLS = new Set([\n \"mem_save\",\n \"mem_tried\",\n \"mem_observe\",\n \"mem_session_end\",\n \"bootstrap_project_save\",\n \"mem_update\",\n \"mem_approve\",\n \"mem_reject\",\n \"mem_delete\",\n \"mem_feedback\",\n \"runtime_journal_append\",\n \"pattern_detect\",\n \"ingest_findings\",\n \"propose_sensor\",\n]);\n\nexport function createHaiveServer(\n options: CreateContextOptions = {},\n): { server: McpServer; context: HaiveContext; tracker: SessionTracker } {\n const context = createContext(options);\n const config = loadConfigSync(context.paths);\n const toolProfile =\n (options.env?.HAIVE_TOOL_PROFILE as ToolProfile | undefined) ??\n config.enforcement?.toolProfile ??\n \"enforcement\";\n const requireBriefingFirst =\n options.env?.HAIVE_REQUIRE_BRIEFING_FIRST === \"0\"\n ? false\n : config.enforcement?.requireBriefingFirst ?? true;\n let briefingLoaded = false;\n const tracker = new SessionTracker(context);\n // Init is async — fire-and-forget at startup (registers shutdown handler if autopilot)\n void tracker.init();\n\n const server = new McpServer(\n { name: SERVER_NAME, version: SERVER_VERSION },\n { capabilities: { tools: {}, prompts: {} } },\n );\n\n const allowedTools = getAllowedToolsForProfile(toolProfile);\n\n const shouldRegisterTool = (name: string): boolean => allowedTools.has(name);\n\n const registerTool = <TInput>(\n name: string,\n description: string,\n schema: Record<string, unknown>,\n handler: (input: TInput) => Promise<unknown> | unknown,\n ): void => {\n if (!shouldRegisterTool(name)) return;\n const tool = server.tool.bind(server) as (\n toolName: string,\n toolDescription: string,\n toolSchema: Record<string, unknown>,\n toolHandler: (input: unknown) => Promise<unknown> | unknown,\n ) => unknown;\n tool(\n name,\n description,\n schema,\n async (input: unknown) => {\n if (BRIEFING_TOOLS.has(name)) {\n briefingLoaded = true;\n return await handler(input as TInput);\n }\n if (requireBriefingFirst && MUTATING_TOOLS.has(name) && !briefingLoaded) {\n // Fall back to the disk-persisted marker before blocking — covers client\n // reconnections where the server process is fresh but a recent briefing ran.\n const hasDiskMarker = await hasRecentBriefingMarker(context.paths).catch(() => false);\n if (hasDiskMarker) {\n briefingLoaded = true;\n } else {\n return jsonResult({\n error: \"haive_briefing_required\",\n message:\n \"This Hivelore project requires get_briefing or mem_relevant_to before state-changing Hivelore tools. Call get_briefing({ task: '...' }) first.\",\n tool: name,\n });\n }\n }\n return await handler(input as TInput);\n },\n );\n };\n\n const shouldRegisterPrompt = (name: string): boolean => {\n if (name === \"bootstrap_project\" || name === \"bootstrap_repo\" || name === \"post_task\") return true;\n if (name === \"import_docs\") return toolProfile !== \"enforcement\";\n return toolProfile === \"experimental\" || toolProfile === \"full\";\n };\n\n // ── Memory creation ────────────────────────────────────────────────────\n\n registerTool(\n \"mem_save\",\n [\n \"Save a piece of knowledge as a persistent memory that survives across AI sessions.\",\n \"\",\n \"USE THIS WHEN you discover something worth remembering for future sessions:\",\n \" - A project convention (how things are done here)\",\n \" - An architectural decision and its rationale\",\n \" - A gotcha or non-obvious behavior that surprised you\",\n \" - A domain term and what it means in this codebase\",\n \"\",\n \"DO NOT USE for failed approaches → use mem_tried instead (better structure).\",\n \"DO NOT USE for code discoveries during exploration → use mem_observe instead.\",\n \"\",\n \"PARAMETERS:\",\n \" type — convention | decision | gotcha | architecture | glossary | attempt\",\n \" slug — short kebab-case id (e.g. 'flyway-no-modify-existing')\",\n \" body — Markdown content with the full knowledge\",\n \" scope — team (shared with all devs) | personal (private) | module (component-scoped)\",\n \" paths — anchor to source files for staleness detection (STRONGLY recommended)\",\n \" topic — stable key for upsert: if a memory with same topic+scope exists, update it in-place\",\n \"\",\n \"RETURNS: { id, scope, file_path, action: 'created'|'updated', warning?, invalid_paths? }\",\n \"WARNING: if paths point to non-existent files, they will be immediately stale after hivelore sync.\",\n \"DEDUP: identical body content within the same scope is rejected — use mem_update to modify.\",\n ].join(\"\\n\"),\n MemSaveInputSchema,\n async (input: MemSaveInput) => {\n tracker.record(\"mem_save\", input.slug);\n return jsonResult(await memSave(input, context));\n },\n );\n\n registerTool(\n \"mem_suggest_topic\",\n [\n \"Propose a stable `topic` key (topic-upsert) from type + short title.\",\n \"\",\n \"USE BEFORE mem_save when you want deterministic updates to the same memory over time;\",\n \"families mimic Engram-style grouping (architecture/*, bug/*, decision/*, …).\",\n \"\",\n \"PARAMETERS:\",\n \" type — convention | decision | gotcha | architecture | glossary | attempt | session_recap\",\n \" title — phrase to slugify under the suggested family prefix\",\n \"\",\n \"RETURNS: { topic_key, family, type }\",\n ].join(\"\\n\"),\n MemSuggestTopicInputSchema,\n async (input: MemSuggestTopicInput) =>\n jsonResult(await memSuggestTopic(input, context)),\n );\n\n registerTool(\n \"mem_tried\",\n [\n \"Record a FAILED approach so future agents don't repeat the same mistake.\",\n \"\",\n \"USE THIS IMMEDIATELY when you try something and it doesn't work. This is the\",\n \"most valuable type of negative knowledge — it saves hours of debugging for\",\n \"future agents working on the same codebase.\",\n \"\",\n \"Auto-validated (no approval cycle). Surfaced FIRST in future get_briefing calls\",\n \"so it's impossible to miss.\",\n \"\",\n \"PARAMETERS:\",\n \" what — short title of what you tried (e.g. 'importing X with ESM dynamic import')\",\n \" why_failed — the exact error or reason it failed\",\n \" instead — what to do instead (the correct approach)\",\n \" scope — team (default) | personal\",\n \" paths — source files where the issue lives\",\n \"\",\n \"RETURNS: { id, file_path, action: 'created' }\",\n ].join(\"\\n\"),\n MemTriedInputSchema,\n async (input: MemTriedInput) => {\n tracker.record(\"mem_tried\", input.what.slice(0, 80));\n return jsonResult(await memTried(input, context));\n },\n );\n\n registerTool(\n \"propose_sensor\",\n [\n \"Propose a discriminating sensor for a gotcha/attempt — YOU write the pattern (you understand the\",\n \"code), Hivelore validates it before trusting it to block. This is how a captured lesson becomes a\",\n \"RELIABLE block instead of an advisory note.\",\n \"\",\n \"USE THIS right after mem_tried / mem_save on a gotcha whose mistake is detectable in code, to\",\n \"upgrade the auto-suggested (warn) sensor into a precise, promotable one.\",\n \"\",\n \"Write a pattern that matches the FAULTY usage, and — crucially — an `absent` regex for the\",\n \"CORRECT-usage marker so it fires on the bug only, not every call (e.g. pattern=the API call,\",\n \"absent=the required option).\",\n \"\",\n \"VALIDATION (a `block` proposal is accepted ONLY if): the pattern is not brittle, stays SILENT on\",\n \"the current (correct) anchored code, and FIRES on the bad example. A rejected proposal is NOT\",\n \"written — the returned `reason`/`guidance` tells you how to revise; then call propose_sensor again.\",\n \"\",\n \"PARAMETERS:\",\n \" memory_id — the gotcha/attempt to protect\",\n \" pattern — regex matching the faulty usage\",\n \" absent — regex for the correct-usage marker (makes it discriminate) — strongly recommended\",\n \" bad_example— a snippet that SHOULD match (else examples are read from the lesson)\",\n \" severity — 'block' (default) | 'warn'\",\n \"\",\n \"RETURNS: { accepted, reason?, guidance?, self_check, file_path? }\",\n ].join(\"\\n\"),\n ProposeSensorInputSchema,\n async (input: ProposeSensorInput) => {\n tracker.record(\"propose_sensor\", input.memory_id);\n return jsonResult(await proposeSensor(input, context));\n },\n );\n\n registerTool(\n \"ingest_findings\",\n [\n \"Turn scanner findings (SonarQube / SARIF) into proposed, anchored memories with sensors.\",\n \"\",\n \"USE THIS to seed Hivelore from your existing quality tooling: each real defect a scanner\",\n \"found becomes a `gotcha`/`convention` memory anchored to the file, pre-filled with a\",\n \"conservative `warn` sensor — so the next agent is steered away from it before re-writing it.\",\n \"This closes the review↔memory loop and kills the cold-start problem.\",\n \"\",\n \"SAFETY: drafts are status=proposed and sensors are warn-only + autogen. This tool NEVER\",\n \"auto-validates and NEVER auto-blocks. A human reviews (mem_pending) and promotes the sensor.\",\n \"\",\n \"PARAMETERS:\",\n \" format — 'sarif' (ESLint/Semgrep/CodeQL) | 'sonar' (SonarQube issues JSON)\",\n \" report_path — project-relative path to the report file (OR pass `report` inline)\",\n \" report — inline JSON content (OR pass `report_path`)\",\n \" type — gotcha (default) | convention\",\n \" scope — team (default) | personal | module\",\n \" min_severity — drop findings below this severity\",\n \" dry_run — preview what would be created without writing\",\n \"\",\n \"RETURNS: { format, parsed, new, skipped_existing, created[], notice }\",\n ].join(\"\\n\"),\n IngestFindingsInputSchema,\n async (input: IngestFindingsInput) => {\n tracker.record(\"ingest_findings\", `${input.format}:${input.report_path ?? \"inline\"}`);\n return jsonResult(await ingestFindings(input, context));\n },\n );\n\n registerTool(\n \"mem_observe\",\n [\n \"Capture a code-level discovery made WHILE READING existing code.\",\n \"\",\n \"USE THIS when you read a file and spot something the team may not know about:\",\n \" - A bug or race condition hiding in the code\",\n \" - A security gap or missing validation\",\n \" - An inconsistency between two files\",\n \" - A missing configuration or environment variable\",\n \" - Anything that could silently break in production\",\n \"\",\n \"DIFFERENCE from mem_save: mem_observe is for REACTIVE discoveries during code\",\n \"reading. mem_save is for deliberate knowledge capture (conventions, decisions).\",\n \"\",\n \"Auto-validated, anchored to file paths for staleness detection.\",\n \"\",\n \"PARAMETERS:\",\n \" what — one-line title (e.g. 'MobilePaymentController: duplicate @RequestBody')\",\n \" where — file path(s) where the issue lives\",\n \" impact — what breaks or could break because of this\",\n \" fix — suggested fix (optional)\",\n \" scope — team (default, since discoveries benefit everyone)\",\n \"\",\n \"RETURNS: { id, file_path }\",\n ].join(\"\\n\"),\n MemObserveInputSchema,\n async (input: MemObserveInput) => {\n tracker.record(\"mem_observe\", input.where);\n return jsonResult(await memObserve(input, context));\n },\n );\n\n registerTool(\n \"mem_session_end\",\n [\n \"Save an end-of-session recap so the NEXT session starts with fresh context.\",\n \"\",\n \"CALL THIS before closing any significant working session. In autopilot mode,\",\n \"the MCP server saves a minimal recap automatically on exit — but calling this\",\n \"manually produces a richer, more useful recap.\",\n \"\",\n \"HOW IT WORKS: uses topic-upsert — one recap per scope is kept and updated\",\n \"in-place (revision_count increments). get_briefing surfaces the latest recap\",\n \"at the very top of the next session's briefing, before project context.\",\n \"\",\n \"PARAMETERS:\",\n \" goal — what you were trying to accomplish (1–2 sentences)\",\n \" accomplished — what was actually done (bullet list recommended)\",\n \" discoveries — bugs, surprises, missing knowledge found during this session\",\n \" files_touched — key files read or modified (used as anchor for staleness)\",\n \" next_steps — what should happen in the next session or for a teammate\",\n \" scope — personal (default) | team\",\n \"\",\n \"RETURNS: { id, scope, action: 'created'|'updated', revision_count }\",\n ].join(\"\\n\"),\n MemSessionEndInputSchema,\n async (input: MemSessionEndInput) => {\n tracker.record(\"mem_session_end\", input.goal.slice(0, 80));\n return jsonResult(await memSessionEnd(input, context));\n },\n );\n\n // ── Memory retrieval ───────────────────────────────────────────────────\n\n registerTool(\n \"get_briefing\",\n [\n \"⭐ DEFAULT-FIRST for coding agents on any repo where `hivelore init` ran: call this BEFORE\",\n \"changing source or project config for the current goal (unless the developer explicitly opts out).\",\n \"One-shot onboarding: everything relevant in a single call under a token budget.\",\n \"\",\n \"PROGRESSIVE DISCLOSURE — after this, drill down only if needed:\",\n \" mem_relevant_to / mem_search (compact lists) → mem_get (full body + anchors).\",\n \"\",\n \"RETURNS (in order of priority):\",\n \" 0. action_required — ⚠️ HANDLE THIS FIRST if non-empty (see protocol below)\",\n \" 1. last_session — recap of the previous session (goal, what was done, next steps)\",\n \" 2. project_context — .ai/project-context.md (auto-generated from code-map if template)\",\n \" 3. module_contexts — relevant .ai/modules/<name>/context.md based on files being edited\",\n \" 4. memories — ranked team memories relevant to your task\",\n \" 5. symbol_locations — file:line:kind for any requested symbols (no grep needed)\",\n \" 6. setup_warnings — actionable warnings if setup is incomplete\",\n \" 7. decay_warnings — memories not read in >90 days (consider reviewing)\",\n \"\",\n \"⚠️ ACTION_REQUIRED PROTOCOL — MANDATORY:\",\n \" If action_required[] is non-empty, STOP and for each item:\",\n \" 1. Show the developer the exact developer_message field verbatim\",\n \" 2. Wait for explicit human confirmation ('yes', 'go ahead', 'oui', etc.)\",\n \" 3. Only then proceed with any code changes\",\n \" NEVER act autonomously on cross-repo breaking changes, dep bumps, or contract diffs.\",\n \"\",\n \"KEY PARAMETERS:\",\n \" task — what you are about to do (1–2 sentences) — ALWAYS provide this\",\n \" files — files you are about to edit — surfaces anchored memories\",\n \" symbols — symbol names to look up in the code-map (e.g. ['PaymentService'])\",\n \" format — 'full' (default) | 'compact' (1-line) | 'actions' (bullet-first excerpts)\",\n \" budget_preset — 'quick' | 'balanced' | 'deep' — scales max_tokens/memories/module contexts\",\n \"\",\n \"EXAMPLE USAGE:\",\n \" get_briefing({ task: 'add a Stripe payment integration', files: ['src/payments/'], symbols: ['PaymentService'] })\",\n \"\",\n \"CONFIDENCE LEVELS in memories:\",\n \" authoritative — validated + read 10+ times (highest trust)\",\n \" trusted — validated or proposed + read 3+ times\",\n \" low — proposed, few reads (take with caution)\",\n \" unverified — draft (unverified: true flag set)\",\n \"\",\n \"Replaces 4–5 separate tool calls. Prefer this first; use mem_search / mem_get only for follow-up.\",\n ].join(\"\\n\"),\n GetBriefingInputSchema,\n async (input: GetBriefingInput) => {\n tracker.record(\"get_briefing\", input.task ?? \"\");\n return jsonResult(await getBriefing(input, context));\n },\n );\n\n registerTool(\n \"mem_search\",\n [\n \"Search memories by keyword or semantic similarity.\",\n \"\",\n \"USE WHEN you need to find a specific memory and don't know its id.\",\n \"For session onboarding, use get_briefing instead (richer, ranked, budgeted).\",\n \"\",\n \"SEARCH MODES:\",\n \" Literal (default): AND search across id, tags, and body — all tokens must match.\",\n \" Falls back to OR automatically if no AND results (partial match).\",\n \" Lexical rank (lexical_rank: true, semantic: false): Okapi-BM25-style scoring on the\",\n \" filtered corpus — good for phrase-like queries without embeddings.\",\n \" Semantic (semantic: true): embedding-based similarity — finds related memories\",\n \" even with different wording. Requires hivelore embeddings index to be built.\",\n \"\",\n \"PARAMETERS:\",\n \" query — search terms or natural language question\",\n \" scope — filter by personal | team | module\",\n \" type — filter by convention | decision | gotcha | architecture | glossary\",\n \" semantic — true for embedding-based search (requires @hivelore/embeddings)\",\n \" lexical_rank — BM25-style ranking (ignored when semantic is true)\",\n \" limit — max results (default 10)\",\n \"\",\n \"RETURNS: array of { id, type, scope, status, confidence, body, match_quality }\",\n ].join(\"\\n\"),\n MemSearchInputSchema,\n async (input: MemSearchInput) => {\n tracker.record(\"mem_search\", input.query.slice(0, 80));\n return jsonResult(await memSearch(input, context));\n },\n );\n\n registerTool(\n \"mem_timeline\",\n [\n \"Chronological view of related memories: by shared frontmatter.topic OR expanded from a seed id\",\n \"(related_ids, same topic, overlapping anchor paths — one extra hop on related_ids).\",\n \"\",\n \"PARAMETERS:\",\n \" memory_id — optional seed memory id\",\n \" topic — optional topic key (required if memory_id omitted)\",\n \" limit — max entries (default 30)\",\n \"\",\n \"RETURNS: { entries: [{ id, type, scope, created_at, one_line, topic? }], total, notice? }\",\n ].join(\"\\n\"),\n MemTimelineInputSchema,\n async (input: MemTimelineInput) => jsonResult(await memTimeline(input, context)),\n );\n\n registerTool(\n \"mem_for_files\",\n [\n \"Surface memories relevant to the files you are currently editing.\",\n \"\",\n \"USE WHEN starting work on specific files and you want to know:\",\n \" - What conventions apply to these files\",\n \" - What gotchas are anchored to these paths\",\n \" - What decisions were made about this module\",\n \"\",\n \"Matching strategy (in priority order):\",\n \" 1. Anchor overlap — memories whose paths overlap with your files\",\n \" 2. Module context — .ai/modules/<name>/context.md if module is inferred\",\n \" 3. Domain/tag match — memories whose tags include path segments\",\n \"\",\n \"PARAMETERS:\",\n \" files — list of project-relative file paths you are editing\",\n \" scope — filter by scope (default: all)\",\n \"\",\n \"RETURNS: { memories: [...], module_contexts: [...] }\",\n ].join(\"\\n\"),\n MemForFilesInputSchema,\n async (input: MemForFilesInput) => jsonResult(await memForFiles(input, context)),\n );\n\n registerTool(\n \"mem_get\",\n [\n \"Fetch a single memory by its full id with all details.\",\n \"\",\n \"USE WHEN get_briefing / mem_relevant_to / mem_search returned a compact hit and you need\",\n \"the full body, or when you know the exact id of a memory.\",\n \"\",\n \"PARAMETERS:\",\n \" id — full memory id (e.g. '2026-04-28-gotcha-flyway-strict-no-ddl')\",\n \"\",\n \"RETURNS: { id, type, scope, status, confidence, body, anchor, tags, usage }\",\n ].join(\"\\n\"),\n MemGetInputSchema,\n async (input: MemGetInput) => jsonResult(await memGet(input, context)),\n );\n\n registerTool(\n \"mem_list\",\n [\n \"List memories with optional filters. Use for browsing, not for task onboarding.\",\n \"\",\n \"For task onboarding use get_briefing (ranked + budgeted).\",\n \"For keyword search use mem_search.\",\n \"\",\n \"PARAMETERS:\",\n \" scope — personal | team | module\",\n \" type — convention | decision | gotcha | architecture | glossary\",\n \" status — draft | proposed | validated | stale | rejected\",\n \" tags — filter by tags (AND match)\",\n \" module — filter by module name\",\n \"\",\n \"RETURNS: array of { id, type, scope, status, confidence, tags, created_at }\",\n ].join(\"\\n\"),\n MemListInputSchema,\n async (input: MemListInput) => jsonResult(await memList(input, context)),\n );\n\n // ── Project context ────────────────────────────────────────────────────\n\n registerTool(\n \"get_project_context\",\n [\n \"Read .ai/project-context.md (and optionally a module context) directly.\",\n \"\",\n \"USE WHEN you need the full project context without the memory ranking and\",\n \"token budgeting of get_briefing — e.g. for a reference architecture review.\",\n \"\",\n \"For normal task onboarding, use get_briefing instead (more efficient).\",\n \"\",\n \"PARAMETERS:\",\n \" module — also load .ai/modules/<module>/context.md if provided\",\n \"\",\n \"RETURNS: { content: string, module_context?: string }\",\n ].join(\"\\n\"),\n GetProjectContextInputSchema,\n async (input: GetProjectContextInput) =>\n jsonResult(await getProjectContext(input, context)),\n );\n\n registerTool(\n \"bootstrap_project_save\",\n [\n \"Persist the project context document (.ai/project-context.md) or a module\",\n \"context (.ai/modules/<name>/context.md) analyzed by the AI.\",\n \"\",\n \"USE AFTER the bootstrap_project MCP prompt: the prompt tells you how to\",\n \"analyze the codebase; this tool saves the result.\",\n \"\",\n \"PARAMETERS:\",\n \" content — full Markdown content of the context document\",\n \" module — if provided, saves as a module context (not root project context)\",\n \"\",\n \"RETURNS: { file_path, module? }\",\n ].join(\"\\n\"),\n BootstrapProjectSaveInputSchema,\n async (input: BootstrapProjectSaveInput) =>\n jsonResult(await bootstrapProjectSave(input, context)),\n );\n\n registerTool(\n \"code_map\",\n [\n \"Look up where symbols (classes, functions, interfaces) are defined in the codebase.\",\n \"\",\n \"USE INSTEAD OF grepping when you need to find where something lives.\",\n \"Requires hivelore index code to have been run (done automatically in autopilot mode).\",\n \"\",\n \"TIP: include symbols in get_briefing directly for auto-lookup at session start.\",\n \"\",\n \"PARAMETERS:\",\n \" symbol — name or partial name to search (e.g. 'PaymentService')\",\n \" file — filter by file path substring\",\n \" max_files — cap on results (default 40)\",\n \"\",\n \"RETURNS: { available: bool, files: [{ path, exports: [{ name, kind, line, description }] }] }\",\n \"If available: false → run hivelore index code first.\",\n ].join(\"\\n\"),\n CodeMapInputSchema,\n async (input: CodeMapInput) => jsonResult(await codeMapTool(input, context)),\n );\n\n registerTool(\n \"mem_resolve_project\",\n [\n \"Diagnostics: resolve which project root Hivelore is using (never throws).\",\n \"\",\n \"USE IN multi-root workspaces or when the agent CWD may not be the repo root —\",\n \"mirrors HAIVE_PROJECT_ROOT, findProjectRoot markers, and presence of .ai/memories.\",\n \"\",\n \"PARAMETERS:\",\n \" cwd — optional directory used for discovery when HAIVE_PROJECT_ROOT is unset\",\n \"\",\n \"RETURNS: { ok: true, info: { cwd, resolved_root, haive_project_root_env, … } }\",\n ].join(\"\\n\"),\n MemResolveProjectInputSchema,\n async (input: MemResolveProjectInput) =>\n jsonResult(await memResolveProject(input, context)),\n );\n\n // ── Memory lifecycle ───────────────────────────────────────────────────\n\n registerTool(\n \"mem_update\",\n [\n \"Update the body, tags, or anchor of an existing memory in-place.\",\n \"\",\n \"USE WHEN a memory exists but its content has become outdated or incomplete.\",\n \"This preserves the memory's id, usage history, and read_count.\",\n \"\",\n \"For evolving memories that you will update repeatedly, use mem_save with a\",\n \"topic key instead (topic-upsert pattern).\",\n \"\",\n \"PARAMETERS:\",\n \" id — full memory id to update\",\n \" body — new Markdown content (replaces existing body)\",\n \" tags — new tag list (replaces existing tags)\",\n \" paths — new anchor paths (replaces existing paths)\",\n \" symbols — new anchor symbols (replaces existing symbols)\",\n \"\",\n \"RETURNS: { id, file_path, updated_fields: string[] }\",\n ].join(\"\\n\"),\n MemUpdateInputSchema,\n async (input: MemUpdateInput) => jsonResult(await memUpdate(input, context)),\n );\n\n registerTool(\n \"mem_verify\",\n [\n \"Check whether memory anchor paths and symbols still exist in the current code.\",\n \"\",\n \"USE WHEN you want to know if a specific memory is still valid after a refactor,\",\n \"or to check all memories for staleness (hivelore sync does this automatically).\",\n \"\",\n \"PARAMETERS:\",\n \" id — check a single memory (omit to check all)\",\n \" update — write 'stale' or 'validated' status back to disk\",\n \"\",\n \"RETURNS: { results: [{ id, status: 'fresh'|'stale'|'anchorless', reason? }] }\",\n \"Stale means the anchored file/symbol no longer exists at that path.\",\n \"Anchorless means the memory has no paths/symbols — staleness is undetectable.\",\n ].join(\"\\n\"),\n MemVerifyInputSchema,\n async (input: MemVerifyInput) => jsonResult(await memVerify(input, context)),\n );\n\n registerTool(\n \"mem_approve\",\n [\n \"Mark a memory as validated (trusted, approved by a human or the team).\",\n \"\",\n \"In autopilot mode, memories are validated automatically — you rarely need this.\",\n \"In manual mode, call this after reviewing a proposed memory to activate it.\",\n \"\",\n \"PARAMETERS:\",\n \" id — full memory id to approve\",\n \"\",\n \"RETURNS: { id, previous_status, new_status: 'validated' }\",\n ].join(\"\\n\"),\n MemApproveInputSchema,\n async (input: MemApproveInput) => jsonResult(await memApprove(input, context)),\n );\n\n registerTool(\n \"mem_reject\",\n [\n \"Mark a memory as rejected and record a reason.\",\n \"\",\n \"USE WHEN a memory is factually wrong, outdated, or not useful.\",\n \"Rejection blocks auto-promotion and lowers the memory's trust signal.\",\n \"Rejected memories are excluded from get_briefing by default.\",\n \"\",\n \"PARAMETERS:\",\n \" id — full memory id to reject\",\n \" reason — why this memory is being rejected (stored in frontmatter)\",\n \"\",\n \"RETURNS: { id, previous_status, new_status: 'rejected' }\",\n ].join(\"\\n\"),\n MemRejectInputSchema,\n async (input: MemRejectInput) => jsonResult(await memReject(input, context)),\n );\n\n registerTool(\n \"mem_feedback\",\n [\n \"Record whether a memory actually HELPED — the closed-loop utility signal.\",\n \"\",\n \"USE right after a memory changed (or failed to change) what you did:\",\n \" - outcome='applied' → the memory steered your work (strong positive signal)\",\n \" - outcome='rejected' → it was wrong/outdated/unhelpful (negative signal)\",\n \"\",\n \"A read only means a memory was surfaced; 'applied' means it demonstrably helped.\",\n \"This powers `hivelore memory impact` (impact tiers + prune candidates) and future ranking.\",\n \"\",\n \"PARAMETERS:\",\n \" id — full memory id the feedback is about\",\n \" outcome — 'applied' | 'rejected'\",\n \" reason — why it was rejected (optional, stored on the usage record)\",\n \"\",\n \"RETURNS: { ok, id, outcome, usage:{read_count,applied_count,rejected_count}, impact:{score,tier,signals} }\",\n ].join(\"\\n\"),\n MemFeedbackInputSchema,\n async (input: MemFeedbackInput) => jsonResult(await memFeedback(input, context)),\n );\n\n registerTool(\n \"mem_pending\",\n [\n \"List memories in 'proposed' status awaiting review, sorted by read count.\",\n \"\",\n \"USE IN MANUAL MODE to see what memories are waiting for human review.\",\n \"In autopilot mode, proposed memories auto-approve after 72h.\",\n \"\",\n \"High read_count on a proposed memory = many agents found it useful without\",\n \"rejecting it = strong signal to approve.\",\n \"\",\n \"RETURNS: array of { id, type, scope, read_count, created_at, body_preview }\",\n ].join(\"\\n\"),\n MemPendingInputSchema,\n async (input: MemPendingInput) => jsonResult(await memPending(input, context)),\n );\n\n registerTool(\n \"mem_delete\",\n [\n \"Permanently delete a memory by id.\",\n \"\",\n \"USE WITH CAUTION — prefer mem_reject for outdated memories (preserves history).\",\n \"Use delete only for accidentally created memories or duplicates.\",\n \"\",\n \"PARAMETERS:\",\n \" id — full memory id to delete\",\n \" delete_usage — also delete usage stats (default: true)\",\n \"\",\n \"RETURNS: { deleted: true, id }\",\n ].join(\"\\n\"),\n MemDeleteInputSchema,\n async (input: MemDeleteInput) => jsonResult(await memDelete(input, context)),\n );\n\n // ── v0.5.0: granular alternatives to get_briefing ─────────────────────\n // Use these when you don't need the full one-shot briefing payload.\n\n registerTool(\n \"get_recap\",\n [\n \"Return ONLY the most recent session_recap. Cheaper than get_briefing when\",\n \"you just want to know 'what was I doing last time?' and don't need project\",\n \"context, modules, or memory ranking.\",\n \"\",\n \"PARAMETERS:\",\n \" scope — 'personal' | 'team' | 'any' (default 'any', returns the most recent across both)\",\n \"\",\n \"RETURNS: { recap: { id, scope, revision_count, created_at, body } | null, notice? }\",\n ].join(\"\\n\"),\n GetRecapInputSchema,\n async (input: GetRecapInput) => {\n tracker.record(\"get_recap\", input.scope);\n return jsonResult(await getRecap(input, context));\n },\n );\n\n registerTool(\n \"mem_relevant_to\",\n [\n \"One-shot ranked memories for a task — use instead of get_briefing when\",\n \"project context is already loaded and you only want the relevant memory layer.\",\n \"\",\n \"Second step in progressive disclosure (after get_briefing): narrow here, then mem_get for full text.\",\n \"\",\n \"Reuses the same ranking pipeline (anchor / module / literal / semantic) but\",\n \"skips project_context, modules, action_required, etc.\",\n \"\",\n \"PARAMETERS:\",\n \" task — 1–2 sentences describing what you are about to do (required)\",\n \" files — files you'll edit (surfaces anchored memories)\",\n \" limit — cap on returned memories (default 8)\",\n \" min_semantic_score — drop weak semantic hits below this cosine (default 0.25)\",\n \" format — 'full' | 'compact' | 'actions' (inherits get_briefing memory framing)\",\n \"\",\n \"RETURNS: { task, search_mode, memories: [...], hints?: [...], empty?: true }\",\n ].join(\"\\n\"),\n MemRelevantToInputSchema,\n async (input: MemRelevantToInput) => {\n tracker.record(\"mem_relevant_to\", input.task.slice(0, 80));\n return jsonResult(await memRelevantTo(input, context));\n },\n );\n\n // ── v0.5.0: code semantic search ──────────────────────────────────────\n\n registerTool(\n \"code_search\",\n [\n \"Semantic search over the codebase — finds exported symbols (functions, classes,\",\n \"interfaces) related to a natural-language query. Replaces blind grep when you\",\n \"don't know the exact symbol name.\",\n \"\",\n \"Requires `hivelore index code-search` to have been run (builds embeddings for every\",\n \"exported symbol from the code-map). Falls back to a notice when index is missing.\",\n \"\",\n \"PARAMETERS:\",\n \" query — natural language (e.g. 'function that hashes passwords', 'JWT signing')\",\n \" k — number of top hits (default 5)\",\n \" min_score — minimum cosine similarity (default 0.2; try 0.3+ for stricter)\",\n \"\",\n \"RETURNS: { available: bool, hits: [{ file, name, kind, line, description?, score }] }\",\n ].join(\"\\n\"),\n CodeSearchInputSchema,\n async (input: CodeSearchInput) => {\n tracker.record(\"code_search\", input.query.slice(0, 80));\n return jsonResult(await codeSearch(input, context));\n },\n );\n\n // ── v0.5.0: file-context lookup ───────────────────────────────────────\n\n registerTool(\n \"why_this_file\",\n [\n \"One-shot file-context lookup: combines recent git history, memories anchored\",\n \"to the path, and the code-map entry. Answers 'why is this file the way it is?'\",\n \"in a single call instead of 3-4 manual ones.\",\n \"\",\n \"PARAMETERS:\",\n \" path — project-relative path (required)\",\n \" git_log_limit — recent commits to include (default 5)\",\n \" memory_limit — anchored memories cap (default 5)\",\n \"\",\n \"RETURNS: { file, exists, recent_commits: [...], memories: [...], code_map_entry, hints? }\",\n ].join(\"\\n\"),\n WhyThisFileInputSchema,\n async (input: WhyThisFileInput) => {\n tracker.record(\"why_this_file\", input.path);\n return jsonResult(await whyThisFile(input, context));\n },\n );\n\n // ── v0.5.0: anti-patterns check ───────────────────────────────────────\n\n registerTool(\n \"anti_patterns_check\",\n [\n \"Scan a diff (or set of paths) against documented attempt/gotcha memories.\",\n \"[Diff-scan layer: the MEMORY-MATCH component. `pre_commit_check` combines this with sensors + stale checks; `hivelore enforce check` is the gate.]\",\n \"Surfaces 'you are about to repeat a known mistake' warnings BEFORE you commit.\",\n \"\",\n \"USE BEFORE finalizing a non-trivial change. Cheap and high-signal: the only\",\n \"memories scanned are 'attempt' and 'gotcha' types.\",\n \"\",\n \"PARAMETERS:\",\n \" diff — raw unified diff text (or any code snippet) — optional if `paths` provided\",\n \" paths — affected file paths (optional if `diff` provided)\",\n \" limit — cap on returned warnings (default 8)\",\n \" semantic — also use semantic search (default true; requires embeddings index)\",\n \"\",\n \"RETURNS: { scanned, warnings: [{ id, type, scope, confidence, body_preview, reasons, semantic_score? }] }\",\n ].join(\"\\n\"),\n AntiPatternsCheckInputSchema,\n async (input: AntiPatternsCheckInput) => {\n tracker.record(\"anti_patterns_check\", input.paths.join(\",\").slice(0, 80));\n return jsonResult(await antiPatternsCheck(input, context));\n },\n );\n\n // ── v0.6.0 additions ───────────────────────────────────────────────────\n\n registerTool(\n \"mem_distill\",\n [\n \"Cluster recurring observations / failed attempts so a human can collapse\",\n \"N similar memories into one richer convention/gotcha. Cheap heuristic\",\n \"(anchor path overlap + body keyword overlap) — no embeddings required.\",\n \"\",\n \"USE periodically (e.g. monthly) to prevent memory pollution from agents\",\n \"saving the same observation many times.\",\n \"\",\n \"PARAMETERS:\",\n \" since_days — only consider memories from the last N days (default 30)\",\n \" min_cluster — minimum cluster size to surface (default 3)\",\n \" type_filter — 'gotcha' | 'attempt' | 'all' (default 'gotcha')\",\n \" scope — 'personal' | 'team' | 'module' | 'any' (default 'any')\",\n \"\",\n \"RETURNS: { scanned, singletons, clusters: [{ suggested_topic, member_ids, ... }] }\",\n \"Output is advisory — nothing is written to disk.\",\n ].join(\"\\n\"),\n MemDistillInputSchema,\n async (input: MemDistillInput) => {\n tracker.record(\"mem_distill\", `${input.type_filter}/since=${input.since_days}d`);\n return jsonResult(await memDistill(input, context));\n },\n );\n\n registerTool(\n \"why_this_decision\",\n [\n \"Trace the genealogy of a memory (especially decision/architecture):\",\n \"the memory itself + memories explicitly linked via related_ids + memories\",\n \"anchored to overlapping paths + recent commits touching those paths.\",\n \"\",\n \"USE WHEN you find a memory and need to understand WHY it was made and\",\n \"what surrounds it. One call instead of 4-5 manual lookups.\",\n \"\",\n \"PARAMETERS:\",\n \" id — memory id (required)\",\n \" git_log_limit — how many recent commits per anchor path (default 5)\",\n \"\",\n \"RETURNS: { decision, related: [...], path_neighbors: [...], recent_commits: [...] }\",\n ].join(\"\\n\"),\n WhyThisDecisionInputSchema,\n async (input: WhyThisDecisionInput) => {\n tracker.record(\"why_this_decision\", input.id);\n return jsonResult(await whyThisDecision(input, context));\n },\n );\n\n registerTool(\n \"mem_conflicts_with\",\n [\n \"Detect memories that potentially CONTRADICT a given memory.\",\n \"\",\n \"USE BEFORE relying on a memory's advice — surfaces 'another memory says\",\n \"the opposite'. Detection uses several heuristics layered together:\",\n \"\",\n \" 1. Opposite status — validated vs rejected on overlapping topic\",\n \" 2. attempt-vs-convention on overlapping anchor paths\",\n \" 3. Polarity keywords — 'use X' vs 'do not use X' among semantic neighbors\",\n \" 4. Explicit #contradicts:<id> tags in either body\",\n \"\",\n \"PARAMETERS:\",\n \" id — memory id to check (required)\",\n \" min_score — minimum cosine similarity for semantic neighbors (default 0.5)\",\n \" semantic — use embeddings (default true)\",\n \"\",\n \"RETURNS: { found, target, scanned, conflicts: [{ id, reasons, similarity, ... }] }\",\n ].join(\"\\n\"),\n MemConflictsInputSchema,\n async (input: MemConflictsInput) => {\n tracker.record(\"mem_conflicts_with\", input.id);\n return jsonResult(await memConflicts(input, context));\n },\n );\n\n registerTool(\n \"mem_conflict_candidates\",\n [\n \"Bulk scan for conflict CANDIDATES (not proof):\",\n \"\",\n \" 1. Lexical similarity (Jaccard) on decision/architecture-like pairs\",\n \" 2. Same frontmatter.topic with validated vs rejected — quick human-review signal\",\n \"\",\n \"Advisory only — follow with mem_conflicts_with on specific ids.\",\n \"\",\n \"PARAMETERS:\",\n \" since_days, types, min_jaccard, max_pairs, max_scan, max_topic_pairs\",\n \"\",\n \"RETURNS: { pairs, topic_status_pairs, scanned, truncated, notice? }\",\n ].join(\"\\n\"),\n MemConflictCandidatesInputSchema,\n async (input: MemConflictCandidatesInput) => {\n tracker.record(\"mem_conflict_candidates\", `${input.since_days}d`);\n return jsonResult(await memConflictCandidates(input, context));\n },\n );\n\n registerTool(\n \"runtime_journal_append\",\n [\n \"Append one line to `.ai/.runtime/session-journal.ndjson` — machine-local session continuity.\",\n \"\",\n \"Does NOT replace team memories; complements mem_session_end recaps for local traces.\",\n \"\",\n \"PARAMETERS: message, kind (note|session_end|mcp), optional tool\",\n \"\",\n \"RETURNS: { ok, path_hint }\",\n ].join(\"\\n\"),\n RuntimeJournalAppendInputSchema,\n async (input: RuntimeJournalAppendInput) =>\n jsonResult(await runtimeJournalAppend(input, context)),\n );\n\n registerTool(\n \"runtime_journal_tail\",\n [\n \"Read the last N entries from the runtime session journal (parsed JSON lines).\",\n \"\",\n \"PARAMETERS: limit (default 30, max 500)\",\n \"\",\n \"RETURNS: { entries: [...], empty?: true }\",\n ].join(\"\\n\"),\n RuntimeJournalTailInputSchema,\n async (input: RuntimeJournalTailInput) =>\n jsonResult(await runtimeJournalTail(input, context)),\n );\n\n registerTool(\n \"pre_commit_check\",\n [\n \"One-shot 'should I block this commit?' check. Combines three signals:\",\n \"[Diff-scan layer: the COMBINED check (sensors + anti-patterns + stale). `hivelore enforce check` is the gate that runs this at commit time.]\",\n \"\",\n \" 1. anti_patterns_check — known gotchas/attempts that match the diff\",\n \" 2. mem_for_files — conventions/decisions anchored to touched files\",\n \" 3. mem_verify — memories whose anchors are stale (knowledge may be wrong)\",\n \"\",\n \"USE FROM A GIT HOOK or before finalizing a non-trivial change.\",\n \"\",\n \"PARAMETERS:\",\n \" diff — raw unified diff text (e.g. `git diff --cached`)\",\n \" paths — affected file paths (project-relative)\",\n \" block_on — 'any' | 'high-confidence' (default) | 'never'\",\n \" semantic — use embeddings in anti_patterns_check (default true)\",\n \"\",\n \"RETURNS: { should_block, summary, warnings, relevant_memories, stale_anchors }\",\n ].join(\"\\n\"),\n PreCommitCheckInputSchema,\n async (input: PreCommitCheckInput) => {\n tracker.record(\"pre_commit_check\", `${input.paths.length}p`);\n return jsonResult(await preCommitCheck(input, context));\n },\n );\n\n registerTool(\n \"pattern_detect\",\n [\n \"Heuristic memory detector — finds knowledge worth saving WITHOUT calling an LLM.\",\n \"\",\n \"Runs three signals over local git history and the tool-usage log:\",\n \" 1. CONFIG_CHANGE — config files modified recently (tsconfig, eslint, prettier, …)\",\n \" → proposes a convention memory with the git diff as body.\",\n \" 2. REPEATED_PATH — same file appears ≥3× in mem_tried/mem_observe events\",\n \" → proposes a gotcha memory anchored to that path.\",\n \" 3. HOT_FILE — source file referenced ≥3× in writing-tool events\",\n \" → proposes a convention memory (frequent edits = pattern emerging).\",\n \"\",\n \"Saves memories with status='proposed'. They feed into auto-promote (Phase 4)\",\n \"or are surfaced in the next post_task distillation for LLM review.\",\n \"\",\n \"USE periodically (e.g. end of sprint) or trigger from post-commit hook.\",\n \"\",\n \"PARAMETERS:\",\n \" since_days — look-back window in days (default 7)\",\n \" dry_run — report matches without saving (default false)\",\n \" scope — 'team' (default) | 'personal'\",\n \"\",\n \"RETURNS: { scanned_events, matches: [{kind, signal, proposed_type, …}], saved, saved_ids }\",\n ].join(\"\\n\"),\n PatternDetectInputSchema,\n async (input: PatternDetectInput) => {\n tracker.record(\"pattern_detect\", `since=${input.since_days}d/dry_run=${input.dry_run}`);\n return jsonResult(await patternDetect(input, context));\n },\n );\n\n registerTool(\n \"mem_diff\",\n [\n \"Compare two memories side-by-side to decide if they should be merged.\",\n \"\",\n \"USE BEFORE merging or deduplicating similar memories.\",\n \"Shows: frontmatter fields that differ + lines unique to each body.\",\n \"\",\n \"PARAMETERS:\",\n \" id_a — first memory id\",\n \" id_b — second memory id\",\n \"\",\n \"RETURNS: { frontmatter_diff: {...}, body_only_in_a: [...], body_only_in_b: [...] }\",\n ].join(\"\\n\"),\n MemDiffInputSchema,\n async (input: MemDiffInput) => jsonResult(await memDiff(input, context)),\n );\n\n if (shouldRegisterPrompt(\"bootstrap_project\")) {\n server.prompt(\n \"bootstrap_project\",\n [\n \"Analyze the project codebase and write .ai/project-context.md — run once after hivelore init.\",\n \"The AI explores the directory structure, reads key files (package.json, README, config),\",\n \"identifies the tech stack, architectural patterns, key modules, and conventions,\",\n \"then persists everything via bootstrap_project_save.\",\n \"For multi-component projects, run with module param to create .ai/modules/<name>/context.md.\",\n ].join(\" \"),\n BootstrapProjectArgsSchema,\n (args: BootstrapProjectArgs) => bootstrapProjectPrompt(args, context),\n );\n }\n\n if (shouldRegisterPrompt(\"bootstrap_repo\")) {\n server.prompt(\n \"bootstrap_repo\",\n [\n \"⭐ First-agent bootstrap — run once on a fresh repo to fill the knowledge layer the bootstrap\",\n \"gate requires: project-context, a module context per component, anchored memories, and a\",\n \"validated sensor per main code area. Tailors a concrete checklist from the current corpus state\",\n \"and walks the agent through bootstrap_project_save, mem_save, and propose_sensor until READY.\",\n ].join(\" \"),\n BootstrapRepoArgsSchema,\n (args: BootstrapRepoArgs) => bootstrapRepoPrompt(args, context),\n );\n }\n\n if (shouldRegisterPrompt(\"post_task\")) {\n server.prompt(\n \"post_task\",\n [\n \"⭐ Post-task reflection — run at the end of every session to capture what you learned:\",\n \"failed approaches (mem_tried), new conventions/decisions/gotchas (mem_save),\",\n \"code discoveries (mem_observe), and an end-of-session recap (mem_session_end).\",\n \"In autopilot mode a minimal recap saves automatically; calling this produces a richer one.\",\n ].join(\" \"),\n PostTaskArgsSchema,\n (args: PostTaskArgs) => postTaskPrompt(args, context),\n );\n }\n\n if (shouldRegisterPrompt(\"import_docs\")) {\n server.prompt(\n \"import_docs\",\n [\n \"Import knowledge from a document (README, ADR, wiki, API spec) as Hivelore memories.\",\n \"Pass the full document content; the AI extracts up to 10 actionable memories\",\n \"(conventions, decisions, gotchas, architecture) and saves them via mem_save.\",\n \"Good candidates: ADRs, onboarding docs, runbooks, team wikis.\",\n ].join(\" \"),\n ImportDocsArgsSchema,\n (args: ImportDocsArgs) => importDocsPrompt(args, context),\n );\n }\n\n return { server, context, tracker };\n}\n\n// ── Stdio runtime (also invoked by `hivelore mcp --stdio` via bundled CLI) ─────\n\n/** Parse argv for the standalone haive-mcp binary / CLI subprocess parity. */\nexport function parseMcpCliArgs(argv: string[]): {\n root?: string;\n versionOnly: boolean;\n} {\n for (let i = 2; i < argv.length; i++) {\n const arg = argv[i];\n if (arg === \"--version\" || arg === \"-V\") {\n return { versionOnly: true };\n }\n }\n const out: { root?: string } = {};\n for (let i = 2; i < argv.length; i++) {\n const arg = argv[i];\n if (arg === \"--root\" || arg === \"-r\") {\n out.root = argv[++i];\n } else if (arg?.startsWith(\"--root=\")) {\n out.root = arg.slice(\"--root=\".length);\n }\n }\n return { root: out.root, versionOnly: false };\n}\n\n/** Print MCP server version (same as haive CLI when bundled together). */\nexport function printHaiveMcpVersion(): void {\n console.log(SERVER_VERSION);\n}\n\n/**\n * Run the MCP server over stdio. Used by `haive-mcp` and by `hivelore mcp --stdio`\n * when the MCP implementation is bundled into the CLI.\n */\nexport async function runHaiveMcpStdio(options: { root?: string }): Promise<void> {\n const { server, context } = createHaiveServer({ root: options.root, env: process.env });\n console.error(\n `[haive-mcp] starting server v${SERVER_VERSION} (project root: ${context.paths.root})`,\n );\n await server.connect(new StdioServerTransport());\n}\n","import { findProjectRoot, resolveHaivePaths, type HaivePaths } from \"@hivelore/core\";\n\nexport interface HaiveContext {\n paths: HaivePaths;\n}\n\nexport interface CreateContextOptions {\n root?: string;\n env?: NodeJS.ProcessEnv;\n cwd?: string;\n}\n\nexport function createContext(options: CreateContextOptions = {}): HaiveContext {\n const env = options.env ?? process.env;\n const cwd = options.cwd ?? process.cwd();\n const root =\n options.root ??\n env.HAIVE_PROJECT_ROOT ??\n findProjectRoot(cwd);\n return { paths: resolveHaivePaths(root) };\n}\n","import { mkdir, writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const BootstrapProjectSaveInputSchema = {\n content: z\n .string()\n .min(1)\n .describe(\"Full Markdown content for the project (or module) context file\"),\n module: z\n .string()\n .optional()\n .describe(\n \"If provided, save under .ai/modules/<module>/context.md instead of .ai/project-context.md\",\n ),\n overwrite: z\n .boolean()\n .default(false)\n .describe(\"Overwrite an existing file instead of failing\"),\n};\n\nexport type BootstrapProjectSaveInput = {\n [K in keyof typeof BootstrapProjectSaveInputSchema]: z.infer<\n (typeof BootstrapProjectSaveInputSchema)[K]\n >;\n};\n\nexport interface BootstrapProjectSaveOutput {\n file_path: string;\n action: \"created\" | \"overwritten\";\n}\n\nexport async function bootstrapProjectSave(\n input: BootstrapProjectSaveInput,\n ctx: HaiveContext,\n): Promise<BootstrapProjectSaveOutput> {\n const target = input.module\n ? path.join(ctx.paths.modulesContextDir, input.module, \"context.md\")\n : ctx.paths.projectContext;\n\n const exists = existsSync(target);\n if (exists && !input.overwrite) {\n throw new Error(\n `${target} already exists. Pass overwrite=true to replace it.`,\n );\n }\n\n await mkdir(path.dirname(target), { recursive: true });\n await writeFile(target, input.content, \"utf8\");\n\n return {\n file_path: target,\n action: exists ? \"overwritten\" : \"created\",\n };\n}\n","import { readFile, readdir } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const GetProjectContextInputSchema = {\n module: z\n .string()\n .optional()\n .describe(\"If provided, also include the matching module's context file\"),\n list_modules: z\n .boolean()\n .default(false)\n .describe(\"Return the list of available module context files\"),\n};\n\nexport type GetProjectContextInput = {\n [K in keyof typeof GetProjectContextInputSchema]: z.infer<\n (typeof GetProjectContextInputSchema)[K]\n >;\n};\n\nexport interface GetProjectContextOutput {\n root_context: string | null;\n module_context?: { name: string; content: string };\n available_modules?: string[];\n}\n\nexport async function getProjectContext(\n input: GetProjectContextInput,\n ctx: HaiveContext,\n): Promise<GetProjectContextOutput> {\n const out: GetProjectContextOutput = { root_context: null };\n\n if (existsSync(ctx.paths.projectContext)) {\n out.root_context = await readFile(ctx.paths.projectContext, \"utf8\");\n }\n\n if (input.module) {\n const modFile = path.join(ctx.paths.modulesContextDir, input.module, \"context.md\");\n if (existsSync(modFile)) {\n out.module_context = {\n name: input.module,\n content: await readFile(modFile, \"utf8\"),\n };\n }\n }\n\n if (input.list_modules) {\n out.available_modules = await listModules(ctx.paths.modulesContextDir);\n }\n\n return out;\n}\n\nasync function listModules(modulesDir: string): Promise<string[]> {\n if (!existsSync(modulesDir)) return [];\n const entries = await readdir(modulesDir, { withFileTypes: true });\n return entries.filter((e) => e.isDirectory()).map((e) => e.name).sort();\n}\n","import { existsSync } from \"node:fs\";\nimport { loadMemoriesFromDir } from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const MemListInputSchema = {\n scope: z.enum([\"personal\", \"team\", \"module\"]).optional(),\n type: z\n .enum([\"convention\", \"decision\", \"gotcha\", \"architecture\", \"glossary\"])\n .optional(),\n module: z.string().optional(),\n tag: z.string().optional(),\n status: z\n .enum([\"draft\", \"proposed\", \"validated\", \"deprecated\", \"stale\", \"rejected\"])\n .optional()\n .describe(\"Filter by a single status. Omit to return all statuses.\"),\n exclude_rejected: z\n .boolean()\n .default(false)\n .describe(\"When true, exclude memories with status=rejected from results.\"),\n include_body: z\n .boolean()\n .default(false)\n .describe(\"Include full body text. Default false to save tokens — use mem_get for a single memory's full content.\"),\n};\n\nexport type MemListInput = {\n [K in keyof typeof MemListInputSchema]: z.infer<(typeof MemListInputSchema)[K]>;\n};\n\nexport interface MemSummary {\n id: string;\n scope: string;\n type: string;\n module?: string;\n status: string;\n tags: string[];\n snippet: string;\n file_path: string;\n body?: string;\n}\n\nexport async function memList(\n input: MemListInput,\n ctx: HaiveContext,\n): Promise<{ memories: MemSummary[] }> {\n if (!existsSync(ctx.paths.memoriesDir)) {\n return { memories: [] };\n }\n const all = await loadMemoriesFromDir(ctx.paths.memoriesDir);\n const filtered = all.filter(({ memory }) => {\n const fm = memory.frontmatter;\n if (input.scope && fm.scope !== input.scope) return false;\n if (input.type && fm.type !== input.type) return false;\n if (input.module && fm.module !== input.module) return false;\n if (input.tag && !fm.tags.includes(input.tag)) return false;\n if (input.status && fm.status !== input.status) return false;\n if (input.exclude_rejected && fm.status === \"rejected\") return false;\n return true;\n });\n const memories: MemSummary[] = filtered.map(({ memory, filePath }) => {\n const fm = memory.frontmatter;\n const snippet = memory.body.replace(/\\s+/g, \" \").trim().slice(0, 120);\n return {\n id: fm.id,\n scope: fm.scope,\n type: fm.type,\n ...(fm.module ? { module: fm.module } : {}),\n status: fm.status,\n tags: fm.tags,\n snippet,\n file_path: filePath,\n ...(input.include_body ? { body: memory.body } : {}),\n };\n });\n return { memories };\n}\n","import { createHash } from \"node:crypto\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n buildFrontmatter,\n loadConfig,\n loadMemoriesFromDir,\n memoryFilePath,\n serializeMemory,\n suggestSensorSeed,\n type Sensor,\n} from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const MemSaveInputSchema = {\n type: z\n .enum([\"convention\", \"decision\", \"gotcha\", \"architecture\", \"glossary\", \"skill\", \"attempt\", \"session_recap\"])\n .describe(\n \"Kind of memory being saved. \" +\n \"Use 'skill' for reusable procedures/playbooks agents should follow for recurring tasks (feedforward harness guide). \" +\n \"Use 'attempt' for failed approaches (auto-validated). \" +\n \"Use 'session_recap' via mem_session_end instead.\",\n ),\n slug: z\n .string()\n .min(1)\n .describe(\"Short human-readable identifier — becomes part of the filename\"),\n body: z\n .string()\n .describe(\"Markdown body of the memory\"),\n scope: z\n .enum([\"personal\", \"team\", \"module\"])\n .optional()\n .describe(\n \"Visibility scope: personal | team | module. \" +\n \"When omitted, falls back to defaultScope in haive.config.json (default: personal).\",\n ),\n module: z\n .string()\n .optional()\n .describe(\"Module name (required when scope=module)\"),\n tags: z.array(z.string()).default([]).describe(\"Tags for filtering\"),\n domain: z.string().optional().describe(\"Domain (e.g. transactions, billing)\"),\n author: z.string().optional().describe(\"Author handle or email\"),\n paths: z\n .array(z.string())\n .default([])\n .describe(\"Anchor paths (file paths this memory references)\"),\n symbols: z\n .array(z.string())\n .default([])\n .describe(\"Anchor symbols (function/class names this memory references)\"),\n commit: z\n .string()\n .optional()\n .describe(\"Anchor commit SHA (for staleness detection later)\"),\n topic: z\n .string()\n .optional()\n .describe(\n \"Stable key for this memory. If a memory with the same topic already exists in this scope, \" +\n \"it is updated in-place (revision_count++). Use for knowledge that evolves over time.\",\n ),\n activation: z\n .object({\n keywords: z.array(z.string()).default([]),\n globs: z.array(z.string()).default([]),\n always: z.boolean().default(false),\n })\n .optional()\n .describe(\n \"Only for type='skill'. Progressive-disclosure triggers: the skill is surfaced ONLY when \" +\n \"a keyword matches the task or a glob matches the edited files (or always=true). Omit to keep \" +\n \"the skill always-eligible.\",\n ),\n};\n\nexport type MemSaveInput = {\n [K in keyof typeof MemSaveInputSchema]: z.infer<(typeof MemSaveInputSchema)[K]>;\n};\n\nexport interface MemSaveOutput {\n id: string;\n scope: string;\n file_path: string;\n action: \"created\" | \"updated\";\n revision_count?: number;\n warning?: string;\n similar_found?: string[];\n /** High textual overlap with existing memory (same scope+type); consider merging instead. */\n body_similar?: { id: string; score: number };\n invalid_paths?: string[];\n /**\n * A gotcha/attempt anchored to code only CLOSES its prevention loop (the gate can block the repeat)\n * once a sensor is VALIDATED via propose_sensor. True until then — the lesson is briefed but not enforced.\n */\n loop_open?: boolean;\n /**\n * Heuristic candidate to PRE-FILL a propose_sensor call (refine, then call it). The agent owns the\n * final pattern — this is a starting point, never a persisted sensor.\n */\n proposed_sensor_seed?: { pattern: string; absent?: string; message: string };\n /** Directive describing how to close the loop (call propose_sensor). */\n sensor_hint?: string;\n}\n\n/**\n * Replace the old \"auto-write a heuristic warn sensor\" behavior: a saved gotcha/attempt no longer\n * persists a sensor. Instead we report whether the prevention loop is still open and, when possible,\n * a SEED to pre-fill propose_sensor — which validates the pattern (silent on current code, fires on\n * the bad example) before it is trusted. propose_sensor is now the sole writer of live sensors.\n */\nfunction sensorLoopState(\n type: string,\n body: string,\n paths: string[],\n existingSensor: Sensor | undefined,\n): Pick<MemSaveOutput, \"loop_open\" | \"proposed_sensor_seed\" | \"sensor_hint\"> {\n if (type !== \"gotcha\" && type !== \"attempt\") return {};\n // Already protected by a sensor (validated via propose_sensor, or a legacy one) → loop closed.\n if (existingSensor) return {};\n if (paths.length === 0) {\n return {\n loop_open: true,\n sensor_hint:\n \"No `paths` given, so this lesson is feedforward-only — it will be briefed but the gate cannot \" +\n \"block the repeat. Re-save with `paths` set to the file(s) where the mistake lives, then call \" +\n \"propose_sensor to close the loop.\",\n };\n }\n const seed = suggestSensorSeed(body, paths);\n if (seed) {\n return {\n loop_open: true,\n proposed_sensor_seed: {\n pattern: seed.pattern,\n ...(seed.absent ? { absent: seed.absent } : {}),\n message: seed.message,\n },\n sensor_hint:\n \"This lesson is NOT yet enforced. Call propose_sensor to turn it into a reliable block — a \" +\n \"candidate is pre-filled in proposed_sensor_seed (refine it: pattern = the faulty usage, \" +\n \"absent = the correct-usage marker). Hivelore validates the proposal (silent on current code, \" +\n \"fires on the bad example) before trusting it to block.\",\n };\n }\n return {\n loop_open: true,\n sensor_hint:\n \"This lesson is NOT yet enforced and no candidate pattern could be derived from the wording. Call \" +\n \"propose_sensor with a discriminating pattern (pattern = faulty usage, absent = correct-usage \" +\n \"marker) to close the loop.\",\n };\n}\n\nfunction bodyHash(body: string): string {\n return createHash(\"sha256\").update(body.trim()).digest(\"hex\").slice(0, 12);\n}\n\nconst WORD_RE = /\\b[a-z0-9]{3,}\\b/gi;\n\nfunction bodyTokenSet(body: string): Set<string> {\n const raw = body.toLowerCase().match(WORD_RE) ?? [];\n return new Set(raw);\n}\n\n/** Jaccard similarity on alphanumeric tokens — warns when corpus has near-duplicate wording. */\nfunction maxBodySimilarity(\n incomingTokens: Set<string>,\n memories: Array<{ memory: { body: string; frontmatter: { scope: string; type: string; id: string; status?: string } } }>,\n scope: string,\n type: string,\n excludeIds?: ReadonlySet<string>,\n): { score: number; id: string } | null {\n if (incomingTokens.size < 6) return null;\n let best: { score: number; id: string } | null = null;\n const skip = excludeIds ?? new Set<string>();\n for (const { memory } of memories) {\n const fm = memory.frontmatter;\n if (skip.has(fm.id)) continue;\n if (fm.scope !== scope || fm.type !== type) continue;\n if (fm.status === \"rejected\" || fm.status === \"deprecated\") continue;\n const other = bodyTokenSet(memory.body);\n if (other.size === 0) continue;\n let inter = 0;\n for (const t of incomingTokens) if (other.has(t)) inter++;\n const uni = incomingTokens.size + other.size - inter;\n const j = uni === 0 ? 0 : inter / uni;\n if (j >= 0.72 && (!best || j > best.score)) best = { score: j, id: fm.id };\n }\n return best;\n}\n\nexport async function memSave(\n input: MemSaveInput,\n ctx: HaiveContext,\n): Promise<MemSaveOutput> {\n if (!existsSync(ctx.paths.haiveDir)) {\n throw new Error(\n `No .ai/ directory at ${ctx.paths.root}. Run 'hivelore init' first.`,\n );\n }\n\n const existing = existsSync(ctx.paths.memoriesDir)\n ? await loadMemoriesFromDir(ctx.paths.memoriesDir)\n : [];\n\n // ── Resolve scope once: explicit input wins over config default ────────\n // Must be computed early so dedup and topic-upsert use the same scope\n // that the new memory will ultimately be saved under.\n const haiveConfig = await loadConfig(ctx.paths);\n const resolvedScope = (\n input.scope ?? haiveConfig.defaultScope ?? \"personal\"\n ) as \"personal\" | \"team\" | \"module\";\n\n // ── Anchor path validation ─────────────────────────────────────────────\n const invalidPaths = input.paths.filter(\n (p) => !existsSync(path.resolve(ctx.paths.root, p)),\n );\n\n // ── Dedup by content hash ──────────────────────────────────────────────\n const incomingHash = bodyHash(input.body);\n const hashDuplicate = existing.find(({ memory }) =>\n bodyHash(memory.body) === incomingHash &&\n memory.frontmatter.scope === resolvedScope,\n );\n if (hashDuplicate) {\n throw new Error(\n `Duplicate content detected — identical body already saved as \"${hashDuplicate.memory.frontmatter.id}\". ` +\n `Use mem_update to modify it, or change the body to add new information.`,\n );\n }\n\n const incomingTokens = bodyTokenSet(input.body);\n\n function bodySimilarWarnings(excludeIds?: ReadonlySet<string>): {\n similarityWarning?: string;\n body_similar?: MemSaveOutput[\"body_similar\"];\n } {\n const dup = maxBodySimilarity(incomingTokens, existing, resolvedScope, input.type, excludeIds);\n if (!dup?.id) return {};\n const body_similar: MemSaveOutput[\"body_similar\"] = {\n id: dup.id,\n score: Math.round(dup.score * 100) / 100,\n };\n return {\n similarityWarning: `Body is ~${Math.round(dup.score * 100)}% similar (token overlap) to existing \"${dup.id}\" — consolidate if redundant.`,\n body_similar,\n };\n }\n\n // ── Topic upsert ───────────────────────────────────────────────────────\n if (input.topic) {\n const topicMatch = existing.find(({ memory }) =>\n memory.frontmatter.topic === input.topic &&\n memory.frontmatter.scope === resolvedScope &&\n (!input.module || memory.frontmatter.module === input.module),\n );\n\n if (topicMatch) {\n const fm = topicMatch.memory.frontmatter;\n const { similarityWarning: simW, body_similar: bs } = bodySimilarWarnings(new Set([fm.id]));\n const newFrontmatter = {\n ...fm,\n tags: input.tags.length ? input.tags : fm.tags,\n revision_count: (fm.revision_count ?? 0) + 1,\n anchor: {\n commit: input.commit ?? fm.anchor.commit,\n paths: input.paths.length ? input.paths : fm.anchor.paths,\n symbols: input.symbols.length ? input.symbols : fm.anchor.symbols,\n },\n };\n await writeFile(\n topicMatch.filePath,\n serializeMemory({ frontmatter: newFrontmatter, body: input.body }),\n \"utf8\",\n );\n const mergedTw = [\n invalidPaths.length > 0\n ? `Anchor path(s) not found in project: ${invalidPaths.join(\", \")}. They will be marked stale by hivelore sync.`\n : null,\n criticalAnchorWarning(input.type, fm.status, newFrontmatter.anchor.paths, newFrontmatter.anchor.symbols),\n simW ?? null,\n ]\n .filter(Boolean)\n .join(\" — \") || undefined;\n\n const sensorState = sensorLoopState(input.type, input.body, newFrontmatter.anchor.paths, newFrontmatter.sensor);\n\n return {\n id: fm.id,\n scope: fm.scope,\n file_path: topicMatch.filePath,\n action: \"updated\",\n revision_count: newFrontmatter.revision_count,\n ...(mergedTw ? { warning: mergedTw } : {}),\n ...(bs ? { body_similar: bs } : {}),\n ...(invalidPaths.length > 0 ? { invalid_paths: invalidPaths } : {}),\n ...sensorState,\n };\n }\n }\n\n // ── Create new memory ──────────────────────────────────────────────────\n // resolvedScope and haiveConfig are already computed above.\n\n const frontmatter = buildFrontmatter({\n type: input.type,\n slug: input.slug,\n scope: resolvedScope,\n module: input.module,\n tags: input.tags,\n domain: input.domain,\n author: input.author,\n paths: input.paths,\n symbols: input.symbols,\n commit: input.commit,\n topic: input.topic,\n status: haiveConfig.defaultStatus === \"validated\" ? \"validated\" : undefined,\n activation: input.type === \"skill\" ? input.activation : undefined,\n });\n // Created already-validated by config (defaultStatus), not by explicit review → mark \"auto\".\n if (frontmatter.status === \"validated\") frontmatter.validated_by = \"auto\";\n\n const file = memoryFilePath(\n ctx.paths,\n frontmatter.scope,\n frontmatter.id,\n frontmatter.module,\n );\n await mkdir(path.dirname(file), { recursive: true });\n\n if (existsSync(file)) {\n throw new Error(`Memory already exists at ${file}`);\n }\n\n // ── Similar slug detection (warn but don't block) ──────────────────────\n let warning: string | undefined;\n let similar_found: string[] | undefined;\n if (existing.length > 0) {\n const slugTokens = input.slug.toLowerCase().split(/[-_\\s]+/).filter(Boolean);\n const similar = existing.filter(({ memory }) => {\n const id = memory.frontmatter.id.toLowerCase();\n return (\n slugTokens.length >= 2 &&\n slugTokens.filter((t) => id.includes(t)).length >= Math.ceil(slugTokens.length * 0.6)\n );\n });\n if (similar.length > 0) {\n similar_found = similar.map((m) => m.memory.frontmatter.id);\n warning = `Possible duplicate: similar memories already exist (${similar_found.join(\", \")}). Consider updating one of these instead.`;\n }\n }\n\n await writeFile(file, serializeMemory({ frontmatter, body: input.body }), \"utf8\");\n\n const { similarityWarning: simWarnNew, body_similar: bsNew } = bodySimilarWarnings();\n\n // Merge warnings: invalid anchors + slug similarity + body similarity\n const finalWarning = [\n invalidPaths.length > 0\n ? `Anchor path(s) not found in project: ${invalidPaths.join(\", \")}. They will be marked stale by \\`hivelore sync\\`.`\n : null,\n criticalAnchorWarning(frontmatter.type, frontmatter.status, frontmatter.anchor.paths, frontmatter.anchor.symbols),\n warning ?? null,\n simWarnNew ?? null,\n ].filter(Boolean).join(\" — \") || undefined;\n\n return {\n id: frontmatter.id,\n scope: frontmatter.scope,\n file_path: file,\n action: \"created\",\n ...(finalWarning ? { warning: finalWarning } : {}),\n ...(similar_found ? { similar_found } : {}),\n ...(bsNew ? { body_similar: bsNew } : {}),\n ...(invalidPaths.length > 0 ? { invalid_paths: invalidPaths } : {}),\n ...sensorLoopState(input.type, input.body, input.paths, frontmatter.sensor),\n };\n}\n\nfunction criticalAnchorWarning(\n type: string,\n status: string,\n paths: string[],\n symbols: string[],\n): string | null {\n if (![\"decision\", \"gotcha\", \"architecture\"].includes(type)) return null;\n if (status !== \"validated\") return null;\n if (paths.length > 0 || symbols.length > 0) return null;\n return `${type} is validated without paths or symbols; add anchors so Hivelore can detect drift.`;\n}\n","import { existsSync } from \"node:fs\";\nimport {\n deriveConfidence,\n extractSnippet,\n getUsage,\n literalMatchesAllTokens,\n literalMatchesAnyToken,\n loadMemoriesFromDir,\n loadUsageIndex,\n pickSnippetNeedle,\n rankMemoriesLexical,\n tokenizeQuery,\n trackReads,\n type ConfidenceLevel,\n type LoadedMemory,\n type UsageIndex,\n} from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const MemSearchInputSchema = {\n query: z.string().describe(\"Substring matched against id, tags, and body\"),\n scope: z\n .enum([\"personal\", \"team\", \"module\"])\n .optional()\n .describe(\"Restrict results to a single scope\"),\n type: z\n .enum([\"convention\", \"decision\", \"gotcha\", \"architecture\", \"glossary\", \"attempt\", \"session_recap\"])\n .optional()\n .describe(\"Restrict results to a memory type. session_recap is excluded by default — use type='session_recap' to include them.\"),\n include_session_recap: z\n .boolean()\n .default(false)\n .describe(\"Include session_recap memories in search results (excluded by default — they surface in get_briefing as last_session).\"),\n module: z.string().optional().describe(\"Restrict results to a module\"),\n status: z\n .enum([\"draft\", \"proposed\", \"validated\", \"deprecated\", \"stale\", \"rejected\"])\n .optional()\n .describe(\"Filter by a single status. Omit to return all statuses.\"),\n exclude_rejected: z\n .boolean()\n .default(false)\n .describe(\"When true, exclude memories with status=rejected from results.\"),\n limit: z.number().int().positive().max(100).default(20).describe(\"Max results\"),\n semantic: z\n .boolean()\n .default(false)\n .describe(\n \"Use semantic similarity from the embeddings index (requires `hivelore embeddings index`).\",\n ),\n lexical_rank: z\n .boolean()\n .default(false)\n .describe(\n \"When true (and semantic is false), rank the filtered corpus with Okapi-BM25-style lexical scoring instead of literal AND/OR. Helps phrase-like queries without embeddings.\",\n ),\n min_score: z\n .number()\n .min(0)\n .max(1)\n .default(0)\n .describe(\"Minimum cosine similarity (semantic mode only)\"),\n track: z\n .boolean()\n .default(true)\n .describe(\"Increment read_count on returned memories (used for passive validation)\"),\n};\n\nexport type MemSearchInput = {\n [K in keyof typeof MemSearchInputSchema]: z.infer<(typeof MemSearchInputSchema)[K]>;\n};\n\n/** session_recap memories are surfaced separately via get_briefing.last_session — not in search results by default. */\nfunction isSessionRecap(fm: { type: string }): boolean {\n return fm.type === \"session_recap\";\n}\n\nexport interface MemSearchHit {\n id: string;\n scope: string;\n type: string;\n module?: string;\n tags: string[];\n status: string;\n confidence: ConfidenceLevel;\n read_count: number;\n snippet: string;\n file_path: string;\n score?: number;\n}\n\nexport interface MemSearchOutput {\n matches: MemSearchHit[];\n total: number;\n mode: \"literal\" | \"semantic\" | \"literal_fallback\" | \"lexical_ranked\";\n notice?: string;\n}\n\nexport async function memSearch(\n input: MemSearchInput,\n ctx: HaiveContext,\n): Promise<MemSearchOutput> {\n if (!existsSync(ctx.paths.memoriesDir)) {\n return { matches: [], total: 0, mode: input.semantic ? \"literal_fallback\" : \"literal\" };\n }\n\n const all = await loadMemoriesFromDir(ctx.paths.memoriesDir);\n const filtered = all.filter(({ memory }) => passesFilters(memory.frontmatter, input));\n const usage = await loadUsageIndex(ctx.paths);\n\n let result: MemSearchOutput;\n if (input.semantic) {\n const semantic = await trySemanticSearch(ctx, input, filtered, usage);\n if (semantic) {\n result = semantic;\n } else {\n result = {\n ...buildLiteralResult(input, filtered, usage),\n mode: \"literal_fallback\",\n notice:\n \"Semantic search unavailable (embeddings index missing or @hivelore/embeddings not installed). Falling back to literal search.\",\n };\n }\n } else if (input.lexical_rank && input.query.trim()) {\n const { ranked, scores } = rankMemoriesLexical(\n filtered,\n input.query,\n input.limit,\n );\n if (ranked.length > 0) {\n const snippetNeedle = pickSnippetNeedle(input.query);\n result = {\n matches: ranked.map((loaded, i) =>\n lexicalHit(loaded, snippetNeedle, usage, scores[i]!),\n ),\n total: ranked.length,\n mode: \"lexical_ranked\",\n };\n } else {\n result = {\n ...buildLiteralResult(input, filtered, usage),\n notice: \"Lexical ranking found no BM25-positive hits — showing literal matches instead.\",\n };\n }\n } else {\n result = buildLiteralResult(input, filtered, usage);\n }\n\n if (input.track && result.matches.length > 0) {\n await trackReads(\n ctx.paths,\n result.matches.map((m) => m.id),\n );\n }\n\n return result;\n}\n\nfunction passesFilters(\n fm: LoadedMemory[\"memory\"][\"frontmatter\"],\n input: MemSearchInput,\n): boolean {\n if (input.scope && fm.scope !== input.scope) return false;\n if (input.type && fm.type !== input.type) return false;\n if (input.module && fm.module !== input.module) return false;\n if (input.status && fm.status !== input.status) return false;\n if (input.exclude_rejected && fm.status === \"rejected\") return false;\n // session_recap memories surface via get_briefing.last_session — exclude unless explicitly requested\n if (!input.include_session_recap && isSessionRecap(fm)) return false;\n return true;\n}\n\nfunction buildLiteralResult(\n input: MemSearchInput,\n filtered: LoadedMemory[],\n usage: UsageIndex,\n): { matches: MemSearchHit[]; total: number; mode: \"literal\"; notice?: string } {\n const tokens = tokenizeQuery(input.query);\n const snippetNeedle = pickSnippetNeedle(input.query);\n\n let andMatched = filtered.filter(({ memory }) => literalMatchesAllTokens(memory, tokens));\n if (andMatched.length > 0) {\n const top = andMatched.slice(0, input.limit);\n return {\n matches: top.map((loaded) => toHit(loaded, snippetNeedle, usage)),\n total: andMatched.length,\n mode: \"literal\",\n };\n }\n\n // AND returned nothing — fall back to OR (any token)\n const orMatched = filtered.filter(({ memory }) => literalMatchesAnyToken(memory, tokens));\n const top = orMatched.slice(0, input.limit);\n return {\n matches: top.map((loaded) => toHit(loaded, snippetNeedle, usage)),\n total: orMatched.length,\n mode: \"literal\",\n notice: `No exact match for all tokens. Showing partial matches (OR fallback) — ${orMatched.length} result${orMatched.length === 1 ? \"\" : \"s\"}.`,\n };\n}\n\nasync function trySemanticSearch(\n ctx: HaiveContext,\n input: MemSearchInput,\n filtered: LoadedMemory[],\n usage: UsageIndex,\n): Promise<MemSearchOutput | null> {\n let mod: typeof import(\"@hivelore/embeddings\");\n try {\n mod = await import(\"@hivelore/embeddings\");\n } catch {\n return null;\n }\n const result = await mod.semanticSearch(ctx.paths, input.query, {\n limit: Math.min(input.limit * 3, 100),\n minScore: input.min_score,\n });\n if (!result) return null;\n\n const allowedIds = new Set(filtered.map((m) => m.memory.frontmatter.id));\n const byId = new Map(filtered.map((m) => [m.memory.frontmatter.id, m]));\n\n const ranked = result.hits\n .filter((h) => allowedIds.has(h.id))\n .slice(0, input.limit);\n\n const matches: MemSearchHit[] = ranked.map((hit) => {\n const loaded = byId.get(hit.id);\n if (!loaded) {\n return {\n id: hit.id,\n scope: \"unknown\",\n type: \"unknown\",\n tags: [],\n status: \"unknown\",\n confidence: \"unverified\" as const,\n read_count: 0,\n snippet: \"\",\n file_path: hit.file_path,\n score: hit.score,\n };\n }\n const base = toHit(loaded, input.query.toLowerCase(), usage);\n return { ...base, score: hit.score };\n });\n\n return {\n matches,\n total: ranked.length,\n mode: \"semantic\",\n };\n}\n\nfunction toHit(loaded: LoadedMemory, needle: string, usage: UsageIndex): MemSearchHit {\n const fm = loaded.memory.frontmatter;\n const u = getUsage(usage, fm.id);\n return {\n id: fm.id,\n scope: fm.scope,\n type: fm.type,\n ...(fm.module ? { module: fm.module } : {}),\n tags: fm.tags,\n status: fm.status,\n confidence: deriveConfidence(fm, u),\n read_count: u.read_count,\n snippet: extractSnippet(loaded.memory.body, needle),\n file_path: loaded.filePath,\n };\n}\n\nfunction lexicalHit(\n loaded: LoadedMemory,\n needle: string,\n usage: UsageIndex,\n lexicalScore: number,\n): MemSearchHit {\n return { ...toHit(loaded, needle, usage), score: lexicalScore };\n}\n","import { writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport {\n loadMemoriesFromDir,\n serializeMemory,\n verifyAnchor,\n type Memory,\n} from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const MemVerifyInputSchema = {\n id: z.string().optional().describe(\"If set, verify only this memory id\"),\n update: z\n .boolean()\n .default(false)\n .describe(\"Write the resulting status back to disk (status=stale or validated)\"),\n};\n\nexport type MemVerifyInput = {\n [K in keyof typeof MemVerifyInputSchema]: z.infer<(typeof MemVerifyInputSchema)[K]>;\n};\n\nexport interface MemVerifyHit {\n id: string;\n file_path: string;\n stale: boolean;\n reason: string | null;\n possible_renames?: string[];\n status_after: string;\n skipped?: boolean;\n}\n\nexport interface MemVerifyOutput {\n results: MemVerifyHit[];\n summary: {\n checked: number;\n fresh: number;\n stale: number;\n anchorless_skipped: number;\n updated: number;\n };\n}\n\nexport async function memVerify(\n input: MemVerifyInput,\n ctx: HaiveContext,\n): Promise<MemVerifyOutput> {\n if (!existsSync(ctx.paths.memoriesDir)) {\n return {\n results: [],\n summary: { checked: 0, fresh: 0, stale: 0, anchorless_skipped: 0, updated: 0 },\n };\n }\n\n const all = await loadMemoriesFromDir(ctx.paths.memoriesDir);\n const targets = input.id\n ? all.filter((m) => m.memory.frontmatter.id === input.id)\n : all;\n\n const results: MemVerifyHit[] = [];\n let fresh = 0;\n let stale = 0;\n let anchorless = 0;\n let updated = 0;\n\n for (const { memory, filePath } of targets) {\n // session_recap records historical context — anchor staleness does not apply\n if (memory.frontmatter.type === \"session_recap\") {\n anchorless++;\n results.push({\n id: memory.frontmatter.id,\n file_path: filePath,\n stale: false,\n reason: null,\n status_after: memory.frontmatter.status,\n skipped: true,\n });\n continue;\n }\n const isAnchored =\n memory.frontmatter.anchor.paths.length > 0 ||\n memory.frontmatter.anchor.symbols.length > 0;\n if (!isAnchored) {\n anchorless++;\n results.push({\n id: memory.frontmatter.id,\n file_path: filePath,\n stale: false,\n reason: null,\n status_after: memory.frontmatter.status,\n skipped: true,\n });\n continue;\n }\n const result = await verifyAnchor(memory, { projectRoot: ctx.paths.root });\n if (result.stale) stale++;\n else fresh++;\n\n let statusAfter = memory.frontmatter.status;\n if (input.update) {\n const next = applyVerification(memory, result);\n await writeFile(filePath, serializeMemory(next), \"utf8\");\n statusAfter = next.frontmatter.status;\n updated++;\n }\n\n results.push({\n id: memory.frontmatter.id,\n file_path: filePath,\n stale: result.stale,\n reason: result.reason,\n ...(result.possibleRenames.length > 0 ? { possible_renames: result.possibleRenames } : {}),\n status_after: statusAfter,\n });\n }\n\n return {\n results,\n summary: {\n checked: results.length + anchorless,\n fresh,\n stale,\n anchorless_skipped: anchorless,\n updated,\n },\n };\n}\n\nfunction applyVerification(\n mem: Memory,\n result: { stale: boolean; reason: string | null },\n): Memory {\n const verifiedAt = new Date().toISOString();\n if (result.stale) {\n return {\n frontmatter: {\n ...mem.frontmatter,\n status: \"stale\",\n verified_at: verifiedAt,\n stale_reason: result.reason,\n },\n body: mem.body,\n };\n }\n const nextStatus =\n mem.frontmatter.status === \"stale\" || mem.frontmatter.status === \"draft\"\n ? \"validated\"\n : mem.frontmatter.status;\n return {\n frontmatter: {\n ...mem.frontmatter,\n status: nextStatus,\n verified_at: verifiedAt,\n stale_reason: null,\n },\n body: mem.body,\n };\n}\n","import { writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport {\n loadMemoriesFromDir,\n loadUsageIndex,\n recordRejection,\n saveUsageIndex,\n serializeMemory,\n} from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const MemRejectInputSchema = {\n id: z.string().min(1).describe(\"Memory id being rejected\"),\n reason: z\n .string()\n .optional()\n .describe(\"Why this memory is being rejected (recorded for review)\"),\n};\n\nexport type MemRejectInput = {\n [K in keyof typeof MemRejectInputSchema]: z.infer<(typeof MemRejectInputSchema)[K]>;\n};\n\nexport interface MemRejectOutput {\n id: string;\n status: string;\n rejected_count: number;\n last_rejected_at: string | null;\n rejection_reason: string | null;\n}\n\nexport async function memReject(\n input: MemRejectInput,\n ctx: HaiveContext,\n): Promise<MemRejectOutput> {\n if (!existsSync(ctx.paths.memoriesDir)) {\n throw new Error(`No .ai/memories at ${ctx.paths.root}.`);\n }\n\n const memories = await loadMemoriesFromDir(ctx.paths.memoriesDir);\n const loaded = memories.find((m) => m.memory.frontmatter.id === input.id);\n if (!loaded) throw new Error(`No memory with id \"${input.id}\".`);\n\n // Write rejected status and reason to disk\n await writeFile(\n loaded.filePath,\n serializeMemory({\n frontmatter: {\n ...loaded.memory.frontmatter,\n status: \"rejected\",\n stale_reason: input.reason ?? loaded.memory.frontmatter.stale_reason ?? null,\n },\n body: loaded.memory.body,\n }),\n \"utf8\",\n );\n\n const idx = await loadUsageIndex(ctx.paths);\n recordRejection(idx, input.id, input.reason ?? null);\n await saveUsageIndex(ctx.paths, idx);\n const u = idx.by_id[input.id];\n return {\n id: input.id,\n status: \"rejected\",\n rejected_count: u?.rejected_count ?? 0,\n last_rejected_at: u?.last_rejected_at ?? null,\n rejection_reason: u?.rejection_reason ?? null,\n };\n}\n","import {\n applyFeedbackAdjustment,\n computeImpact,\n getUsage,\n loadMemoriesFromDir,\n loadUsageIndex,\n recordApplied,\n recordRejection,\n recommendFeedbackAdjustment,\n saveUsageIndex,\n serializeMemory,\n type ImpactTier,\n type FeedbackAdjustment,\n} from \"@hivelore/core\";\nimport { existsSync } from \"node:fs\";\nimport { writeFile } from \"node:fs/promises\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const MemFeedbackInputSchema = {\n id: z.string().min(1).describe(\"Full memory id the feedback is about\"),\n outcome: z\n .enum([\"applied\", \"rejected\"])\n .describe(\n \"'applied' = this memory changed what you did (strong positive utility signal); \" +\n \"'rejected' = it was wrong/outdated/unhelpful (negative signal, blocks auto-promotion).\",\n ),\n reason: z\n .string()\n .optional()\n .describe(\"Why it was rejected (stored on the memory's usage record). Only used for outcome='rejected'.\"),\n};\n\nexport type MemFeedbackInput = {\n [K in keyof typeof MemFeedbackInputSchema]: z.infer<(typeof MemFeedbackInputSchema)[K]>;\n};\n\nexport interface MemFeedbackOutput {\n ok: boolean;\n id: string;\n outcome?: \"applied\" | \"rejected\";\n error?: string;\n usage?: {\n read_count: number;\n applied_count: number;\n rejected_count: number;\n };\n impact?: {\n score: number;\n tier: ImpactTier;\n signals: string[];\n };\n feedback_adjustment?: FeedbackAdjustment;\n}\n\n/**\n * Record a closed-loop utility outcome for a memory. This is what turns Hivelore's\n * memory store from a passive index into a learning system: agents report whether\n * a surfaced memory actually steered their work, and that feeds impact scoring\n * (`hivelore memory impact`) and future pruning/ranking.\n */\nexport async function memFeedback(\n input: MemFeedbackInput,\n ctx: HaiveContext,\n): Promise<MemFeedbackOutput> {\n if (!existsSync(ctx.paths.memoriesDir)) {\n return { ok: false, id: input.id, error: \"No .ai/memories — run `hivelore init` first.\" };\n }\n\n const all = await loadMemoriesFromDir(ctx.paths.memoriesDir);\n const target = all.find((m) => m.memory.frontmatter.id === input.id);\n if (!target) {\n return { ok: false, id: input.id, error: `No memory with id '${input.id}'.` };\n }\n\n const index = await loadUsageIndex(ctx.paths);\n if (input.outcome === \"applied\") {\n recordApplied(index, input.id);\n } else {\n recordRejection(index, input.id, input.reason ?? null);\n }\n await saveUsageIndex(ctx.paths, index);\n\n const usage = getUsage(index, input.id);\n const adjustment = input.outcome === \"rejected\"\n ? recommendFeedbackAdjustment(target.memory.frontmatter, usage)\n : { action: \"none\" as const, reason: \"No automatic adjustment needed.\" };\n const adjustedFrontmatter = applyFeedbackAdjustment(target.memory.frontmatter, adjustment);\n if (adjustedFrontmatter !== target.memory.frontmatter) {\n target.memory.frontmatter = adjustedFrontmatter;\n await writeFile(target.filePath, serializeMemory(target.memory), \"utf8\");\n }\n const impact = computeImpact(target.memory.frontmatter, usage);\n\n return {\n ok: true,\n id: input.id,\n outcome: input.outcome,\n usage: {\n read_count: usage.read_count,\n applied_count: usage.applied_count,\n rejected_count: usage.rejected_count,\n },\n impact: { score: impact.score, tier: impact.tier, signals: impact.signals },\n feedback_adjustment: adjustment,\n };\n}\n","import { readFile, readdir } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n deriveConfidence,\n getUsage,\n inferModulesFromPaths,\n loadMemoriesFromDir,\n loadUsageIndex,\n memoryMatchesAnchorPaths,\n trackReads,\n type ConfidenceLevel,\n type LoadedMemory,\n} from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const MemForFilesInputSchema = {\n files: z\n .array(z.string())\n .min(1)\n .describe(\"Project-relative file paths the agent is currently working on\"),\n include_module_contexts: z\n .boolean()\n .default(true)\n .describe(\"Inline the matching .ai/modules/<name>/context.md contents\"),\n track: z\n .boolean()\n .default(true)\n .describe(\"Increment read_count on returned memories\"),\n};\n\nexport type MemForFilesInput = {\n [K in keyof typeof MemForFilesInputSchema]: z.infer<(typeof MemForFilesInputSchema)[K]>;\n};\n\nexport interface MemMatch {\n id: string;\n scope: string;\n type: string;\n module?: string;\n tags: string[];\n status: string;\n confidence: ConfidenceLevel;\n read_count: number;\n reason: \"anchor_overlap\" | \"module\" | \"domain\";\n /** Anchor paths recorded in the memory frontmatter — used by pre_commit_check to scope stale warnings. */\n anchor_paths: string[];\n file_path: string;\n body: string;\n}\n\nexport interface MemForFilesOutput {\n inferred_modules: string[];\n by_anchor: MemMatch[];\n by_module: MemMatch[];\n by_domain: MemMatch[];\n module_contexts: Array<{ name: string; content: string }>;\n}\n\nexport async function memForFiles(\n input: MemForFilesInput,\n ctx: HaiveContext,\n): Promise<MemForFilesOutput> {\n const inferred = inferModulesFromPaths(input.files);\n\n if (!existsSync(ctx.paths.memoriesDir)) {\n return {\n inferred_modules: inferred,\n by_anchor: [],\n by_module: [],\n by_domain: [],\n module_contexts: await loadModuleContexts(ctx, inferred, input.include_module_contexts),\n };\n }\n\n const all = await loadMemoriesFromDir(ctx.paths.memoriesDir);\n const usage = await loadUsageIndex(ctx.paths);\n const seen = new Set<string>();\n\n const byAnchor: MemMatch[] = [];\n const byModule: MemMatch[] = [];\n const byDomain: MemMatch[] = [];\n\n for (const loaded of all) {\n // session_recap surfaces in get_briefing.last_session — skip here\n if (loaded.memory.frontmatter.type === \"session_recap\") continue;\n if (memoryMatchesAnchorPaths(loaded.memory, input.files)) {\n byAnchor.push(toMatch(loaded, \"anchor_overlap\", usage));\n seen.add(loaded.memory.frontmatter.id);\n }\n }\n\n // Extract meaningful path segments from input files for tag matching\n const pathSegments = extractPathSegments(input.files);\n\n for (const loaded of all) {\n if (seen.has(loaded.memory.frontmatter.id)) continue;\n if (loaded.memory.frontmatter.type === \"session_recap\") continue;\n const fm = loaded.memory.frontmatter;\n const moduleHit =\n (fm.module && inferred.includes(fm.module)) ||\n fm.tags.some((t) => inferred.includes(t)) ||\n fm.tags.some((t) => {\n const tl = t.toLowerCase();\n return pathSegments.has(tl) || pathSegments.has(tl.replace(/[-_]/g, \"\"));\n });\n if (moduleHit) {\n byModule.push(toMatch(loaded, \"module\", usage));\n seen.add(fm.id);\n }\n }\n\n for (const loaded of all) {\n if (seen.has(loaded.memory.frontmatter.id)) continue;\n if (loaded.memory.frontmatter.type === \"session_recap\") continue;\n const domain = loaded.memory.frontmatter.domain;\n if (domain && inferred.includes(domain)) {\n byDomain.push(toMatch(loaded, \"domain\", usage));\n seen.add(loaded.memory.frontmatter.id);\n }\n }\n\n if (input.track) {\n await trackReads(ctx.paths, [...seen]);\n }\n\n return {\n inferred_modules: inferred,\n by_anchor: byAnchor,\n by_module: byModule,\n by_domain: byDomain,\n module_contexts: await loadModuleContexts(ctx, inferred, input.include_module_contexts),\n };\n}\n\nfunction toMatch(\n loaded: LoadedMemory,\n reason: MemMatch[\"reason\"],\n usage: Parameters<typeof getUsage>[0],\n): MemMatch {\n const fm = loaded.memory.frontmatter;\n const u = getUsage(usage, fm.id);\n return {\n id: fm.id,\n scope: fm.scope,\n type: fm.type,\n ...(fm.module ? { module: fm.module } : {}),\n tags: fm.tags,\n status: fm.status,\n confidence: deriveConfidence(fm, u),\n read_count: u.read_count,\n reason,\n anchor_paths: fm.anchor.paths,\n file_path: loaded.filePath,\n body: loaded.memory.body,\n };\n}\n\n/**\n * Extract lowercase path segments from file paths that are likely domain/module names.\n * Filters out generic segments like src, main, java, com, org, test, etc.\n */\nfunction extractPathSegments(files: string[]): Set<string> {\n const GENERIC = new Set([\n \"src\", \"main\", \"java\", \"kotlin\", \"python\", \"go\", \"lib\", \"libs\",\n \"com\", \"org\", \"net\", \"io\", \"app\", \"apps\", \"pkg\", \"internal\",\n \"test\", \"tests\", \"spec\", \"specs\", \"impl\", \"domain\", \"shared\",\n \"resources\", \"static\", \"assets\", \"config\", \"configs\",\n ]);\n const out = new Set<string>();\n for (const file of files) {\n const parts = file.replace(/\\\\/g, \"/\").split(\"/\");\n for (const part of parts) {\n const seg = part.toLowerCase().replace(/\\.[^.]+$/, \"\"); // strip extension\n if (seg.length >= 3 && !GENERIC.has(seg) && /^[a-z]/.test(seg)) {\n out.add(seg);\n // Also split camelCase / kebab-case segments: mobilepayment → mobile, payment\n for (const sub of seg.split(/[-_]/).filter((s) => s.length >= 3)) {\n out.add(sub);\n }\n }\n }\n }\n return out;\n}\n\nasync function loadModuleContexts(\n ctx: HaiveContext,\n modules: string[],\n enabled: boolean,\n): Promise<Array<{ name: string; content: string }>> {\n if (!enabled || modules.length === 0) return [];\n if (!existsSync(ctx.paths.modulesContextDir)) return [];\n const available = new Set(\n (await readdir(ctx.paths.modulesContextDir, { withFileTypes: true }))\n .filter((d) => d.isDirectory())\n .map((d) => d.name),\n );\n const out: Array<{ name: string; content: string }> = [];\n for (const m of modules) {\n if (!available.has(m)) continue;\n const file = path.join(ctx.paths.modulesContextDir, m, \"context.md\");\n if (existsSync(file)) {\n out.push({ name: m, content: await readFile(file, \"utf8\") });\n }\n }\n return out;\n}\n","import { existsSync } from \"node:fs\";\nimport {\n deriveConfidence,\n getUsage,\n loadMemoriesFromDir,\n loadUsageIndex,\n type ConfidenceLevel,\n} from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const MemGetInputSchema = {\n id: z.string().min(1).describe(\"Memory id to fetch\"),\n};\n\nexport type MemGetInput = {\n [K in keyof typeof MemGetInputSchema]: z.infer<(typeof MemGetInputSchema)[K]>;\n};\n\nexport interface MemGetOutput {\n id: string;\n scope: string;\n type: string;\n module?: string;\n tags: string[];\n status: string;\n confidence: ConfidenceLevel;\n read_count: number;\n rejected_count: number;\n created_at: string;\n verified_at: string | null;\n stale_reason: string | null;\n anchor: { commit?: string; paths: string[]; symbols: string[] };\n body: string;\n file_path: string;\n}\n\nexport async function memGet(input: MemGetInput, ctx: HaiveContext): Promise<MemGetOutput> {\n if (!existsSync(ctx.paths.memoriesDir)) {\n throw new Error(`No .ai/memories at ${ctx.paths.root}.`);\n }\n const all = await loadMemoriesFromDir(ctx.paths.memoriesDir);\n const found = all.find((m) => m.memory.frontmatter.id === input.id);\n if (!found) throw new Error(`No memory with id \"${input.id}\".`);\n const fm = found.memory.frontmatter;\n const u = getUsage(await loadUsageIndex(ctx.paths), fm.id);\n return {\n id: fm.id,\n scope: fm.scope,\n type: fm.type,\n ...(fm.module ? { module: fm.module } : {}),\n tags: fm.tags,\n status: fm.status,\n confidence: deriveConfidence(fm, u),\n read_count: u.read_count,\n rejected_count: u.rejected_count,\n created_at: fm.created_at,\n verified_at: fm.verified_at,\n stale_reason: fm.stale_reason,\n anchor: {\n ...(fm.anchor.commit ? { commit: fm.anchor.commit } : {}),\n paths: fm.anchor.paths,\n symbols: fm.anchor.symbols,\n },\n body: found.memory.body,\n file_path: found.filePath,\n };\n}\n","import { existsSync } from \"node:fs\";\nimport { unlink } from \"node:fs/promises\";\nimport {\n loadMemoriesFromDir,\n loadUsageIndex,\n saveUsageIndex,\n} from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const MemDeleteInputSchema = {\n id: z.string().min(1).describe(\"Memory id to delete\"),\n keep_usage: z\n .boolean()\n .default(false)\n .describe(\"Keep the usage.json entry instead of removing it alongside the file\"),\n};\n\nexport type MemDeleteInput = {\n [K in keyof typeof MemDeleteInputSchema]: z.infer<(typeof MemDeleteInputSchema)[K]>;\n};\n\nexport interface MemDeleteOutput {\n id: string;\n deleted_file: string;\n usage_removed: boolean;\n}\n\nexport async function memDelete(\n input: MemDeleteInput,\n ctx: HaiveContext,\n): Promise<MemDeleteOutput> {\n if (!existsSync(ctx.paths.memoriesDir)) {\n throw new Error(`No .ai/memories at ${ctx.paths.root}.`);\n }\n const all = await loadMemoriesFromDir(ctx.paths.memoriesDir);\n const found = all.find((m) => m.memory.frontmatter.id === input.id);\n if (!found) throw new Error(`No memory with id \"${input.id}\".`);\n\n await unlink(found.filePath);\n\n let usageRemoved = false;\n if (!input.keep_usage) {\n const idx = await loadUsageIndex(ctx.paths);\n if (idx.by_id[input.id]) {\n delete idx.by_id[input.id];\n await saveUsageIndex(ctx.paths, idx);\n usageRemoved = true;\n }\n }\n\n return { id: input.id, deleted_file: found.filePath, usage_removed: usageRemoved };\n}\n","import { writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { loadMemoriesFromDir, serializeMemory } from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const MemUpdateInputSchema = {\n id: z.string().min(1).describe(\"Id of the memory to update\"),\n body: z.string().optional().describe(\"New Markdown body — replaces the existing body\"),\n tags: z\n .array(z.string())\n .optional()\n .describe(\"New tags array — fully replaces existing tags\"),\n paths: z\n .array(z.string())\n .optional()\n .describe(\"New anchor paths — fully replaces existing anchor.paths\"),\n symbols: z\n .array(z.string())\n .optional()\n .describe(\"New anchor symbols — fully replaces existing anchor.symbols\"),\n commit: z.string().optional().describe(\"New anchor commit SHA\"),\n domain: z.string().optional().describe(\"New domain label\"),\n author: z.string().optional().describe(\"New author handle or email\"),\n};\n\nexport type MemUpdateInput = {\n [K in keyof typeof MemUpdateInputSchema]: z.infer<(typeof MemUpdateInputSchema)[K]>;\n};\n\nexport interface MemUpdateOutput {\n id: string;\n file_path: string;\n updated_fields: string[];\n}\n\nexport async function memUpdate(\n input: MemUpdateInput,\n ctx: HaiveContext,\n): Promise<MemUpdateOutput> {\n if (!existsSync(ctx.paths.memoriesDir)) {\n throw new Error(`No .ai/memories at ${ctx.paths.root}.`);\n }\n\n const memories = await loadMemoriesFromDir(ctx.paths.memoriesDir);\n const loaded = memories.find((m) => m.memory.frontmatter.id === input.id);\n if (!loaded) throw new Error(`No memory with id \"${input.id}\".`);\n\n const { frontmatter, body } = loaded.memory;\n const updated_fields: string[] = [];\n\n const newAnchor = { ...frontmatter.anchor };\n if (input.paths !== undefined) { newAnchor.paths = input.paths; updated_fields.push(\"anchor.paths\"); }\n if (input.symbols !== undefined) { newAnchor.symbols = input.symbols; updated_fields.push(\"anchor.symbols\"); }\n if (input.commit !== undefined) { newAnchor.commit = input.commit; updated_fields.push(\"anchor.commit\"); }\n\n const newFrontmatter = {\n ...frontmatter,\n anchor: newAnchor,\n ...(input.tags !== undefined ? { tags: input.tags } : {}),\n ...(input.domain !== undefined ? { domain: input.domain } : {}),\n ...(input.author !== undefined ? { author: input.author } : {}),\n };\n\n if (input.tags !== undefined) updated_fields.push(\"tags\");\n if (input.domain !== undefined) updated_fields.push(\"domain\");\n if (input.author !== undefined) updated_fields.push(\"author\");\n\n const newBody = input.body !== undefined ? input.body : body;\n if (input.body !== undefined) updated_fields.push(\"body\");\n\n if (updated_fields.length === 0) {\n throw new Error(\"No fields to update — provide at least one of: body, tags, paths, symbols, commit, domain, author.\");\n }\n\n await writeFile(\n loaded.filePath,\n serializeMemory({ frontmatter: newFrontmatter, body: newBody }),\n \"utf8\",\n );\n\n return { id: input.id, file_path: loaded.filePath, updated_fields };\n}\n","import { existsSync } from \"node:fs\";\nimport {\n getUsage,\n loadMemoriesFromDir,\n loadUsageIndex,\n} from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const MemPendingInputSchema = {\n scope: z.enum([\"personal\", \"team\", \"module\"]).optional(),\n};\n\nexport type MemPendingInput = {\n [K in keyof typeof MemPendingInputSchema]: z.infer<(typeof MemPendingInputSchema)[K]>;\n};\n\nexport interface MemPendingHit {\n id: string;\n scope: string;\n type: string;\n module?: string;\n tags: string[];\n age_days: number;\n read_count: number;\n rejected_count: number;\n file_path: string;\n}\n\nexport interface MemPendingOutput {\n pending: MemPendingHit[];\n}\n\nexport async function memPending(\n input: MemPendingInput,\n ctx: HaiveContext,\n): Promise<MemPendingOutput> {\n if (!existsSync(ctx.paths.memoriesDir)) return { pending: [] };\n const all = await loadMemoriesFromDir(ctx.paths.memoriesDir);\n const usage = await loadUsageIndex(ctx.paths);\n const now = Date.now();\n const proposed = all.filter(({ memory }) => {\n if (memory.frontmatter.status !== \"proposed\") return false;\n if (input.scope && memory.frontmatter.scope !== input.scope) return false;\n return true;\n });\n\n proposed.sort(\n (a, b) =>\n getUsage(usage, b.memory.frontmatter.id).read_count -\n getUsage(usage, a.memory.frontmatter.id).read_count,\n );\n\n return {\n pending: proposed.map(({ memory, filePath }) => {\n const fm = memory.frontmatter;\n const u = getUsage(usage, fm.id);\n return {\n id: fm.id,\n scope: fm.scope,\n type: fm.type,\n ...(fm.module ? { module: fm.module } : {}),\n tags: fm.tags,\n age_days: Math.floor((now - new Date(fm.created_at).getTime()) / 86_400_000),\n read_count: u.read_count,\n rejected_count: u.rejected_count,\n file_path: filePath,\n };\n }),\n };\n}\n","import { writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport {\n loadMemoriesFromDir,\n serializeMemory,\n} from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const MemApproveInputSchema = {\n id: z.string().min(1).describe(\"Memory id to approve (sets status=validated immediately)\"),\n};\n\nexport type MemApproveInput = {\n [K in keyof typeof MemApproveInputSchema]: z.infer<(typeof MemApproveInputSchema)[K]>;\n};\n\nexport interface MemApproveOutput {\n id: string;\n previous_status: string;\n status: \"validated\";\n file_path: string;\n}\n\nexport async function memApprove(\n input: MemApproveInput,\n ctx: HaiveContext,\n): Promise<MemApproveOutput> {\n if (!existsSync(ctx.paths.memoriesDir)) {\n throw new Error(`No .ai/memories at ${ctx.paths.root}.`);\n }\n const all = await loadMemoriesFromDir(ctx.paths.memoriesDir);\n const found = all.find((m) => m.memory.frontmatter.id === input.id);\n if (!found) throw new Error(`No memory with id \"${input.id}\".`);\n\n const previous = found.memory.frontmatter.status;\n const next = {\n // MCP is the agent surface → record AI provenance so a human can tell it from human-approved knowledge.\n frontmatter: { ...found.memory.frontmatter, status: \"validated\" as const, validated_by: \"agent\" as const },\n body: found.memory.body,\n };\n await writeFile(found.filePath, serializeMemory(next), \"utf8\");\n return {\n id: input.id,\n previous_status: previous,\n status: \"validated\",\n file_path: found.filePath,\n };\n}\n","import { mkdir, writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n buildFrontmatter,\n memoryFilePath,\n serializeMemory,\n suggestSensorSeed,\n} from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const MemTriedInputSchema = {\n what: z.string().min(1).describe(\"Brief description of the approach that was tried\"),\n why_failed: z\n .string()\n .min(1)\n .describe(\"Why it failed or why it should NOT be used\"),\n instead: z\n .string()\n .optional()\n .describe(\"What to use or do instead (recommended alternative)\"),\n scope: z\n .enum([\"personal\", \"team\", \"module\"])\n .default(\"personal\")\n .describe(\"Visibility scope\"),\n module: z.string().optional().describe(\"Module name (required when scope=module)\"),\n tags: z.array(z.string()).default([]).describe(\"Tags for filtering\"),\n paths: z\n .array(z.string())\n .default([])\n .describe(\"Anchor file paths this applies to\"),\n author: z.string().optional().describe(\"Author handle or email\"),\n};\n\nexport type MemTriedInput = {\n [K in keyof typeof MemTriedInputSchema]: z.infer<(typeof MemTriedInputSchema)[K]>;\n};\n\nexport interface MemTriedOutput {\n id: string;\n scope: string;\n file_path: string;\n /**\n * A captured attempt closes its prevention loop (gate can block the repeat) only once a sensor is\n * VALIDATED via propose_sensor. True until then — the lesson is briefed but not enforced.\n */\n loop_open: boolean;\n /** Heuristic candidate to PRE-FILL a propose_sensor call (refine, then call it). Never a persisted sensor. */\n proposed_sensor_seed?: { pattern: string; absent?: string; message: string };\n /** Next-step guidance: how to close the loop via propose_sensor. */\n hint?: string;\n}\n\nexport async function memTried(\n input: MemTriedInput,\n ctx: HaiveContext,\n): Promise<MemTriedOutput> {\n if (!existsSync(ctx.paths.haiveDir)) {\n throw new Error(`No .ai/ directory at ${ctx.paths.root}. Run 'hivelore init' first.`);\n }\n\n const slug = input.what\n .toLowerCase()\n .replace(/[^a-z0-9\\s]/g, \"\")\n .trim()\n .split(/\\s+/)\n .slice(0, 5)\n .join(\"-\");\n\n const baseFm = buildFrontmatter({\n type: \"attempt\",\n slug,\n scope: input.scope,\n module: input.module,\n tags: input.tags,\n paths: input.paths,\n author: input.author,\n });\n // attempt memories are immediately validated — no review cycle needed\n const frontmatter = { ...baseFm, status: \"validated\" as const };\n\n const lines: string[] = [`# ${input.what}`, \"\"];\n lines.push(`**Why it failed / do NOT use:** ${input.why_failed}`);\n if (input.instead) {\n lines.push(\"\", `**Instead, use:** ${input.instead}`);\n }\n const body = lines.join(\"\\n\") + \"\\n\";\n\n const file = memoryFilePath(ctx.paths, frontmatter.scope, frontmatter.id, frontmatter.module);\n await mkdir(path.dirname(file), { recursive: true });\n\n if (existsSync(file)) {\n throw new Error(`Memory already exists at ${file}`);\n }\n\n await writeFile(file, serializeMemory({ frontmatter, body }), \"utf8\");\n\n // A captured attempt only CLOSES the loop (gate blocks the repeat) once a sensor is VALIDATED via\n // propose_sensor. We no longer auto-write a heuristic warn sensor; instead we hand the agent a SEED\n // (when one can be derived) to pre-fill propose_sensor, and tell it the loop is open until then.\n const seed = input.paths.length > 0 ? suggestSensorSeed(body, input.paths) : null;\n const hint =\n input.paths.length === 0\n ? \"No `paths` given, so this attempt is feedforward-only — it will be briefed but the gate cannot block the repeat. Re-run with `paths` set to the file(s) where the mistake lives, then call propose_sensor to close the loop.\"\n : seed\n ? \"This attempt is NOT yet enforced. Call propose_sensor to turn it into a reliable block — a candidate is pre-filled in proposed_sensor_seed (refine it: pattern = the faulty usage, absent = the correct-usage marker). Hivelore validates the proposal (silent on current code, fires on the bad example) before trusting it to block.\"\n : \"This attempt is NOT yet enforced and no candidate pattern could be derived from the wording. Call propose_sensor with a discriminating pattern (pattern = faulty usage, absent = correct-usage marker) to close the loop.\";\n\n return {\n id: frontmatter.id,\n scope: frontmatter.scope,\n file_path: file,\n loop_open: true,\n ...(seed\n ? {\n proposed_sensor_seed: {\n pattern: seed.pattern,\n ...(seed.absent ? { absent: seed.absent } : {}),\n message: seed.message,\n },\n }\n : {}),\n hint,\n };\n}\n","/**\n * propose_sensor — the agent (LLM), which understands the code, PROPOSES a sensor; core VALIDATES it.\n *\n * This is the \"generate via the LLM-in-the-loop, validate deterministically\" half of making the\n * auto-generation layer excellent. The heuristic generator (suggestSensorFromMemory) only recognizes\n * a few shapes; an agent that has read the code can write a precise discriminating pattern. But a\n * proposal is only TRUSTED to hard-block after `judgeProposedSensor` proves it discriminates:\n * - not brittle, and\n * - SILENT on the current (presumed-correct) anchored code, and\n * - FIRES on the bad example (from input, or extracted from the lesson body).\n * A rejected proposal is NOT written; the verdict tells the agent how to revise and re-propose.\n */\nimport { execSync } from \"node:child_process\";\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n extractSensorExamples,\n judgeProposedSensor,\n loadMemoriesFromDir,\n serializeMemory,\n type Sensor,\n type SensorTarget,\n} from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const ProposeSensorInputSchema = {\n memory_id: z.string().min(1).describe(\"Id of the gotcha/attempt memory this sensor protects.\"),\n pattern: z\n .string()\n .min(1)\n .describe(\"Regex matching the FAULTY usage (the risky call/token), e.g. 'stripe\\\\.paymentIntents\\\\.create'.\"),\n absent: z\n .string()\n .optional()\n .describe(\n \"Regex for the CORRECT-usage marker (e.g. 'idempotencyKey'). When it appears in the window around \" +\n \"a match, the catch is suppressed — this is what makes the sensor discriminate the faulty call \" +\n \"from the correct one. STRONGLY recommended for 'X without Y' lessons.\",\n ),\n bad_example: z\n .string()\n .optional()\n .describe(\"A code snippet that SHOULD match — proves the sensor catches the mistake. If omitted, examples are read from the lesson body.\"),\n severity: z\n .enum([\"warn\", \"block\"])\n .default(\"block\")\n .describe(\"block = hard-fail the gate (accepted ONLY if it passes self-validation). warn = advisory.\"),\n message: z.string().optional().describe(\"LLM-facing fix message shown when it fires. Defaults to one derived from the lesson.\"),\n flags: z.string().optional().describe(\"Optional regex flags (e.g. 'i' for case-insensitive).\"),\n paths: z\n .array(z.string())\n .default([])\n .describe(\"Override scope paths. Defaults to the memory's anchor paths.\"),\n};\n\nexport type ProposeSensorInput = {\n [K in keyof typeof ProposeSensorInputSchema]: z.infer<(typeof ProposeSensorInputSchema)[K]>;\n};\n\nexport interface ProposeSensorOutput {\n accepted: boolean;\n memory_id: string;\n severity: \"warn\" | \"block\";\n /** Set when rejected — why, and how to revise. */\n reason?: string;\n guidance?: string;\n self_check: {\n silent_on_current: boolean;\n fires_on_bad: boolean | null;\n fired_on: string[];\n };\n file_path?: string;\n}\n\nfunction deriveMessage(body: string, pattern: string, absent?: string): string {\n const instead = body.match(/\\*\\*Instead,\\s*use:\\*\\*\\s*([^\\n]+)/i)?.[1]?.trim();\n if (absent) {\n const base = `${pattern} without ${absent}`;\n return instead ? `${base} — ${instead}` : `${base} — add the required companion.`;\n }\n const heading = body\n .split(\"\\n\")\n .map((l) => l.replace(/^#+\\s*/, \"\").trim())\n .find((l) => l.length > 0 && !l.startsWith(\"---\"));\n return heading?.slice(0, 180) || `Avoid ${pattern}.`;\n}\n\n/**\n * Read the PRESUMED-CORRECT contents of anchored files for sensor self-checks.\n *\n * \"Silent on current\" must test the last COMMITTED state (HEAD), not the working tree: an agent\n * typically proposes a sensor right after hitting the failure, while the bad pattern is still\n * sitting uncommitted in the anchored file — validating against the working tree then rejects\n * every honest proposal with fires-on-current. HEAD already passed the gate, so it is the\n * presumed-correct baseline; fall back to the working tree for files not yet in git.\n */\nexport async function readPresumedCorrectTargets(\n root: string,\n relPaths: string[],\n): Promise<SensorTarget[]> {\n const targets: SensorTarget[] = [];\n for (const rel of relPaths) {\n try {\n // \"./\" keeps the path relative to cwd even if the project root is a git subdirectory.\n const content = execSync(`git show ${JSON.stringify(`HEAD:./${rel}`)}`, {\n cwd: root,\n encoding: \"utf8\",\n maxBuffer: 10 * 1024 * 1024,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n });\n targets.push({ path: rel, content });\n continue;\n } catch { /* not in HEAD or not a git repo — fall back to the working tree */ }\n const abs = path.resolve(root, rel);\n if (!existsSync(abs)) continue;\n try {\n targets.push({ path: rel, content: await readFile(abs, \"utf8\") });\n } catch { /* unreadable — skip */ }\n }\n return targets;\n}\n\nexport async function proposeSensor(\n input: ProposeSensorInput,\n ctx: HaiveContext,\n): Promise<ProposeSensorOutput> {\n if (!existsSync(ctx.paths.memoriesDir)) {\n throw new Error(`No .ai/memories at ${ctx.paths.root}. Run 'hivelore init' first.`);\n }\n\n // Validate the regex(es) compile before anything else.\n try {\n new RegExp(input.pattern, input.flags ?? \"\");\n if (input.absent) new RegExp(input.absent, input.flags ?? \"\");\n } catch (err) {\n return {\n accepted: false,\n memory_id: input.memory_id,\n severity: input.severity,\n reason: \"invalid-regex\",\n guidance: `The pattern or absent regex does not compile: ${String(err)}`,\n self_check: { silent_on_current: false, fires_on_bad: null, fired_on: [] },\n };\n }\n\n const loaded = await loadMemoriesFromDir(ctx.paths.memoriesDir);\n const found = loaded.find(({ memory }) => memory.frontmatter.id === input.memory_id);\n if (!found) {\n throw new Error(`No memory found with id ${input.memory_id}`);\n }\n\n const anchorPaths = input.paths.length > 0 ? input.paths : found.memory.frontmatter.anchor.paths;\n const currentTargets = await readPresumedCorrectTargets(ctx.paths.root, anchorPaths);\n\n const badExamples = [\n ...(input.bad_example ? [input.bad_example] : []),\n ...extractSensorExamples(found.memory.body),\n ];\n\n const sensor: Sensor = {\n kind: \"regex\",\n pattern: input.pattern,\n ...(input.absent ? { absent: input.absent } : {}),\n ...(input.flags ? { flags: input.flags } : {}),\n paths: anchorPaths,\n message: input.message?.trim() || deriveMessage(found.memory.body, input.pattern, input.absent),\n severity: input.severity,\n autogen: false, // deliberately authored by the agent and validated — higher trust than heuristic\n last_fired: null,\n };\n\n const verdict = judgeProposedSensor(sensor, { currentTargets, badExamples });\n const self_check = {\n silent_on_current: verdict.self_check.silent_on_current,\n fires_on_bad: verdict.self_check.fires_on_bad,\n fired_on: verdict.self_check.fired_on,\n };\n\n if (!verdict.accepted) {\n const guidance =\n verdict.reason === \"fires-on-current\"\n ? `The sensor matches the CURRENT (correct) code in ${verdict.self_check.fired_on.join(\", \")}. Add or tighten the 'absent' companion so correct usage is excluded, then re-propose.`\n : verdict.reason === \"missed-bad-example\"\n ? \"The sensor did not match the bad example, so it won't catch the mistake. Adjust the pattern to match the faulty code, then re-propose.\"\n : verdict.reason === \"brittle\"\n ? `The pattern is brittle (${verdict.brittle}). Use a durable pattern (avoid hardcoded line numbers), then re-propose.`\n : \"Re-propose with a discriminating pattern.\";\n return {\n accepted: false,\n memory_id: input.memory_id,\n severity: input.severity,\n reason: verdict.reason ?? \"rejected\",\n guidance,\n self_check,\n };\n }\n\n // Accepted — persist the sensor onto the memory frontmatter.\n const next = {\n frontmatter: { ...found.memory.frontmatter, sensor },\n body: found.memory.body,\n };\n await writeFile(found.filePath, serializeMemory(next), \"utf8\");\n\n return {\n accepted: true,\n memory_id: input.memory_id,\n severity: input.severity,\n self_check,\n file_path: found.filePath,\n };\n}\n","import { existsSync } from \"node:fs\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n draftsFromFindings,\n filterNewDrafts,\n loadMemoriesFromDir,\n memoryFilePath,\n parseFindings,\n serializeMemory,\n type FindingSeverity,\n type MemoryDraft,\n} from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const IngestFindingsInputSchema = {\n format: z.enum([\"sarif\", \"sonar\"]).describe(\"Report format: 'sarif' (ESLint/Semgrep/CodeQL) or 'sonar' (SonarQube issues JSON)\"),\n report_path: z\n .string()\n .optional()\n .describe(\"Project-relative path to the findings JSON file. Provide this OR `report`.\"),\n report: z\n .string()\n .optional()\n .describe(\"Inline findings JSON content. Provide this OR `report_path`.\"),\n type: z\n .enum([\"gotcha\", \"convention\"])\n .default(\"gotcha\")\n .describe(\"Memory type for the created drafts\"),\n scope: z\n .enum([\"personal\", \"team\", \"module\"])\n .default(\"team\")\n .describe(\"Visibility scope for the created memories\"),\n module: z.string().optional().describe(\"Module name (required when scope=module)\"),\n min_severity: z\n .enum([\"info\", \"minor\", \"major\", \"critical\", \"blocker\"])\n .optional()\n .describe(\"Ignore findings below this severity\"),\n include_stylistic: z\n .boolean()\n .optional()\n .describe(\"Also ingest auto-fixable stylistic rules (semi/quotes/prefer-const…); off by default as low-value noise\"),\n limit: z.number().int().positive().optional().describe(\"Cap the number of memories created\"),\n author: z.string().optional().describe(\"Author handle or email\"),\n dry_run: z\n .boolean()\n .default(false)\n .describe(\"When true, return the drafts that WOULD be created without writing them\"),\n};\n\nexport type IngestFindingsInput = {\n [K in keyof typeof IngestFindingsInputSchema]: z.infer<(typeof IngestFindingsInputSchema)[K]>;\n};\n\nexport interface IngestFindingsOutput {\n format: string;\n parsed: number;\n new: number;\n skipped_existing: number;\n dry_run: boolean;\n created: Array<{\n id: string;\n topic: string;\n path: string;\n rule: string;\n severity: FindingSeverity;\n has_sensor: boolean;\n file_path?: string;\n }>;\n notice: string;\n}\n\nexport async function ingestFindings(\n input: IngestFindingsInput,\n ctx: HaiveContext,\n): Promise<IngestFindingsOutput> {\n if (!existsSync(ctx.paths.haiveDir)) {\n throw new Error(`No .ai/ directory at ${ctx.paths.root}. Run 'hivelore init' first.`);\n }\n\n let raw: string;\n if (input.report && input.report.trim()) {\n raw = input.report;\n } else if (input.report_path) {\n const file = path.resolve(ctx.paths.root, input.report_path);\n if (!existsSync(file)) throw new Error(`Report file not found: ${file}`);\n raw = await readFile(file, \"utf8\");\n } else {\n throw new Error(\"Provide either `report_path` or `report`.\");\n }\n\n const findings = parseFindings(input.format, raw);\n const drafts = draftsFromFindings(findings, {\n type: input.type,\n scope: input.scope,\n module: input.module,\n author: input.author,\n ...(input.min_severity ? { minSeverity: input.min_severity } : {}),\n ...(input.include_stylistic ? { includeStylistic: true } : {}),\n ...(input.limit ? { limit: input.limit } : {}),\n });\n\n const existing = existsSync(ctx.paths.memoriesDir)\n ? await loadMemoriesFromDir(ctx.paths.memoriesDir)\n : [];\n const existingTopics = new Set(\n existing.map(({ memory }) => memory.frontmatter.topic).filter((t): t is string => Boolean(t)),\n );\n const fresh = filterNewDrafts(drafts, existingTopics);\n const skipped = drafts.length - fresh.length;\n\n const created: IngestFindingsOutput[\"created\"] = [];\n for (const draft of fresh) {\n let filePath: string | undefined;\n if (!input.dry_run) filePath = await writeDraft(ctx, draft);\n created.push({\n id: draft.frontmatter.id,\n topic: draft.topic,\n path: draft.finding.path,\n rule: draft.finding.ruleId,\n severity: draft.finding.severity,\n has_sensor: draft.has_sensor,\n ...(filePath ? { file_path: filePath } : {}),\n });\n }\n\n const notice = input.dry_run\n ? `Dry run — ${fresh.length} memory(ies) would be created (status=proposed). Re-run with dry_run=false to write them.`\n : `Created ${fresh.length} proposed memory(ies). They are NOT validated and their sensors are warn-only — review with mem_pending and promote with 'hivelore sensors promote'.`;\n\n return {\n format: input.format,\n parsed: drafts.length,\n new: fresh.length,\n skipped_existing: skipped,\n dry_run: input.dry_run,\n created,\n notice,\n };\n}\n\nasync function writeDraft(ctx: HaiveContext, draft: MemoryDraft): Promise<string> {\n const file = memoryFilePath(\n ctx.paths,\n draft.frontmatter.scope,\n draft.frontmatter.id,\n draft.frontmatter.module,\n );\n await mkdir(path.dirname(file), { recursive: true });\n await writeFile(file, serializeMemory({ frontmatter: draft.frontmatter, body: draft.body }), \"utf8\");\n return file;\n}\n","import { mkdir, writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n buildFrontmatter,\n isLikelyGuessable,\n memoryFilePath,\n serializeMemory,\n} from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\n/**\n * mem_observe — capture a code-level discovery made during exploration.\n *\n * Unlike mem_tried (failed approaches) or mem_save (conventions/decisions),\n * mem_observe is for bugs, inconsistencies, and security gaps discovered by\n * reading existing code that were NOT in the briefing. Auto-validated (no review).\n */\nexport const MemObserveInputSchema = {\n what: z\n .string()\n .min(1)\n .describe(\"Short title: what did you observe? (e.g. 'MobilePaymentController has two @RequestBody on handleWebhook')\"),\n where: z\n .string()\n .min(1)\n .describe(\"File path(s) where the issue lives — be specific\"),\n impact: z\n .string()\n .min(1)\n .describe(\"What breaks or could break because of this (e.g. 'Spring MVC rejects the handler at startup')\"),\n fix: z\n .string()\n .optional()\n .describe(\"Suggested fix or workaround (optional — leave empty if unknown)\"),\n scope: z\n .enum([\"personal\", \"team\", \"module\"])\n .default(\"team\")\n .describe(\"Visibility scope — defaults to team since discoveries benefit everyone\"),\n module: z.string().optional().describe(\"Module name (required when scope=module)\"),\n tags: z.array(z.string()).default([]).describe(\"Tags for filtering\"),\n author: z.string().optional().describe(\"Author handle or email\"),\n force: z\n .boolean()\n .default(false)\n .describe(\n \"Save even if the observation looks like generic, guessable knowledge. By default, \" +\n \"low-specificity observations (things a capable model already knows) are SKIPPED to keep \" +\n \"the corpus high-signal — only unguessable, team-specific discoveries are worth storing.\",\n ),\n};\n\nexport type MemObserveInput = {\n [K in keyof typeof MemObserveInputSchema]: z.infer<(typeof MemObserveInputSchema)[K]>;\n};\n\nexport interface MemObserveOutput {\n id: string;\n scope: string;\n file_path: string;\n /** True when the observation was NOT saved because it looked generic/guessable. */\n skipped?: boolean;\n reason?: string;\n}\n\nexport async function memObserve(\n input: MemObserveInput,\n ctx: HaiveContext,\n): Promise<MemObserveOutput> {\n if (!existsSync(ctx.paths.haiveDir)) {\n throw new Error(`No .ai/ directory at ${ctx.paths.root}. Run 'hivelore init' first.`);\n }\n\n // Capture filter: Hivelore only earns its keep on UNGUESSABLE, team-specific knowledge.\n // Skip generic observations a capable model already makes by default — they only add noise\n // and token cost to future briefings. The caller can override with force=true.\n const signalText = [input.what, input.impact, input.fix ?? \"\"].join(\" \");\n if (!input.force && isLikelyGuessable(signalText)) {\n return {\n id: \"\",\n scope: input.scope,\n file_path: \"\",\n skipped: true,\n reason:\n \"Observation looks like generic, guessable knowledge (low specificity) — not saved. \" +\n \"Capture only arbitrary, team-specific facts (exact names, values, formats). Pass force=true to override.\",\n };\n }\n\n const slug = input.what\n .toLowerCase()\n .replace(/[^a-z0-9\\s]/g, \"\")\n .trim()\n .split(/\\s+/)\n .slice(0, 6)\n .join(\"-\");\n\n // Parse where into anchor paths (comma-separated or single path)\n const anchorPaths = input.where\n .split(/[,\\n]/)\n .map((s) => s.trim())\n .filter(Boolean);\n\n const baseFm = buildFrontmatter({\n type: \"gotcha\",\n slug,\n scope: input.scope,\n module: input.module,\n tags: input.tags,\n paths: anchorPaths,\n author: input.author,\n });\n // Observations are immediately validated — no review cycle needed\n const frontmatter = { ...baseFm, status: \"validated\" as const };\n\n const lines: string[] = [`# ${input.what}`, \"\"];\n lines.push(`**Where:** \\`${input.where}\\``);\n lines.push(\"\", `**Impact:** ${input.impact}`);\n if (input.fix) {\n lines.push(\"\", `**Fix/workaround:** ${input.fix}`);\n }\n const body = lines.join(\"\\n\") + \"\\n\";\n\n const file = memoryFilePath(ctx.paths, frontmatter.scope, frontmatter.id, frontmatter.module);\n await mkdir(path.dirname(file), { recursive: true });\n\n if (existsSync(file)) {\n throw new Error(`Memory already exists at ${file}`);\n }\n\n await writeFile(file, serializeMemory({ frontmatter, body }), \"utf8\");\n\n return { id: frontmatter.id, scope: frontmatter.scope, file_path: file };\n}\n","/**\n * mem_session_end — save a structured end-of-session recap.\n *\n * Engram-inspired: explicit session lifecycle lets the next session start with\n * rich context about what was just done, which files were touched, and what\n * remains. Uses topic-upsert so there is always exactly ONE \"current recap\"\n * per scope/module: revisions accumulate in-place rather than creating clutter.\n */\nimport { writeFile, mkdir } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n buildFrontmatter,\n loadMemoriesFromDir,\n memoryFilePath,\n serializeMemory,\n} from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\nimport { clearPendingDistill } from \"../session-tracker.js\";\n\nexport const MemSessionEndInputSchema = {\n goal: z\n .string()\n .min(1)\n .describe(\"What you were trying to accomplish this session (1–2 sentences)\"),\n accomplished: z\n .string()\n .describe(\"What was actually done — bullet list recommended\"),\n discoveries: z\n .string()\n .default(\"\")\n .describe(\n \"Any bugs, inconsistencies, surprises, or missing knowledge found during this session. \" +\n \"Empty if nothing surprising was found.\",\n ),\n files_touched: z\n .array(z.string())\n .default([])\n .describe(\"Key files that were read or modified — used as anchor paths\"),\n next_steps: z\n .string()\n .default(\"\")\n .describe(\"What should happen next (for the next session or a teammate)\"),\n scope: z\n .enum([\"personal\", \"team\", \"module\"])\n .default(\"personal\")\n .describe(\"Visibility: personal = private to you, team = shared with the team\"),\n module: z\n .string()\n .optional()\n .describe(\"Module name (required when scope=module)\"),\n};\n\nexport type MemSessionEndInput = {\n [K in keyof typeof MemSessionEndInputSchema]: z.infer<(typeof MemSessionEndInputSchema)[K]>;\n};\n\nexport interface MemSessionEndOutput {\n id: string;\n scope: string;\n file_path: string;\n action: \"created\" | \"updated\";\n revision_count: number;\n}\n\n/** Stable topic key for upsert — one recap per scope/module. */\nfunction recapTopic(scope: string, module?: string): string {\n return module ? `session-recap-${scope}-${module}` : `session-recap-${scope}`;\n}\n\nfunction buildBody(input: MemSessionEndInput): string {\n const lines: string[] = [];\n\n lines.push(`## Goal\\n${input.goal}`);\n lines.push(`\\n## Accomplished\\n${input.accomplished}`);\n\n if (input.discoveries.trim()) {\n lines.push(`\\n## Discoveries & surprises\\n${input.discoveries}`);\n }\n\n if (input.files_touched.length > 0) {\n lines.push(`\\n## Files touched\\n${input.files_touched.map((f) => `- \\`${f}\\``).join(\"\\n\")}`);\n }\n\n if (input.next_steps.trim()) {\n lines.push(`\\n## Next steps\\n${input.next_steps}`);\n }\n\n return lines.join(\"\\n\");\n}\n\nexport async function memSessionEnd(\n input: MemSessionEndInput,\n ctx: HaiveContext,\n): Promise<MemSessionEndOutput> {\n if (!existsSync(ctx.paths.haiveDir)) {\n throw new Error(`No .ai/ directory at ${ctx.paths.root}. Run 'hivelore init' first.`);\n }\n\n const body = buildBody(input);\n const topic = recapTopic(input.scope, input.module);\n\n // Normalize to project-relative paths (guards against absolute paths from agents)\n const normalizedFiles = input.files_touched.map((p) => {\n if (!p || !path.isAbsolute(p)) return p;\n const rel = path.relative(ctx.paths.root, p);\n return rel.startsWith(\"..\") ? p : rel;\n });\n\n // Validate anchor paths exist before saving\n const invalidPaths = normalizedFiles.filter(\n (p) => !existsSync(path.resolve(ctx.paths.root, p)),\n );\n if (invalidPaths.length > 0) {\n // Non-blocking for session end — just log in the output\n console.warn(`[haive] session end: anchor path(s) not found: ${invalidPaths.join(\", \")}`);\n }\n\n const existing = existsSync(ctx.paths.memoriesDir)\n ? await loadMemoriesFromDir(ctx.paths.memoriesDir)\n : [];\n\n // ── Topic upsert: update existing recap in-place ───────────────────────\n const topicMatch = existing.find(({ memory }) =>\n memory.frontmatter.topic === topic &&\n memory.frontmatter.scope === input.scope &&\n (!input.module || memory.frontmatter.module === input.module),\n );\n\n if (topicMatch) {\n const fm = topicMatch.memory.frontmatter;\n const revisionCount = (fm.revision_count ?? 0) + 1;\n const newFrontmatter = {\n ...fm,\n verified_at: new Date().toISOString(),\n revision_count: revisionCount,\n anchor: {\n ...fm.anchor,\n paths: normalizedFiles.length ? normalizedFiles : fm.anchor.paths,\n },\n };\n await writeFile(\n topicMatch.filePath,\n serializeMemory({ frontmatter: newFrontmatter, body }),\n \"utf8\",\n );\n // Clear pending distill — a manual post_task flow completed successfully.\n await clearPendingDistill(ctx);\n return {\n id: fm.id,\n scope: fm.scope,\n file_path: topicMatch.filePath,\n action: \"updated\",\n revision_count: revisionCount,\n };\n }\n\n // ── Create new recap (first session) ──────────────────────────────────\n const frontmatter = buildFrontmatter({\n type: \"session_recap\",\n slug: \"recap\",\n scope: input.scope,\n module: input.module,\n tags: [\"session\", \"recap\"],\n paths: normalizedFiles,\n topic,\n status: \"validated\",\n });\n\n const file = memoryFilePath(\n ctx.paths,\n frontmatter.scope,\n frontmatter.id,\n frontmatter.module,\n );\n await mkdir(path.dirname(file), { recursive: true });\n\n await writeFile(file, serializeMemory({ frontmatter, body }), \"utf8\");\n\n // A successful manual mem_session_end (post_task flow) means the distillation\n // has been done properly — clear the shallow auto-recap marker so the next\n // get_briefing doesn't ask again.\n await clearPendingDistill(ctx);\n\n return {\n id: frontmatter.id,\n scope: frontmatter.scope,\n file_path: file,\n action: \"created\",\n revision_count: 0,\n };\n}\n","/**\n * Auto-session tracker for autopilot mode.\n *\n * Tracks which MCP tools were called during a server session.\n * On SIGTERM/SIGINT (i.e. when the AI client closes), automatically:\n * 1. Saves a session recap via mem_session_end (always)\n * 2. Writes .ai/.cache/pending-distill.json so the next get_briefing\n * surfaces an action_required item prompting the agent to invoke\n * post_task for a richer LLM-driven distillation.\n */\nimport {\n appendUsageEvent,\n appendRuntimeJournalEntry,\n loadConfig,\n writeSessionHandoff,\n type HaiveConfig,\n} from \"@hivelore/core\";\nimport { mkdir, writeFile, rm } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { execSync } from \"node:child_process\";\nimport type { HaiveContext } from \"./context.js\";\nimport { memSessionEnd } from \"./tools/mem-session-end.js\";\n\nexport interface SessionEvent {\n tool: string;\n at: string; // ISO timestamp\n /** Partial input snapshot (non-sensitive fields only) */\n summary?: string;\n}\n\n/** Written to .ai/.cache/pending-distill.json at session end. */\nexport interface PendingDistill {\n session_start: string;\n session_end: string;\n total_tool_calls: number;\n /** Human-readable summary of which tools were called (\"get_briefing ×3, mem_save ×2\") */\n tool_summary: string;\n /** IDs of memories saved during this session */\n memories_saved: string[];\n /** True when git diff was captured and stored in git_diff field */\n git_diff_available: boolean;\n /** Snapshot of `git diff HEAD` at session close (truncated to 8 KB) */\n git_diff?: string;\n /** ID of the auto-generated session recap memory */\n recap_id?: string;\n}\n\n/** Path to the pending distill marker file. */\nexport function pendingDistillPath(ctx: HaiveContext): string {\n return path.join(ctx.paths.haiveDir, \".cache\", \"pending-distill.json\");\n}\n\nexport class SessionTracker {\n private events: SessionEvent[] = [];\n private startedAt: string = new Date().toISOString();\n private config: HaiveConfig | null = null;\n private ctx: HaiveContext;\n private shutdownRegistered = false;\n\n constructor(ctx: HaiveContext) {\n this.ctx = ctx;\n }\n\n async init(): Promise<void> {\n this.config = await loadConfig(this.ctx.paths);\n if (this.config.autoSessionEnd) {\n this.registerShutdownHandler();\n }\n }\n\n record(tool: string, summary?: string): void {\n const event: SessionEvent = { tool, at: new Date().toISOString(), summary };\n this.events.push(event);\n // Persist to .ai/.usage/tool-usage.jsonl for cross-session stats (hivelore stats).\n // Best-effort: never blocks the tool execution, never throws.\n void appendUsageEvent(this.ctx.paths, event);\n }\n\n private registerShutdownHandler(): void {\n if (this.shutdownRegistered) return;\n this.shutdownRegistered = true;\n\n const save = async (): Promise<void> => {\n const writingTools = this.events.filter((e) =>\n [\"mem_save\", \"mem_tried\", \"mem_observe\", \"mem_update\", \"bootstrap_project_save\"].includes(e.tool),\n );\n const totalCalls = this.events.length;\n\n if (totalCalls === 0) return;\n\n const toolSummary = summarizeTools(this.events);\n const filesSet = new Set<string>();\n for (const e of this.events) {\n if (e.summary) {\n const matches = e.summary.match(/[^\\s\"',]+\\.[a-zA-Z]{1,6}/g) ?? [];\n for (const m of matches) filesSet.add(m);\n }\n }\n\n // ── 1. Capture git diff (best-effort, 8 KB cap) ──────────────────────\n let gitDiff: string | undefined;\n try {\n const raw = execSync(\"git diff HEAD\", {\n cwd: this.ctx.paths.root,\n timeout: 5000,\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n });\n gitDiff = raw.slice(0, 8192) || undefined;\n } catch { /* not a git repo or no diff — ok */ }\n\n // ── 2. Save minimal session recap MEMORY (unless disabled) ───────────\n // autoSessionRecap=false stops the low-signal recap dump from accumulating in\n // (and biasing) the .ai/ corpus. Pair with sessionHandoff for an ephemeral NEXT.md.\n let recapId: string | undefined;\n if (this.config?.autoSessionRecap !== false) {\n try {\n const result = await memSessionEnd(\n {\n goal: `Auto-captured session (${totalCalls} tool call${totalCalls === 1 ? \"\" : \"s\"})`,\n accomplished: toolSummary,\n discoveries: writingTools.length > 0\n ? `${writingTools.length} memor${writingTools.length === 1 ? \"y\" : \"ies\"} saved during this session.`\n : \"No new memories saved this session.\",\n files_touched: [...filesSet].slice(0, 10),\n next_steps: \"\",\n scope: (this.config?.defaultScope as \"personal\" | \"team\") ?? \"personal\",\n module: undefined,\n },\n this.ctx,\n );\n recapId = result.id;\n } catch {\n // Non-fatal — never block process exit\n }\n }\n\n // ── 2b. Ephemeral NEXT.md handoff (opt-in via sessionHandoff) ─────────\n // One overwritten file at the repo root: open threads (what was tried) + next steps,\n // instead of an accumulating corpus memory. Best-effort; never blocks exit.\n if (this.config?.sessionHandoff) {\n const triedThreads = this.events\n .filter((e) => e.tool === \"mem_tried\")\n .map((e) => e.summary ?? \"\")\n .filter(Boolean);\n let diffStat: string | undefined;\n try {\n diffStat = execSync(\"git diff --stat HEAD\", {\n cwd: this.ctx.paths.root,\n timeout: 5000,\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n }).trim() || undefined;\n } catch { /* not a git repo / no diff */ }\n try {\n await writeSessionHandoff(this.ctx.paths.root, {\n goal: `Auto-captured session (${totalCalls} tool call${totalCalls === 1 ? \"\" : \"s\"})`,\n summary: toolSummary,\n openThreads: triedThreads,\n filesTouched: [...filesSet].slice(0, 20),\n ...(diffStat ? { diffStat } : {}),\n });\n } catch {\n // Non-fatal\n }\n }\n\n void appendRuntimeJournalEntry(this.ctx.paths, {\n kind: \"session_end\",\n message: recapId\n ? `auto session close | ${toolSummary} | recap:${recapId}`\n : `auto session close | ${toolSummary}`,\n meta: {\n recap_id: recapId ?? null,\n total_tool_calls: totalCalls,\n },\n });\n\n // ── 3. Write pending-distill.json so next get_briefing can prompt ─────\n // Skip if the agent already ran post_task this session (no shallow recap).\n // Also skip trivial sessions (1-2 tool calls with no writes) — they don't\n // contain distillation candidates and the action_required would just be noise.\n const ranPostTask = this.events.some((e) =>\n e.tool === \"mem_session_end\" && !e.summary?.startsWith(\"Auto-captured\"),\n );\n const isSubstantialSession = totalCalls >= 3 || writingTools.length > 0;\n if (!ranPostTask && isSubstantialSession && existsSync(this.ctx.paths.haiveDir)) {\n try {\n const memoriesSaved = writingTools\n .map((e) => e.summary ?? \"\")\n .filter(Boolean)\n .slice(0, 20);\n\n const payload: PendingDistill = {\n session_start: this.startedAt,\n session_end: new Date().toISOString(),\n total_tool_calls: totalCalls,\n tool_summary: toolSummary,\n memories_saved: memoriesSaved,\n git_diff_available: !!gitDiff,\n ...(gitDiff ? { git_diff: gitDiff } : {}),\n ...(recapId ? { recap_id: recapId } : {}),\n };\n\n const cacheDir = path.join(this.ctx.paths.haiveDir, \".cache\");\n await mkdir(cacheDir, { recursive: true });\n await writeFile(\n pendingDistillPath(this.ctx),\n JSON.stringify(payload, null, 2) + \"\\n\",\n \"utf8\",\n );\n } catch { /* Non-fatal */ }\n }\n };\n\n process.once(\"SIGTERM\", () => { void save().finally(() => process.exit(0)); });\n process.once(\"SIGINT\", () => { void save().finally(() => process.exit(0)); });\n }\n}\n\n/** Delete the pending distill marker if it exists. Called by mem_session_end. */\nexport async function clearPendingDistill(ctx: HaiveContext): Promise<void> {\n const p = pendingDistillPath(ctx);\n if (existsSync(p)) {\n try { await rm(p); } catch { /* non-fatal */ }\n }\n}\n\nfunction summarizeTools(events: SessionEvent[]): string {\n const counts = new Map<string, number>();\n for (const e of events) {\n counts.set(e.tool, (counts.get(e.tool) ?? 0) + 1);\n }\n return [...counts.entries()]\n .sort((a, b) => b[1] - a[1])\n .map(([t, n]) => `${t} ×${n}`)\n .join(\", \");\n}\n","import { readFile, writeFile, readdir } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n allocateBudget,\n assessBootstrapState,\n renderBootstrapChecklist,\n briefingProofLine,\n computeImpact,\n DEFAULT_AUTO_PROMOTE_RULE,\n deriveConfidence,\n estimateTokens,\n evaluateSkillActivation,\n compactAutoRecapBody,\n extractActionsBriefBody,\n getUsage,\n inferModulesFromPaths,\n isAutoPromoteEligible,\n isDecaying,\n isRetiredMemory,\n literalMatchesAllTokens,\n literalMatchesAnyToken,\n loadCodeMap,\n loadConfig,\n memoryHasExcludedTag,\n hashProjectContext,\n loadMemoriesFromDir,\n loadPreventionEvents,\n loadUsageIndex,\n memoryMatchesAnchorPaths,\n projectContextRecentlyEmitted,\n rankMemoriesLexical,\n recordProjectContextEmission,\n queryCodeMap,\n readSessionHandoff,\n resolveBriefingBudget,\n serializeMemory,\n specificityScore,\n GUESSABLE_THRESHOLD,\n tokenizeQuery,\n trackReads,\n truncateToTokens,\n writeBriefingMarker,\n type LoadedMemory,\n type UsageIndex,\n} from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\nimport { pendingDistillPath, type PendingDistill } from \"../session-tracker.js\";\nimport type {\n ActionRequiredItem,\n BriefingBreadcrumbItem,\n BriefingBreadcrumbs,\n BriefingMemory,\n BriefingOutput,\n} from \"./briefing-types.js\";\nimport {\n classifyBriefingQuality,\n classifyMemoryPriority,\n compactSummary,\n explainWhySurfaced,\n loadModuleContexts,\n priorityRank,\n trySemanticHits,\n} from \"./briefing-helpers.js\";\n\n// Re-export types so existing importers (server.ts, mem-relevant-to.ts) don't need to change.\nexport type {\n ActionRequiredItem,\n BriefingMemory,\n BriefingMemoryPriority,\n BriefingOutput,\n BriefingQuality,\n CodeMapSymbolHit,\n} from \"./briefing-types.js\";\n\nexport const GetBriefingInputSchema = {\n task: z\n .string()\n .optional()\n .describe(\n \"What you are about to do, in 1–2 sentences. Used to rank relevant memories semantically.\",\n ),\n files: z\n .array(z.string())\n .default([])\n .describe(\"Project-relative file paths the agent is currently looking at or about to edit\"),\n max_tokens: z\n .number()\n .int()\n .positive()\n .default(8000)\n .describe(\n \"Approximate token budget for the entire briefing. Each section is allocated a share and truncated to fit.\",\n ),\n max_memories: z\n .number()\n .int()\n .positive()\n .default(8)\n .describe(\"Cap on memories surfaced regardless of token budget\"),\n include_project_context: z.boolean().default(true),\n dedupe_project_context: z\n .boolean()\n .optional()\n .describe(\n \"Token saver (default ON): skip re-emitting the project-context body if an identical copy was \" +\n \"already sent within the last few minutes this session (the agent still has it). Set false to always include it.\",\n ),\n include_module_contexts: z.boolean().default(true),\n semantic: z\n .boolean()\n .default(true)\n .describe(\n \"Use semantic ranking when a task is provided (requires `hivelore embeddings index`).\",\n ),\n include_stale: z\n .boolean()\n .default(false)\n .describe(\"Include stale memories (excluded by default — they may be outdated)\"),\n track: z.boolean().default(true).describe(\"Increment read_count on returned memories\"),\n format: z\n .enum([\"full\", \"compact\", \"actions\"])\n .default(\"full\")\n .describe(\n \"Output format: 'full' returns memory bodies (honors token budget via truncation); \" +\n \"'compact' returns a 1-line summary per memory (call mem_get for detail); \" +\n \"'actions' squeezes bodies to actionable bullet lines — fewer tokens vs full.\",\n ),\n symbols: z\n .array(z.string())\n .default([])\n .describe(\n \"Symbol names to look up in the code-map (e.g. ['PaymentService', 'TenantFilter']). \" +\n \"Returns the file(s) exporting each symbol so agents don't need to grep. \" +\n \"Requires `hivelore index code` to have been run.\",\n ),\n min_semantic_score: z\n .number()\n .min(0)\n .max(1)\n .default(0)\n .describe(\n \"Drop semantic-only memory hits whose cosine score is below this threshold. \" +\n \"Useful to avoid weakly-related noise when the task is short or the corpus is broad. \" +\n \"Has no effect on memories matched via anchor/module/literal — those are always kept. \" +\n \"Try 0.25–0.4 for stricter matching.\",\n ),\n budget_preset: z\n .enum([\"quick\", \"balanced\", \"deep\"])\n .optional()\n .describe(\n \"Shortcut token budget: 'quick' minimizes tokens/skip module CONTEXT slices; 'balanced' mirrors historical defaults; \" +\n \"'deep' uses a larger briefing. When set, overrides max_tokens, max_memories, and include_module_contexts.\",\n ),\n};\n\nexport const GetBriefingZod = z.object(GetBriefingInputSchema);\nexport type GetBriefingInput = z.infer<typeof GetBriefingZod>;\n\nexport async function getBriefing(\n input: GetBriefingInput,\n ctx: HaiveContext,\n): Promise<BriefingOutput> {\n const resolvedBudget = resolveBriefingBudget(input.budget_preset, {\n max_tokens: input.max_tokens,\n max_memories: input.max_memories,\n include_module_contexts: input.include_module_contexts,\n });\n const briefingMaxTokens = resolvedBudget.max_tokens;\n const briefingMaxMemories = resolvedBudget.max_memories;\n const briefingIncludeModules = resolvedBudget.include_module_contexts;\n\n const inferred = inferModulesFromPaths(input.files);\n const memories: BriefingMemory[] = [];\n let searchMode: BriefingOutput[\"search_mode\"] = \"literal\";\n let usage: UsageIndex = { version: 1, updated_at: \"\", by_id: {} };\n let byId = new Map<string, LoadedMemory>();\n\n // ── Session recap ──────────────────────────────────────────────────────\n let lastSession: BriefingOutput[\"last_session\"] | undefined;\n\n if (existsSync(ctx.paths.memoriesDir)) {\n const allLoaded = await loadMemoriesFromDir(ctx.paths.memoriesDir);\n\n const recaps = allLoaded\n .filter(({ memory }) => memory.frontmatter.type === \"session_recap\")\n .sort((a, b) =>\n new Date(b.memory.frontmatter.created_at).getTime() -\n new Date(a.memory.frontmatter.created_at).getTime(),\n );\n if (recaps.length > 0) {\n const r = recaps[0]!;\n const fm = r.memory.frontmatter;\n lastSession = {\n id: fm.id,\n scope: fm.scope,\n revision_count: fm.revision_count ?? 0,\n // Auto-generated recaps are low-signal tool dumps — compact them so they inform without\n // dominating the briefing head. Human/post_task recaps pass through unchanged.\n body: compactAutoRecapBody(r.memory.body),\n };\n }\n\n // Fallback: when no recap memory exists (e.g. autoSessionRecap=false), surface the ephemeral\n // NEXT.md handoff so the next session still resumes with open threads + next steps.\n if (!lastSession) {\n const handoff = await readSessionHandoff(ctx.paths.root);\n if (handoff) {\n lastSession = { id: \"next-handoff\", scope: \"ephemeral\", revision_count: 0, body: handoff };\n }\n }\n\n // Strategy/positioning memories are excluded from AUTOMATIC surfacing so they can't bias the\n // agent's opinions on every task (they remain searchable via mem_search). See briefingExcludeTags.\n const briefingCfg = await loadConfig(ctx.paths).catch(() => null);\n const excludeTags = briefingCfg?.briefingExcludeTags;\n\n const allMemories = allLoaded.filter(({ memory }) => {\n const s = memory.frontmatter.status;\n if (s === \"rejected\" || s === \"deprecated\") return false;\n if (!input.include_stale && s === \"stale\") return false;\n if (!input.include_stale && isRetiredMemory(memory.frontmatter, memory.body)) return false;\n if (memory.frontmatter.type === \"session_recap\") return false;\n if (memoryHasExcludedTag(memory.frontmatter, excludeTags)) return false;\n return true;\n });\n usage = await loadUsageIndex(ctx.paths);\n\n // byId MUST be populated before the semanticHits loop that uses it.\n // (gotcha: 2026-05-02-gotcha-getbriefing-semantic-hits-silently-dropped-byid)\n byId = new Map(allMemories.map((m) => [m.memory.frontmatter.id, m]));\n\n const semanticHits = input.task && input.semantic\n ? await trySemanticHits(ctx, input.task, allMemories.length * 2)\n : null;\n\n if (input.task && input.semantic) {\n searchMode = semanticHits ? \"semantic\" : \"literal_fallback\";\n }\n\n const seen = new Map<string, BriefingMemory>();\n\n const addOrUpdate = (\n loaded: LoadedMemory,\n reason: BriefingMemory[\"reasons\"][number],\n score?: number,\n matchQuality?: BriefingMemory[\"match_quality\"],\n ): void => {\n const fm = loaded.memory.frontmatter;\n const existing = seen.get(fm.id);\n if (existing) {\n if (!existing.reasons.includes(reason)) existing.reasons.push(reason);\n if (score !== undefined && (existing.semantic_score ?? 0) < score) {\n existing.semantic_score = score;\n }\n if (matchQuality === \"exact\" && existing.match_quality !== \"exact\") {\n existing.match_quality = \"exact\";\n } else if (matchQuality === \"semantic\" && existing.match_quality === \"partial\") {\n existing.match_quality = \"semantic\";\n }\n return;\n }\n const u = getUsage(usage, fm.id);\n const imp = computeImpact(fm, u);\n seen.set(fm.id, {\n id: fm.id,\n scope: fm.scope,\n type: fm.type,\n ...(fm.module ? { module: fm.module } : {}),\n tags: fm.tags,\n status: fm.status,\n confidence: deriveConfidence(fm, u),\n ...(fm.status === \"draft\" || fm.status === \"proposed\" ? { unverified: true as const } : {}),\n read_count: u.read_count,\n impact_score: imp.score,\n impact_tier: imp.tier,\n reasons: [reason],\n match_quality: matchQuality ?? \"partial\",\n ...(score !== undefined ? { semantic_score: score } : {}),\n priority: \"background\",\n body: loaded.memory.body,\n file_path: loaded.filePath,\n });\n };\n\n // ── Matching passes ────────────────────────────────────────────────────\n if (input.files.length > 0) {\n for (const loaded of allMemories) {\n if (memoryMatchesAnchorPaths(loaded.memory, input.files)) addOrUpdate(loaded, \"anchor\", undefined, \"exact\");\n }\n for (const loaded of allMemories) {\n const fm = loaded.memory.frontmatter;\n if (fm.module && inferred.includes(fm.module)) addOrUpdate(loaded, \"module\", undefined, \"partial\");\n if (fm.domain && inferred.includes(fm.domain)) addOrUpdate(loaded, \"domain\", undefined, \"partial\");\n if (fm.tags.some((t) => inferred.includes(t))) addOrUpdate(loaded, \"module\", undefined, \"partial\");\n }\n }\n\n if (input.symbols.length > 0) {\n const wanted = new Set(input.symbols.map((s) => s.toLowerCase()));\n for (const loaded of allMemories) {\n const symbols = loaded.memory.frontmatter.anchor.symbols.map((s) => s.toLowerCase());\n if (symbols.some((s) => wanted.has(s))) addOrUpdate(loaded, \"symbol\", undefined, \"exact\");\n }\n }\n\n if (input.task) {\n const tokens = tokenizeQuery(input.task);\n const andHits = allMemories.filter((m) => literalMatchesAllTokens(m.memory, tokens));\n for (const loaded of andHits) addOrUpdate(loaded, \"semantic\", undefined, \"exact\");\n if (andHits.length === 0 && tokens.length > 1) {\n for (const loaded of allMemories) {\n if (literalMatchesAnyToken(loaded.memory, tokens)) addOrUpdate(loaded, \"semantic\", undefined, \"partial\");\n }\n }\n if (semanticHits) {\n for (const hit of semanticHits) {\n if (hit.score < input.min_semantic_score && !seen.has(hit.id)) continue;\n const loaded = byId.get(hit.id);\n if (loaded) addOrUpdate(loaded, \"semantic\", hit.score, \"semantic\");\n }\n }\n }\n\n // ── Progressive disclosure for skills ────────────────────────────────────\n // A skill that declares `activation` triggers is disclosed only when the task or\n // edited files match; an activated skill earns a ranking boost (it's a playbook\n // to follow now). Skills without an activation block keep legacy behavior.\n const activatedSkills = new Set<string>();\n for (const [id, m] of seen) {\n if (m.type !== \"skill\") continue;\n const loaded = byId.get(id);\n if (!loaded) continue;\n const act = evaluateSkillActivation(loaded.memory.frontmatter, {\n task: input.task,\n files: input.files,\n });\n if (act.applicable && !act.activated) {\n seen.delete(id);\n continue;\n }\n if (act.applicable && act.activated) activatedSkills.add(id);\n }\n\n // ── Lexical relevance (BM25) ─────────────────────────────────────────────\n // Semantic cosine alone (0..1) is too weak to overcome the type/confidence/impact\n // bonuses, so popular high-read attempt memories dominated EVERY task — the actually\n // relevant memory got buried. A BM25 score over the candidate set rewards overlap on\n // the query's *distinctive* terms (high IDF), pulling the on-topic memory up. It does\n // not touch anchored ranking: anchor/symbol hits stay must_read (priority * 100).\n const lexNorm = new Map<string, number>();\n if (input.task) {\n const candidates = [...seen.keys()]\n .map((id) => byId.get(id))\n .filter((x): x is LoadedMemory => Boolean(x));\n const lex = rankMemoriesLexical(candidates, input.task, candidates.length);\n const maxScore = lex.scores.reduce((m, s) => (s > m ? s : m), 0);\n if (maxScore > 0) {\n lex.ranked.forEach((loaded, i) => {\n lexNorm.set(loaded.memory.frontmatter.id, (lex.scores[i] ?? 0) / maxScore);\n });\n }\n }\n\n // ── Ranking ────────────────────────────────────────────────────────────\n const ranked = [...seen.values()].sort((a, b) => {\n const reasonScore = (m: BriefingMemory): number =>\n (m.type === \"attempt\" ? 3 : 0) +\n (m.reasons.includes(\"anchor\") ? 4 : 0) +\n (m.reasons.includes(\"symbol\") ? 4 : 0) +\n (m.reasons.includes(\"module\") ? 2 : 0) +\n (m.reasons.includes(\"semantic\") ? 2 : 0) +\n (m.reasons.includes(\"domain\") ? 1 : 0);\n const confidenceScore = (m: BriefingMemory): number =>\n m.confidence === \"authoritative\" ? 4 :\n m.confidence === \"trusted\" ? 3 :\n m.confidence === \"low\" ? 1 :\n m.confidence === \"stale\" ? -2 : 0;\n // Demonstrated-utility nudge (0..3): a memory that agents actually applied — or\n // whose sensor caught a regression — edges out an equally-relevant one that\n // never proved useful. Small on purpose: never overrides anchor/symbol relevance.\n const impactScore = (m: BriefingMemory): number => (m.impact_score ?? 0) * 3;\n // An explicitly-activated skill is an actionable playbook for this exact task — surface it high.\n const activationBoost = (m: BriefingMemory): number => (activatedSkills.has(m.id) ? 5 : 0);\n // Lexical relevance weight (0..12): strong enough to lift the on-topic memory above a\n // popular-but-unrelated attempt (whose type+confidence head start is ~7), yet far below\n // the priority tier (×100) so anchored/symbol matches are never displaced.\n const lexScore = (m: BriefingMemory): number => 12 * (lexNorm.get(m.id) ?? 0);\n const sa = priorityRank(classifyMemoryPriority(a, byId.get(a.id), input.files, input.symbols)) * 100\n + reasonScore(a) + confidenceScore(a) + impactScore(a) + activationBoost(a) + lexScore(a) + (a.semantic_score ?? 0);\n const sb = priorityRank(classifyMemoryPriority(b, byId.get(b.id), input.files, input.symbols)) * 100\n + reasonScore(b) + confidenceScore(b) + impactScore(b) + activationBoost(b) + lexScore(b) + (b.semantic_score ?? 0);\n return sb - sa;\n });\n\n // Expand related_ids from top results\n for (const mem of ranked.slice(0, briefingMaxMemories)) {\n if (seen.size >= briefingMaxMemories * 2) break;\n const loaded = byId.get(mem.id);\n if (!loaded) continue;\n for (const relId of loaded.memory.frontmatter.related_ids ?? []) {\n if (seen.has(relId)) continue;\n const related = byId.get(relId);\n if (related) addOrUpdate(related, \"anchor\", undefined, \"partial\");\n }\n }\n\n memories.push(...ranked.slice(0, briefingMaxMemories));\n\n // ── Track reads + inline auto-promote ─────────────────────────────────\n if (input.track && memories.length > 0) {\n await trackReads(ctx.paths, memories.map((m) => m.id));\n const freshUsage = await loadUsageIndex(ctx.paths);\n // Use configured autoPromoteMinReads — not the hardcoded default.\n // (gotcha: 2026-05-04-gotcha-auto-promote-ignores-config-minreads)\n const cfg = await loadConfig(ctx.paths);\n const rule = {\n minReads: cfg.autoPromoteMinReads ?? DEFAULT_AUTO_PROMOTE_RULE.minReads,\n maxRejections: DEFAULT_AUTO_PROMOTE_RULE.maxRejections,\n };\n for (const m of memories) {\n const loaded = byId.get(m.id);\n if (!loaded) continue;\n const u = getUsage(freshUsage, m.id);\n if (!isAutoPromoteEligible(loaded.memory.frontmatter, u, rule)) continue;\n // Auto-promotion trusts a memory WITHOUT review → mark it \"auto\" so a human can audit it later.\n const newFm = { ...loaded.memory.frontmatter, status: \"validated\" as const, validated_by: \"auto\" as const };\n try {\n await writeFile(loaded.filePath, serializeMemory({ frontmatter: newFm, body: loaded.memory.body }), \"utf8\");\n m.status = \"validated\";\n m.confidence = \"trusted\";\n } catch { /* non-fatal */ }\n }\n }\n }\n\n // ── Project context ────────────────────────────────────────────────────\n let projectContextRaw =\n input.include_project_context && existsSync(ctx.paths.projectContext)\n ? await readFile(ctx.paths.projectContext, \"utf8\")\n : \"\";\n // Token saver: within a session, don't re-emit an UNCHANGED project context — the agent already\n // has it from the earlier call. First emission records a marker; repeats within the window omit.\n let contextOmittedRecent = false;\n if (projectContextRaw && input.dedupe_project_context !== false) {\n const ctxHash = hashProjectContext(projectContextRaw);\n if (await projectContextRecentlyEmitted(ctx.paths, ctxHash)) {\n contextOmittedRecent = true;\n projectContextRaw = \"\";\n } else {\n await recordProjectContextEmission(ctx.paths, ctxHash);\n }\n }\n const isTemplateContext =\n projectContextRaw.includes(\"TODO — high-level overview\") ||\n projectContextRaw.includes(\"Generated by `hivelore init`\");\n\n const setupWarnings: string[] = [];\n let autoContextGenerated = false;\n let projectContext = isTemplateContext ? \"\" : projectContextRaw;\n\n if ((isTemplateContext || !existsSync(ctx.paths.projectContext)) && input.include_project_context) {\n const haiveConfig = await loadConfig(ctx.paths);\n if (haiveConfig.autoContext) {\n const codeMap = await loadCodeMap(ctx.paths);\n if (codeMap) {\n const totalFiles = Object.keys(codeMap.files).length;\n const extensions = new Map<string, number>();\n for (const filePath of Object.keys(codeMap.files)) {\n const ext = filePath.slice(filePath.lastIndexOf(\".\") + 1).toLowerCase();\n extensions.set(ext, (extensions.get(ext) ?? 0) + 1);\n }\n const topExts = [...extensions.entries()]\n .sort((a, b) => b[1] - a[1])\n .slice(0, 5)\n .map(([e, n]) => `${e} (${n})`)\n .join(\", \");\n const topSymbols = Object.entries(codeMap.files)\n .flatMap(([fp, entry]) =>\n entry.exports.slice(0, 3).map((e) => `${e.name} (${fp.split(\"/\").slice(-2).join(\"/\")})`),\n )\n .slice(0, 15)\n .join(\", \");\n\n // \"How do I run tests/build here?\" is the #1 non-guessable cold-start fact — surface the\n // detected package.json scripts so a session-1 agent doesn't have to hunt for them.\n const commands = await detectRunCommands(ctx.paths.root);\n\n projectContext =\n `# Project context (auto-generated by Hivelore)\\n\\n` +\n `> ⚠ This is a minimal auto-generated context based on the code-map. ` +\n `Invoke the \\`bootstrap_project\\` MCP prompt to replace it with a full analysis.\\n\\n` +\n `## Codebase overview\\n` +\n `- **${totalFiles} files** indexed in code-map\\n` +\n `- **Main file types:** ${topExts}\\n` +\n `- **Generated at:** ${codeMap.generated_at}\\n\\n` +\n (commands ? `## Commands\\n${commands}\\n\\n` : \"\") +\n `## Key exports (sample)\\n` +\n topSymbols + \"\\n\";\n\n autoContextGenerated = true;\n setupWarnings.push(\n \"project-context.md is still the default template. \" +\n \"A minimal auto-generated context has been injected from the code-map. \" +\n \"Invoke bootstrap_project to replace it with a full AI-analyzed context.\",\n );\n } else {\n setupWarnings.push(\n \"project-context.md is still the default template and no code-map found. \" +\n \"Run `hivelore index code` then invoke bootstrap_project for a full context.\",\n );\n }\n } else {\n setupWarnings.push(\n isTemplateContext\n ? \"project-context.md still contains the default template. \" +\n \"Invoke the bootstrap_project MCP prompt to auto-fill it from your codebase. \" +\n \"Until then, get_briefing returns no project context.\"\n : \"No project-context.md found. Run `hivelore init` then invoke the bootstrap_project MCP prompt.\",\n );\n }\n }\n\n // ── Module contexts + budget allocation ───────────────────────────────\n const moduleContents = briefingIncludeModules\n ? await loadModuleContexts(ctx, inferred)\n : [];\n\n const memoriesText = memories\n .map((m) => {\n const unverified = m.status === \"proposed\" ? \" [UNVERIFIED — not yet validated]\" : \"\";\n return `### ${m.id} (${m.scope}/${m.type}, ${m.confidence})${unverified}\\n${m.body.trim()}`;\n })\n .join(\"\\n\\n---\\n\\n\");\n\n const slices = allocateBudget(\n [\n { key: \"project\", text: projectContext, weight: 3, mode: \"head\" },\n {\n key: \"modules\",\n text: moduleContents.map((m) => `## ${m.name}\\n${m.content}`).join(\"\\n\\n---\\n\\n\"),\n weight: 3,\n mode: \"head\",\n },\n { key: \"memories\", text: memoriesText, weight: 4, mode: \"head\" },\n ],\n briefingMaxTokens,\n );\n\n const projectSlice = slices.find((s) => s.key === \"project\")!;\n const modulesSlice = slices.find((s) => s.key === \"modules\")!;\n const memoriesSlice = slices.find((s) => s.key === \"memories\")!;\n\n const trimmedModules: BriefingOutput[\"module_contexts\"] = [];\n if (modulesSlice.text.length > 0 && moduleContents.length > 0) {\n const subSlices = allocateBudget(\n moduleContents.map((m) => ({ key: m.name, text: m.content, weight: 1, mode: \"head\" as const })),\n modulesSlice.allocatedTokens,\n );\n for (const m of moduleContents) {\n const sub = subSlices.find((s) => s.key === m.name)!;\n trimmedModules.push({ name: m.name, content: sub.text, truncated: sub.truncated });\n }\n }\n\n // Cascade budget: top-ranked memories get full budget first; lower-ranked are dropped.\n const trimmedMemories: BriefingMemory[] = [];\n if (!memoriesSlice.truncated) {\n trimmedMemories.push(...memories);\n } else {\n let remaining = memoriesSlice.allocatedTokens;\n for (const m of memories) {\n const bodyTokens = estimateTokens(m.body);\n if (remaining <= 0) break;\n if (bodyTokens <= remaining) {\n trimmedMemories.push(m);\n remaining -= bodyTokens;\n } else if (remaining > 80) {\n const t = truncateToTokens(m.body, { maxTokens: remaining, mode: \"head\" });\n trimmedMemories.push({ ...m, body: t.text });\n remaining = 0;\n }\n }\n }\n\n const totalTokens =\n projectSlice.estimatedTokens + modulesSlice.estimatedTokens + memoriesSlice.estimatedTokens;\n\n // ── Decay warnings ─────────────────────────────────────────────────────\n const decayWarnings: string[] = [];\n for (const m of trimmedMemories) {\n const u = getUsage(usage, m.id);\n const loaded = byId.get(m.id);\n const createdAt = loaded?.memory.frontmatter.created_at ?? new Date().toISOString();\n if (isDecaying(u, createdAt)) decayWarnings.push(m.id);\n }\n\n // ── Format + priority + why ────────────────────────────────────────────\n const formattedMemories =\n input.format === \"compact\"\n ? trimmedMemories.map((m) => ({ ...m, body: compactSummary(m.body) }))\n : input.format === \"actions\"\n ? trimmedMemories.map((m) => ({ ...m, body: extractActionsBriefBody(m.body) }))\n : trimmedMemories;\n\n const outputMemories = formattedMemories.map((m) => ({\n ...m,\n priority: classifyMemoryPriority(m, byId.get(m.id), input.files, input.symbols),\n why: explainWhySurfaced(m, byId.get(m.id), input.files, inferred),\n }));\n\n const briefingQuality = classifyBriefingQuality(outputMemories, {\n isTemplateContext,\n autoContextGenerated,\n hasLastSession: Boolean(lastSession),\n searchMode,\n });\n\n // ── Code-map symbol lookup ─────────────────────────────────────────────\n let symbolLocations: BriefingOutput[\"symbol_locations\"];\n const symbolsToLookup = new Set<string>(input.symbols);\n for (const m of outputMemories) {\n for (const sym of byId.get(m.id)?.memory.frontmatter.anchor.symbols ?? []) {\n symbolsToLookup.add(sym);\n }\n }\n if (symbolsToLookup.size > 0) {\n const codeMap = await loadCodeMap(ctx.paths);\n if (codeMap) {\n symbolLocations = [];\n for (const sym of symbolsToLookup) {\n const { files } = queryCodeMap(codeMap, { symbol: sym });\n if (files.length > 0) {\n symbolLocations.push({\n symbol: sym,\n locations: files.flatMap((f) =>\n f.entry.exports\n .filter((e) => e.name.toLowerCase().includes(sym.toLowerCase()))\n .map((e) => ({\n file: f.path,\n kind: e.kind,\n line: e.line,\n ...(e.description ? { description: e.description } : {}),\n })),\n ),\n });\n }\n }\n if (symbolLocations.length === 0) symbolLocations = undefined;\n }\n }\n\n // ── action_required ────────────────────────────────────────────────────\n const actionRequired: ActionRequiredItem[] = [];\n\n const extractActionItem = (id: string, body: string): ActionRequiredItem => {\n const bodyLines = body.split(\"\\n\");\n const quoteBlock = bodyLines\n .filter((l) => l.startsWith(\"> \"))\n .map((l) => l.slice(2))\n .join(\" \")\n .replace(/^\\*«\\s*/, \"\")\n .replace(/\\s*»\\*$/, \"\")\n .trim();\n const headingLine = bodyLines.find((l) => l.startsWith(\"## \"));\n const summary = headingLine?.replace(/^##\\s*/, \"\").trim() ?? id;\n return {\n id,\n summary,\n developer_message: quoteBlock ||\n `A potentially incompatible external change was detected (${id}). ` +\n `Do you want me to analyze the impact and propose updates?`,\n };\n };\n\n for (const m of outputMemories) {\n const loaded = byId.get(m.id);\n if (loaded?.memory.frontmatter.requires_human_approval) {\n actionRequired.push(extractActionItem(m.id, loaded.memory.body));\n }\n }\n if (existsSync(ctx.paths.memoriesDir)) {\n const allMems = await loadMemoriesFromDir(ctx.paths.memoriesDir);\n for (const { memory } of allMems) {\n const fm = memory.frontmatter;\n if (!fm.requires_human_approval) continue;\n if (fm.status === \"rejected\" || fm.status === \"deprecated\") continue;\n if (actionRequired.some((a) => a.id === fm.id)) continue;\n actionRequired.push(extractActionItem(fm.id, memory.body));\n }\n }\n\n // ── Pending distill ────────────────────────────────────────────────────\n const pendingDistillFile = pendingDistillPath(ctx);\n if (existsSync(pendingDistillFile)) {\n try {\n const raw = await readFile(pendingDistillFile, \"utf8\");\n const pd = JSON.parse(raw) as PendingDistill;\n const ageMs = Date.now() - new Date(pd.session_end).getTime();\n const SEVEN_DAYS = 7 * 24 * 60 * 60 * 1000;\n if (ageMs < SEVEN_DAYS) {\n const savedNote = pd.memories_saved.length > 0\n ? ` ${pd.memories_saved.length} memor${pd.memories_saved.length === 1 ? \"y was\" : \"ies were\"} saved.`\n : \" No memories were saved.\";\n const diffNote = pd.git_diff_available\n ? \" A git diff snapshot is available in the pending-distill file for context.\"\n : \"\";\n actionRequired.push({\n id: \"__pending_distill__\",\n summary: \"Previous session has undistilled learnings — invoke post_task to capture them\",\n developer_message:\n `The previous session (${pd.total_tool_calls} tool calls, ${pd.tool_summary}) ` +\n `was closed by autopilot without a full post_task distillation.${savedNote}${diffNote}\\n\\n` +\n `**Before starting your task:** invoke the MCP prompt \\`post_task\\` to capture any ` +\n `decisions, gotchas, or conventions from that session. This takes ~30 seconds and ` +\n `prevents institutional knowledge from being lost.\\n\\n` +\n `When done, call \\`mem_session_end\\` to acknowledge — this clears the pending distill marker.`,\n });\n } else {\n try {\n const { rm } = await import(\"node:fs/promises\");\n await rm(pendingDistillFile);\n } catch { /* non-fatal */ }\n }\n } catch { /* malformed or deleted between check and read — skip */ }\n }\n\n // ── low_value + adaptive trim + hints ─────────────────────────────────\n const memoriesEmpty = outputMemories.length === 0;\n const hasMemoriesDir = existsSync(ctx.paths.memoriesDir);\n const isColdStart = isTemplateContext && memoriesEmpty && !lastSession && !autoContextGenerated;\n\n const hasUnguessableSignal = outputMemories.some(\n (m) =>\n (m.priority === \"must_read\" || m.priority === \"useful\") &&\n specificityScore(m.body) >= GUESSABLE_THRESHOLD,\n );\n const briefingValueLow = !hasUnguessableSignal;\n const adaptiveConfig = await loadConfig(ctx.paths);\n const bootstrapUnfilled =\n /Auto-generated by `hivelore init/i.test(projectContextRaw) &&\n (projectContextRaw.match(/TODO —/g)?.length ?? 0) >= 2;\n const contextIsInferable = isTemplateContext || autoContextGenerated || bootstrapUnfilled;\n const adaptiveTrim =\n adaptiveConfig.adaptiveBriefing !== false && briefingValueLow && contextIsInferable;\n\n // ── First-agent bootstrap directive (cold corpus → force the baseline) ─────\n // The trigger is the corpus state, not an agent identity: while the knowledge layer is incomplete,\n // every briefing surfaces a top-priority action_required so the first agent fills project-context,\n // module contexts, anchored memories, and a sensor per main code area. The enforce gate\n // (bootstrap-complete) blocks the commit/finish until then. Once ready, this goes silent forever.\n const bootstrapGateMode = adaptiveConfig.enforcement?.bootstrapGate ?? \"block\";\n if (bootstrapGateMode !== \"off\") {\n try {\n // Read project-context fresh — `projectContextRaw` may have been emptied by the dedupe token-saver.\n let pcRaw = \"\";\n try { pcRaw = await readFile(ctx.paths.projectContext, \"utf8\"); } catch { /* absent */ }\n const allForBootstrap = existsSync(ctx.paths.memoriesDir)\n ? await loadMemoriesFromDir(ctx.paths.memoriesDir)\n : [];\n const cmForBootstrap = await loadCodeMap(ctx.paths);\n let existingModules: string[] = [];\n try {\n const entries = await readdir(ctx.paths.modulesContextDir, { withFileTypes: true });\n existingModules = entries.filter((e) => e.isDirectory()).map((e) => e.name);\n } catch { /* no modules dir yet */ }\n const bootstrap = assessBootstrapState({\n projectContextRaw: pcRaw,\n memories: allForBootstrap,\n codeFiles: cmForBootstrap ? Object.keys(cmForBootstrap.files) : [],\n existingModules,\n });\n // Surface the directive only when there are genuine main code areas — that is exactly when the\n // enforce gate will block, so the \"your commit will be blocked\" message stays truthful.\n if (bootstrap.state !== \"ready\" && bootstrap.metrics.mainAreas > 0) {\n actionRequired.unshift({\n id: \"__bootstrap_required__\",\n summary: \"First-agent bootstrap: fill the repo knowledge layer before substantive work\",\n developer_message:\n `You are the first agent on this repo — its Hivelore knowledge layer is ${bootstrap.state}. ` +\n `Later agents (and the commit/enforce gates) will rely on it; with ` +\n `enforcement.bootstrapGate=${bootstrapGateMode} your commit/finish will ` +\n `${bootstrapGateMode === \"block\" ? \"be BLOCKED\" : \"warn\"} until it exists.\\n\\n` +\n `Invoke the \\`bootstrap_repo\\` MCP prompt, or close these gaps directly:\\n` +\n renderBootstrapChecklist(bootstrap),\n });\n }\n } catch { /* best-effort: never let the bootstrap probe break a briefing */ }\n }\n\n const hints: string[] = [];\n if (isColdStart) {\n hints.push(\n \"haive is uninitialized for this project (project-context.md is template, \" +\n \"0 memories, no past session). Skip future get_briefing calls until memories exist — \" +\n \"use Read/Grep directly. Run `hivelore init` and the bootstrap_project prompt to fix.\",\n );\n } else {\n if (outputMemories.some((m) => m.type === \"attempt\")) {\n hints.push(\n \"⚠️ One or more 'attempt' memories matched — these document failed approaches. \" +\n \"Read them BEFORE writing code to avoid repeating the mistake.\",\n );\n }\n if (outputMemories.some((m) => m.type === \"gotcha\")) {\n hints.push(\n \"Gotcha memories matched — non-obvious traps. Verify the 'how to apply' line still holds \" +\n \"before assuming behavior.\",\n );\n }\n if (memoriesEmpty && hasMemoriesDir && input.task) {\n hints.push(\n \"No memories matched this task. Try mem_search with broader/different terms, \" +\n \"or call mem_for_files with the files you intend to edit.\",\n );\n }\n if (input.task && outputMemories.length > 0 && actionRequired.length === 0) {\n hints.push(\n \"After completing the task: capture new gotchas with mem_observe, \" +\n \"failed approaches with mem_tried, validated patterns with mem_save.\",\n );\n }\n if (\n outputMemories.length > 2 &&\n !input.budget_preset &&\n input.task &&\n !hints.some((h) => h.includes(\"budget_preset\"))\n ) {\n hints.push(\n \"For tighter token budgets on small tasks pass budget_preset:'quick'; \" +\n \"for refactor-sized work use budget_preset:'deep'.\",\n );\n }\n }\n if (adaptiveTrim) {\n hints.push(\n \"No team-specific policy matched these files/task — nothing here a capable model can't \" +\n \"infer. The auto-generated project context was trimmed to keep this briefing near-zero-cost; \" +\n \"proceed with normal Read/Grep.\",\n );\n }\n\n // ── Proof line (Lot B × Lot C coordination point) ─────────────────────\n // Surface the measured outcome — \"this harness prevented N repeated mistakes\" — directly in the\n // briefing so the moat is visible in-context, not only in `hivelore dashboard`. briefingProofLine()\n // returns null when there are no recent catches, so an empty/cold corpus never shows a hollow claim.\n if (outputMemories.length > 0 && existsSync(ctx.paths.haiveDir)) {\n const proof = briefingProofLine(await loadPreventionEvents(ctx.paths));\n if (proof) hints.push(proof);\n }\n\n const breadcrumbs = buildBriefingBreadcrumbs({\n memories: outputMemories,\n byId,\n symbolLocations,\n task: input.task,\n files: input.files,\n symbols: input.symbols,\n adaptiveTrim,\n });\n // Breadcrumbs add to the wire payload, so count them honestly toward the budget instead of\n // silently understating estimated_tokens (they were previously omitted from totalTokens/spent).\n const breadcrumbTokens = breadcrumbs\n ? estimateTokens([...breadcrumbs.start_here, ...breadcrumbs.drill_down, breadcrumbs.note ?? \"\"].join(\"\\n\"))\n : 0;\n\n // ── Briefing marker (satisfies enforcement gate for MCP-native agents) ─\n if (existsSync(ctx.paths.haiveDir)) {\n await writeBriefingMarker(ctx.paths, {\n sessionId: process.env.HAIVE_SESSION_ID,\n ...(input.task ? { task: input.task } : {}),\n source: \"mcp-get-briefing\",\n files: input.files,\n memoryIds: outputMemories.map((m) => m.id),\n }).catch(() => { /* marker is best-effort — never fail the briefing on it */ });\n }\n\n return {\n ...(input.task ? { task: input.task } : {}),\n server_version: serverVersion(),\n search_mode: searchMode,\n inferred_modules: inferred,\n ...(lastSession ? { last_session: lastSession } : {}),\n project_context: contextOmittedRecent\n ? {\n content:\n \"(project context unchanged — omitted to save tokens; it was provided earlier this \" +\n \"session. Pass dedupe_project_context:false to force a full copy.)\",\n truncated: false,\n omitted_recent: true,\n }\n : adaptiveTrim\n ? {\n content:\n \"(adaptive briefing: auto-generated context omitted — no team-specific policy \" +\n \"matched, so a capable model needs nothing extra here)\",\n truncated: false,\n ...(isTemplateContext && !autoContextGenerated ? { is_template: true } : {}),\n ...(autoContextGenerated ? { auto_generated: true } : {}),\n }\n : (projectContextRaw || autoContextGenerated)\n ? {\n content: projectSlice.text,\n truncated: projectSlice.truncated,\n ...(isTemplateContext && !autoContextGenerated ? { is_template: true } : {}),\n ...(autoContextGenerated ? { auto_generated: true } : {}),\n }\n : null,\n module_contexts: trimmedModules,\n memories: outputMemories,\n briefing_quality: briefingQuality,\n ...(breadcrumbs ? { breadcrumbs } : {}),\n ...(symbolLocations ? { symbol_locations: symbolLocations } : {}),\n action_required: actionRequired,\n decay_warnings: decayWarnings,\n setup_warnings: setupWarnings,\n ...(isColdStart ? { low_value: true as const } : {}),\n briefing_value: briefingValueLow ? \"low\" : \"high\",\n ...(hints.length > 0 ? { hints } : {}),\n estimated_tokens: totalTokens + breadcrumbTokens,\n budget: {\n max_tokens: briefingMaxTokens,\n ...(input.budget_preset ? { preset_applied: input.budget_preset } : {}),\n spent: {\n project: projectSlice.estimatedTokens,\n modules: modulesSlice.estimatedTokens,\n memories: memoriesSlice.estimatedTokens,\n ...(breadcrumbTokens ? { breadcrumbs: breadcrumbTokens } : {}),\n },\n },\n };\n}\n\n/**\n * Read the project's package.json and surface the run commands an agent needs on session 1\n * (test/build/lint/typecheck/dev/start). Returns a markdown bullet list, or null when there is no\n * package.json or no relevant scripts. Best-effort: a malformed manifest yields null, never throws.\n */\nasync function detectRunCommands(root: string): Promise<string | null> {\n const pkgPath = path.join(root, \"package.json\");\n if (!existsSync(pkgPath)) return null;\n try {\n const pkg = JSON.parse(await readFile(pkgPath, \"utf8\")) as { scripts?: Record<string, string> };\n const scripts = pkg.scripts ?? {};\n const order = [\"test\", \"build\", \"lint\", \"typecheck\", \"type-check\", \"dev\", \"start\"];\n const lines = order\n .filter((name) => typeof scripts[name] === \"string\" && scripts[name]!.trim() !== \"\")\n .map((name) => `- \\`${name}\\`: \\`${scripts[name]}\\``);\n return lines.length > 0 ? lines.join(\"\\n\") : null;\n } catch {\n return null;\n }\n}\n\nfunction buildBriefingBreadcrumbs(input: {\n memories: BriefingMemory[];\n byId: Map<string, LoadedMemory>;\n symbolLocations: BriefingOutput[\"symbol_locations\"];\n task?: string;\n files: string[];\n symbols: string[];\n adaptiveTrim: boolean;\n}): BriefingBreadcrumbs | undefined {\n const startHere: string[] = [];\n const startHereItems: BriefingBreadcrumbItem[] = [];\n const drillDown: string[] = [];\n\n // Breadcrumbs are a *map*, not the content: a terse pointer (priority · id · scope/type · anchor).\n // The body already lives in `memories[]` (and is one `mem_get` away), so we deliberately do NOT\n // re-summarize it here — that kept the default payload small instead of duplicating it.\n // `start_here_items` is the structured twin (same pointers, machine-readable) — also never a copy.\n for (const memory of input.memories.slice(0, 4)) {\n const loaded = input.byId.get(memory.id);\n const anchor = loaded?.memory.frontmatter.anchor.paths[0];\n const anchorNote = anchor ? ` · applies to ${anchor}` : \"\";\n startHere.push(`${memory.priority}: memory ${memory.id} (${memory.scope}/${memory.type})${anchorNote}`);\n startHereItems.push({\n type: \"memory\",\n id: memory.id,\n scope: memory.scope,\n mem_type: memory.type,\n priority: memory.priority,\n ...(anchor ? { file: anchor } : {}),\n });\n }\n\n for (const hit of input.symbolLocations?.slice(0, 4) ?? []) {\n const first = hit.locations[0];\n if (!first) continue;\n startHere.push(`code: ${hit.symbol} -> ${first.file}:${first.line} [${first.kind}]`);\n startHereItems.push({ type: \"code\", symbol: hit.symbol, file: first.file, line: first.line, kind: first.kind });\n }\n\n if (startHere.length === 0 && input.files.length > 0) {\n startHere.push(`files: ${input.files.slice(0, 4).join(\", \")}${input.files.length > 4 ? \", ...\" : \"\"}`);\n for (const f of input.files.slice(0, 4)) startHereItems.push({ type: \"files\", file: f });\n }\n\n const topDeepMemories = input.memories\n .filter((m) => m.priority === \"must_read\" || m.priority === \"useful\")\n .slice(0, 3);\n for (const memory of topDeepMemories) {\n drillDown.push(`mem_get(\"${memory.id}\") for the full memory`);\n }\n\n if (input.task && input.files.length > 0) {\n drillDown.push(\n `mem_relevant_to(task:\"${oneLine(input.task)}\", files:[${input.files.map((f) => `\"${f}\"`).join(\", \")}], format:\"actions\")`,\n );\n }\n if (input.task) {\n drillDown.push(`code_search(query:\"${oneLine(input.task)}\", k:5)`);\n }\n for (const symbol of input.symbols.slice(0, 3)) {\n drillDown.push(`code_map(symbol:\"${oneLine(symbol)}\")`);\n }\n\n const uniqueDrillDown = [...new Set(drillDown)].slice(0, 6);\n if (startHere.length === 0 && uniqueDrillDown.length === 0 && !input.adaptiveTrim) return undefined;\n\n return {\n start_here: startHere.slice(0, 6),\n ...(startHereItems.length > 0 ? { start_here_items: startHereItems.slice(0, 6) } : {}),\n drill_down: uniqueDrillDown,\n note: input.adaptiveTrim\n ? \"No repo-specific policy matched; keep going with normal Read/Grep and pull deeper Hivelore context only if needed.\"\n : \"Breadcrumbs first: read these pointers, then drill down only when the task still needs more context.\",\n };\n}\n\nfunction oneLine(value: string): string {\n return value.replace(/\\s+/g, \" \").replace(/\"/g, '\\\\\"').trim().slice(0, 120);\n}\n\n// Build-time version constant (tsup `define`, same as server.ts). `typeof` guard keeps unit tests —\n// which import this module without the define — from throwing on the undeclared identifier.\ndeclare const __HAIVE_VERSION__: string;\nfunction serverVersion(): string {\n return typeof __HAIVE_VERSION__ === \"string\" ? __HAIVE_VERSION__ : \"dev\";\n}\n","import { readdir, readFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n classifyMemoryPriority as coreClassifyPriority,\n isGlobPath,\n pathsOverlap,\n priorityRank as corePriorityRank,\n} from \"@hivelore/core\";\nimport type { LoadedMemory } from \"@hivelore/core\";\nimport type { HaiveContext } from \"../context.js\";\nimport type {\n BriefingMemory,\n BriefingMemoryPriority,\n BriefingOutput,\n BriefingQuality,\n} from \"./briefing-types.js\";\n\nexport function compactSummary(body: string): string {\n for (const line of body.split(\"\\n\")) {\n const trimmed = line.replace(/^#+\\s*/, \"\").trim();\n if (trimmed.length > 0) return trimmed.slice(0, 120);\n }\n return body.slice(0, 120);\n}\n\n/**\n * Map the MCP briefing's evidence into the shared core classifier. Behavior is identical to the old\n * inline logic — the single source of truth now lives in `@hivelore/core` so the CLI cannot drift.\n */\nexport function classifyMemoryPriority(\n memory: BriefingMemory,\n loaded: LoadedMemory | undefined,\n inputFiles: string[],\n inputSymbols: string[],\n): BriefingMemoryPriority {\n const fm = loaded?.memory.frontmatter;\n const directAnchor = Boolean(\n fm && inputFiles.length > 0 &&\n fm.anchor.paths.some((p) => inputFiles.some((file) => pathsOverlap(p, file))),\n );\n const directSymbol = Boolean(\n fm && inputSymbols.length > 0 &&\n fm.anchor.symbols.some((sym) =>\n inputSymbols.some((wanted) => wanted.toLowerCase() === sym.toLowerCase()),\n ),\n );\n const semantic = memory.semantic_score ?? 0;\n\n return coreClassifyPriority({\n type: memory.type,\n tags: fm?.tags ?? memory.tags ?? [],\n requiresHumanApproval: Boolean(fm?.requires_human_approval),\n directAnchor,\n directSymbol,\n exactTaskMatch: memory.match_quality === \"exact\",\n strongSemantic: semantic >= 0.65,\n usefulSemantic: semantic >= 0.35,\n moduleOrDomainMatch: memory.reasons.includes(\"module\") || memory.reasons.includes(\"domain\"),\n tagTaskMatch: false, // MCP ranking doesn't use a separate tag-token signal\n });\n}\n\nexport function priorityRank(priority: BriefingMemoryPriority): number {\n return corePriorityRank(priority);\n}\n\nexport function classifyBriefingQuality(\n memories: BriefingMemory[],\n context: {\n isTemplateContext: boolean;\n autoContextGenerated: boolean;\n hasLastSession: boolean;\n searchMode: BriefingOutput[\"search_mode\"];\n },\n): BriefingQuality {\n const mustRead = memories.filter((m) => m.priority === \"must_read\").length;\n const useful = memories.filter((m) => m.priority === \"useful\").length;\n const background = memories.filter((m) => m.priority === \"background\").length;\n const weakSemantic = memories.filter((m) =>\n m.reasons.length === 1 &&\n m.reasons.includes(\"semantic\") &&\n (m.semantic_score ?? 0) > 0 &&\n (m.semantic_score ?? 0) < 0.35,\n ).length;\n const reasons: string[] = [];\n\n if (memories.length === 0) reasons.push(\"no memories matched the task or files\");\n if (context.isTemplateContext && !context.autoContextGenerated) reasons.push(\"project context is still a template\");\n if (!context.hasLastSession) reasons.push(\"no previous session recap\");\n if (mustRead > 0) reasons.push(`${mustRead} must_read memor${mustRead === 1 ? \"y\" : \"ies\"} matched directly`);\n if (useful > 0) reasons.push(`${useful} useful memor${useful === 1 ? \"y\" : \"ies\"} matched`);\n if (background > useful + mustRead && background > 2) reasons.push(`${background} background memories dominate the result`);\n if (weakSemantic > 0) reasons.push(`${weakSemantic} weak semantic-only match${weakSemantic === 1 ? \"\" : \"es\"}`);\n if (context.searchMode === \"literal_fallback\") reasons.push(\"semantic index unavailable or empty; literal fallback used\");\n\n if (memories.length === 0 || (mustRead === 0 && useful === 0)) {\n return { level: \"thin\", reasons };\n }\n // A direct must_read hit means the briefing is actionable even when background seeds\n // outnumber it — \"noisy\" as the headline verdict right after the corpus gained its first\n // anchored memories reads as a regression. Background domination stays in `reasons`.\n if (mustRead === 0 && background > useful && background > 2) {\n return { level: \"noisy\", reasons };\n }\n return { level: \"strong\", reasons };\n}\n\nexport function explainWhySurfaced(\n memory: BriefingMemory,\n loaded: LoadedMemory | undefined,\n inputFiles: string[],\n inferredModules: string[],\n): string[] {\n const why: string[] = [];\n const fm = loaded?.memory.frontmatter;\n if (memory.reasons.includes(\"anchor\") && fm) {\n const matching = fm.anchor.paths.filter((p) =>\n inputFiles.length === 0 || inputFiles.some((file) => pathsOverlap(p, file)),\n );\n if (matching.length > 0) {\n const exact = matching.filter((p) =>\n !isGlobPath(p) && inputFiles.some((file) => p === file || pathsOverlap(p, file)),\n );\n const glob = matching.filter((p) => isGlobPath(p));\n if (exact.length > 0) {\n why.push(`Exact/file anchor match: ${exact.slice(0, 4).join(\", \")}`);\n }\n if (glob.length > 0) {\n why.push(`Glob anchor match: ${glob.slice(0, 4).join(\", \")}`);\n }\n if (exact.length === 0 && glob.length === 0) {\n why.push(`Anchored to touched path${matching.length === 1 ? \"\" : \"s\"}: ${matching.slice(0, 4).join(\", \")}`);\n }\n } else if (fm.anchor.paths.length > 0) {\n why.push(`Pulled by related anchor: ${fm.anchor.paths.slice(0, 4).join(\", \")}`);\n }\n if (fm.anchor.symbols.length > 0) {\n why.push(`Anchor symbol${fm.anchor.symbols.length === 1 ? \"\" : \"s\"}: ${fm.anchor.symbols.slice(0, 4).join(\", \")}`);\n }\n }\n if (memory.reasons.includes(\"symbol\") && fm) {\n why.push(`Explicit symbol match: ${fm.anchor.symbols.slice(0, 4).join(\", \")}`);\n }\n if (memory.reasons.includes(\"module\")) {\n const moduleHints = [\n ...(memory.module ? [memory.module] : []),\n ...memory.tags.filter((tag) => inferredModules.includes(tag)),\n ];\n const shown = moduleHints.length > 0 ? [...new Set(moduleHints)].join(\", \") : inferredModules.join(\", \");\n why.push(shown ? `Matched inferred module/tag: ${shown}` : \"Matched inferred module context.\");\n }\n if (memory.reasons.includes(\"domain\")) {\n why.push(\"Matched inferred domain from the target file paths.\");\n }\n if (memory.reasons.includes(\"semantic\")) {\n const score = memory.semantic_score !== undefined\n ? ` score=${Math.round(memory.semantic_score * 100) / 100}`\n : \"\";\n why.push(`${memory.match_quality === \"exact\" ? \"Literal task match\" : \"Semantic/task relevance\"}${score}.`);\n }\n why.push(`Confidence: ${memory.confidence}; read ${memory.read_count} time${memory.read_count === 1 ? \"\" : \"s\"}.`);\n if (memory.type === \"attempt\") why.push(\"Failed-approach record; read before repeating the same path.\");\n if (memory.type === \"skill\") why.push(\"Skill (reusable procedure/playbook) — follow the steps described when doing this type of task.\");\n if (memory.status === \"proposed\" || memory.status === \"draft\") {\n why.push(\"Unvalidated record; use cautiously or ask a human before treating it as policy.\");\n }\n return why;\n}\n\nexport async function trySemanticHits(\n ctx: HaiveContext,\n task: string,\n limit: number,\n): Promise<Array<{ id: string; score: number }> | null> {\n let mod: typeof import(\"@hivelore/embeddings\");\n try {\n mod = await import(\"@hivelore/embeddings\");\n } catch {\n return null;\n }\n const result = await mod.semanticSearch(ctx.paths, task, { limit });\n if (!result) return null;\n return result.hits.map((h) => ({ id: h.id, score: h.score }));\n}\n\nexport async function loadModuleContexts(\n ctx: HaiveContext,\n modules: string[],\n): Promise<Array<{ name: string; content: string }>> {\n if (modules.length === 0) return [];\n if (!existsSync(ctx.paths.modulesContextDir)) return [];\n const available = new Set(\n (await readdir(ctx.paths.modulesContextDir, { withFileTypes: true }))\n .filter((d) => d.isDirectory())\n .map((d) => d.name),\n );\n const out: Array<{ name: string; content: string }> = [];\n for (const m of modules) {\n if (!available.has(m)) continue;\n const file = path.join(ctx.paths.modulesContextDir, m, \"context.md\");\n if (existsSync(file)) {\n out.push({ name: m, content: await readFile(file, \"utf8\") });\n }\n }\n return out;\n}\n","import { estimateTokens, loadCodeMap, queryCodeMap } from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const CodeMapInputSchema = {\n file: z\n .string()\n .optional()\n .describe(\"Filter to files whose path contains this substring\"),\n symbol: z\n .string()\n .optional()\n .describe(\"Filter to files exporting a symbol whose name contains this substring\"),\n paths: z\n .array(z.string())\n .default([])\n .describe(\n \"Filter to files under any of these path prefixes (e.g. ['packages/mcp/src/tools/', 'src/auth/']). \" +\n \"OR-joined with `file` substring; useful to get a focused view of one module.\",\n ),\n max_files: z\n .number()\n .int()\n .positive()\n .default(40)\n .describe(\"Cap on returned files (hard limit, applied after token budget)\"),\n max_tokens: z\n .number()\n .int()\n .positive()\n .optional()\n .describe(\n \"Approximate token budget for the response. When the matching set exceeds it, \" +\n \"files are ranked by export density (exports per LOC) and the highest-signal ones are kept first. \" +\n \"Omit to disable budgeting (legacy behavior).\",\n ),\n};\n\nexport const CodeMapInputZod = z.object(CodeMapInputSchema);\nexport type CodeMapInput = z.infer<typeof CodeMapInputZod>;\n\nexport interface CodeMapToolOutput {\n available: boolean;\n generated_at?: string;\n total_files?: number;\n files: Array<{\n path: string;\n summary?: string;\n loc: number;\n exports: Array<{ name: string; kind: string; description?: string; line: number }>;\n }>;\n /** Number of matched files dropped due to max_files / max_tokens. */\n truncated?: number;\n /** True when at least one file was dropped to fit the token budget. */\n budget_clipped?: true;\n notice?: string;\n}\n\nexport async function codeMapTool(\n input: CodeMapInput,\n ctx: HaiveContext,\n): Promise<CodeMapToolOutput> {\n const map = await loadCodeMap(ctx.paths);\n if (!map) {\n return {\n available: false,\n files: [],\n notice: \"No code map found. Run `hivelore index code` to generate `.ai/code-map.json`.\",\n };\n }\n const { files: matched } = queryCodeMap(map, { file: input.file, symbol: input.symbol });\n\n // Apply `paths` prefix filter on top of the substring match (OR within paths, AND with file).\n const pathsFiltered = input.paths.length === 0\n ? matched\n : matched.filter((f) => input.paths.some((p) => f.path.startsWith(stripLeadingSlash(p))));\n\n // Default order: alphabetical by path (predictable for callers).\n const alphabetical = [...pathsFiltered].sort((a, b) => a.path.localeCompare(b.path));\n\n let kept = alphabetical;\n let budgetClipped = false;\n if (input.max_tokens !== undefined) {\n // Density-rank to PICK which files to KEEP under budget, then re-sort alphabetically for output.\n const byDensity = [...alphabetical].sort((a, b) => {\n const da = density(a.entry.exports.length, a.entry.loc);\n const db = density(b.entry.exports.length, b.entry.loc);\n if (da !== db) return db - da;\n return a.path.localeCompare(b.path);\n });\n const keepSet = new Set<string>();\n let spent = 0;\n for (const f of byDensity) {\n const cost = estimateFileEntryTokens(f);\n if (spent + cost > input.max_tokens && keepSet.size > 0) {\n budgetClipped = true;\n break;\n }\n keepSet.add(f.path);\n spent += cost;\n }\n if (budgetClipped) {\n kept = alphabetical.filter((f) => keepSet.has(f.path));\n }\n }\n\n const finalFiles = kept.slice(0, input.max_files);\n const totalDropped = pathsFiltered.length - finalFiles.length;\n\n return {\n available: true,\n generated_at: map.generated_at,\n total_files: Object.keys(map.files).length,\n files: finalFiles.map((f) => ({\n path: f.path,\n ...(f.entry.summary ? { summary: f.entry.summary } : {}),\n loc: f.entry.loc,\n exports: f.entry.exports,\n })),\n ...(totalDropped > 0 ? { truncated: totalDropped } : {}),\n ...(budgetClipped ? { budget_clipped: true as const } : {}),\n };\n}\n\nfunction density(exports: number, loc: number): number {\n if (loc <= 0) return 0;\n return exports / Math.max(loc, 1);\n}\n\nfunction stripLeadingSlash(p: string): string {\n return p.startsWith(\"/\") ? p.slice(1) : p;\n}\n\nfunction estimateFileEntryTokens(f: { path: string; entry: { summary?: string; loc: number; exports: Array<{ name: string; kind: string; description?: string; line: number }> } }): number {\n // Rough payload size: path + summary + each export (~6 tokens for name+kind+line + description).\n const exportsCost = f.entry.exports.reduce(\n (acc, e) => acc + 6 + estimateTokens(e.description ?? \"\"),\n 0,\n );\n return estimateTokens(f.path) + estimateTokens(f.entry.summary ?? \"\") + exportsCost + 4;\n}\n","import { existsSync } from \"node:fs\";\nimport { loadMemoriesFromDir } from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const MemDiffInputSchema = {\n id_a: z.string().min(1).describe(\"First memory id\"),\n id_b: z.string().min(1).describe(\"Second memory id\"),\n};\n\nexport type MemDiffInput = {\n [K in keyof typeof MemDiffInputSchema]: z.infer<(typeof MemDiffInputSchema)[K]>;\n};\n\nexport interface MemDiffOutput {\n id_a: string;\n id_b: string;\n frontmatter_diff: Record<string, { a: unknown; b: unknown }>;\n body_diff: {\n lines_only_in_a: string[];\n lines_only_in_b: string[];\n common_lines: number;\n };\n}\n\nexport async function memDiff(input: MemDiffInput, ctx: HaiveContext): Promise<MemDiffOutput> {\n if (!existsSync(ctx.paths.memoriesDir)) {\n throw new Error(`No .ai/memories at ${ctx.paths.root}.`);\n }\n const all = await loadMemoriesFromDir(ctx.paths.memoriesDir);\n const foundA = all.find((m) => m.memory.frontmatter.id === input.id_a);\n const foundB = all.find((m) => m.memory.frontmatter.id === input.id_b);\n if (!foundA) throw new Error(`No memory with id \"${input.id_a}\".`);\n if (!foundB) throw new Error(`No memory with id \"${input.id_b}\".`);\n\n const fmA = foundA.memory.frontmatter as Record<string, unknown>;\n const fmB = foundB.memory.frontmatter as Record<string, unknown>;\n\n const frontmatterDiff: Record<string, { a: unknown; b: unknown }> = {};\n const allKeys = new Set([...Object.keys(fmA), ...Object.keys(fmB)]);\n for (const key of allKeys) {\n const va = fmA[key];\n const vb = fmB[key];\n if (JSON.stringify(va) !== JSON.stringify(vb)) {\n frontmatterDiff[key] = { a: va, b: vb };\n }\n }\n\n const linesA = new Set(foundA.memory.body.split(\"\\n\").map((l) => l.trim()).filter(Boolean));\n const linesB = new Set(foundB.memory.body.split(\"\\n\").map((l) => l.trim()).filter(Boolean));\n\n const onlyA = [...linesA].filter((l) => !linesB.has(l));\n const onlyB = [...linesB].filter((l) => !linesA.has(l));\n const common = [...linesA].filter((l) => linesB.has(l)).length;\n\n return {\n id_a: input.id_a,\n id_b: input.id_b,\n frontmatter_diff: frontmatterDiff,\n body_diff: {\n lines_only_in_a: onlyA,\n lines_only_in_b: onlyB,\n common_lines: common,\n },\n };\n}\n","import { existsSync } from \"node:fs\";\nimport { loadMemoriesFromDir } from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const GetRecapInputSchema = {\n scope: z\n .enum([\"personal\", \"team\", \"any\"])\n .default(\"any\")\n .describe(\n \"Limit to a specific scope's recap. Default 'any' returns the most recent recap \" +\n \"across both personal and team scopes.\",\n ),\n};\n\nexport type GetRecapInput = {\n [K in keyof typeof GetRecapInputSchema]: z.infer<(typeof GetRecapInputSchema)[K]>;\n};\n\nexport interface GetRecapOutput {\n recap: {\n id: string;\n scope: string;\n revision_count: number;\n created_at: string;\n body: string;\n } | null;\n notice?: string;\n}\n\n/**\n * Lightweight alternative to get_briefing when you ONLY need the previous\n * session recap (e.g. resuming a long task between sessions). Skips project\n * context, modules, and memory ranking — pays only the recap's token cost.\n */\nexport async function getRecap(\n input: GetRecapInput,\n ctx: HaiveContext,\n): Promise<GetRecapOutput> {\n if (!existsSync(ctx.paths.memoriesDir)) {\n return { recap: null, notice: \"No .ai/memories directory — haive not initialized here.\" };\n }\n\n const all = await loadMemoriesFromDir(ctx.paths.memoriesDir);\n const recaps = all\n .filter(({ memory }) => memory.frontmatter.type === \"session_recap\")\n .filter(({ memory }) => input.scope === \"any\" || memory.frontmatter.scope === input.scope)\n .sort(\n (a, b) =>\n new Date(b.memory.frontmatter.created_at).getTime() -\n new Date(a.memory.frontmatter.created_at).getTime(),\n );\n\n if (recaps.length === 0) {\n return {\n recap: null,\n notice:\n input.scope === \"any\"\n ? \"No session recap saved yet. Run mem_session_end (or post_task prompt) to capture one.\"\n : `No session recap found in scope '${input.scope}'.`,\n };\n }\n\n const r = recaps[0]!;\n const fm = r.memory.frontmatter;\n return {\n recap: {\n id: fm.id,\n scope: fm.scope,\n revision_count: fm.revision_count ?? 0,\n created_at: fm.created_at,\n body: r.memory.body,\n },\n };\n}\n","import { z } from \"zod\";\nimport {\n getBriefing,\n type BriefingMemory,\n type BriefingQuality,\n type GetBriefingInput,\n} from \"./get-briefing.js\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const MemRelevantToInputSchema = {\n task: z\n .string()\n .min(1)\n .describe(\"What you are about to do, in 1–2 sentences. Used to rank relevant memories.\"),\n files: z\n .array(z.string())\n .default([])\n .describe(\"Optional: files you are about to edit — surfaces anchored memories.\"),\n limit: z\n .number()\n .int()\n .positive()\n .max(30)\n .default(8)\n .describe(\"Cap on returned memories.\"),\n min_semantic_score: z\n .number()\n .min(0)\n .max(1)\n .default(0.25)\n .describe(\"Drop weakly-related semantic hits below this cosine threshold.\"),\n format: z\n .enum([\"full\", \"compact\", \"actions\"])\n .default(\"full\")\n .describe(\"'compact' = id + 1-line summary; 'full' = complete bodies; 'actions' = bullet-first excerpts.\"),\n};\n\nexport type MemRelevantToInput = {\n [K in keyof typeof MemRelevantToInputSchema]: z.infer<(typeof MemRelevantToInputSchema)[K]>;\n};\n\nexport interface MemRelevantToOutput {\n task: string;\n search_mode: \"semantic\" | \"literal_fallback\" | \"literal\";\n memories: BriefingMemory[];\n briefing_quality: BriefingQuality;\n hints?: string[];\n /**\n * True when the search returned zero memories — clients can skip surfacing\n * an empty payload to the model.\n */\n empty?: true;\n}\n\n/**\n * One-shot ranked memories for a task. Use instead of get_briefing when you\n * already have project context loaded and only want the relevant memory layer.\n *\n * Runs the same ranking (anchor / module / literal / semantic) as get_briefing\n * but skips project_context, module_contexts, action_required, etc. — paying\n * only the cost of the memory bodies you actually get back.\n */\nexport async function memRelevantTo(\n input: MemRelevantToInput,\n ctx: HaiveContext,\n): Promise<MemRelevantToOutput> {\n // Reuse the briefing pipeline but turn off the heavy bits.\n const briefingInput: GetBriefingInput = {\n task: input.task,\n files: input.files,\n max_tokens: 16000,\n max_memories: input.limit,\n include_project_context: false,\n include_module_contexts: false,\n semantic: true,\n include_stale: false,\n track: true,\n format: input.format,\n symbols: [],\n min_semantic_score: input.min_semantic_score,\n };\n\n const briefing = await getBriefing(briefingInput, ctx);\n\n const out: MemRelevantToOutput = {\n task: input.task,\n search_mode: briefing.search_mode,\n memories: briefing.memories,\n briefing_quality: briefing.briefing_quality,\n };\n if (briefing.hints && briefing.hints.length > 0) out.hints = briefing.hints;\n if (briefing.memories.length === 0) out.empty = true;\n return out;\n}\n","import { z } from \"zod\";\nimport { loadCodeMap } from \"@hivelore/core\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const CodeSearchInputSchema = {\n query: z\n .string()\n .min(1)\n .describe(\n \"Natural-language description of what you are looking for in the codebase \" +\n \"(e.g. 'function that hashes passwords', 'JWT signing logic', 'route registration').\",\n ),\n k: z\n .number()\n .int()\n .positive()\n .max(50)\n .default(5)\n .describe(\"Number of top hits to return.\"),\n min_score: z\n .number()\n .min(0)\n .max(1)\n .default(0.2)\n .describe(\n \"Minimum cosine similarity. Hits below this threshold are dropped to avoid noise. \" +\n \"Try 0.3+ for stricter matching.\",\n ),\n};\n\nexport type CodeSearchInput = {\n [K in keyof typeof CodeSearchInputSchema]: z.infer<(typeof CodeSearchInputSchema)[K]>;\n};\n\nexport interface CodeSearchHit {\n file: string;\n name: string;\n kind: string;\n line: number;\n description?: string;\n score: number;\n}\n\nexport interface CodeSearchOutput {\n available: boolean;\n hits: CodeSearchHit[];\n /** True when the embeddings index was built from an older code-map — results may miss new/moved symbols. */\n stale?: true;\n notice?: string;\n}\n\nexport async function codeSearch(\n input: CodeSearchInput,\n ctx: HaiveContext,\n): Promise<CodeSearchOutput> {\n let mod: typeof import(\"@hivelore/embeddings\");\n try {\n mod = await import(\"@hivelore/embeddings\");\n } catch {\n return {\n available: false,\n hits: [],\n notice:\n \"@hivelore/embeddings is not installed. Install it (`pnpm add @hivelore/embeddings`) \" +\n \"and run `hivelore index code-search` to enable semantic code search.\",\n };\n }\n\n const result = await mod.codeSemanticSearch(ctx.paths, input.query, {\n limit: input.k,\n minScore: input.min_score,\n });\n\n if (!result) {\n return {\n available: false,\n hits: [],\n notice:\n \"Code semantic-search index not built. Run `hivelore index code-search` to generate it \" +\n \"(builds embeddings for every exported symbol in the code-map).\",\n };\n }\n\n // Flag (don't hide) a stale index: the code-map was rebuilt after the embeddings index, so newly\n // added or moved symbols may be missing/mislocated. Best-effort — never fail the search over this.\n let stale = false;\n try {\n const codeMap = await loadCodeMap(ctx.paths);\n if (codeMap) stale = mod.isCodeIndexStale(result.index.source_generated_at, codeMap.generated_at);\n } catch {\n // ignore — staleness is advisory\n }\n\n return {\n available: true,\n hits: result.hits,\n ...(stale\n ? {\n stale: true as const,\n notice:\n \"Code-search index is stale (built from an older code-map); newly added or moved symbols \" +\n \"may be missing or mislocated. Rebuild with `hivelore index code && hivelore index code-search`.\",\n }\n : {}),\n };\n}\n","import { existsSync } from \"node:fs\";\nimport { spawn } from \"node:child_process\";\nimport path from \"node:path\";\nimport {\n deriveConfidence,\n getUsage,\n loadCodeMap,\n loadMemoriesFromDir,\n loadUsageIndex,\n memoryMatchesAnchorPaths,\n} from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const WhyThisFileInputSchema = {\n path: z\n .string()\n .min(1)\n .describe(\n \"Project-relative path to the file you want context on (e.g. 'packages/mcp/src/tools/mem-save.ts').\",\n ),\n git_log_limit: z\n .number()\n .int()\n .positive()\n .max(20)\n .default(5)\n .describe(\"How many recent commits touching this file to include.\"),\n memory_limit: z\n .number()\n .int()\n .positive()\n .max(20)\n .default(5)\n .describe(\"Cap on memories anchored to this path.\"),\n};\n\nexport type WhyThisFileInput = {\n [K in keyof typeof WhyThisFileInputSchema]: z.infer<(typeof WhyThisFileInputSchema)[K]>;\n};\n\nexport interface WhyThisFileOutput {\n file: string;\n exists: boolean;\n recent_commits: Array<{ sha: string; author: string; relative_date: string; subject: string }>;\n memories: Array<{\n id: string;\n type: string;\n scope: string;\n confidence: string;\n body_preview: string;\n }>;\n code_map_entry: {\n summary?: string;\n loc: number;\n exports: Array<{ name: string; kind: string; line: number; description?: string }>;\n } | null;\n hints?: string[];\n}\n\n/**\n * One-shot file-context lookup: combines recent git history, memories anchored\n * to the path, and the code-map entry. Designed to answer \"why is this file\n * the way it is?\" in a single call instead of 3-4 manual ones.\n */\nexport async function whyThisFile(\n input: WhyThisFileInput,\n ctx: HaiveContext,\n): Promise<WhyThisFileOutput> {\n const fileExists = existsSync(path.join(ctx.paths.root, input.path));\n\n const [commits, memories, codeMap] = await Promise.all([\n runGitLog(ctx.paths.root, input.path, input.git_log_limit).catch(() => []),\n collectAnchoredMemories(ctx, input.path, input.memory_limit),\n loadCodeMap(ctx.paths),\n ]);\n\n const codeMapEntry = codeMap?.files[input.path];\n\n const hints: string[] = [];\n if (!fileExists) {\n hints.push(`File '${input.path}' does not exist on disk — path may be wrong or file removed.`);\n }\n if (commits.length === 0 && fileExists) {\n hints.push(\"No git history found — file may be untracked or git not initialized.\");\n }\n if (memories.length === 0 && fileExists) {\n hints.push(\n \"No memories anchored here. If you discover something non-obvious while editing, \" +\n \"use mem_observe (with where=\" + input.path + \") to capture it.\",\n );\n }\n if (memories.some((m) => m.type === \"attempt\" || m.type === \"gotcha\")) {\n hints.push(\"⚠️ attempt/gotcha memories anchored to this file — read them BEFORE editing.\");\n }\n\n return {\n file: input.path,\n exists: fileExists,\n recent_commits: commits,\n memories,\n code_map_entry: codeMapEntry\n ? {\n ...(codeMapEntry.summary ? { summary: codeMapEntry.summary } : {}),\n loc: codeMapEntry.loc,\n exports: codeMapEntry.exports.map((e) => ({\n name: e.name,\n kind: e.kind,\n line: e.line,\n ...(e.description ? { description: e.description } : {}),\n })),\n }\n : null,\n ...(hints.length > 0 ? { hints } : {}),\n };\n}\n\nasync function collectAnchoredMemories(\n ctx: HaiveContext,\n filePath: string,\n limit: number,\n): Promise<WhyThisFileOutput[\"memories\"]> {\n if (!existsSync(ctx.paths.memoriesDir)) return [];\n const all = await loadMemoriesFromDir(ctx.paths.memoriesDir);\n const usage = await loadUsageIndex(ctx.paths);\n const out: WhyThisFileOutput[\"memories\"] = [];\n for (const { memory } of all) {\n const fm = memory.frontmatter;\n if (fm.status === \"rejected\" || fm.status === \"deprecated\") continue;\n if (fm.type === \"session_recap\") continue;\n if (!memoryMatchesAnchorPaths(memory, [filePath])) continue;\n const u = getUsage(usage, fm.id);\n out.push({\n id: fm.id,\n type: fm.type,\n scope: fm.scope,\n confidence: deriveConfidence(fm, u),\n body_preview: memory.body.split(\"\\n\").slice(0, 6).join(\"\\n\"),\n });\n if (out.length >= limit) break;\n }\n return out;\n}\n\nasync function runGitLog(\n cwd: string,\n filePath: string,\n limit: number,\n): Promise<WhyThisFileOutput[\"recent_commits\"]> {\n const sep = \"<<HV>>\";\n const fmt = `%h${sep}%an${sep}%ar${sep}%s`;\n const output = await runCommand(\n \"git\",\n [\"log\", `-n`, String(limit), `--pretty=format:${fmt}`, \"--\", filePath],\n cwd,\n );\n if (!output.trim()) return [];\n return output\n .split(\"\\n\")\n .map((line) => {\n const [sha = \"\", author = \"\", relative_date = \"\", subject = \"\"] = line.split(sep);\n return { sha, author, relative_date, subject };\n })\n .filter((c) => c.sha);\n}\n\nfunction runCommand(cmd: string, args: string[], cwd: string): Promise<string> {\n return new Promise((resolve, reject) => {\n const proc = spawn(cmd, args, { cwd, stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n let stdout = \"\";\n let stderr = \"\";\n proc.stdout.on(\"data\", (chunk) => {\n stdout += chunk.toString();\n });\n proc.stderr.on(\"data\", (chunk) => {\n stderr += chunk.toString();\n });\n proc.on(\"error\", reject);\n proc.on(\"close\", (code) => {\n if (code === 0) resolve(stdout);\n else reject(new Error(stderr || `${cmd} exited with code ${code}`));\n });\n });\n}\n","import { existsSync } from \"node:fs\";\nimport {\n addedLinesFromDiff,\n BRIDGE_TARGET_PATH,\n buildDocFrequency,\n CODE_STOPWORDS,\n deriveConfidence,\n diffHasDistinctiveOverlap,\n getUsage,\n isRetiredMemory,\n loadMemoriesFromDir,\n loadUsageIndex,\n literalMatchesAnyToken,\n memoryMatchesAnchorPaths,\n recordPreventionHits,\n runSensors,\n sensorTargetsFromDiff,\n tokenizeQuery,\n type DocFrequency,\n} from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const AntiPatternsCheckInputSchema = {\n diff: z\n .string()\n .optional()\n .describe(\n \"Raw unified diff text (or any code/text snippet) to scan for previously documented anti-patterns. \" +\n \"Tokens from the diff are used to match memory bodies and the embeddings index.\",\n ),\n paths: z\n .array(z.string())\n .default([])\n .describe(\n \"File paths affected by the change. Memories anchored to any of these paths are surfaced regardless of the diff content.\",\n ),\n limit: z\n .number()\n .int()\n .positive()\n .max(20)\n .default(8)\n .describe(\"Cap on returned warnings.\"),\n semantic: z\n .boolean()\n .default(true)\n .describe(\n \"When true, also use semantic search (requires @hivelore/embeddings + memory index) to find related anti-patterns.\",\n ),\n min_semantic_score: z\n .number()\n .min(0)\n .max(1)\n .default(0.45)\n .describe(\n \"Minimum cosine score for semantic-only anti-pattern hits. Anchor/literal matches still surface. \" +\n \"Default 0.45 keeps broad, weakly-related memories out of review noise.\",\n ),\n};\n\nexport interface AntiPatternsCheckInput {\n diff?: string;\n paths: string[];\n limit: number;\n semantic: boolean;\n min_semantic_score?: number;\n}\n\nexport interface AntiPatternsWarning {\n id: string;\n type: \"attempt\" | \"gotcha\";\n scope: string;\n confidence: string;\n body_preview: string;\n reasons: Array<\"anchor\" | \"literal\" | \"semantic\" | \"sensor\">;\n /**\n * True when the LITERAL overlap includes a token that is *distinctive* to this memory\n * (rare across the gotcha corpus) — e.g. `BigInt`, `open-in-view`. Only a distinctive\n * literal overlap is precise enough to hard-block; a shared common word (\"memory\",\n * \"scope\", \"version\") sets only the `literal` reason for review. Powers the gate.\n */\n distinctive_literal?: boolean;\n semantic_score?: number;\n /** When a regex sensor fired: its self-correction message and severity. */\n sensor_message?: string;\n sensor_severity?: \"warn\" | \"block\";\n /** Memory tags — used downstream (e.g. pre_commit_check) to weight a warning by topic. */\n tags?: string[];\n /** Anchor paths of the memory — lets the gate tell what kind of file this warning is about. */\n anchor_paths?: string[];\n /**\n * True when the memory has an executable sensor defined.\n * Used by the pre-commit gate: if a sensor exists but did NOT fire (no \"sensor\" reason),\n * the sensor is the authoritative check and literal matching alone should not block.\n */\n has_sensor?: boolean;\n}\n\nexport interface AntiPatternsCheckOutput {\n /** Total number of attempt+gotcha memories that exist in this project. */\n scanned: number;\n warnings: AntiPatternsWarning[];\n notice?: string;\n}\n\n/**\n * Tokenize a diff for LITERAL anti-pattern matching.\n *\n * `tokenizeQuery` splits on whitespace only, so code without spaces around an identifier\n * (e.g. `Number(BigInt(a))`) collapses into one un-matchable blob and the \"literal\" signal\n * silently disappears — leaving the gate to lean on the (non-deterministic, warmup-sensitive)\n * semantic score. We additionally split on non-word boundaries and keep identifier-length\n * tokens (>= 4 chars, not a ubiquitous keyword) so `BigInt`, `lodash`, `openInView`, etc. are\n * matched reliably. The set is unioned with the whitespace tokens to preserve existing behavior.\n */\nfunction tokenizeDiffForLiteral(diff: string): string[] {\n // If this is a unified diff, only consider ADDED lines. The gate should fire on\n // \"you introduced the bad pattern\", not \"you touched a file that merely mentions it\"\n // (or \"you REMOVED it\"). This cuts false positives on refactors that edit anchored files.\n const lines = diff.split(\"\\n\");\n const looksLikeDiff = lines.some((l) => /^[+-]/.test(l));\n const addedOnly = looksLikeDiff\n ? lines.filter((l) => l.startsWith(\"+\") && !l.startsWith(\"+++\")).join(\"\\n\")\n : diff;\n const source = addedOnly.trim().length > 0 ? addedOnly : diff;\n\n const wsTokens = tokenizeQuery(source);\n const wordTokens = source\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((t) => t.length >= 4 && !CODE_STOPWORDS.has(t));\n return [...new Set([...wsTokens, ...wordTokens])];\n}\n\n/**\n * Files Hivelore generates/writes that are NOT application code: agent bridges (Lot A init + Lot C\n * bridges), the MCP client configs, and `.gitignore` (init appends a Hivelore block). Scanning any of\n * these for anti-patterns self-matches the corpus they mirror (a bridge listing the seeded gotchas,\n * a `.gitignore` line that merely contains \"cache\", etc.).\n */\nconst HAIVE_GENERATED_FILES = new Set<string>([\n ...Object.values(BRIDGE_TARGET_PATH), // .clinerules, .windsurfrules, .continuerules, .rules, AGENTS.md, .github/copilot-instructions.md, .sourcegraph/cody-rules.md\n \"CLAUDE.md\",\n \".cursorrules\",\n \".gitignore\",\n \".mcp.json\",\n \".cursor/mcp.json\",\n \".vscode/mcp.json\",\n]);\n\n/**\n * True for files Hivelore itself owns/generates: the `.ai/` knowledge base, plus the agent-bridge,\n * config, and workflow files it writes from that same corpus. Scanning these for anti-patterns\n * self-matches the memories they mirror and fabricates \"prevented mistake\" events on the very first\n * post-init commit (which stages the seeded corpus AND everything init generated, all at once).\n */\nexport function isHaiveOwnedPath(p: string): boolean {\n if (p.startsWith(\".ai/\")) return true;\n if (HAIVE_GENERATED_FILES.has(p)) return true;\n if (p.startsWith(\".cursor/rules/\")) return true; // haive-mcp-required.mdc and siblings\n if (/^\\.github\\/workflows\\/haive-.*\\.ya?ml$/.test(p)) return true;\n return false;\n}\n\n/**\n * Drop hunks for Hivelore-owned files (see {@link isHaiveOwnedPath}) from a unified diff. Anti-patterns\n * are about CODE reintroducing a known mistake — editing Hivelore's own knowledge base or the bridge\n * files it generates from that corpus must never corroborate a literal/semantic match. Without this,\n * re-tagging a memory, or simply committing a fresh `hivelore init` (which writes the seeded corpus AND\n * its bridges in one commit), self-matches and can hard-block or inflate prevention counts.\n * See gotcha 2026-06-03-gotcha-antipattern-self-match-on-memory-file-edit.\n */\n/** Test/spec files — they deliberately exercise the symbols & patterns gotchas warn about. */\nconst TEST_PATH_RE = /(?:^|\\/)(?:tests?|__tests__|__mocks__|e2e|fixtures)\\/|\\.(?:test|spec)\\.[cm]?[jt]sx?$/i;\nexport function isTestPath(p: string): boolean {\n return TEST_PATH_RE.test(p);\n}\n\n/**\n * Drop test/spec hunks from a diff before anti-pattern matching. A test that asserts on a documented\n * gotcha (e.g. `expect(serializeMemory(x))…`, or `import lodash` in a \"no lodash\" test) legitimately\n * contains the very token/pattern the gotcha describes — using it is not reintroducing the mistake.\n * Letting test edits corroborate a literal/semantic match is a recurring false-positive source, so the\n * scan ignores them (production-code blocking, incl. anchored gotchas, is unaffected).\n */\nexport function stripTestHunks(diff: string): string {\n if (!diff.includes(\"diff --git\")) return diff;\n const out: string[] = [];\n let block: string[] = [];\n let keep = true;\n const flush = (): void => {\n if (keep) out.push(...block);\n block = [];\n keep = true;\n };\n for (const line of diff.split(\"\\n\")) {\n if (line.startsWith(\"diff --git \")) {\n flush();\n const target = line.match(/ b\\/(.+)$/)?.[1] ?? \"\";\n keep = !isTestPath(target);\n }\n block.push(line);\n }\n flush();\n return out.join(\"\\n\");\n}\n\nexport function stripAiDirHunks(diff: string): string {\n if (!diff.includes(\"diff --git\")) return diff; // no file headers to split on — leave as-is\n const out: string[] = [];\n let block: string[] = [];\n let keep = true;\n const flush = (): void => {\n if (keep) out.push(...block);\n block = [];\n keep = true;\n };\n for (const line of diff.split(\"\\n\")) {\n if (line.startsWith(\"diff --git \")) {\n flush();\n const target = line.match(/ b\\/(.+)$/)?.[1] ?? \"\";\n keep = !isHaiveOwnedPath(target);\n }\n block.push(line);\n }\n flush();\n return out.join(\"\\n\");\n}\n\n/**\n * Scan a diff (or set of paths) against documented attempt/gotcha memories.\n * Surfaces \"you are about to repeat a known mistake\" warnings BEFORE you commit.\n *\n * Matching strategy:\n * 1. Anchor — memories anchored to any of the changed paths\n * 2. Literal — tokens from the diff overlap with memory body\n * 3. Semantic — cosine similarity (when enabled and index available)\n */\nexport async function antiPatternsCheck(\n input: AntiPatternsCheckInput,\n ctx: HaiveContext,\n): Promise<AntiPatternsCheckOutput> {\n if (!input.diff && input.paths.length === 0) {\n return {\n scanned: 0,\n warnings: [],\n notice: \"Nothing to check — provide either `diff` text or `paths`.\",\n };\n }\n if (!existsSync(ctx.paths.memoriesDir)) {\n return { scanned: 0, warnings: [], notice: \"No .ai/memories directory — nothing to check against.\" };\n }\n\n const all = await loadMemoriesFromDir(ctx.paths.memoriesDir);\n const minSemanticScore = input.min_semantic_score ?? 0.45;\n const negative = all.filter(({ memory }) => {\n const t = memory.frontmatter.type;\n if (t !== \"attempt\" && t !== \"gotcha\") return false;\n const s = memory.frontmatter.status;\n return s !== \"rejected\" && s !== \"deprecated\" && s !== \"stale\" &&\n !isRetiredMemory(memory.frontmatter, memory.body);\n });\n\n if (negative.length === 0) {\n return { scanned: 0, warnings: [], notice: \"No attempt/gotcha memories found yet.\" };\n }\n\n const usage = await loadUsageIndex(ctx.paths);\n // Document frequency over the gotcha/attempt corpus — drives distinctive-token\n // corroboration so a shared *common* word never hard-blocks (false positives).\n const docFreq: DocFrequency = buildDocFrequency(negative.map(({ memory }) => memory.body));\n const seen = new Map<string, AntiPatternsWarning>();\n\n const upsert = (\n fm: { id: string; type: string; scope: string; tags?: string[]; anchor?: { paths?: string[] }; sensor?: unknown },\n body: string,\n reason: AntiPatternsWarning[\"reasons\"][number],\n score?: number,\n ): void => {\n const existing = seen.get(fm.id);\n if (existing) {\n if (!existing.reasons.includes(reason)) existing.reasons.push(reason);\n if (score !== undefined && (existing.semantic_score ?? 0) < score) {\n existing.semantic_score = score;\n }\n return;\n }\n const u = getUsage(usage, fm.id);\n seen.set(fm.id, {\n id: fm.id,\n type: fm.type as \"attempt\" | \"gotcha\",\n scope: fm.scope,\n confidence: deriveConfidence(fm as Parameters<typeof deriveConfidence>[0], u),\n body_preview: body.split(\"\\n\").slice(0, 5).join(\"\\n\").slice(0, 400),\n reasons: [reason],\n tags: fm.tags ?? [],\n anchor_paths: fm.anchor?.paths ?? [],\n ...(fm.sensor != null ? { has_sensor: true } : {}),\n ...(score !== undefined ? { semantic_score: score } : {}),\n });\n };\n\n // 1. Anchor matches\n if (input.paths.length > 0) {\n for (const { memory } of negative) {\n if (memoryMatchesAnchorPaths(memory, input.paths)) {\n upsert(memory.frontmatter, memory.body, \"anchor\");\n }\n }\n }\n\n // Code-only view of the diff: `.ai/` knowledge-base edits never corroborate \"you reintroduced a\n // bad pattern in code\" (they'd self-match the very memory that documents it).\n const scanDiff = input.diff ? stripTestHunks(stripAiDirHunks(input.diff)) : input.diff;\n\n // 2. Literal token overlap from diff\n if (scanDiff) {\n const tokens = tokenizeDiffForLiteral(scanDiff);\n const added = addedLinesFromDiff(scanDiff);\n const addedText = added.trim().length > 0 ? added : scanDiff;\n if (tokens.length > 0) {\n for (const { memory } of negative) {\n if (literalMatchesAnyToken(memory, tokens)) {\n upsert(memory.frontmatter, memory.body, \"literal\");\n // Distinguish a meaningful overlap (the diff contains a token rare to this\n // gotcha) from incidental shared domain words. Only the former can hard-block.\n if (diffHasDistinctiveOverlap(addedText, memory.body, docFreq)) {\n const w = seen.get(memory.frontmatter.id);\n if (w) w.distinctive_literal = true;\n }\n }\n }\n }\n }\n\n // 2b. Sensor matches — deterministic regex checks derived from memories.\n // A sensor fires on the ADDED lines of the diff (\"you introduced the bad pattern\").\n // This is the feedback *computational* signal: same result every time, no warmup.\n if (scanDiff) {\n const added = addedLinesFromDiff(scanDiff);\n const diffTargets = sensorTargetsFromDiff(scanDiff);\n const hasFileTargets = diffTargets.some((target) => target.path.length > 0);\n // Never run sensors against Hivelore-owned files — a memory/bridge that documents a bad pattern\n // contains that pattern and would self-fire (see stripAiDirHunks / isHaiveOwnedPath).\n const codePaths = input.paths.filter((p) => !isHaiveOwnedPath(p));\n const fallbackContent = added.trim().length > 0 ? added : scanDiff;\n const targets = diffTargets.length > 0 && hasFileTargets\n ? diffTargets\n : codePaths.length > 0\n ? codePaths.map((p) => ({ path: p, content: fallbackContent }))\n : [{ path: \"\", content: fallbackContent }];\n const hits = runSensors(negative.map(({ memory }) => memory), targets);\n for (const hit of hits) {\n const found = negative.find(({ memory }) => memory.frontmatter.id === hit.memory_id);\n if (!found) continue;\n upsert(found.memory.frontmatter, found.memory.body, \"sensor\");\n const w = seen.get(found.memory.frontmatter.id);\n if (w) {\n w.sensor_message = hit.message;\n w.sensor_severity = hit.severity;\n }\n }\n }\n\n // 3. Semantic search\n if (input.semantic && scanDiff) {\n try {\n const mod = await import(\"@hivelore/embeddings\");\n // Embed the ADDED lines only — \"what you INTRODUCED\" — not the raw diff. The raw diff carries\n // context lines, removed lines and file headers; embedding that whole blob blurs the query and\n // inflates cosine similarity against broadly-related memories (a big release matches *some*\n // high-confidence gotcha at ≥0.75 and hard-blocks even though no added hunk reintroduces it).\n // This mirrors the literal + sensor layers, which already match on added lines, and tightens\n // the only layer that could hard-block on topical resemblance alone.\n const added = addedLinesFromDiff(scanDiff);\n const semanticQuery = added.trim().length > 0 ? added : scanDiff;\n const result = await mod.semanticSearch(ctx.paths, semanticQuery, { limit: input.limit * 2 });\n if (result) {\n const negativeIds = new Set(negative.map(({ memory }) => memory.frontmatter.id));\n for (const hit of result.hits) {\n if (!negativeIds.has(hit.id)) continue;\n if (hit.score < minSemanticScore && !seen.has(hit.id)) continue;\n const found = negative.find(({ memory }) => memory.frontmatter.id === hit.id);\n if (found) upsert(found.memory.frontmatter, found.memory.body, \"semantic\", hit.score);\n }\n }\n } catch {\n // embeddings not installed — silently skip semantic\n }\n }\n\n // Rank: anchor > literal > semantic, then by confidence\n const warnings = [...seen.values()]\n .sort((a, b) => {\n const score = (w: AntiPatternsWarning): number => {\n const reasonW =\n (w.reasons.includes(\"sensor\") ? 8 : 0) +\n (w.reasons.includes(\"anchor\") ? 4 : 0) +\n (w.reasons.includes(\"literal\") ? 2 : 0) +\n (w.reasons.includes(\"semantic\") ? 1 : 0);\n const confW =\n w.confidence === \"authoritative\" ? 3 :\n w.confidence === \"trusted\" ? 2 :\n w.confidence === \"low\" ? 1 : 0;\n return reasonW + confW + (w.semantic_score ?? 0);\n };\n return score(b) - score(a);\n })\n .slice(0, input.limit);\n\n // OUTCOME measurement: record as prevention ONLY catches that would actually HARD-BLOCK a diff —\n // never the mere re-surfacing of an anchored note. A prevention event is a measured claim (\"a known\n // mistake was intercepted before it landed\"); if it's cheap to trigger, the dashboard / gate-precision\n // / proof-line inflate on noise (the \"485 repeats blocked\" that was really one note matching every\n // package.json commit). SENSOR-ONLY, mirroring the gate (classifyWarning): a deterministic sensor\n // firing is the single hard-block path — sensor-less semantic matches (even ≥ 0.75) no longer block\n // because cosine scores vary across environments, so counting them as \"prevented\" would claim an\n // outcome the gate no longer produces. Anchor/literal/semantic matches still SURFACE for review;\n // they just aren't counted as prevented outcomes. Debounced via recordPrevention.\n const isHardBlockCatch = (w: { reasons: string[] }): boolean => w.reasons.includes(\"sensor\");\n const strongCatches = warnings.filter(isHardBlockCatch);\n // THE shared recorder — same path the git-hook gate and `hivelore sensors check` use (debounced).\n await recordPreventionHits(ctx.paths, strongCatches.map((w) => w.id), \"anti-pattern\");\n\n return {\n scanned: negative.length,\n warnings,\n };\n}\n","import { existsSync } from \"node:fs\";\nimport {\n loadMemoriesFromDir,\n tokenizeQuery,\n type LoadedMemory,\n} from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const MemDistillInputSchema = {\n since_days: z\n .number()\n .int()\n .positive()\n .default(30)\n .describe(\"Only consider memories created in the last N days.\"),\n min_cluster: z\n .number()\n .int()\n .min(2)\n .default(3)\n .describe(\"Minimum cluster size to surface.\"),\n type_filter: z\n .enum([\"gotcha\", \"attempt\", \"all\"])\n .default(\"gotcha\")\n .describe(\n \"Memory type to scan. 'gotcha' targets observe-style discoveries that recur, \" +\n \"'attempt' surfaces failed approaches that repeat, 'all' considers both.\",\n ),\n scope: z\n .enum([\"personal\", \"team\", \"module\", \"any\"])\n .default(\"any\")\n .describe(\"Restrict to a specific scope.\"),\n};\n\nexport type MemDistillInput = {\n [K in keyof typeof MemDistillInputSchema]: z.infer<(typeof MemDistillInputSchema)[K]>;\n};\n\nexport interface DistillCluster {\n suggested_topic: string;\n suggested_type: \"convention\" | \"gotcha\";\n member_ids: string[];\n overlapping_paths: string[];\n common_keywords: string[];\n sample_titles: string[];\n /** ISO date of the latest member */\n latest_at: string;\n}\n\nexport interface MemDistillOutput {\n scanned: number;\n /** Memories that didn't fit any cluster (kept here so callers can inspect singletons). */\n singletons: number;\n clusters: DistillCluster[];\n notice?: string;\n}\n\nconst MS_PER_DAY = 24 * 60 * 60 * 1000;\n\nconst STOP_WORDS = new Set([\n \"the\",\"and\",\"for\",\"with\",\"that\",\"this\",\"from\",\"into\",\"when\",\"then\",\"also\",\"must\",\n \"have\",\"does\",\"not\",\"but\",\"you\",\"your\",\"its\",\"because\",\"why\",\"how\",\"what\",\n \"use\",\"using\",\"used\",\"add\",\"added\",\"make\",\"made\",\"fix\",\"fixed\",\"bug\",\"error\",\n]);\n\n/**\n * Cluster recurring observations / attempts so a human can collapse N similar\n * memories into one richer convention/gotcha. Uses cheap heuristics (anchor\n * path overlap + body keyword overlap) — no embeddings needed.\n *\n * Output is *advisory*: nothing is written to disk. The caller (CLI / human)\n * decides whether to mem_save the consolidated form.\n */\nexport async function memDistill(\n input: MemDistillInput,\n ctx: HaiveContext,\n): Promise<MemDistillOutput> {\n if (!existsSync(ctx.paths.memoriesDir)) {\n return { scanned: 0, singletons: 0, clusters: [], notice: \"No .ai/memories directory.\" };\n }\n\n const cutoff = Date.now() - input.since_days * MS_PER_DAY;\n const all = await loadMemoriesFromDir(ctx.paths.memoriesDir);\n const candidates = all.filter(({ memory }) => {\n const fm = memory.frontmatter;\n if (fm.status === \"rejected\" || fm.status === \"deprecated\" || fm.status === \"stale\") return false;\n if (input.scope !== \"any\" && fm.scope !== input.scope) return false;\n if (input.type_filter === \"gotcha\" && fm.type !== \"gotcha\") return false;\n if (input.type_filter === \"attempt\" && fm.type !== \"attempt\") return false;\n if (input.type_filter === \"all\" && fm.type !== \"gotcha\" && fm.type !== \"attempt\") return false;\n if (Date.parse(fm.created_at) < cutoff) return false;\n return true;\n });\n\n if (candidates.length < input.min_cluster) {\n return {\n scanned: candidates.length,\n singletons: candidates.length,\n clusters: [],\n notice: candidates.length === 0\n ? `No matching memories in the last ${input.since_days} days.`\n : `Only ${candidates.length} candidate${candidates.length === 1 ? \"\" : \"s\"} — below min_cluster=${input.min_cluster}.`,\n };\n }\n\n // Pre-compute features per memory: keyword set + path set\n const features = candidates.map((loaded) => ({\n loaded,\n keywords: keywordSet(loaded),\n paths: new Set<string>(loaded.memory.frontmatter.anchor.paths),\n }));\n\n // Single-linkage clustering: union-find by similarity threshold.\n const parent: number[] = features.map((_, i) => i);\n const find = (i: number): number => (parent[i] === i ? i : (parent[i] = find(parent[i] ?? 0)));\n const union = (a: number, b: number): void => {\n const ra = find(a), rb = find(b);\n if (ra !== rb) parent[ra] = rb;\n };\n\n for (let i = 0; i < features.length; i++) {\n for (let j = i + 1; j < features.length; j++) {\n const fi = features[i]!, fj = features[j]!;\n const pathSim = jaccard(fi.paths, fj.paths);\n const kwSim = jaccard(fi.keywords, fj.keywords);\n // Either strong path overlap OR strong keyword overlap qualifies.\n if (pathSim >= 0.5 || kwSim >= 0.4) union(i, j);\n }\n }\n\n // Group by root parent\n const groups = new Map<number, number[]>();\n for (let i = 0; i < features.length; i++) {\n const root = find(i);\n const arr = groups.get(root) ?? [];\n arr.push(i);\n groups.set(root, arr);\n }\n\n const clusters: DistillCluster[] = [];\n let singletons = 0;\n for (const indices of groups.values()) {\n if (indices.length < input.min_cluster) {\n singletons += indices.length;\n continue;\n }\n const members = indices.map((i) => features[i]!);\n const allPaths = new Set<string>();\n const allKeywords = new Map<string, number>();\n let latest = 0;\n for (const m of members) {\n for (const p of m.paths) allPaths.add(p);\n for (const k of m.keywords) allKeywords.set(k, (allKeywords.get(k) ?? 0) + 1);\n const t = Date.parse(m.loaded.memory.frontmatter.created_at);\n if (t > latest) latest = t;\n }\n const commonKeywords = [...allKeywords.entries()]\n .filter(([, n]) => n >= Math.max(2, Math.floor(members.length / 2)))\n .sort((a, b) => b[1] - a[1])\n .slice(0, 5)\n .map(([k]) => k);\n\n const titles = members\n .map((m) => firstHeading(m.loaded.memory.body) ?? m.loaded.memory.frontmatter.id)\n .slice(0, 5);\n\n const suggestedType: DistillCluster[\"suggested_type\"] =\n members.every((m) => m.loaded.memory.frontmatter.type === \"attempt\") ? \"gotcha\" : \"convention\";\n\n clusters.push({\n suggested_topic: commonKeywords.slice(0, 3).join(\"-\") || \"merged-observations\",\n suggested_type: suggestedType,\n member_ids: members.map((m) => m.loaded.memory.frontmatter.id),\n overlapping_paths: [...allPaths].slice(0, 10),\n common_keywords: commonKeywords,\n sample_titles: titles,\n latest_at: new Date(latest).toISOString(),\n });\n }\n\n // Sort clusters by size desc\n clusters.sort((a, b) => b.member_ids.length - a.member_ids.length);\n\n return {\n scanned: candidates.length,\n singletons,\n clusters,\n };\n}\n\nfunction keywordSet(loaded: LoadedMemory): Set<string> {\n const text = (loaded.memory.body + \" \" + loaded.memory.frontmatter.tags.join(\" \")).slice(0, 800);\n const tokens = tokenizeQuery(text)\n .filter((t) => t.length >= 4 && !STOP_WORDS.has(t));\n return new Set(tokens);\n}\n\nfunction jaccard<T>(a: Set<T>, b: Set<T>): number {\n if (a.size === 0 && b.size === 0) return 0;\n let intersect = 0;\n for (const x of a) if (b.has(x)) intersect++;\n const union = a.size + b.size - intersect;\n return union === 0 ? 0 : intersect / union;\n}\n\nfunction firstHeading(body: string): string | undefined {\n for (const line of body.split(\"\\n\")) {\n const t = line.trim();\n if (t.startsWith(\"#\")) return t.replace(/^#+\\s*/, \"\").slice(0, 80);\n if (t.length > 0) return t.slice(0, 80);\n }\n return undefined;\n}\n","import { existsSync } from \"node:fs\";\nimport { spawn } from \"node:child_process\";\nimport {\n deriveConfidence,\n getUsage,\n loadMemoriesFromDir,\n loadUsageIndex,\n pathsOverlap as singlePathsOverlap,\n} from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const WhyThisDecisionInputSchema = {\n id: z\n .string()\n .min(1)\n .describe(\"Memory id to inspect (e.g. '2026-04-25-decision-esm-only').\"),\n git_log_limit: z\n .number()\n .int()\n .positive()\n .max(20)\n .default(5)\n .describe(\"How many recent commits per anchor path to surface.\"),\n};\n\nexport type WhyThisDecisionInput = {\n [K in keyof typeof WhyThisDecisionInputSchema]: z.infer<(typeof WhyThisDecisionInputSchema)[K]>;\n};\n\nexport interface WhyThisDecisionOutput {\n found: boolean;\n decision?: {\n id: string;\n type: string;\n scope: string;\n status: string;\n confidence: string;\n body: string;\n created_at: string;\n };\n /** Memories explicitly linked via related_ids on the decision (or vice versa). */\n related: Array<{\n id: string;\n type: string;\n scope: string;\n confidence: string;\n body_preview: string;\n relation: \"explicit\" | \"back-link\";\n }>;\n /** Other memories anchored to overlapping paths — implicit context. */\n path_neighbors: Array<{\n id: string;\n type: string;\n scope: string;\n confidence: string;\n overlap: string[];\n body_preview: string;\n }>;\n /** Recent git commits touching any of the decision's anchored paths. */\n recent_commits: Array<{\n path: string;\n sha: string;\n author: string;\n relative_date: string;\n subject: string;\n }>;\n hints?: string[];\n notice?: string;\n}\n\n/**\n * Trace the genealogy of a `decision` memory: the decision itself + memories\n * explicitly linked to it + memories anchored to overlapping paths + recent\n * commits touching those paths. One call instead of 4-5 manual lookups.\n *\n * Works on any memory type, but is optimized for `decision` and `architecture`.\n */\nexport async function whyThisDecision(\n input: WhyThisDecisionInput,\n ctx: HaiveContext,\n): Promise<WhyThisDecisionOutput> {\n if (!existsSync(ctx.paths.memoriesDir)) {\n return {\n found: false,\n related: [],\n path_neighbors: [],\n recent_commits: [],\n notice: \"No .ai/memories directory.\",\n };\n }\n const all = await loadMemoriesFromDir(ctx.paths.memoriesDir);\n const usage = await loadUsageIndex(ctx.paths);\n const target = all.find(({ memory }) => memory.frontmatter.id === input.id);\n if (!target) {\n return {\n found: false,\n related: [],\n path_neighbors: [],\n recent_commits: [],\n notice: `Memory '${input.id}' not found.`,\n };\n }\n\n const fm = target.memory.frontmatter;\n const targetUsage = getUsage(usage, fm.id);\n const decision = {\n id: fm.id,\n type: fm.type,\n scope: fm.scope,\n status: fm.status,\n confidence: deriveConfidence(fm, targetUsage),\n body: target.memory.body,\n created_at: fm.created_at,\n };\n\n // ── related: explicit related_ids + reverse links ──────────────────────\n const relatedSet = new Set(fm.related_ids ?? []);\n const related: WhyThisDecisionOutput[\"related\"] = [];\n for (const { memory } of all) {\n if (memory.frontmatter.id === fm.id) continue;\n const isExplicit = relatedSet.has(memory.frontmatter.id);\n const isBackLink = (memory.frontmatter.related_ids ?? []).includes(fm.id);\n if (!isExplicit && !isBackLink) continue;\n const u = getUsage(usage, memory.frontmatter.id);\n related.push({\n id: memory.frontmatter.id,\n type: memory.frontmatter.type,\n scope: memory.frontmatter.scope,\n confidence: deriveConfidence(memory.frontmatter, u),\n body_preview: memory.body.split(\"\\n\").slice(0, 4).join(\"\\n\").slice(0, 300),\n relation: isExplicit ? \"explicit\" : \"back-link\",\n });\n }\n\n // ── path_neighbors: memories anchored to overlapping paths ─────────────\n const targetPaths = fm.anchor.paths;\n const path_neighbors: WhyThisDecisionOutput[\"path_neighbors\"] = [];\n if (targetPaths.length > 0) {\n for (const { memory } of all) {\n if (memory.frontmatter.id === fm.id) continue;\n if (relatedSet.has(memory.frontmatter.id)) continue; // already in related\n const overlappingPaths = memory.frontmatter.anchor.paths.filter((p) =>\n targetPaths.some((tp) => singlePathsOverlap(p, tp)),\n );\n if (overlappingPaths.length === 0) continue;\n const u = getUsage(usage, memory.frontmatter.id);\n path_neighbors.push({\n id: memory.frontmatter.id,\n type: memory.frontmatter.type,\n scope: memory.frontmatter.scope,\n confidence: deriveConfidence(memory.frontmatter, u),\n overlap: overlappingPaths,\n body_preview: memory.body.split(\"\\n\").slice(0, 3).join(\"\\n\").slice(0, 200),\n });\n if (path_neighbors.length >= 10) break;\n }\n }\n\n // ── recent_commits: git log on each anchored path ──────────────────────\n const recent_commits: WhyThisDecisionOutput[\"recent_commits\"] = [];\n for (const p of targetPaths.slice(0, 5)) {\n try {\n const commits = await runGitLog(ctx.paths.root, p, input.git_log_limit);\n for (const c of commits) recent_commits.push({ path: p, ...c });\n } catch {\n /* git not available or path untracked — silent */\n }\n }\n\n const hints: string[] = [];\n if (decision.confidence === \"low\" || decision.confidence === \"stale\") {\n hints.push(`⚠️ Confidence is ${decision.confidence}. Verify this decision still applies before quoting it.`);\n }\n if (related.length === 0 && path_neighbors.length === 0 && targetPaths.length === 0) {\n hints.push(\"No related memories and no anchored paths — this decision is isolated; consider adding related_ids or paths.\");\n }\n if (fm.type !== \"decision\" && fm.type !== \"architecture\") {\n hints.push(`Memory type is '${fm.type}', not 'decision'/'architecture' — output may be less informative.`);\n }\n\n return {\n found: true,\n decision,\n related,\n path_neighbors,\n recent_commits,\n ...(hints.length > 0 ? { hints } : {}),\n };\n}\n\nasync function runGitLog(\n cwd: string,\n filePath: string,\n limit: number,\n): Promise<Array<{ sha: string; author: string; relative_date: string; subject: string }>> {\n const sep = \"<<HV>>\";\n const fmt = `%h${sep}%an${sep}%ar${sep}%s`;\n const output = await runCommand(\n \"git\",\n [\"log\", \"-n\", String(limit), `--pretty=format:${fmt}`, \"--\", filePath],\n cwd,\n );\n if (!output.trim()) return [];\n return output\n .split(\"\\n\")\n .map((line) => {\n const [sha = \"\", author = \"\", relative_date = \"\", subject = \"\"] = line.split(sep);\n return { sha, author, relative_date, subject };\n })\n .filter((c) => c.sha);\n}\n\nfunction runCommand(cmd: string, args: string[], cwd: string): Promise<string> {\n return new Promise((resolve, reject) => {\n const proc = spawn(cmd, args, { cwd, stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n let stdout = \"\";\n let stderr = \"\";\n proc.stdout.on(\"data\", (chunk) => { stdout += chunk.toString(); });\n proc.stderr.on(\"data\", (chunk) => { stderr += chunk.toString(); });\n proc.on(\"error\", reject);\n proc.on(\"close\", (code) => {\n if (code === 0) resolve(stdout);\n else reject(new Error(stderr || `${cmd} exited with code ${code}`));\n });\n });\n}\n","import { existsSync } from \"node:fs\";\nimport {\n deriveConfidence,\n getUsage,\n loadMemoriesFromDir,\n loadUsageIndex,\n pathsOverlap,\n tokenizeQuery,\n type LoadedMemory,\n} from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const MemConflictsInputSchema = {\n id: z\n .string()\n .min(1)\n .describe(\"Memory id to check for conflicts.\"),\n min_score: z\n .number()\n .min(0)\n .max(1)\n .default(0.5)\n .describe(\"Minimum cosine similarity to consider a memory as a potential conflict (semantic mode).\"),\n semantic: z\n .boolean()\n .default(true)\n .describe(\"Use embeddings for similarity. Falls back to keyword overlap when embeddings are not installed.\"),\n};\n\nexport type MemConflictsInput = {\n [K in keyof typeof MemConflictsInputSchema]: z.infer<(typeof MemConflictsInputSchema)[K]>;\n};\n\nexport type ConflictReason =\n | \"opposite-status\"\n | \"attempt-vs-convention-same-paths\"\n | \"polarity-keywords\"\n | \"explicit-contradiction-tag\";\n\nexport interface ConflictHit {\n id: string;\n type: string;\n scope: string;\n status: string;\n confidence: string;\n body_preview: string;\n similarity: number | null;\n reasons: ConflictReason[];\n shared_paths: string[];\n}\n\nexport interface MemConflictsOutput {\n found: boolean;\n target?: { id: string; type: string; status: string };\n scanned: number;\n conflicts: ConflictHit[];\n notice?: string;\n}\n\nconst POSITIVE_PATTERNS = /\\b(use|prefer|always|should use|do this|recommended|ok to)\\b/i;\nconst NEGATIVE_PATTERNS = /\\b(do not use|don'?t use|never|avoid|forbidden|deprecated|stop using|do NOT|❌)\\b/i;\n\n/**\n * Find memories that potentially CONTRADICT the given memory. Useful before\n * relying on a memory's advice — surfaces \"another memory says the opposite\".\n *\n * Detection layers (any of these triggers a hit):\n * - Opposite status: target is validated, neighbor is rejected — for the same topic\n * - Type mismatch on overlapping paths: an `attempt` (don't do X) coexists with\n * a `convention` (do X) anchored to overlapping paths\n * - Polarity keywords: target says \"use X\" while a semantic neighbor says \"don't use X\"\n * - Explicit contradiction tag (#contradicts:<id>) in either body\n */\nexport async function memConflicts(\n input: MemConflictsInput,\n ctx: HaiveContext,\n): Promise<MemConflictsOutput> {\n if (!existsSync(ctx.paths.memoriesDir)) {\n return { found: false, scanned: 0, conflicts: [], notice: \"No .ai/memories directory.\" };\n }\n const all = await loadMemoriesFromDir(ctx.paths.memoriesDir);\n const target = all.find(({ memory }) => memory.frontmatter.id === input.id);\n if (!target) {\n return { found: false, scanned: 0, conflicts: [], notice: `Memory '${input.id}' not found.` };\n }\n\n const usage = await loadUsageIndex(ctx.paths);\n const others = all.filter(({ memory }) =>\n memory.frontmatter.id !== input.id &&\n memory.frontmatter.type !== \"session_recap\"\n );\n\n // Optional: get semantic similarity scores via embeddings\n const simScores = input.semantic ? await trySemanticSimilarities(ctx, target, others) : null;\n\n const targetText = (target.memory.body + \" \" + target.memory.frontmatter.tags.join(\" \"))\n .toLowerCase();\n const targetTokens = new Set(tokenizeQuery(targetText));\n const targetPolarity = polarity(targetText);\n const targetPaths = target.memory.frontmatter.anchor.paths;\n const explicitContradicts = extractContradictsTags(target.memory.body);\n\n const conflicts: ConflictHit[] = [];\n\n for (const other of others) {\n const fm = other.memory.frontmatter;\n const otherText = (other.memory.body + \" \" + fm.tags.join(\" \")).toLowerCase();\n const reasons: ConflictReason[] = [];\n\n const sim = simScores?.get(fm.id) ?? null;\n\n // Pre-filter: at least some keyword or path overlap or semantic hit.\n const hasPathOverlap = fm.anchor.paths.some((p) => targetPaths.some((tp) => pathsOverlap(p, tp)));\n const otherTokens = new Set(tokenizeQuery(otherText));\n const tokenOverlap = countIntersection(targetTokens, otherTokens);\n const isSemanticNeighbor = sim !== null && sim >= input.min_score;\n if (!hasPathOverlap && tokenOverlap < 4 && !isSemanticNeighbor) continue;\n\n // 1. Explicit contradicts tag\n const otherContradicts = extractContradictsTags(other.memory.body);\n if (explicitContradicts.has(fm.id) || otherContradicts.has(input.id)) {\n reasons.push(\"explicit-contradiction-tag\");\n }\n\n // 2. Opposite status (one validated, the other rejected on the same topic)\n if (\n target.memory.frontmatter.status === \"validated\" && fm.status === \"rejected\" ||\n target.memory.frontmatter.status === \"rejected\" && fm.status === \"validated\"\n ) {\n if (tokenOverlap >= 4 || isSemanticNeighbor) reasons.push(\"opposite-status\");\n }\n\n // 3. attempt vs convention/decision on overlapping paths\n if (hasPathOverlap) {\n const tType = target.memory.frontmatter.type;\n const oType = fm.type;\n const isAttemptVsRule = (tType === \"attempt\" && (oType === \"convention\" || oType === \"decision\")) ||\n (oType === \"attempt\" && (tType === \"convention\" || tType === \"decision\"));\n if (isAttemptVsRule) reasons.push(\"attempt-vs-convention-same-paths\");\n }\n\n // 4. Polarity inversion on shared keywords\n if (isSemanticNeighbor) {\n const otherPolarity = polarity(otherText);\n if (\n (targetPolarity === \"positive\" && otherPolarity === \"negative\") ||\n (targetPolarity === \"negative\" && otherPolarity === \"positive\")\n ) {\n reasons.push(\"polarity-keywords\");\n }\n }\n\n if (reasons.length === 0) continue;\n\n const u = getUsage(usage, fm.id);\n conflicts.push({\n id: fm.id,\n type: fm.type,\n scope: fm.scope,\n status: fm.status,\n confidence: deriveConfidence(fm, u),\n body_preview: other.memory.body.split(\"\\n\").slice(0, 4).join(\"\\n\").slice(0, 300),\n similarity: sim,\n reasons,\n shared_paths: fm.anchor.paths.filter((p) => targetPaths.some((tp) => pathsOverlap(p, tp))),\n });\n }\n\n // Rank: explicit > opposite-status > others; tiebreak by similarity desc\n conflicts.sort((a, b) => {\n const score = (c: ConflictHit): number =>\n (c.reasons.includes(\"explicit-contradiction-tag\") ? 100 : 0) +\n (c.reasons.includes(\"opposite-status\") ? 50 : 0) +\n (c.reasons.includes(\"attempt-vs-convention-same-paths\") ? 25 : 0) +\n (c.reasons.includes(\"polarity-keywords\") ? 10 : 0) +\n (c.similarity ?? 0) * 5;\n return score(b) - score(a);\n });\n\n return {\n found: true,\n target: {\n id: target.memory.frontmatter.id,\n type: target.memory.frontmatter.type,\n status: target.memory.frontmatter.status,\n },\n scanned: others.length,\n conflicts: conflicts.slice(0, 10),\n };\n}\n\nfunction polarity(text: string): \"positive\" | \"negative\" | \"neutral\" {\n const neg = NEGATIVE_PATTERNS.test(text);\n const pos = POSITIVE_PATTERNS.test(text);\n if (neg && !pos) return \"negative\";\n if (pos && !neg) return \"positive\";\n return \"neutral\";\n}\n\nfunction extractContradictsTags(body: string): Set<string> {\n const out = new Set<string>();\n for (const m of body.matchAll(/#contradicts:([\\w-]+)/g)) {\n if (m[1]) out.add(m[1]);\n }\n return out;\n}\n\nfunction countIntersection<T>(a: Set<T>, b: Set<T>): number {\n let n = 0;\n for (const x of a) if (b.has(x)) n++;\n return n;\n}\n\nasync function trySemanticSimilarities(\n ctx: HaiveContext,\n target: LoadedMemory,\n others: LoadedMemory[],\n): Promise<Map<string, number> | null> {\n let mod: typeof import(\"@hivelore/embeddings\");\n try {\n mod = await import(\"@hivelore/embeddings\");\n } catch {\n return null;\n }\n const result = await mod.semanticSearch(\n ctx.paths,\n target.memory.body,\n { limit: others.length },\n );\n if (!result) return null;\n const map = new Map<string, number>();\n for (const hit of result.hits) map.set(hit.id, hit.score);\n return map;\n}\n","import { pathsOverlap } from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\nimport { antiPatternsCheck, isHaiveOwnedPath, type AntiPatternsWarning } from \"./anti-patterns-check.js\";\nimport { memForFiles } from \"./mem-for-files.js\";\nimport { memVerify } from \"./mem-verify.js\";\n\nexport const PreCommitCheckInputSchema = {\n diff: z\n .string()\n .optional()\n .describe(\n \"Raw unified diff text to scan. If omitted, only `paths` is used. \" +\n \"When called from a pre-commit hook, pipe the output of `git diff --cached`.\",\n ),\n paths: z\n .array(z.string())\n .default([])\n .describe(\"Project-relative paths affected by the change. At least one of `diff` or `paths` should be provided.\"),\n block_on: z\n .enum([\"any\", \"high-confidence\", \"never\"])\n .default(\"high-confidence\")\n .describe(\n \"When to set should_block=true: \" +\n \"'any' = any warning blocks; \" +\n \"'high-confidence' = only warnings from authoritative/trusted memories block; \" +\n \"'never' = report only, never block.\",\n ),\n semantic: z\n .boolean()\n .default(true)\n .describe(\"Enable semantic search in anti_patterns_check (requires embeddings index).\"),\n anchored_blocks: z\n .boolean()\n .default(false)\n .describe(\n \"When true, ALSO block a high-confidence anti-pattern (attempt/gotcha) that is anchored to a \" +\n \"touched file AND corroborated by the diff (literal token overlap, or semantic >= 0.45) — not just \" +\n \"very strong semantic matches. Powers the 'anchored' enforcement gate. Config/docs-only commits are \" +\n \"still downgraded. Default false preserves the soft, semantic-only blocking behavior.\",\n ),\n};\n\nexport type PreCommitCheckInput = {\n [K in keyof typeof PreCommitCheckInputSchema]: z.infer<(typeof PreCommitCheckInputSchema)[K]>;\n};\n\nexport interface PreCommitCheckOutput {\n /** True when at least one finding meets the configured block_on threshold. */\n should_block: boolean;\n /** Per-section summary; clients should surface the warnings + reasons to the user. */\n summary: {\n anti_patterns: number;\n blocking_warnings?: number;\n review_warnings?: number;\n info_warnings?: number;\n relevant_memories: number;\n stale_anchors: number;\n };\n warnings: ClassifiedAntiPatternsWarning[];\n /** Memories anchored to the touched files — convention reminders for the change author. */\n relevant_memories: Array<{\n id: string;\n type: string;\n confidence: string;\n body_preview: string;\n }>;\n /** Memories whose anchored paths overlap with the diff AND are now stale — likely outdated knowledge. */\n stale_anchors: Array<{\n id: string;\n paths: string[];\n body_preview: string;\n }>;\n notice?: string;\n}\n\nexport type AntiPatternLevel = \"blocking\" | \"review\" | \"info\";\n\nexport interface ClassifiedAntiPatternsWarning extends AntiPatternsWarning {\n /**\n * blocking = commit gate should fail for the configured threshold;\n * review = plausible but not strong enough to block;\n * info = weak signal, hidden by default in human CLI output.\n */\n level: AntiPatternLevel;\n rationale: string;\n affected_files: string[];\n repair_command: string;\n}\n\n/**\n * One-shot \"should I block this commit?\" check.\n *\n * Combines three signals into a single call agents and git hooks can consume:\n * 1. anti_patterns_check — known gotchas/attempts that match the diff\n * 2. mem_for_files — conventions/decisions anchored to touched files\n * 3. mem_verify — memories whose anchors are stale (knowledge may be wrong)\n *\n * Returns should_block per the configured threshold, plus the raw findings so\n * the caller can render them. CLI wrapper: `hivelore precommit`.\n */\nexport async function preCommitCheck(\n input: PreCommitCheckInput,\n ctx: HaiveContext,\n): Promise<PreCommitCheckOutput> {\n if (!input.diff && input.paths.length === 0) {\n return {\n should_block: false,\n summary: { anti_patterns: 0, relevant_memories: 0, stale_anchors: 0 },\n warnings: [],\n relevant_memories: [],\n stale_anchors: [],\n notice: \"Nothing to check — provide either `diff` or `paths`.\",\n };\n }\n\n // 1. Known anti-patterns\n const apResult = await antiPatternsCheck({\n diff: input.diff,\n paths: input.paths,\n limit: 20,\n semantic: input.semantic,\n }, ctx);\n\n // 2. Relevant conventions/decisions for the touched files\n const relevant = input.paths.length > 0\n ? await memForFiles({ files: input.paths, include_module_contexts: false, track: false }, ctx)\n : { by_anchor: [], by_module: [], by_domain: [], module_contexts: [], inferred_modules: [] };\n // Anchor matches are the most relevant for pre-commit; include module hits as a softer signal.\n const relevantMatches = [...relevant.by_anchor, ...relevant.by_module];\n\n // 3. Verify anchors — surface stale memories that touch these files\n const verifyResult = input.paths.length > 0\n ? await memVerify({ update: false, id: undefined }, ctx)\n : { results: [], summary: { checked: 0, fresh: 0, stale: 0, anchorless_skipped: 0, updated: 0 } };\n // We surface a stale memory when at least one of the verify hits says stale=true.\n // We don't have direct access to the memory's anchored paths from MemVerifyHit, so we rely on\n // mem_for_files to scope these to \"memories that touch our files\".\n const filesTouching = new Set(relevantMatches.map((m) => m.id));\n const staleHits = verifyResult.results.filter((r) => r.stale && filesTouching.has(r.id));\n\n // Determine should_block\n const blockOn = input.block_on;\n const classifiedWarnings = apResult.warnings.map((warning) => classifyWarning(warning, input.paths, input.anchored_blocks));\n const blockingWarnings = classifiedWarnings.filter((w) => w.level === \"blocking\");\n const reviewWarnings = classifiedWarnings.filter((w) => w.level === \"review\");\n const infoWarnings = classifiedWarnings.filter((w) => w.level === \"info\");\n let should_block = false;\n if (blockOn !== \"never\") {\n if (blockOn === \"any\" && (blockingWarnings.length > 0 || reviewWarnings.length > 0 || staleHits.length > 0)) should_block = true;\n if (blockOn === \"high-confidence\" && (blockingWarnings.length > 0 || staleHits.length > 0)) should_block = true;\n }\n\n // Map mem_for_files output to a simpler shape\n const relevant_memories = relevantMatches.slice(0, 8).map((m) => ({\n id: m.id,\n type: m.type,\n confidence: String(m.confidence),\n body_preview: (m.body ?? \"\").split(\"\\n\").slice(0, 4).join(\"\\n\").slice(0, 250),\n }));\n\n return {\n should_block,\n summary: {\n anti_patterns: apResult.warnings.length,\n blocking_warnings: blockingWarnings.length,\n review_warnings: reviewWarnings.length,\n info_warnings: infoWarnings.length,\n relevant_memories: relevant_memories.length,\n stale_anchors: staleHits.length,\n },\n warnings: classifiedWarnings,\n relevant_memories,\n stale_anchors: staleHits.map((r) => {\n const match = relevantMatches.find((m) => m.id === r.id);\n // Intersect the stale memory's anchor paths with the paths the caller provided\n // so the output lists only the touched files that are actually anchored to this memory.\n const overlapping = match\n ? input.paths.filter((p) =>\n match.anchor_paths.some((ap) => ap === p || p.startsWith(ap + \"/\") || ap.startsWith(p + \"/\")),\n )\n : [];\n return {\n id: r.id,\n paths: overlapping.length > 0 ? overlapping : (match ? input.paths : []),\n body_preview: r.reason ?? \"anchored code drifted; verify before relying on this memory\",\n };\n }),\n };\n}\n\nfunction classifyWarning(\n warning: AntiPatternsWarning,\n paths: string[],\n anchoredBlocks = false,\n): ClassifiedAntiPatternsWarning {\n // \"Which files is this warning about?\" — the changed CODE files, never Hivelore's own\n // knowledge/bridge files (a post-init commit stages `.ai/` + bridges alongside the code,\n // and listing `.ai/code-map.json` as the affected file sends the repair command to the\n // wrong place). When the memory is anchored, narrow further to the changed files its\n // anchors actually cover.\n const codeFiles = paths.filter((p) => !p.startsWith(\".ai/\") && !isHaiveOwnedPath(p));\n const anchorHits = (warning.anchor_paths ?? []).length > 0\n ? codeFiles.filter((p) => (warning.anchor_paths ?? []).some((ap) => pathsOverlap(ap, p)))\n : [];\n const affectedFiles = anchorHits.length > 0 ? anchorHits : codeFiles;\n const repairCommand = repairCommandForWarning(warning, affectedFiles);\n const fileDowngrade = fileTypeDowngradeReason(warning, affectedFiles);\n\n if (fileDowngrade) {\n return {\n ...warning,\n level: \"info\",\n rationale: fileDowngrade,\n affected_files: affectedFiles,\n repair_command: repairCommand,\n };\n }\n\n if (warning.reasons.includes(\"sensor\")) {\n if (warning.sensor_severity === \"block\") {\n return {\n ...warning,\n level: \"blocking\",\n rationale: \"deterministic Hivelore sensor with block severity matched the added diff\",\n affected_files: affectedFiles,\n repair_command: repairCommand,\n };\n }\n return {\n ...warning,\n level: \"review\",\n rationale: \"deterministic Hivelore sensor with warn severity matched the added diff\",\n affected_files: affectedFiles,\n repair_command: repairCommand,\n };\n }\n\n if (isBlockingWarning(warning)) {\n if (warning.scope === \"personal\") {\n return {\n ...warning,\n level: \"review\",\n rationale:\n \"personal anti-pattern memories are review guidance unless a deterministic block-severity sensor fires\",\n affected_files: affectedFiles,\n repair_command: repairCommand,\n };\n }\n // Sensor veto applies here too: even a very strong semantic match should not\n // hard-block when the memory's authoritative sensor did not fire. The sensor\n // encodes the exact bad pattern; a non-firing sensor means the diff doesn't\n // contain it, so downgrade to review regardless of the semantic score.\n if (warning.has_sensor && !warning.reasons.includes(\"sensor\")) {\n return {\n ...warning,\n level: \"review\",\n rationale:\n \"memory has a sensor that did not fire — sensor is the authoritative check; strong semantic match alone is insufficient to block\",\n affected_files: affectedFiles,\n repair_command: repairCommand,\n };\n }\n // Sensor-less memories never hard-block, even at semantic >= 0.75. Cosine scores are\n // environment-dependent (fresh model download, runtime, warmup): the v0.29.12 release\n // passed the local gate and hard-blocked on GitHub Actions with the SAME diff and corpus.\n // A gate that answers differently per machine trains agents to bypass it. Deterministic\n // blocking is the sensor's job — propose_sensor is the path to make this memory block.\n return {\n ...warning,\n level: \"review\",\n rationale:\n \"very strong semantic match (>= 0.75) but the memory has no sensor — semantic scores vary \" +\n \"across environments, so this surfaces for review; add a sensor via propose_sensor to block deterministically\",\n affected_files: affectedFiles,\n repair_command: repairCommand,\n };\n }\n\n const hasSemantic = warning.reasons.includes(\"semantic\");\n const semanticScore = warning.semantic_score ?? 0;\n const highConfidence =\n warning.confidence === \"authoritative\" || warning.confidence === \"trusted\";\n\n // Anchored gate: when the caller opts in, a high-confidence anti-pattern that is anchored to a\n // touched file AND corroborated by the diff (literal token overlap, or a moderate semantic match)\n // is precise enough to block. This is what makes \"known bad approaches are blocked before commit\"\n // true for the case it matters most — you are editing the exact file a documented attempt/gotcha\n // warns about, and the diff contains the same idea. Config/docs-only commits already returned\n // above via fileTypeDowngradeReason, so this cannot re-introduce that false-positive class.\n if (\n anchoredBlocks &&\n highConfidence &&\n warning.scope !== \"personal\" &&\n warning.reasons.includes(\"anchor\") &&\n // A literal overlap only corroborates a BLOCK when it is on a token *distinctive*\n // to this gotcha (rare in the corpus). Sharing a common domain word (\"memory\",\n // \"scope\", \"version\") — or a version-bump diff — no longer hard-blocks; it falls\n // through to `review` below. This kills the incidental-token false positives that\n // made agents work for nothing. A moderate semantic match still corroborates.\n (warning.distinctive_literal === true || (hasSemantic && semanticScore >= 0.45))\n ) {\n // Sensor veto: if the memory has a sensor and it did NOT fire, the sensor is the\n // authoritative check for this memory. Broad literal token matching is too noisy\n // to block on its own — the sensor encodes the exact bad pattern. Downgrade to review\n // so the human sees the warning without being hard-blocked on a false positive.\n if (warning.has_sensor && !warning.reasons.includes(\"sensor\")) {\n return {\n ...warning,\n level: \"review\",\n rationale:\n \"memory has a sensor that did not fire — literal match alone is insufficient to block; sensor is the authoritative check\",\n affected_files: affectedFiles,\n repair_command: repairCommand,\n };\n }\n\n // Sensor-less gotcha: anchor + a distinctive shared token (or moderate semantic) proves you are\n // editing the documented file with RELATED terms — NOT that you reintroduced the specific mistake.\n // A distinctive token can be the gotcha's SUBJECT used correctly (e.g. the gotcha \"serializeMemory\n // crashes on undefined\" says *always use serializeMemory()* — a diff that calls it is fine), so\n // token co-occurrence on an edited file is too noisy to hard-block without a deterministic check.\n // Only a STRONG semantic match (>= 0.75) hard-blocks a sensor-less gotcha here; weaker relevance\n // signals surface as review. Add a sensor (propose_sensor) to make such a gotcha block reliably.\n if (!warning.has_sensor && !(hasSemantic && semanticScore >= 0.75)) {\n return {\n ...warning,\n level: \"review\",\n rationale:\n \"sensor-less anti-pattern anchored to a touched file, corroborated only by relevance signals \" +\n \"(shared distinctive token / moderate semantic < 0.75) — surfaced for review, not blocked. \" +\n \"Add a sensor via propose_sensor to make it block deterministically.\",\n affected_files: affectedFiles,\n repair_command: repairCommand,\n };\n }\n\n // Same determinism rule as above: without a sensor, an anchored + strongly-semantic match\n // is still an environment-dependent signal — review, never block.\n return {\n ...warning,\n level: \"review\",\n rationale:\n \"anchored high-confidence match corroborated only by semantic similarity — sensor-less memories \" +\n \"surface for review; add a sensor via propose_sensor to block deterministically (anchored gate)\",\n affected_files: affectedFiles,\n repair_command: repairCommand,\n };\n }\n\n // Sensor veto for review: a memory that carries a deterministic sensor which did NOT fire, and is\n // not anchored to any touched file, is strong evidence the diff does not contain its pattern — the\n // sensor is the authoritative check. Surfacing it as \"review\" is pure noise (this was the bulk of\n // the 11 review hits on a 3-line `: any` diff). Demote to info (hidden in concise output).\n if (warning.has_sensor && !warning.reasons.includes(\"sensor\") && !warning.reasons.includes(\"anchor\")) {\n return {\n ...warning,\n level: \"info\",\n rationale:\n \"memory has a deterministic sensor that did not fire and is not anchored to a touched file — treated as non-violation noise\",\n affected_files: affectedFiles,\n repair_command: repairCommand,\n };\n }\n\n // A bare semantic match (not anchored to a touched file, no distinctive token) needs a stronger\n // score to be worth a human's attention. At 0.45–0.65 against generic text it is mostly noise — and\n // review noise trains agents to ignore the gate. Corroborated matches (anchored or distinctive\n // literal) keep the lower 0.45 bar; everything weaker falls through to \"info\" (hidden by default).\n const corroborated = warning.reasons.includes(\"anchor\") || warning.distinctive_literal === true;\n const semanticReviewFloor = corroborated ? 0.45 : 0.65;\n if (\n (hasSemantic && semanticScore >= semanticReviewFloor) ||\n (highConfidence && warning.reasons.includes(\"anchor\") && warning.reasons.includes(\"literal\"))\n ) {\n return {\n ...warning,\n level: \"review\",\n rationale:\n hasSemantic\n ? \"semantic match is plausible but below blocking threshold\"\n : \"anchored high-confidence memory also matched diff tokens, but no strong semantic proof\",\n affected_files: affectedFiles,\n repair_command: repairCommand,\n };\n }\n\n return {\n ...warning,\n level: \"info\",\n rationale:\n \"weak signal only (literal/anchor/low semantic evidence); surfaced for audit, hidden in concise CLI output\",\n affected_files: affectedFiles,\n repair_command: repairCommand,\n };\n}\n\nfunction isBlockingWarning(warning: AntiPatternsWarning): boolean {\n const highConfidence = warning.confidence === \"authoritative\" || warning.confidence === \"trusted\";\n if (!highConfidence) return false;\n\n // Anchors and lexical matches prove relevance, not violation. A broad diff\n // can touch package files or share common tokens with old gotchas. Require\n // a semantic corroboration strong enough to indicate the same mistake. Scores\n // in the 0.65-0.75 range are still useful review signals, but are too noisy\n // to block commits reliably even when the memory is anchored to a test file.\n if (!warning.reasons.includes(\"semantic\")) return false;\n return (warning.semantic_score ?? 0) >= 0.75;\n}\n\nexport function classifyAntiPatternWarningForTest(\n warning: AntiPatternsWarning,\n paths: string[],\n anchoredBlocks = false,\n): ClassifiedAntiPatternsWarning {\n return classifyWarning(warning, paths, anchoredBlocks);\n}\n\nfunction fileTypeDowngradeReason(\n warning: AntiPatternsWarning,\n paths: string[],\n): string | null {\n if (paths.length === 0) return null;\n if (paths.every((p) => p.startsWith(\".ai/.usage/\") || p === \".ai/.usage/tool-usage.jsonl\")) {\n return \".ai usage logs are local telemetry and never block commits.\";\n }\n\n const docsOnly = paths.every(isDocLikePath);\n if (docsOnly && !hasStrongSemantic(warning)) {\n return \"docs/changelog-only change; anti-pattern is downgraded unless semantic evidence is strong.\";\n }\n\n const configOnly = paths.every(isPackageOrConfigPath);\n // Any non-anchored, non-strongly-semantic warning is suppressed on config/workflow-only commits.\n // Gotchas that happen to share tokens with config file names (npm, install, package.json,\n // hivelore init, workspace:*) would otherwise fire on every dependency bump or workflow change.\n if (configOnly && !warning.reasons.includes(\"anchor\") && !hasStrongSemantic(warning)) {\n return \"package/config-only change; warning has no anchor on these files and no strong semantic match — downgraded to info.\";\n }\n\n // Inverse case: a package/build/tooling gotcha firing on a change that touches NO\n // package/build file. These match by shared tokens (\"install\", \"package\", \"build\")\n // and are almost always false positives on pure source edits.\n const touchesBuildFile = paths.some(isPackageOrConfigPath);\n if (!touchesBuildFile && isBuildScopedWarning(warning) && !warning.reasons.includes(\"anchor\") && !hasStrongSemantic(warning)) {\n return \"build/packaging gotcha, but no package/build file changed — downgraded to info.\";\n }\n\n return null;\n}\n\n/**\n * True when a warning is about build/packaging/tooling concerns — by its tags, or\n * because every path it is anchored to is itself a package/config file.\n */\nfunction isBuildScopedWarning(warning: AntiPatternsWarning): boolean {\n const tags = warning.tags ?? [];\n if (tags.some((t) => BUILD_SCOPED_TAGS.has(t.toLowerCase()))) return true;\n const anchors = warning.anchor_paths ?? [];\n return anchors.length > 0 && anchors.every(isPackageOrConfigPath);\n}\n\nconst BUILD_SCOPED_TAGS = new Set([\n \"npm\", \"pnpm\", \"yarn\", \"publish\", \"install\", \"packaging\", \"package\",\n \"build\", \"tsup\", \"bundler\", \"monorepo\", \"workspace\", \"versioning\", \"version\",\n \"dev-workflow\", \"hotswap\", \"ci\", \"workflow\", \"release\", \"changelog\",\n \"dependencies\", \"deps\", \"dependency\", \"tooling\", \"config\",\n]);\n\nfunction hasStrongSemantic(warning: AntiPatternsWarning): boolean {\n return warning.reasons.includes(\"semantic\") && (warning.semantic_score ?? 0) >= 0.65;\n}\n\nfunction isDocLikePath(file: string): boolean {\n const lower = file.toLowerCase();\n return lower.endsWith(\".md\") ||\n lower.includes(\"changelog\") ||\n lower.startsWith(\"docs/\") ||\n lower.startsWith(\".github/\") && lower.endsWith(\".md\");\n}\n\nfunction isPackageOrConfigPath(file: string): boolean {\n const lower = file.toLowerCase();\n const base = lower.split(\"/\").pop() ?? lower;\n return lower.endsWith(\"package.json\") ||\n lower.endsWith(\"package-lock.json\") ||\n lower.endsWith(\"pnpm-lock.yaml\") ||\n lower.endsWith(\"yarn.lock\") ||\n lower.endsWith(\"bun.lockb\") ||\n lower.endsWith(\".config.ts\") ||\n lower.endsWith(\".config.js\") ||\n isJsonConfigFile(base) ||\n lower.endsWith(\".yml\") ||\n lower.endsWith(\".yaml\") ||\n lower.endsWith(\".toml\") ||\n lower.startsWith(\".github/workflows/\") ||\n lower.startsWith(\".github/\") && lower.endsWith(\".yml\") ||\n // Dotfiles that are pure configuration/tooling — never trigger runtime gotchas\n base === \".gitignore\" ||\n base === \".gitattributes\" ||\n base === \".gitmodules\" ||\n base === \".editorconfig\" ||\n base === \".nvmrc\" ||\n base === \".node-version\" ||\n base === \".npmrc\" ||\n base === \".yarnrc\" ||\n base === \".yarnrc.yml\" ||\n base === \".dockerignore\" ||\n base === \"dockerfile\" ||\n base.startsWith(\"dockerfile.\") ||\n base === \".env.example\" ||\n base === \".env.template\" ||\n lower.endsWith(\".prettierrc\") ||\n lower.endsWith(\".eslintrc\") ||\n lower.endsWith(\".eslintignore\") ||\n lower.endsWith(\".prettierignore\") ||\n lower.endsWith(\".stylelintrc\") ||\n lower.endsWith(\".browserslistrc\");\n}\n\n/**\n * Returns true only for JSON files that are known build/tool configs.\n * Avoids treating application data files (fixtures, translations, schemas) as config.\n */\nfunction isJsonConfigFile(base: string): boolean {\n const knownConfigs = new Set([\n \"tsconfig.json\", \"jsconfig.json\",\n \"deno.json\", \"deno.jsonc\",\n \"nx.json\", \"turbo.json\", \"lerna.json\", \"rush.json\",\n \"jest.config.json\", \"vitest.config.json\", \"babel.config.json\",\n \".babelrc.json\", \".swcrc\", \".mocharc.json\",\n \"renovate.json\", \"dependabot.json\",\n \".prettierrc.json\", \".eslintrc.json\", \".stylelintrc.json\",\n ]);\n if (knownConfigs.has(base)) return true;\n // tsconfig.*.json (e.g. tsconfig.build.json, tsconfig.test.json)\n if (/^tsconfig\\..+\\.json$/.test(base)) return true;\n // .*rc.json (e.g. .eslintrc.json already covered, but be safe)\n if (/^\\.[a-z]+rc\\.json$/.test(base)) return true;\n return false;\n}\n\nfunction repairCommandForWarning(warning: AntiPatternsWarning, paths: string[]): string {\n const targetPath = repairTargetPathForWarning(warning, paths);\n return targetPath\n ? `hivelore briefing --files \"${targetPath}\" --task \"review ${warning.id}\"`\n : `hivelore memory show ${warning.id}`;\n}\n\nfunction repairTargetPathForWarning(warning: AntiPatternsWarning, paths: string[]): string | undefined {\n const usablePaths = paths.filter((p) =>\n !p.startsWith(\".ai/.usage/\") &&\n !p.startsWith(\".ai/.cache/\") &&\n !p.startsWith(\".ai/.runtime/\")\n );\n const anchors = warning.anchor_paths ?? [];\n for (const file of usablePaths) {\n if (anchors.some((anchor) => anchor === file || file.startsWith(`${anchor}/`) || anchor.startsWith(`${file}/`))) {\n return file;\n }\n }\n return usablePaths[0];\n}\n","/**\n * pattern_detect — heuristic memory detector that runs without an LLM.\n *\n * Three signals (no LLM required):\n * 1. CONFIG_CHANGE: git diff shows changes to config files\n * (tsconfig, eslint, prettier, vitest, .env.example, …)\n * → proposes a convention memory with the diff as body.\n *\n * 2. REPEATED_PATH: same file path appears in ≥ N consecutive mem_tried /\n * mem_observe events in the usage log\n * → proposes a gotcha memory anchored to that path.\n *\n * 3. HOT_FILE: a non-config source file appears in mem_save / mem_tried /\n * mem_observe summaries ≥ 3 times in the look-back window\n * → proposes a convention memory (frequent edits signal a pattern).\n *\n * Output is `status: proposed` — auto-promote (Phase 4) or the next\n * get_briefing post_task flow will validate/reject them.\n *\n * Runs entirely from the local filesystem: git, usage log, no network.\n */\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { execSync } from \"node:child_process\";\nimport {\n buildFrontmatter,\n memoryFilePath,\n readUsageEvents,\n serializeMemory,\n} from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\n// ── Constants ──────────────────────────────────────────────────────────────\n\n/** Glob patterns (lowercased) that identify config files. */\nconst CONFIG_PATTERNS = [\n \".eslintrc\", \"eslint.config\", \"prettier.config\", \".prettierrc\",\n \"tsconfig\", \"jsconfig\",\n \"vitest.config\", \"jest.config\",\n \".env.example\", \".env.defaults\",\n \"tailwind.config\", \"vite.config\", \"next.config\",\n \"babel.config\", \"postcss.config\",\n \"renovate.json\", \"dependabot.yml\",\n];\n\n/** Max length of a git diff included in a proposed memory body. */\nconst MAX_DIFF_BYTES = 4096;\n\n/** Threshold: path must appear this many times to trigger a HOT_FILE signal. */\nconst HOT_FILE_MIN = 3;\n\n// ── Input / Output ─────────────────────────────────────────────────────────\n\nexport const PatternDetectInputSchema = {\n since_days: z\n .number()\n .int()\n .min(1)\n .default(7)\n .describe(\"Look-back window in days for both git history and usage log.\"),\n dry_run: z\n .boolean()\n .default(false)\n .describe(\"When true, report matches without writing any memory files.\"),\n scope: z\n .enum([\"personal\", \"team\"])\n .default(\"team\")\n .describe(\"Scope for proposed memories.\"),\n};\n\nexport type PatternDetectInput = {\n [K in keyof typeof PatternDetectInputSchema]: z.infer<(typeof PatternDetectInputSchema)[K]>;\n};\n\nexport type PatternKind = \"config_change\" | \"repeated_path\" | \"hot_file\";\n\nexport interface PatternMatch {\n kind: PatternKind;\n signal: string;\n proposed_type: \"convention\" | \"gotcha\";\n proposed_slug: string;\n proposed_body: string;\n anchor_paths: string[];\n}\n\nexport interface PatternDetectOutput {\n scanned_events: number;\n matches: PatternMatch[];\n /** Number of proposed memories saved (0 if dry_run). */\n saved: number;\n /** IDs of saved memories. */\n saved_ids: string[];\n notice?: string;\n}\n\n// ── Implementation ─────────────────────────────────────────────────────────\n\nexport async function patternDetect(\n input: PatternDetectInput,\n ctx: HaiveContext,\n): Promise<PatternDetectOutput> {\n if (!existsSync(ctx.paths.haiveDir)) {\n return {\n scanned_events: 0, matches: [], saved: 0, saved_ids: [],\n notice: \"No .ai/ directory found. Run 'hivelore init' first.\",\n };\n }\n\n const matches: PatternMatch[] = [];\n\n // ── Signal 1: CONFIG_CHANGE ─────────────────────────────────────────────\n try {\n const changedFiles = gitChangedFiles(ctx.paths.root, input.since_days);\n const configFiles = changedFiles.filter((f) =>\n CONFIG_PATTERNS.some((p) => path.basename(f.toLowerCase()).includes(p)),\n );\n for (const file of configFiles.slice(0, 5)) {\n const diff = gitFileDiff(ctx.paths.root, file, input.since_days);\n if (!diff) continue;\n // Include the nearest parent dir so `cli/vitest.config.ts` and\n // `core/vitest.config.ts` produce distinct slugs instead of colliding.\n const parentDir = path.basename(path.dirname(file));\n const baseName = path.basename(file).replace(/\\.[^.]+$/, \"\");\n const slug = `${parentDir}-${baseName}`\n .replace(/[^a-z0-9]/gi, \"-\")\n .toLowerCase()\n .slice(0, 40);\n matches.push({\n kind: \"config_change\",\n signal: `Config file modified: ${file}`,\n proposed_type: \"convention\",\n proposed_slug: `config-change-${slug}`,\n proposed_body: [\n `# Config change: \\`${file}\\``,\n \"\",\n \"This configuration file was recently modified. The diff below captures the intent.\",\n \"Review and update this memory with the **reason** for the change if known.\",\n \"\",\n \"```diff\",\n diff.slice(0, MAX_DIFF_BYTES),\n \"```\",\n ].join(\"\\n\"),\n anchor_paths: [file],\n });\n }\n } catch { /* git not available or no history — skip */ }\n\n // ── Signals 2 & 3: usage log analysis ──────────────────────────────────\n const events = await readUsageEvents(ctx.paths);\n const cutoff = Date.now() - input.since_days * 24 * 60 * 60 * 1000;\n const recent = events.filter((e) => Date.parse(e.at) >= cutoff);\n\n // Build per-path occurrence counts from writing tools\n const pathCounts = new Map<string, { count: number; tools: Set<string> }>();\n for (const e of recent) {\n if (![\"mem_tried\", \"mem_observe\", \"mem_save\"].includes(e.tool)) continue;\n if (!e.summary) continue;\n // Extract file-like tokens from the summary\n const tokens = e.summary.match(/[^\\s\"'`,;()[\\]{}]+\\.[a-zA-Z]{1,6}/g) ?? [];\n for (const t of tokens) {\n const key = t.toLowerCase();\n const existing = pathCounts.get(key);\n if (existing) {\n existing.count++;\n existing.tools.add(e.tool);\n } else {\n pathCounts.set(key, { count: 1, tools: new Set([e.tool]) });\n }\n }\n }\n\n // Signal 2: REPEATED_PATH — path appears mostly in mem_tried / mem_observe\n for (const [p, { count, tools }] of pathCounts) {\n if (count < HOT_FILE_MIN) continue;\n const isGotchaSignal = tools.has(\"mem_tried\") || tools.has(\"mem_observe\");\n if (!isGotchaSignal) continue;\n const slug = p.replace(/[^a-z0-9]/g, \"-\").replace(/-+/g, \"-\").slice(0, 40);\n matches.push({\n kind: \"repeated_path\",\n signal: `Path '${p}' appears ${count}× in mem_tried/mem_observe events`,\n proposed_type: \"gotcha\",\n proposed_slug: `repeated-issue-${slug}`,\n proposed_body: [\n `# Recurring issue near \\`${p}\\``,\n \"\",\n `This file appeared ${count} times in failed-approach or observation events ` +\n `over the last ${input.since_days} days. ` +\n \"Review the related attempt/gotcha memories and consolidate them into a single authoritative gotcha.\",\n \"\",\n `**Source signals:** ${[...tools].join(\", \")} (${count} events)`,\n ].join(\"\\n\"),\n anchor_paths: [p],\n });\n }\n\n // Signal 3: HOT_FILE — any path appearing ≥ HOT_FILE_MIN times in any writing tool\n for (const [p, { count, tools }] of pathCounts) {\n if (count < HOT_FILE_MIN) continue;\n if (tools.has(\"mem_tried\") || tools.has(\"mem_observe\")) continue; // already covered by Signal 2\n // Only flag non-config source files\n if (CONFIG_PATTERNS.some((cp) => path.basename(p).includes(cp))) continue;\n const slug = p.replace(/[^a-z0-9]/g, \"-\").replace(/-+/g, \"-\").slice(0, 40);\n matches.push({\n kind: \"hot_file\",\n signal: `Path '${p}' referenced ${count}× across mem_save events`,\n proposed_type: \"convention\",\n proposed_slug: `hot-file-${slug}`,\n proposed_body: [\n `# Frequent edits to \\`${p}\\``,\n \"\",\n `This file was referenced ${count} times in memory-saving events over the last ` +\n `${input.since_days} days — a signal that a recurring pattern or convention applies here.`,\n \"\",\n \"**Suggested action:** review recent memories anchored to this path and extract the \" +\n \"common pattern as a named convention.\",\n ].join(\"\\n\"),\n anchor_paths: [p],\n });\n }\n\n if (matches.length === 0) {\n return {\n scanned_events: recent.length,\n matches: [],\n saved: 0,\n saved_ids: [],\n notice: `No patterns detected in the last ${input.since_days} days (${recent.length} events scanned).`,\n };\n }\n\n if (input.dry_run) {\n return { scanned_events: recent.length, matches, saved: 0, saved_ids: [] };\n }\n\n // ── Save proposed memories ──────────────────────────────────────────────\n const savedIds: string[] = [];\n for (const match of matches) {\n try {\n const fm = buildFrontmatter({\n type: match.proposed_type,\n slug: match.proposed_slug,\n scope: input.scope,\n tags: [\"pattern-detect\", match.kind],\n paths: match.anchor_paths,\n status: \"proposed\",\n });\n const file = memoryFilePath(\n ctx.paths,\n fm.scope === \"shared\" ? \"team\" : fm.scope,\n fm.id,\n undefined,\n );\n if (existsSync(file)) continue; // don't overwrite existing\n await mkdir(path.dirname(file), { recursive: true });\n await writeFile(\n file,\n serializeMemory({ frontmatter: fm, body: match.proposed_body }),\n \"utf8\",\n );\n savedIds.push(fm.id);\n } catch { /* skip failures — non-blocking */ }\n }\n\n return {\n scanned_events: recent.length,\n matches,\n saved: savedIds.length,\n saved_ids: savedIds,\n };\n}\n\n// ── Git helpers ────────────────────────────────────────────────────────────\n\nfunction gitChangedFiles(root: string, sinceDays: number): string[] {\n try {\n const out = execSync(\n `git log --name-only --pretty=\"\" --diff-filter=AM --since=\"${sinceDays} days ago\"`,\n { cwd: root, encoding: \"utf8\", timeout: 5000, stdio: [\"ignore\", \"pipe\", \"ignore\"] },\n );\n return [...new Set(out.split(\"\\n\").map((l) => l.trim()).filter(Boolean))];\n } catch {\n return [];\n }\n}\n\nfunction gitFileDiff(root: string, file: string, sinceDays: number): string | null {\n try {\n const out = execSync(\n `git log -p --follow --since=\"${sinceDays} days ago\" -- \"${file}\"`,\n { cwd: root, encoding: \"utf8\", timeout: 5000, stdio: [\"ignore\", \"pipe\", \"ignore\"] },\n );\n if (!out.trim()) return null;\n // Extract only the diff hunks (lines starting with +/- or @@)\n const diffLines = out.split(\"\\n\").filter((l) =>\n l.startsWith(\"+\") || l.startsWith(\"-\") || l.startsWith(\"@@\") || l.startsWith(\"diff\"),\n );\n return diffLines.join(\"\\n\").slice(0, MAX_DIFF_BYTES) || null;\n } catch {\n return null;\n }\n}\n","import { existsSync } from \"node:fs\";\nimport {\n findLexicalConflictPairs,\n findTopicStatusConflictPairs,\n loadMemoriesFromDir,\n planConflictResolution,\n type LoadedMemory,\n} from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\ninterface SuggestedResolution {\n keep_id: string;\n supersede_id: string;\n reason: string;\n /** Copy-paste command that APPLIES the guided supersede (promotes winner, deprecates loser). */\n command: string;\n}\n\n/**\n * Turn a detected pair into a guided action: which memory wins, which is superseded, and the exact\n * command to apply it. Detection without a recommended next step is just noise the team ignores.\n */\nfunction suggestResolution(\n byId: Map<string, LoadedMemory>,\n idA: string,\n idB: string,\n): SuggestedResolution | null {\n const a = byId.get(idA);\n const b = byId.get(idB);\n if (!a || !b) return null;\n const plan = planConflictResolution(a, b);\n return {\n keep_id: plan.keep_id,\n supersede_id: plan.supersede_id,\n reason: plan.reason,\n command: `hivelore memory resolve-conflict ${plan.keep_id} ${plan.supersede_id} --yes`,\n };\n}\n\nexport const MemConflictCandidatesInputSchema = {\n since_days: z\n .number()\n .int()\n .positive()\n .max(3650)\n .default(365)\n .describe(\"Only memories created since N days ago\"),\n types: z\n .array(z.enum([\"decision\", \"architecture\", \"convention\", \"gotcha\"]))\n .default([\"decision\", \"architecture\"])\n .describe(\"Memory types scanned for pairwise lexical overlap\"),\n min_jaccard: z\n .number()\n .min(0)\n .max(1)\n .default(0.45)\n .describe(\"Minimum Jaccard token similarity to surface as a candidate pair\"),\n max_pairs: z\n .number()\n .int()\n .positive()\n .max(100)\n .default(20)\n .describe(\"Cap pairs returned\"),\n max_scan: z\n .number()\n .int()\n .positive()\n .max(2000)\n .default(500)\n .describe(\"Maximum memories sampled for O(n²) scan — excess dropped after chronological sort.\"),\n max_topic_pairs: z\n .number()\n .int()\n .positive()\n .max(100)\n .default(20)\n .describe(\n \"Cap for extra signal: memories sharing the same topic with validated vs rejected status.\",\n ),\n};\n\nexport type MemConflictCandidatesInput = {\n [K in keyof typeof MemConflictCandidatesInputSchema]: z.infer<\n (typeof MemConflictCandidatesInputSchema)[K]\n >;\n};\n\nexport async function memConflictCandidates(\n input: MemConflictCandidatesInput,\n ctx: HaiveContext,\n) {\n if (!existsSync(ctx.paths.memoriesDir)) {\n return {\n pairs: [],\n topic_status_pairs: [],\n scanned: 0,\n truncated: false,\n notice: \"No .ai/memories directory.\",\n };\n }\n\n const all = await loadMemoriesFromDir(ctx.paths.memoriesDir);\n const byId = new Map<string, LoadedMemory>(all.map((m) => [m.memory.frontmatter.id, m]));\n const { pairs, scanned, truncated } = findLexicalConflictPairs(all, {\n sinceDays: input.since_days,\n types: input.types,\n minJaccard: input.min_jaccard,\n maxPairs: input.max_pairs,\n maxScan: input.max_scan,\n });\n const topicStatusPairs = findTopicStatusConflictPairs(all, input.max_topic_pairs);\n\n // Guided supersede: attach the deterministic winner/loser + apply command to every pair.\n const enrichedPairs = pairs.map((p) => ({\n ...p,\n suggested_resolution: suggestResolution(byId, p.id_a, p.id_b),\n }));\n const enrichedTopicStatusPairs = topicStatusPairs.map((p) => ({\n ...p,\n suggested_resolution: suggestResolution(byId, p.id_a, p.id_b),\n }));\n\n const notice =\n pairs.length === 0 && topicStatusPairs.length === 0\n ? \"No lexical or topic-status candidates — widen since_days/types or lower min_jaccard.\"\n : undefined;\n\n return {\n pairs: enrichedPairs,\n topic_status_pairs: enrichedTopicStatusPairs,\n scanned,\n truncated,\n notice,\n };\n}\n","import { resolveProjectInfo } from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\n/** Input is intentionally minimal — callers may pass cwd for multi-root clients. */\nexport const MemResolveProjectInputSchema = {\n cwd: z\n .string()\n .optional()\n .describe(\"Directory used for root discovery when HAIVE_PROJECT_ROOT is unset.\"),\n};\n\nexport type MemResolveProjectInput = {\n [K in keyof typeof MemResolveProjectInputSchema]: z.infer<(typeof MemResolveProjectInputSchema)[K]>;\n};\n\nexport async function memResolveProject(\n input: MemResolveProjectInput,\n _ctx: HaiveContext,\n): Promise<{ info: ReturnType<typeof resolveProjectInfo>; ok: true }> {\n void _ctx;\n return {\n ok: true,\n info: resolveProjectInfo({\n cwd: input.cwd,\n }),\n };\n}\n","import { MemoryTypeSchema, suggestTopicKey } from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const MemSuggestTopicInputSchema = {\n type: MemoryTypeSchema.describe(\"Memory kind — drives the suggested topic family.\"),\n title: z\n .string()\n .min(1)\n .describe(\"Short title or phrase (headers, headings) — turned into slug\"),\n};\n\nexport type MemSuggestTopicInput = {\n [K in keyof typeof MemSuggestTopicInputSchema]: z.infer<(typeof MemSuggestTopicInputSchema)[K]>;\n};\n\nexport async function memSuggestTopic(\n input: MemSuggestTopicInput,\n _ctx: HaiveContext,\n): Promise<{ topic_key: string; family: string; type: string }> {\n void _ctx;\n const suggestion = suggestTopicKey(input.type, input.title);\n return { topic_key: suggestion.topic_key, family: suggestion.family, type: input.type };\n}\n","import { existsSync } from \"node:fs\";\nimport { collectTimelineEntries, loadMemoriesFromDir } from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const MemTimelineInputSchema = {\n memory_id: z.string().optional().describe(\"Seed id — expands via related_ids, topic, anchors\"),\n topic: z\n .string()\n .optional()\n .describe(\"Frontmatter.topic value — chronological list when memory_id omitted\"),\n limit: z\n .number()\n .int()\n .positive()\n .max(100)\n .default(30)\n .describe(\"Max timeline entries returned\"),\n};\n\nexport type MemTimelineInput = {\n [K in keyof typeof MemTimelineInputSchema]: z.infer<(typeof MemTimelineInputSchema)[K]>;\n};\n\nexport async function memTimeline(input: MemTimelineInput, ctx: HaiveContext) {\n if (!existsSync(ctx.paths.memoriesDir)) {\n return { entries: [], total: 0, notice: \"No .ai/memories directory.\" };\n }\n\n const all = await loadMemoriesFromDir(ctx.paths.memoriesDir);\n const { entries, notice } = collectTimelineEntries(all, {\n memoryId: input.memory_id,\n topic: input.topic,\n limit: input.limit,\n });\n return { entries, total: entries.length, notice };\n}\n","import { appendRuntimeJournalEntry } from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const RuntimeJournalAppendInputSchema = {\n message: z.string().min(1).describe(\"Short line to append to the runtime session journal\"),\n kind: z.enum([\"note\", \"session_end\", \"mcp\"]).default(\"note\"),\n tool: z.string().optional().describe(\"When kind=mcp, which tool name (optional)\"),\n};\n\nexport type RuntimeJournalAppendInput = {\n [K in keyof typeof RuntimeJournalAppendInputSchema]: z.infer<\n (typeof RuntimeJournalAppendInputSchema)[K]\n >;\n};\n\nexport async function runtimeJournalAppend(\n input: RuntimeJournalAppendInput,\n ctx: HaiveContext,\n): Promise<{ ok: true; path_hint: string }> {\n await appendRuntimeJournalEntry(ctx.paths, {\n kind: input.kind,\n message: input.message,\n ...(input.tool ? { tool: input.tool } : {}),\n });\n return {\n ok: true,\n path_hint: `${ctx.paths.runtimeDir}/session-journal.ndjson`,\n };\n}\n","import { readRuntimeJournalTail } from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const RuntimeJournalTailInputSchema = {\n limit: z\n .number()\n .int()\n .positive()\n .max(500)\n .default(30)\n .describe(\"Last N journal entries to return\"),\n};\n\nexport type RuntimeJournalTailInput = {\n [K in keyof typeof RuntimeJournalTailInputSchema]: z.infer<\n (typeof RuntimeJournalTailInputSchema)[K]\n >;\n};\n\nexport async function runtimeJournalTail(\n input: RuntimeJournalTailInput,\n ctx: HaiveContext,\n): Promise<{ entries: Awaited<ReturnType<typeof readRuntimeJournalTail>>; empty?: boolean }> {\n const entries = await readRuntimeJournalTail(ctx.paths, input.limit);\n if (entries.length === 0) {\n return { entries: [], empty: true };\n }\n return { entries };\n}\n","import { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const BootstrapProjectArgsSchema = {\n module: z\n .string()\n .optional()\n .describe(\n \"Optional module name to scope the analysis to (writes to .ai/modules/<module>/context.md)\",\n ),\n focus: z\n .string()\n .optional()\n .describe(\"Optional area to emphasize (e.g. 'data layer', 'API surface')\"),\n};\n\nexport type BootstrapProjectArgs = {\n [K in keyof typeof BootstrapProjectArgsSchema]: z.infer<\n (typeof BootstrapProjectArgsSchema)[K]\n >;\n};\n\nconst ROOT_TEMPLATE = `# Project context\n\n## Architecture\n<one or two paragraphs on the high-level architecture>\n\n## Key modules\n- <module-name>: <one line on its purpose>\n- ...\n\n## Conventions\n- <convention>: <why it matters here>\n- ...\n\n## Glossary\n- <term>: <definition in this codebase>\n- ...\n\n## Gotchas\n- <surprising behavior, hidden coupling, or known traps>\n- ...\n`;\n\nconst MODULE_TEMPLATE = `# Module context — {module}\n\n## Purpose\n<what this module is for>\n\n## Public surface\n- <exported symbol>: <one line>\n- ...\n\n## Internals\n<key files / classes / functions and how they connect>\n\n## Conventions specific to this module\n- ...\n\n## Gotchas\n- ...\n`;\n\nexport function bootstrapProjectPrompt(\n args: BootstrapProjectArgs,\n ctx: HaiveContext,\n): { description: string; messages: Array<{ role: \"user\"; content: { type: \"text\"; text: string } }> } {\n const target = args.module\n ? `\\`.ai/modules/${args.module}/context.md\\``\n : \"`.ai/project-context.md`\";\n const template = args.module\n ? MODULE_TEMPLATE.replace(\"{module}\", args.module)\n : ROOT_TEMPLATE;\n const focusLine = args.focus\n ? `\\nEmphasis area for this analysis: **${args.focus}**.\\n`\n : \"\";\n\n const text = `You are bootstrapping a Hivelore shared project context for the team.\n\nProject root: \\`${ctx.paths.root}\\`\nTarget file: ${target}\n${focusLine}\n## What to do\n\n1. Explore the codebase: read the package manifests, top-level directories, build configs, and a representative sample of source files. Do not read every file — pick what gives you the highest signal per file (entry points, config, README if present, main domain models).\n2. Synthesize a concise, high-signal context document. Prefer load-bearing facts over exhaustive enumeration. A new teammate (human or AI) should be able to read it in 5 minutes and feel oriented.\n3. Match the structure of the template below. Keep each section short — link to files instead of repeating large code chunks.\n4. When you are done, call the \\`bootstrap_project_save\\` tool with the full Markdown content. Use \\`overwrite=true\\` only if the file already exists and you intend to replace it.\n\n## Template to fill\n\n\\`\\`\\`markdown\n${template}\\`\\`\\`\n\n## Tips\n\n- Anchor claims to file paths so future readers can verify them.\n- Write what is true *now*, not aspirational. Note open questions explicitly.\n- Skip sections that have nothing meaningful to say rather than padding them.\n`;\n\n return {\n description: args.module\n ? `Bootstrap context for module \"${args.module}\"`\n : \"Bootstrap the root project context\",\n messages: [\n {\n role: \"user\",\n content: { type: \"text\", text },\n },\n ],\n };\n}\n","import { readFile, readdir } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport {\n assessBootstrapState,\n loadCodeMap,\n loadMemoriesFromDir,\n renderBootstrapChecklist,\n type BootstrapAssessment,\n} from \"@hivelore/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const BootstrapRepoArgsSchema = {\n focus: z\n .string()\n .optional()\n .describe(\"Optional area to emphasize first (e.g. 'payments', 'auth').\"),\n};\n\nexport type BootstrapRepoArgs = {\n [K in keyof typeof BootstrapRepoArgsSchema]: z.infer<(typeof BootstrapRepoArgsSchema)[K]>;\n};\n\nasync function currentAssessment(ctx: HaiveContext): Promise<BootstrapAssessment> {\n let projectContextRaw = \"\";\n try { projectContextRaw = await readFile(ctx.paths.projectContext, \"utf8\"); } catch { /* absent */ }\n const memories = existsSync(ctx.paths.memoriesDir)\n ? await loadMemoriesFromDir(ctx.paths.memoriesDir)\n : [];\n const codeMap = await loadCodeMap(ctx.paths);\n let existingModules: string[] = [];\n try {\n const entries = await readdir(ctx.paths.modulesContextDir, { withFileTypes: true });\n existingModules = entries.filter((e) => e.isDirectory()).map((e) => e.name);\n } catch { /* none */ }\n return assessBootstrapState({\n projectContextRaw,\n memories,\n codeFiles: codeMap ? Object.keys(codeMap.files) : [],\n existingModules,\n });\n}\n\nexport async function bootstrapRepoPrompt(\n args: BootstrapRepoArgs,\n ctx: HaiveContext,\n): Promise<{ description: string; messages: Array<{ role: \"user\"; content: { type: \"text\"; text: string } }> }> {\n const assessment = await currentAssessment(ctx);\n const focusLine = args.focus ? `\\nEmphasis first: **${args.focus}**.\\n` : \"\";\n const status =\n assessment.state === \"ready\"\n ? \"The knowledge layer is already READY — verify and stop; do not pad it with generic advice.\"\n : `Current state: **${assessment.state}**. Outstanding gaps:\\n\\n${renderBootstrapChecklist(assessment)}`;\n const areas = assessment.metrics.components.length > 0\n ? assessment.metrics.components.join(\", \")\n : \"(no code-map yet — run `hivelore index code` first)\";\n\n const text = `You are the FIRST agent on this repository. Your job before any substantive coding is to fill\nHivelore's knowledge layer so every later agent (and the commit/enforce gates) can rely on it. This is\nforced by the bootstrap gate: while the layer is incomplete, commits/finish are blocked.\n${focusLine}\nProject root: \\`${ctx.paths.root}\\`\nMain code areas detected: ${areas}\n\n## ${status}\n\n## How to close the gaps (do these in order, then re-check)\n\n1. **Project context** — explore high-signal files (manifests, entry points, build configs, main domain\n models). Synthesize a concise overview and save it with the **\\`bootstrap_project_save\\`** tool. A new\n teammate should be oriented in 5 minutes; link to files instead of pasting big code chunks.\n\n2. **Module contexts** — for each main code area, save a per-module context with\n **\\`bootstrap_project_save\\`** using \\`module=<name>\\` (writes \\`.ai/modules/<name>/context.md\\`).\n\n3. **Anchored memories** — for each main area, capture the team's real, non-obvious knowledge with\n **\\`mem_save\\`** (\\`type\\`: decision | gotcha | convention | architecture) anchored with \\`paths\\`.\n Only record what a capable model could NOT guess from the code — arbitrary repo rules, invariants,\n footguns. Skip generic best practice; the gate's quality floor rejects it.\n\n4. **Sensors (the exhaustive bar)** — for each main area, turn at least one lesson into an enforceable\n guardrail with **\\`propose_sensor\\`**: \\`pattern\\` = the faulty usage, \\`absent\\` = the correct-usage\n marker for \"X without Y\" lessons. Hivelore VALIDATES your proposal (must be silent on the current\n correct code and fire on the bad example) before trusting it to block — if rejected, the verdict\n tells you how to revise, then propose again.\n\n5. **Re-check** — call \\`get_briefing\\` again. When the \\`__bootstrap_required__\\` action_required is gone,\n the layer is READY and the gate will pass.\n\n## Rules\n- Write what is true *now*, not aspirational. Note open questions explicitly.\n- Prefer a few load-bearing facts over exhaustive enumeration.\n- Every memory must be specific to THIS repo; anchor each claim to a file path.\n`;\n\n return {\n description:\n assessment.state === \"ready\"\n ? \"Repo knowledge layer is already ready\"\n : `First-agent bootstrap — ${assessment.gaps.length} gap(s) to close`,\n messages: [{ role: \"user\", content: { type: \"text\", text } }],\n };\n}\n","import { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const PostTaskArgsSchema = {\n task_summary: z\n .string()\n .optional()\n .describe(\"One sentence describing what you just did\"),\n files_touched: z\n .array(z.string())\n .optional()\n .describe(\"Files you created or modified during the task\"),\n};\n\nexport type PostTaskArgs = {\n [K in keyof typeof PostTaskArgsSchema]: z.infer<(typeof PostTaskArgsSchema)[K]>;\n};\n\nexport function postTaskPrompt(\n args: PostTaskArgs,\n ctx: HaiveContext,\n): { description: string; messages: Array<{ role: \"user\"; content: { type: \"text\"; text: string } }> } {\n const taskLine = args.task_summary ? `\\nTask just completed: **${args.task_summary}**` : \"\";\n const filesLine =\n args.files_touched && args.files_touched.length > 0\n ? `\\nFiles touched: ${args.files_touched.map((f) => `\\`${f}\\``).join(\", \")}`\n : \"\";\n\n const text = `You have just finished a task. Before closing this session, take 60 seconds to capture what you learned.\n${taskLine}${filesLine}\n\nProject root: \\`${ctx.paths.root}\\`\n\n## Checklist — answer each question honestly\n\nGo through each item. If the answer is yes, call the corresponding tool immediately.\n\n### 0. Did you read existing code and discover bugs, inconsistencies, or security gaps that weren't in the briefing?\nThis is the most important question. Deep code reading surfaces issues that no memory captures yet.\nExamples of things to look for:\n- A method with an invalid signature (e.g. two \\`@RequestBody\\` on the same handler)\n- A configuration that looks wrong or missing (e.g. webhook path not whitelisted in SecurityConfig)\n- A component scan / DI issue (e.g. a Spring bean not picked up because the package isn't scanned)\n- A DB constraint that will break when you add a new enum value\n- A hardcoded value that should be dynamic (e.g. hardcoded tenant id \"default-tenant\")\n- Anything that will silently break in production\n\n→ If yes, call **\\`mem_save\\`** with \\`type=\"gotcha\"\\`, \\`scope=\"team\"\\`, and **anchor it to the file** with \\`paths\\`.\n This transforms your discovery into institutional knowledge that protects every future agent.\n\n### 1. Did you try an approach that failed?\n→ If yes, call **\\`mem_tried\\`** with:\n - \\`what\\`: the approach you tried (e.g. \"importing gray-matter with ESM dynamic import\")\n - \\`why_failed\\`: why it didn't work\n - \\`instead\\`: what worked instead\n - \\`scope\\`: \"team\" if others will hit the same issue, \"personal\" if specific to your setup\n - \\`paths\\`: the files where the issue manifested\n\n### 2. Did you discover a convention that isn't documented?\n→ If yes, call **\\`mem_save\\`** with \\`type=\"convention\"\\` and \\`scope=\"team\"\\`\n\n### 3. Did you make an architectural decision?\n→ If yes, call **\\`mem_save\\`** with \\`type=\"decision\"\\` and document the WHY (constraints, tradeoffs), not just the what\n\n### 4. Did you hit a non-obvious bug or surprising behavior in a library or framework?\n→ If yes, call **\\`mem_save\\`** with \\`type=\"gotcha\"\\` and anchor it to the relevant file paths\n\n### 5. Did you find that an existing memory is outdated or wrong?\n→ If yes, call **\\`mem_update\\`** with the correct information, or **\\`mem_reject\\`** if it's completely wrong\n\n## Rules\n\n- One memory per insight. Don't cram multiple lessons into one body.\n- Anchor memories to file paths when possible (the \\`paths\\` field) — this enables staleness detection.\n- Prefer \\`scope=\"team\"\\` for anything a teammate or future agent would benefit from.\n- Skip sections where you genuinely have nothing to add. Don't fabricate memories.\n- **Question 0 is not optional** — always scan your exploration history for code-level discoveries.\n\n### 6. Close the session — always\nCall **\\`mem_session_end\\`** with:\n- \\`goal\\`: what you set out to do\n- \\`accomplished\\`: what was actually done (bullet list)\n- \\`discoveries\\`: anything surprising or broken found during this session (leave empty if none)\n- \\`files_touched\\`: the key files you read or modified\n- \\`next_steps\\`: what remains for the next session or a teammate\n- \\`scope\\`: \"team\" if this task affects the whole team, \"personal\" otherwise\n\nThis creates/updates a single rolling recap that **get_briefing automatically surfaces** at the start of every subsequent session — no token waste re-explaining what happened.\n\nCalling \\`mem_session_end\\` also **clears the pending-distill marker** (if any), confirming that this session's learnings have been properly captured rather than left as an auto-recap skeleton.\n\n### 7. Verify the git/release/pipeline exit protocol — always\nRun **\\`hivelore enforce finish\\`** before your final response.\n\nThis executable gate checks the multi-agent git-sync decision:\n- no completed work is left as an uncommitted local diff\n- shippable package changes have a lockstep version bump\n- the release tag \\`vX.Y.Z\\` exists when a version was bumped\n- commits and tags have been pushed\n- the pushed HEAD's GitHub Actions workflow runs have completed successfully when the repo has a GitHub remote\n- agents never run \\`npm publish\\` (publication remains human-owned)\n\nIf it blocks, fix the reported Git/version/tag/push/pipeline issue before telling the developer the task is done.\n\nWhen done, respond with a brief summary: \"Saved N memories: [list of IDs]. Session recap saved. Hivelore finish gate passed; GitHub Actions passed when applicable.\"\n`;\n\n\n return {\n description: \"Post-task reflection: capture what you learned before closing the session\",\n messages: [\n {\n role: \"user\",\n content: { type: \"text\", text },\n },\n ],\n };\n}\n","import { z } from \"zod\";\nimport type { HaiveContext } from \"../context.js\";\n\nexport const ImportDocsArgsSchema = {\n content: z\n .string()\n .describe(\"The documentation content to analyze and import as memories (Markdown, README, ADR, etc.)\"),\n source: z\n .string()\n .optional()\n .describe(\"Origin of the content (file path, URL, or document title) — used to anchor memories\"),\n scope: z\n .enum([\"personal\", \"team\"])\n .default(\"team\")\n .describe(\"Scope to assign to created memories\"),\n dry_run: z\n .boolean()\n .default(false)\n .describe(\"If true, describe what would be saved without actually calling mem_save\"),\n};\n\nexport type ImportDocsArgs = {\n [K in keyof typeof ImportDocsArgsSchema]: z.infer<(typeof ImportDocsArgsSchema)[K]>;\n};\n\nexport function importDocsPrompt(\n args: ImportDocsArgs,\n ctx: HaiveContext,\n): { description: string; messages: Array<{ role: \"user\"; content: { type: \"text\"; text: string } }> } {\n const sourceLine = args.source ? `\\nSource: **${args.source}**` : \"\";\n const dryRunNote = args.dry_run\n ? \"\\n> **DRY RUN** — describe what you would save but do not call any tools.\"\n : \"\";\n\n const text = `You are given documentation to analyze and import into the Hivelore memory system.\n${sourceLine}\nScope: **${args.scope}**\nProject root: \\`${ctx.paths.root}\\`\n${dryRunNote}\n\n## Your task\n\nRead the documentation below and extract actionable memories. For each distinct piece of knowledge:\n\n1. **Identify the memory type** — which category fits best?\n - \\`convention\\` — how things are done here (naming, patterns, workflow)\n - \\`decision\\` — a choice that was made and why (tradeoffs, constraints)\n - \\`gotcha\\` — non-obvious behavior, traps, things that surprise newcomers\n - \\`architecture\\` — structural overview of a system or module\n - \\`glossary\\` — domain terms and their meaning in this project\n\n2. **Determine the anchor** — which files or symbols does this knowledge apply to? List them in \\`paths\\`.\n\n3. **Write a focused body** — one memory = one insight. Do not combine multiple unrelated facts.\n - Start with the key fact or rule\n - Add context: why it matters, when it applies\n - Add examples if helpful\n\n4. **Call \\`mem_save\\`** for each memory (unless dry_run).\n - Set \\`scope=\"${args.scope}\"\\`\n - Set \\`slug\\` to a short kebab-case identifier\n - Set \\`paths\\` to the relevant file paths (extracted from the doc if present)\n\n## Rules\n\n- Skip generic documentation that applies to any project (e.g., \"install with npm install\").\n- Prioritize gotchas, non-obvious decisions, and domain-specific conventions.\n- If the same knowledge is repeated in different sections, save it once.\n- Maximum 10 memories per import — select the most actionable ones.\n\n## Documentation to import\n\n---\n\n${args.content}\n\n---\n\nWhen done, respond with: \"Imported N memories: [list of IDs]\" or \"Nothing actionable found.\"\n`;\n\n return {\n description: \"Import documentation as Hivelore memories\",\n messages: [\n {\n role: \"user\",\n content: { type: \"text\", text },\n },\n ],\n };\n}\n","import { spawnSync } from \"node:child_process\";\nimport { readFile, writeFile, mkdir } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n DEFAULT_AUTO_PROMOTE_RULE,\n buildFrontmatter,\n findProjectRoot,\n getUsage,\n isAutoPromoteEligible,\n isDecaying,\n isStackPackSeed,\n loadCodeMap,\n loadConfig,\n loadMemoriesFromDir,\n loadUsageIndex,\n pullCrossRepoSources,\n resolveHaivePaths,\n resolveManifestFiles,\n serializeMemory,\n trackDependencies,\n verifyAnchor,\n watchContracts,\n} from \"@hivelore/core\";\nimport { BRIDGE_TARGETS, type BridgeTarget } from \"@hivelore/core\";\nimport { ui } from \"../utils/ui.js\";\nimport { applyAutopilotRepairs } from \"../utils/autopilot.js\";\nimport { writeBridgeFiles } from \"../utils/bridge-files.js\";\n\nconst BRIDGE_START = \"<!-- haive:memories-start -->\";\nconst BRIDGE_END = \"<!-- haive:memories-end -->\";\n\ninterface SyncOptions {\n dir?: string;\n quiet?: boolean;\n since?: string;\n verify?: boolean;\n promote?: boolean;\n injectBridge?: boolean;\n bridgeFile?: string;\n bridgeMaxMemories?: string;\n embed?: boolean;\n noCrossRepo?: boolean;\n noDeps?: boolean;\n noContracts?: boolean;\n noBridges?: boolean;\n dryRun?: boolean;\n}\n\nexport function registerSync(program: Command): void {\n program\n .command(\"sync\")\n .description(\n \"Refresh memory state after a git pull or merge.\\n\" +\n \" What it does:\\n\" +\n \" 1. Verifies anchor paths — marks stale if files/symbols moved or deleted\\n\" +\n \" 2. Re-validates previously stale memories that are now fresh\\n\" +\n \" 3. Auto-promotes proposed memories (by usage count or time delay in autopilot)\\n\" +\n \" 4. Auto-refreshes code-map if source files changed\\n\" +\n \" 5. Reports decay warnings for memories unused >90 days\\n\\n\" +\n \" Install git hooks to run sync automatically: hivelore install-hooks\\n\\n\" +\n \" Examples:\\n\" +\n \" hivelore sync\\n\" +\n \" hivelore sync --dry-run # preview what would change without writing\\n\" +\n \" hivelore sync --since main # also report memories changed since main\\n\" +\n \" hivelore sync --embed # also rebuild embeddings index\\n\",\n )\n .option(\"-d, --dir <dir>\", \"project root\")\n .option(\"--quiet\", \"minimal output (suitable for git hooks)\")\n .option(\n \"--since <ref>\",\n \"git ref/commit to compare against; report memories added/modified/removed since\",\n )\n .option(\"--no-verify\", \"skip the anchor verification step\")\n .option(\"--no-promote\", \"skip the auto-promotion step\")\n .option(\n \"--inject-bridge\",\n \"refresh CLAUDE.md + AGENTS.md Hivelore managed blocks (or --bridge-file legacy custom injection)\",\n )\n .option(\"--bridge-file <path>\", \"bridge file to inject into (default: CLAUDE.md)\")\n .option(\"--bridge-max-memories <n>\", \"max memories to inject into bridge file\", \"5\")\n .option(\"--embed\", \"rebuild embeddings index after sync (requires @haive/embeddings)\")\n .option(\"--no-cross-repo\", \"skip cross-repo memory pull even if crossRepoSources is configured\")\n .option(\"--no-deps\", \"skip dependency version tracking\")\n .option(\"--no-contracts\", \"skip contract file diff checking\")\n .option(\"--no-bridges\", \"skip auto-refresh of existing native agent bridge files (.cursor/rules, .clinerules, …)\")\n .option(\"--dry-run\", \"report what would change without writing any files\")\n .action(async (opts: SyncOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.memoriesDir)) {\n if (!opts.quiet) ui.warn(`No .ai/memories at ${root}. Run \\`hivelore init\\` first.`);\n process.exitCode = 1;\n return;\n }\n\n const log = (msg: string): void => {\n if (!opts.quiet) console.log(msg);\n };\n\n const config = await loadConfig(paths);\n const autoApproveDelayHours = config.autoApproveDelayHours ?? null;\n const autoPromoteMinReads = config.autoPromoteMinReads ?? DEFAULT_AUTO_PROMOTE_RULE.minReads;\n const autoRepair = config.autoRepair ?? {};\n\n const dryRun = opts.dryRun === true;\n if (dryRun) log(ui.yellow(\"(dry run — no files will be written)\"));\n\n let staleMarked = 0;\n let revalidated = 0;\n let promoted = 0;\n let autoApproved = 0;\n\n if (opts.verify !== false) {\n const memories = await loadMemoriesFromDir(paths.memoriesDir);\n for (const { memory, filePath } of memories) {\n // session_recap records historical context — staleness doesn't apply.\n // If one was incorrectly stale-marked by a prior sync, auto-revalidate it now.\n if (memory.frontmatter.type === \"session_recap\") {\n if (memory.frontmatter.status === \"stale\") {\n if (!dryRun) {\n await writeFile(\n filePath,\n serializeMemory({\n frontmatter: {\n ...memory.frontmatter,\n status: \"validated\",\n stale_reason: null,\n verified_at: new Date().toISOString(),\n },\n body: memory.body,\n }),\n \"utf8\",\n );\n }\n revalidated++;\n }\n continue;\n }\n const isAnchored =\n memory.frontmatter.anchor.paths.length > 0 ||\n memory.frontmatter.anchor.symbols.length > 0;\n if (!isAnchored) continue;\n\n const result = await verifyAnchor(memory, { projectRoot: root });\n const verifiedAt = new Date().toISOString();\n\n if (result.stale) {\n if (memory.frontmatter.status !== \"stale\") {\n if (!dryRun) {\n await writeFile(\n filePath,\n serializeMemory({\n frontmatter: {\n ...memory.frontmatter,\n status: \"stale\",\n verified_at: verifiedAt,\n stale_reason: result.reason,\n },\n body: memory.body,\n }),\n \"utf8\",\n );\n }\n staleMarked++;\n }\n } else if (memory.frontmatter.status === \"stale\") {\n if (!dryRun) {\n await writeFile(\n filePath,\n serializeMemory({\n frontmatter: {\n ...memory.frontmatter,\n status: \"validated\",\n verified_at: verifiedAt,\n stale_reason: null,\n },\n body: memory.body,\n }),\n \"utf8\",\n );\n }\n revalidated++;\n }\n }\n }\n\n if (opts.promote !== false) {\n const memories = await loadMemoriesFromDir(paths.memoriesDir);\n const usage = await loadUsageIndex(paths);\n const nowMs = Date.now();\n for (const { memory, filePath } of memories) {\n const fm = memory.frontmatter;\n if (fm.type === \"session_recap\") continue;\n\n // Usage-based auto-promotion (existing logic, threshold from config)\n if (\n isAutoPromoteEligible(fm, getUsage(usage, fm.id), {\n minReads: autoPromoteMinReads,\n maxRejections: DEFAULT_AUTO_PROMOTE_RULE.maxRejections,\n })\n ) {\n if (!dryRun) {\n await writeFile(\n filePath,\n serializeMemory({ frontmatter: { ...fm, status: \"validated\" }, body: memory.body }),\n \"utf8\",\n );\n }\n promoted++;\n continue;\n }\n\n // Time-based auto-approve: proposed memories older than N hours → validated\n if (\n autoApproveDelayHours !== null &&\n fm.status === \"proposed\" &&\n fm.scope === \"team\"\n ) {\n const ageHours =\n (nowMs - new Date(fm.created_at).getTime()) / (1000 * 60 * 60);\n if (ageHours >= autoApproveDelayHours) {\n if (!dryRun) {\n await writeFile(\n filePath,\n serializeMemory({\n frontmatter: {\n ...fm,\n status: \"validated\",\n verified_at: new Date().toISOString(),\n },\n body: memory.body,\n }),\n \"utf8\",\n );\n }\n autoApproved++;\n }\n }\n }\n }\n\n if (!dryRun && (config.autopilot || autoRepair.context || autoRepair.corpus)) {\n const repairs = await applyAutopilotRepairs(root, paths, {\n applyContext: autoRepair.context ?? config.autopilot,\n applyCorpus: autoRepair.corpus ?? config.autopilot,\n applyCodeMap: false,\n applyCodeSearch: false,\n });\n for (const repair of repairs) log(ui.dim(`autopilot: ${repair.message}`));\n }\n\n const sinceReport = opts.since ? collectSinceChanges(root, opts.since) : null;\n\n const draftMemories = (await loadMemoriesFromDir(paths.memoriesDir)).filter(\n (m) => m.memory.frontmatter.status === \"draft\",\n );\n const draftCount = draftMemories.length;\n\n const autoApprovedNote = autoApproved > 0 ? ` · ${autoApproved} auto-approved` : \"\";\n log(\n `${ui.dim(\"sync:\")} ${staleMarked} stale · ${revalidated} revalidated · ${promoted} promoted${autoApprovedNote}${sinceReport ? ` · ${sinceReport.added.length}+/${sinceReport.modified.length}~/${sinceReport.removed.length}- since ${opts.since}` : \"\"}`,\n );\n if (!opts.quiet && draftCount > 0) {\n log(\n ui.dim(\n `ℹ ${draftCount} memor${draftCount === 1 ? \"y\" : \"ies\"} in draft — run \\`hivelore memory approve <id>\\` to activate or \\`hivelore memory list --status draft\\` to review`,\n ),\n );\n }\n\n if (opts.injectBridge) {\n const maxInject = Math.max(1, Number(opts.bridgeMaxMemories ?? 5));\n if (opts.bridgeFile) {\n await injectBridge(path.resolve(opts.bridgeFile), paths.memoriesDir, maxInject, root, opts.quiet);\n } else if (!dryRun) {\n const res = await writeBridgeFiles(root, paths, {\n targets: [\"claude\", \"agents\"],\n maxMemories: maxInject,\n onlyExisting: true,\n });\n for (const warning of res.warnings) ui.warn(`bridge refresh failed: ${warning}`);\n const touched = res.created.length + res.updated.length;\n if (touched > 0) {\n log(ui.dim(`bridges: refreshed ${touched} instruction bridge file(s)`));\n }\n } else {\n const res = await writeBridgeFiles(root, paths, {\n targets: [\"claude\", \"agents\"],\n maxMemories: maxInject,\n onlyExisting: true,\n dryRun,\n });\n for (const warning of res.warnings) ui.warn(`bridge refresh failed: ${warning}`);\n const touched = res.created.length + res.updated.length;\n if (touched > 0) {\n log(ui.dim(`bridges: would refresh ${touched} instruction bridge file(s)`));\n }\n }\n }\n\n // ── Auto-refresh existing native bridges (keep reach configs fresh) ─────\n // Refresh only files that already exist on disk, so a pull/merge never leaves\n // stale native bridge configs behind and never creates surprise files.\n if (opts.noBridges !== true) {\n try {\n const res = await writeBridgeFiles(root, paths, {\n targets: BRIDGE_TARGETS,\n onlyExisting: true,\n dryRun,\n });\n const touched = res.created.length + res.updated.length;\n for (const warning of res.warnings) ui.warn(`bridge refresh failed: ${warning}`);\n if (touched > 0) {\n log(\n ui.dim(\n `bridges: ${dryRun ? \"would refresh\" : \"refreshed\"} ${touched} native bridge file(s)` +\n (res.unchanged.length > 0 ? ` · ${res.unchanged.length} unchanged` : \"\") +\n (res.skipped.length > 0 ? ` · ${res.skipped.length} skipped` : \"\"),\n ),\n );\n }\n } catch (err) {\n if (!opts.quiet) ui.warn(`bridge refresh failed: ${String(err)}`);\n }\n }\n\n if (sinceReport && !opts.quiet) {\n if (sinceReport.added.length > 0) {\n log(ui.bold(\"\\nNew memories:\"));\n for (const f of sinceReport.added) log(` + ${f}`);\n }\n if (sinceReport.modified.length > 0) {\n log(ui.bold(\"\\nModified:\"));\n for (const f of sinceReport.modified) log(` ~ ${f}`);\n }\n if (sinceReport.removed.length > 0) {\n log(ui.bold(\"\\nRemoved:\"));\n for (const f of sinceReport.removed) log(` - ${f}`);\n }\n }\n\n // Decay report: memories not read in >90 days\n if (!opts.quiet) {\n const allForDecay = await loadMemoriesFromDir(paths.memoriesDir);\n const usageForDecay = await loadUsageIndex(paths);\n const decaying = allForDecay.filter(({ memory }) => {\n const fm = memory.frontmatter;\n if (fm.status === \"rejected\" || fm.status === \"deprecated\" || fm.status === \"stale\") return false;\n const u = getUsage(usageForDecay, fm.id);\n return isDecaying(u, fm.created_at);\n });\n if (decaying.length > 0) {\n log(ui.yellow(`\\n⚠ ${decaying.length} memor${decaying.length === 1 ? \"y\" : \"ies\"} not read in >90 days (consider reviewing or deprecating):`));\n for (const { memory } of decaying) {\n log(ui.dim(` ${memory.frontmatter.id}`));\n }\n }\n }\n\n // ── Cross-repo pull ────────────────────────────────────────────────────────\n if (opts.noCrossRepo !== true && (config.crossRepoSources ?? []).length > 0) {\n try {\n const crossReports = await pullCrossRepoSources(paths, config, root);\n for (const r of crossReports) {\n const total = r.imported.length + r.updated.length;\n if (total > 0 || r.errors.length > 0) {\n log(\n ui.dim(\n `cross-repo [${r.source}]: ${r.imported.length} imported · ${r.updated.length} updated · ${r.skipped.length} unchanged` +\n (r.errors.length > 0 ? ` · ⚠ ${r.errors.length} error(s)` : \"\"),\n ),\n );\n for (const e of r.errors) ui.warn(` cross-repo error: ${e}`);\n }\n }\n } catch (err) {\n ui.warn(`cross-repo pull failed: ${String(err)}`);\n }\n }\n\n // ── Dependency tracker ─────────────────────────────────────────────────────\n if (opts.noDeps !== true) {\n try {\n const manifestFiles = resolveManifestFiles(root, config.dependencyFiles);\n if (manifestFiles.length > 0) {\n const depResults = await trackDependencies(root, paths.haiveDir, manifestFiles);\n for (const result of depResults) {\n const majorBumps = result.changes.filter((c) => c.isMajorBump);\n const minorChanges = result.changes.filter((c) => !c.isMajorBump);\n if (result.changes.length > 0) {\n log(\n ui.yellow(\n `⚠ dependency changes in ${result.file}: ${majorBumps.length} major bump(s) · ${minorChanges.length} minor change(s)`,\n ),\n );\n for (const c of majorBumps) {\n log(ui.yellow(` MAJOR: ${c.name} ${c.from} → ${c.to}`));\n }\n for (const c of minorChanges) {\n log(ui.dim(` minor: ${c.name} ${c.from} → ${c.to}`));\n }\n // Create a gotcha memory for major bumps\n if (majorBumps.length > 0) {\n const slugParts = result.file.replace(/[^a-z0-9]/gi, \"-\").toLowerCase();\n const slug = `dep-major-bump-${slugParts}-${Date.now().toString(36)}`;\n const depList = majorBumps\n .map((c) => `- 🔴 **${c.name}** : \\`${c.from}\\` → \\`${c.to}\\``)\n .join(\"\\n\");\n const body =\n `## ⚠️ Action required — human confirmation required\\n\\n` +\n `Dependencies in \\`${result.file}\\` changed major version.\\n` +\n `A major version can contain **breaking changes** that affect this project.\\n\\n` +\n `${depList}\\n\\n` +\n `---\\n\\n` +\n `**🚫 Do not modify code autonomously.**\\n\\n` +\n `Inform the developer with this message:\\n\\n` +\n `> *\"I detected that ${majorBumps.map((c) => `\\`${c.name}\\``).join(\", \")} ` +\n `changed major version (${majorBumps.map((c) => `${c.from} → ${c.to}`).join(\", \")}). ` +\n `This can introduce incompatibilities in this project. ` +\n `Do you want me to analyze the impact and propose updates?\"*\\n\\n` +\n `Wait for **explicit confirmation** before acting.\\n\\n` +\n `**Next steps (if confirmed):**\\n` +\n `- Check the CHANGELOG: \\`hivelore memory import-changelog --from node_modules/<pkg>/CHANGELOG.md\\`\\n` +\n `- Verify anchored memories: \\`hivelore memory verify\\``;\n const fm = buildFrontmatter({\n type: \"gotcha\",\n slug,\n scope: \"team\",\n status: \"validated\",\n tags: [\"dependency\", \"breaking-change\", \"auto-generated\", \"requires-human-approval\"],\n paths: [result.file],\n topic: `dep-bump-${slugParts}`,\n });\n if (!dryRun) {\n const teamDir = path.join(paths.memoriesDir, \"team\");\n await mkdir(teamDir, { recursive: true });\n await writeFile(\n path.join(teamDir, `${fm.id}.md`),\n serializeMemory({ frontmatter: { ...fm, requires_human_approval: true }, body }),\n \"utf8\",\n );\n }\n log(ui.yellow(` → memory${dryRun ? \" would be\" : \"\"} created: ${fm.id}`));\n }\n }\n }\n }\n } catch (err) {\n ui.warn(`dependency tracker failed: ${String(err)}`);\n }\n }\n\n // ── Contract watcher ───────────────────────────────────────────────────────\n if (opts.noContracts !== true && (config.contractFiles ?? []).length > 0) {\n try {\n const diffs = await watchContracts(root, paths.haiveDir, config.contractFiles!);\n for (const diff of diffs) {\n const breaking = diff.changes.filter((c) => c.severity === \"breaking\");\n const additive = diff.changes.filter((c) => c.severity === \"additive\");\n log(\n ui.yellow(\n `⚠ contract changed [${diff.contract}]: ${breaking.length} breaking · ${additive.length} additive`,\n ),\n );\n for (const c of diff.changes) {\n const icon = c.severity === \"breaking\" ? \"🔴\" : c.severity === \"additive\" ? \"🟢\" : \"🟡\";\n log(` ${icon} ${c.description}`);\n }\n // Create a gotcha memory for breaking contract changes\n if (breaking.length > 0) {\n const slug = `contract-breaking-${diff.contract.replace(/[^a-z0-9]/gi, \"-\").toLowerCase()}-${Date.now().toString(36)}`;\n const breakingList = breaking.map((c) => `- 🔴 **${c.kind}** : ${c.description}`).join(\"\\n\");\n const addList = additive.length > 0\n ? `\\n\\n### Non-breaking changes (additive)\\n` +\n additive.map((c) => `- 🟢 ${c.description}`).join(\"\\n\")\n : \"\";\n const body =\n `## ⚠️ Action required — human confirmation required\\n\\n` +\n `Contract **\\`${diff.contract}\\`** (\\`${diff.file}\\`) was modified.\\n` +\n `**Breaking changes** were detected — this project may consume that contract.\\n\\n` +\n `${breakingList}${addList}\\n\\n` +\n `---\\n\\n` +\n `**🚫 Do not modify code autonomously.**\\n\\n` +\n `Inform the developer with this message:\\n\\n` +\n `> *\"I detected that contract \\`${diff.contract}\\` changed: ` +\n `${breaking.length} breaking change(s) detected. ` +\n `This project may depend on that contract. ` +\n `Do you want me to analyze the impact and propose updates?\"*\\n\\n` +\n `Wait for **explicit confirmation** before acting.\\n\\n` +\n `**Next steps (if confirmed):**\\n` +\n `- Search usages: \\`hivelore memory for-files <affected files>\\`\\n` +\n `- Check related memories: \\`hivelore memory search ${diff.contract}\\``;\n const fm = buildFrontmatter({\n type: \"gotcha\",\n slug,\n scope: \"team\",\n status: \"validated\",\n tags: [\"api-contract\", \"breaking-change\", diff.contract, \"auto-generated\", \"requires-human-approval\"],\n paths: [diff.file],\n topic: `contract-breaking-${diff.contract}`,\n });\n if (!dryRun) {\n const teamDir = path.join(paths.memoriesDir, \"team\");\n await mkdir(teamDir, { recursive: true });\n await writeFile(\n path.join(teamDir, `${fm.id}.md`),\n serializeMemory({ frontmatter: { ...fm, requires_human_approval: true }, body }),\n \"utf8\",\n );\n }\n log(ui.yellow(` → memory${dryRun ? \" would be\" : \"\"} created: ${fm.id}`));\n }\n }\n } catch (err) {\n ui.warn(`contract watcher failed: ${String(err)}`);\n }\n }\n\n // ── Auto-refresh code-map if source files changed since it was generated ──\n const existingMap = await loadCodeMap(paths);\n if (!dryRun && !existingMap && (config.autopilot || autoRepair.codeMap)) {\n try {\n const { buildCodeMap, saveCodeMap } = await import(\"@hivelore/core\");\n log(ui.dim(\"code-map: missing — building index…\"));\n const newMap = await buildCodeMap(root);\n await saveCodeMap(paths, newMap);\n log(ui.dim(`code-map: built (${Object.keys(newMap.files).length} files)`));\n } catch {\n // Non-fatal — code-map refresh is best-effort\n }\n } else if (existingMap) {\n const mapAge = new Date(existingMap.generated_at).getTime();\n // Check if any tracked source files are newer than the map\n const gitResult = spawnSync(\n \"git\",\n [\n \"diff\",\n \"--name-only\",\n \"--diff-filter=ACMR\",\n `@{${new Date(mapAge).toISOString()}}..HEAD`,\n \"--\",\n \"*.ts\", \"*.tsx\", \"*.js\", \"*.jsx\",\n \"*.java\", \"*.kt\",\n \"*.py\",\n \"*.go\",\n \"*.rs\",\n \"*.cs\",\n \"*.php\",\n ],\n { cwd: root, encoding: \"utf8\" },\n );\n const changedSourceFiles = (gitResult.stdout ?? \"\").trim();\n if (changedSourceFiles.length > 0) {\n if (!dryRun) {\n try {\n const { buildCodeMap, saveCodeMap } = await import(\"@hivelore/core\");\n log(ui.dim(\"code-map: source files changed — refreshing index…\"));\n const newMap = await buildCodeMap(root);\n await saveCodeMap(paths, newMap);\n log(ui.dim(`code-map: refreshed (${Object.keys(newMap.files).length} files)`));\n } catch {\n // Non-fatal — code-map refresh is best-effort\n }\n } else {\n log(ui.dim(\"code-map: source files changed — would refresh index (skipped in dry-run)\"));\n }\n }\n }\n\n // --embed or autopilot autoRepair.codeSearch: rebuild embeddings index after sync\n if (!dryRun && (opts.embed || autoRepair.codeSearch)) {\n try {\n const { Embedder, rebuildCodeIndex, rebuildIndex } = await import(\"@hivelore/embeddings\");\n log(ui.dim(\"embed: rebuilding index…\"));\n const embedder = await Embedder.create();\n const { report } = await rebuildIndex(paths, embedder);\n const { report: codeReport } = await rebuildCodeIndex(paths, embedder);\n log(\n ui.dim(\n `embed: memory index rebuilt (${report.added} added, ${report.updated} updated, ${report.removed} removed)`,\n ),\n );\n log(\n ui.dim(\n `embed: code index rebuilt (${codeReport.total} symbols, ${codeReport.added} added, ${codeReport.updated} updated, ${codeReport.removed} removed)`,\n ),\n );\n } catch {\n ui.warn(\"--embed: @hivelore/embeddings not available or index build failed. Run `hivelore embeddings index` manually.\");\n }\n }\n });\n}\n\n/** First meaningful line of a memory body, condensed to a single bridge-friendly summary. */\nfunction bridgeSummaryLine(body: string): string {\n const firstLine = body\n .split(\"\\n\")\n .map((l) => l.replace(/^#+\\s*/, \"\").trim()) // strip markdown heading markers\n .find((l) => l.length > 0) ?? \"\";\n const oneLine = firstLine.replace(/\\s+/g, \" \");\n return oneLine.length > 140 ? oneLine.slice(0, 137) + \"…\" : oneLine;\n}\n\nasync function injectBridge(\n bridgeFile: string,\n memoriesDir: string,\n maxMemories: number,\n root: string,\n quiet?: boolean,\n): Promise<void> {\n if (!existsSync(memoriesDir)) return;\n\n const all = await loadMemoriesFromDir(memoriesDir);\n const top = all\n .filter(({ memory }) => {\n const s = memory.frontmatter.status;\n if (memory.frontmatter.type === \"session_recap\") return false;\n // Generic stack-pack seeds are background context, not repo-specific\n // breadcrumbs — keep them out of the always-loaded bridge.\n if (isStackPackSeed(memory.frontmatter)) return false;\n return s === \"validated\" || s === \"proposed\";\n })\n .sort((a, b) => {\n const score = (m: typeof a) => {\n const s = m.memory.frontmatter.status;\n return (s === \"validated\" ? 2 : 1);\n };\n return score(b) - score(a);\n })\n .slice(0, maxMemories);\n\n // One line per memory: the bridge is a table of contents, not the full corpus.\n // Agents pull the full body on demand via get_briefing / mem_get.\n const block = top\n .map((m) => {\n const fm = m.memory.frontmatter;\n const unverified = fm.status === \"proposed\" ? \" [UNVERIFIED]\" : \"\";\n return `- \\`${fm.id}\\` (${fm.scope}/${fm.type})${unverified} — ${bridgeSummaryLine(m.memory.body)}`;\n })\n .join(\"\\n\");\n\n const injected =\n `${BRIDGE_START}\\n` +\n `<!-- AUTO-GENERATED by hivelore sync --inject-bridge — do not edit between these markers -->\\n` +\n `<!-- Top memories — call get_briefing / mem_get for the full body. -->\\n\\n` +\n block +\n `\\n\\n${BRIDGE_END}`;\n\n const fileExists = existsSync(bridgeFile);\n let existing = fileExists ? await readFile(bridgeFile, \"utf8\") : \"\";\n // Normalize line endings to avoid \\r\\n accumulation\n existing = existing.replace(/\\r\\n/g, \"\\n\");\n\n const startIdx = existing.indexOf(BRIDGE_START);\n const endIdx = existing.indexOf(BRIDGE_END);\n\n // Detect partial markers — safer to abort than silently corrupt the file\n if (startIdx !== -1 && endIdx === -1) {\n ui.warn(`${path.relative(root, bridgeFile)}: found ${BRIDGE_START} without ${BRIDGE_END}. Fix the file manually before running --inject-bridge.`);\n return;\n }\n if (startIdx === -1 && endIdx !== -1) {\n ui.warn(`${path.relative(root, bridgeFile)}: found ${BRIDGE_END} without ${BRIDGE_START}. Fix the file manually before running --inject-bridge.`);\n return;\n }\n\n let updated: string;\n if (startIdx !== -1 && endIdx !== -1 && endIdx > startIdx) {\n updated = existing.slice(0, startIdx) + injected + existing.slice(endIdx + BRIDGE_END.length);\n } else {\n if (!fileExists && !quiet) {\n ui.info(`Creating ${path.relative(root, bridgeFile)} with hivelore memory block.`);\n }\n updated = existing + (existing.endsWith(\"\\n\") ? \"\" : \"\\n\") + \"\\n\" + injected + \"\\n\";\n }\n\n await writeFile(bridgeFile, updated, \"utf8\");\n if (!quiet) {\n console.log(\n ui.dim(`bridge: injected ${top.length} memor${top.length === 1 ? \"y\" : \"ies\"} into ${path.relative(root, bridgeFile)}`),\n );\n }\n}\n\ninterface SinceReport {\n added: string[];\n modified: string[];\n removed: string[];\n}\n\nfunction collectSinceChanges(root: string, ref: string): SinceReport | null {\n const result = spawnSync(\n \"git\",\n [\"-C\", root, \"diff\", \"--name-status\", \"--diff-filter=AMD\", `${ref}...HEAD`, \"--\", \".ai/memories\"],\n { encoding: \"utf8\" },\n );\n if (result.status !== 0) return null;\n\n const report: SinceReport = { added: [], modified: [], removed: [] };\n for (const line of result.stdout.split(\"\\n\")) {\n const [status, ...rest] = line.split(\"\\t\");\n const file = rest.join(\"\\t\").trim();\n if (!file) continue;\n if (status === \"A\") report.added.push(file);\n else if (status === \"M\") report.modified.push(file);\n else if (status === \"D\") report.removed.push(file);\n }\n return report;\n}\n","import { createHash } from \"node:crypto\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Command, Option } from \"commander\";\nimport {\n buildFrontmatter,\n suggestSensorSeed,\n findProjectRoot,\n inferModulesFromPaths,\n loadConfig,\n loadMemoriesFromDir,\n memoryFilePath,\n resolveHaivePaths,\n serializeMemory,\n type MemoryFrontmatter,\n type MemoryScope,\n type MemoryType,\n} from \"@hivelore/core\";\nimport { applyAutopilotRepairs } from \"../utils/autopilot.js\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface AddOptions {\n type: MemoryType;\n slug?: string;\n title?: string;\n scope?: MemoryScope;\n module?: string;\n tags?: string;\n domain?: string;\n author?: string;\n paths?: string;\n files?: string;\n symbols?: string;\n commit?: string;\n body?: string;\n bodyFile?: string;\n topic?: string;\n activationKeyword?: string;\n activationGlob?: string;\n activationAlways?: boolean;\n dir?: string;\n}\n\nexport function registerMemoryAdd(memory: Command): void {\n memory\n .command(\"save\")\n .alias(\"add\")\n .description(\n \"Save a piece of knowledge as a persistent memory. Mirrors MCP mem_save. Alias: add.\\n\\n\" +\n \" Memory types:\\n\" +\n \" skill — reusable procedure/playbook agents follow for a recurring task (e.g. deploy, review)\\n\" +\n \" convention — how things are done here (naming, patterns, tooling)\\n\" +\n \" decision — a choice made and WHY (tradeoffs, constraints)\\n\" +\n \" gotcha — non-obvious behavior that surprises newcomers\\n\" +\n \" architecture — structural overview of a system or module\\n\" +\n \" glossary — domain terms and their meaning in this codebase\\n\" +\n \" attempt — failed approach (prefer 'hivelore memory tried' for better structure)\\n\\n\" +\n \" Tips:\\n\" +\n \" • --paths anchors the memory to source files for staleness detection\\n\" +\n \" • --topic enables upsert: future adds with the same topic update the existing memory\\n\" +\n \" • In autopilot mode, memories go directly to validated with team scope by default\\n\\n\" +\n \" Examples:\\n\" +\n \" hivelore memory add --type gotcha --slug jpa-open-in-view --scope team \\\\\\\\\\n\" +\n \" --paths src/main/resources/application.properties \\\\\\\\\\n\" +\n \" --body \\\"spring.jpa.open-in-view=false is intentional — do not re-enable.\\\"\\n\" +\n \" hivelore memory add --type convention --slug flyway-no-modify --topic flyway \\\\\\\\\\n\" +\n \" --scope team --body \\\"Never modify existing migrations. Create V{n+1}__desc.sql.\\\"\\n\",\n )\n .requiredOption(\"--type <type>\", \"skill | convention | decision | gotcha | architecture | glossary | attempt\")\n .option(\"--slug <slug>\", \"short kebab-case identifier used in the file name (auto-derived from --title/--body when omitted)\")\n .option(\"--title <text>\", \"memory title — becomes the first heading of the body\")\n .option(\"--scope <scope>\", \"personal | team | module (default: config default; team in autopilot)\")\n .option(\"--module <name>\", \"module name (required when scope=module)\")\n .option(\"--tags <csv>\", \"comma-separated tags for easier retrieval\")\n .option(\"--domain <domain>\", \"domain (e.g. transactions)\")\n .option(\"--author <author>\", \"author email or handle\")\n .option(\"--paths <csv>\", \"anchor to source files — used for staleness detection by hivelore sync\")\n .option(\"--files <csv>\", \"alias for --paths (matches the MCP `files` parameter)\")\n .option(\"--symbols <csv>\", \"anchor to specific symbols (class/function names)\")\n .option(\"--commit <sha>\", \"anchor to a specific commit SHA\")\n .option(\"--body <text>\", \"memory body content (Markdown) — overrides --title default body\")\n // Hidden synonym: agents reliably guess `--content` and a bare \"unknown option\" dead-ends\n // them. Kept out of help so `--body` stays the one documented flag.\n .addOption(new Option(\"--content <text>\", \"alias for --body\").hideHelp())\n .option(\"--body-file <path>\", \"read memory body from a Markdown file — for long content\")\n .option(\"--no-auto-tag\", \"disable automatic tag suggestions inferred from anchor paths\")\n .option(\"--topic <key>\", \"stable key for upsert: if a memory with this topic+scope already exists, update it in-place (revision_count++)\")\n .option(\"--activation-keyword <csv>\", \"skill only: comma-separated keywords that trigger progressive disclosure of this skill\")\n .option(\"--activation-glob <csv>\", \"skill only: comma-separated path globs that trigger this skill\")\n .option(\"--activation-always\", \"skill only: always surface this skill (no triggers needed)\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: AddOptions & { autoTag?: boolean; content?: string }) => {\n if (opts.body === undefined && opts.content !== undefined) opts.body = opts.content;\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.haiveDir)) {\n ui.error(`No .ai/ found at ${root}. Run \\`hivelore init\\` first.`);\n process.exitCode = 1;\n return;\n }\n const config = await loadConfig(paths);\n\n const userTags = parseCsv(opts.tags);\n const anchorPaths = parseCsv(opts.paths ?? opts.files);\n // Skill progressive-disclosure triggers (ignored for non-skill types).\n const activation =\n opts.type === \"skill\" &&\n (opts.activationKeyword || opts.activationGlob || opts.activationAlways)\n ? {\n keywords: parseCsv(opts.activationKeyword),\n globs: parseCsv(opts.activationGlob),\n always: Boolean(opts.activationAlways),\n }\n : undefined;\n const autoTagsEnabled = opts.autoTag !== false;\n const inferredTags = autoTagsEnabled ? inferModulesFromPaths(anchorPaths) : [];\n const mergedTags = Array.from(new Set([...userTags, ...inferredTags]));\n\n // ── Anchor path validation ────────────────────────────────────────\n if (anchorPaths.length > 0) {\n const missing = anchorPaths.filter((p) => !existsSync(path.resolve(root, p)));\n if (missing.length > 0) {\n ui.warn(`Anchor path${missing.length > 1 ? \"s\" : \"\"} not found in project:`);\n for (const p of missing) ui.warn(` ✗ ${p}`);\n ui.warn(\n \"Memories anchored to non-existent paths will be immediately marked stale by \\`hivelore sync\\`.\\n\" +\n \" Verify the paths are relative to the project root and the files/directories exist.\",\n );\n }\n }\n\n const title = opts.title ?? titleFromText(opts.slug ?? opts.body ?? opts.topic ?? opts.type);\n const slug = slugify(opts.slug ?? opts.title ?? opts.topic ?? opts.body ?? `${opts.type}-memory`);\n let body: string;\n if (opts.bodyFile !== undefined) {\n if (!existsSync(opts.bodyFile)) {\n ui.error(`--body-file not found: ${opts.bodyFile}`);\n process.exitCode = 1;\n return;\n }\n const fileContent = await readFile(opts.bodyFile, \"utf8\");\n body = normalizeBody(fileContent, title, Boolean(opts.title));\n } else if (opts.body !== undefined) {\n body = normalizeBody(opts.body, title, Boolean(opts.title));\n } else {\n body = `# ${title}\\n\\nTODO — write the memory body.\\n`;\n }\n\n // ── Dedup by content hash ─────────────────────────────────────────\n const scope = opts.scope ?? config.defaultScope ?? \"personal\";\n if (existsSync(paths.memoriesDir)) {\n const incomingHash = createHash(\"sha256\").update(body.trim()).digest(\"hex\").slice(0, 12);\n const allForHash = await loadMemoriesFromDir(paths.memoriesDir);\n const hashDup = allForHash.find(({ memory }) =>\n createHash(\"sha256\").update(memory.body.trim()).digest(\"hex\").slice(0, 12) === incomingHash &&\n memory.frontmatter.scope === scope,\n );\n if (hashDup) {\n ui.error(`Duplicate content detected — identical body already saved as \"${hashDup.memory.frontmatter.id}\".`);\n ui.error(\"Use \\`hivelore memory update\\` to modify it, or change the body to add new information.\");\n process.exitCode = 1;\n return;\n }\n }\n\n // ── Topic upsert ─────────────────────────────────────────────────\n if (opts.topic && existsSync(paths.memoriesDir)) {\n const existing = await loadMemoriesFromDir(paths.memoriesDir);\n const topicMatch = existing.find(({ memory }) =>\n memory.frontmatter.topic === opts.topic &&\n memory.frontmatter.scope === scope &&\n (!opts.module || memory.frontmatter.module === opts.module),\n );\n if (topicMatch) {\n const fm = topicMatch.memory.frontmatter;\n const revisionCount = (fm.revision_count ?? 0) + 1;\n const newFrontmatter: MemoryFrontmatter = {\n ...fm,\n revision_count: revisionCount,\n ...(activation ? { activation } : {}),\n tags: mergedTags.length ? mergedTags : fm.tags,\n anchor: {\n commit: opts.commit ?? fm.anchor.commit,\n paths: anchorPaths.length ? anchorPaths : fm.anchor.paths,\n symbols: parseCsv(opts.symbols).length ? parseCsv(opts.symbols) : fm.anchor.symbols,\n },\n };\n await writeFile(topicMatch.filePath, serializeMemory({ frontmatter: newFrontmatter, body }), \"utf8\");\n ui.success(`Updated (topic upsert) ${path.relative(root, topicMatch.filePath)}`);\n ui.info(`id=${fm.id} revision=${revisionCount}`);\n printSensorLoopHint(opts.type, body, newFrontmatter.anchor.paths, Boolean(newFrontmatter.sensor));\n await runPostMemoryAutopilot(root, paths, config);\n return;\n }\n }\n\n const frontmatter = buildFrontmatter({\n type: opts.type,\n slug,\n scope,\n module: opts.module,\n tags: mergedTags,\n domain: opts.domain,\n author: opts.author,\n paths: anchorPaths,\n symbols: parseCsv(opts.symbols),\n commit: opts.commit,\n topic: opts.topic,\n status: config.defaultStatus === \"validated\" ? \"validated\" : undefined,\n activation,\n });\n // Created already-validated by config (defaultStatus), not by explicit review → mark \"auto\".\n if (frontmatter.status === \"validated\") frontmatter.validated_by = \"auto\";\n\n const file = memoryFilePath(paths, frontmatter.scope, frontmatter.id, frontmatter.module);\n await mkdir(path.dirname(file), { recursive: true });\n\n if (existsSync(file)) {\n ui.error(`Memory already exists at ${file}`);\n process.exitCode = 1;\n return;\n }\n\n // Dedup check: warn if a similar slug already exists\n if (existsSync(paths.memoriesDir)) {\n const existing = await loadMemoriesFromDir(paths.memoriesDir);\n const slugTokens = slug.toLowerCase().split(/[-_\\s]+/).filter(Boolean);\n const similar = existing.filter(({ memory }) => {\n const id = memory.frontmatter.id.toLowerCase();\n return (\n slugTokens.length >= 2 &&\n slugTokens.filter((t) => id.includes(t)).length >= Math.ceil(slugTokens.length * 0.6)\n );\n });\n if (similar.length > 0) {\n ui.warn(`Possible duplicate — similar memories exist: ${similar.map((m) => m.memory.frontmatter.id).join(\", \")}`);\n ui.warn(\"Consider updating one of these with \\`hivelore memory update\\` instead.\");\n }\n }\n\n await writeFile(file, serializeMemory({ frontmatter, body }), \"utf8\");\n ui.success(`Created ${path.relative(root, file)}`);\n ui.info(`id=${frontmatter.id} scope=${frontmatter.scope} status=${frontmatter.status}`);\n printSensorLoopHint(opts.type, body, anchorPaths, Boolean(frontmatter.sensor));\n await runPostMemoryAutopilot(root, paths, config);\n if (inferredTags.length > 0) {\n ui.info(`auto-tagged: ${inferredTags.join(\", \")} (use --no-auto-tag to disable)`);\n }\n\n // Anchorless warning: without paths the memory cannot be verified for staleness\n // (skill, glossary, session_recap are procedure/reference types that don't need code anchors)\n const typeNeedsAnchor = ![\"skill\", \"glossary\", \"session_recap\"].includes(opts.type as string);\n if (anchorPaths.length === 0 && typeNeedsAnchor) {\n ui.warn(\n `This memory has no anchor paths — staleness cannot be detected automatically.` +\n `\\n Add file anchors: hivelore memory update ${frontmatter.id} --paths <file1,file2>`,\n );\n }\n\n // Workflow hint\n if (frontmatter.status === \"validated\") {\n console.log(ui.dim(\"→ autopilot: memory is already validated and active\"));\n } else if (scope === \"personal\") {\n console.log(\n ui.dim(\n `→ next: hivelore memory approve ${frontmatter.id} (activate)` +\n ` | hivelore memory promote ${frontmatter.id} (share with team)`,\n ),\n );\n } else {\n console.log(\n ui.dim(`→ next: hivelore memory approve ${frontmatter.id} (mark as validated)`),\n );\n }\n });\n}\n\nasync function runPostMemoryAutopilot(\n root: string,\n paths: ReturnType<typeof resolveHaivePaths>,\n config: Awaited<ReturnType<typeof loadConfig>>,\n): Promise<void> {\n if (!config.autopilot && config.autoRepair?.corpus !== true) return;\n const repairs = await applyAutopilotRepairs(root, paths, {\n applyConfig: false,\n applyContext: false,\n applyCorpus: true,\n applyCodeMap: false,\n applyCodeSearch: false,\n });\n for (const repair of repairs) {\n ui.info(repair.message);\n }\n}\n\nfunction parseCsv(value: string | undefined): string[] {\n if (!value) return [];\n return value\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n}\n\n/**\n * A gotcha/attempt no longer auto-writes a heuristic warn sensor. It closes its prevention loop only\n * once a sensor is VALIDATED via propose_sensor. Print whether the loop is open and, when a candidate\n * can be derived, a SEED to pre-fill that proposal. (Skip when the memory already carries a sensor.)\n */\nfunction printSensorLoopHint(\n type: MemoryType,\n body: string,\n anchorPaths: string[],\n hasSensor: boolean,\n): void {\n if (hasSensor) return;\n if (type !== \"gotcha\" && type !== \"attempt\") return;\n if (anchorPaths.length === 0) {\n ui.warn(\n \"No --paths given — lesson is briefed but NOT enforced. Add --paths to the file(s) where the \" +\n \"mistake lives, then call propose_sensor (MCP) to close the loop.\",\n );\n return;\n }\n const seed = suggestSensorSeed(body, anchorPaths);\n if (seed) {\n ui.warn(\"Lesson NOT yet enforced — close the loop with a validated sensor via propose_sensor (MCP).\");\n ui.info(\n ` candidate pattern=${JSON.stringify(seed.pattern)}` +\n (seed.absent ? ` absent=${JSON.stringify(seed.absent)}` : \"\") +\n \" — refine, then validate (silent on current code, fires on the bad example).\",\n );\n } else {\n ui.warn(\n \"Lesson NOT yet enforced and no candidate pattern could be derived from the wording. Author a \" +\n \"discriminating sensor (pattern = faulty usage, absent = correct-usage marker) via propose_sensor.\",\n );\n }\n}\n\nfunction normalizeBody(rawBody: string, title: string, titleExplicit: boolean): string {\n const trimmed = rawBody.trim();\n if (/^#{1,3}\\s+\\S/m.test(trimmed)) return `${trimmed}\\n`;\n const heading = titleExplicit ? title : titleFromText(title);\n return [\n `# ${heading}`,\n \"\",\n \"## Guidance\",\n trimmed,\n \"\",\n \"## Why\",\n \"Recorded in Hivelore so future agents can apply this project rule consistently.\",\n \"\",\n ].join(\"\\n\");\n}\n\nfunction titleFromText(value: string): string {\n const cleaned = value\n .replace(/[#*_`>()[\\]{}]/g, \" \")\n .replace(/https?:\\/\\/\\S+/g, \"\")\n .split(/\\s+/)\n .filter(Boolean)\n .slice(0, 8)\n .join(\" \");\n const base = cleaned || \"Memory\";\n return base\n .split(/[-_\\s]+/)\n .filter(Boolean)\n .map((part) => part.slice(0, 1).toUpperCase() + part.slice(1))\n .join(\" \");\n}\n\nfunction slugify(value: string): string {\n const slug = value\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-|-$/g, \"\")\n .slice(0, 60);\n return slug || \"memory\";\n}\n","import { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport { findProjectRoot, resolveHaivePaths, type MemoryScope, type MemoryType } from \"@hivelore/core\";\nimport { loadMemoriesFromDir, type LoadedMemory } from \"../utils/fs.js\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface ListOptions {\n scope?: MemoryScope;\n type?: MemoryType;\n tag?: string;\n module?: string;\n status?: string;\n showRejected?: boolean;\n limit?: string;\n dir?: string;\n}\n\nexport function registerMemoryList(memory: Command): void {\n memory\n .command(\"list\")\n .description(\"List memories with optional filters\")\n .option(\"--scope <scope>\", \"personal | team | module\")\n .option(\"--type <type>\", \"filter by type\")\n .option(\"--tag <tag>\", \"filter by tag\")\n .option(\"--module <name>\", \"filter by module name\")\n .option(\"--status <csv>\", \"filter by status (draft,proposed,validated,stale,rejected,deprecated)\")\n .option(\"--show-rejected\", \"include rejected memories (hidden by default)\")\n .option(\"--limit <n>\", \"max memories to display\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: ListOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.memoriesDir)) {\n ui.error(`No memories directory at ${paths.memoriesDir}. Run \\`hivelore init\\` first.`);\n process.exitCode = 1;\n return;\n }\n\n const all = await loadMemoriesFromDir(paths.memoriesDir);\n const statusFilter = opts.status ? opts.status.split(\",\").map((s) => s.trim()) : null;\n const limit = opts.limit ? Math.max(1, parseInt(opts.limit, 10)) : undefined;\n const filtered = all.filter((m) => {\n if (!matchesFilters(m, opts)) return false;\n const status = m.memory.frontmatter.status;\n if (!opts.showRejected && !statusFilter && status === \"rejected\") return false;\n if (statusFilter && !statusFilter.includes(status)) return false;\n return true;\n });\n\n // Count hidden rejected (not covered by an explicit status filter)\n const hiddenRejectedCount =\n !opts.showRejected && !statusFilter\n ? all.filter(\n (m) => matchesFilters(m, opts) && m.memory.frontmatter.status === \"rejected\",\n ).length\n : 0;\n\n if (filtered.length === 0) {\n ui.info(\"No memories match the filters.\");\n if (hiddenRejectedCount > 0) {\n ui.info(`(${hiddenRejectedCount} rejected hidden — use --show-rejected to include)`);\n }\n return;\n }\n\n const displayed = limit !== undefined ? filtered.slice(0, limit) : filtered;\n const clipped = filtered.length - displayed.length;\n\n for (const { memory: mem, filePath } of displayed) {\n const fm = mem.frontmatter;\n const tagStr = fm.tags.length ? ui.dim(` [${fm.tags.join(\", \")}]`) : \"\";\n const moduleStr = fm.module ? ui.dim(` (${fm.module})`) : \"\";\n const statusBadge = ui.statusBadge(fm.status);\n // Provenance of validation: who/what trusted this memory (human review vs AI vs auto-rule).\n const provLabel: Record<string, string> = { human: \"✋ human\", agent: \"🤖 AI\", auto: \"⚙ auto\" };\n const provStr =\n fm.status === \"validated\" && fm.validated_by\n ? ui.dim(` · ${provLabel[fm.validated_by] ?? fm.validated_by}`)\n : \"\";\n console.log(\n `${ui.bold(fm.id)} ${ui.dim(fm.scope)}/${ui.dim(fm.type)} ${statusBadge}${provStr}${moduleStr}${tagStr}`,\n );\n const title = mem.body.match(/^#\\s+(.+)$/m)?.[1]?.trim();\n if (title && title !== fm.id) console.log(` ${title}`);\n console.log(` ${ui.dim(path.relative(root, filePath))}`);\n }\n const totalLabel = clipped > 0\n ? `\\n${displayed.length} of ${filtered.length} memories shown (use --limit to adjust)`\n : `\\n${filtered.length} memor${filtered.length === 1 ? \"y\" : \"ies\"}`;\n console.log(ui.dim(totalLabel));\n\n // Always show rejected hint when memories are hidden\n if (hiddenRejectedCount > 0) {\n console.log(\n ui.dim(`(${hiddenRejectedCount} rejected hidden — use --show-rejected to include)`),\n );\n }\n\n // Draft hint: scope-aware\n const draftItems = filtered.filter((m) => m.memory.frontmatter.status === \"draft\");\n if (draftItems.length > 0) {\n const hasPersonalDrafts = draftItems.some(\n (m) => m.memory.frontmatter.scope === \"personal\",\n );\n const hasTeamDrafts = draftItems.some(\n (m) => m.memory.frontmatter.scope !== \"personal\",\n );\n let hint = `ℹ ${draftItems.length} in draft — use \\`hivelore memory approve <id>\\` to activate`;\n if (hasPersonalDrafts && !hasTeamDrafts) {\n hint += \" or `hivelore memory promote <id>` to share with team\";\n }\n console.log(ui.dim(hint));\n }\n });\n}\n\nfunction matchesFilters(loaded: LoadedMemory, opts: ListOptions): boolean {\n const fm = loaded.memory.frontmatter;\n if (opts.scope && fm.scope !== opts.scope) return false;\n if (opts.type && fm.type !== opts.type) return false;\n if (opts.tag && !fm.tags.includes(opts.tag)) return false;\n if (opts.module && fm.module !== opts.module) return false;\n return true;\n}\n","export {\n loadMemoriesFromDir,\n loadMemory,\n listMarkdownFilesRecursive,\n type LoadedMemory,\n} from \"@hivelore/core\";\n","import { mkdir, unlink, writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n findProjectRoot,\n memoryFilePath,\n resolveHaivePaths,\n serializeMemory,\n} from \"@hivelore/core\";\nimport { loadMemoriesFromDir } from \"../utils/fs.js\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface PromoteOptions {\n dir?: string;\n}\n\nexport function registerMemoryPromote(memory: Command): void {\n memory\n .command(\"promote <id>\")\n .description(\"Promote a personal memory to team scope (status -> proposed)\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (id: string, opts: PromoteOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.memoriesDir)) {\n ui.error(`No memories directory at ${paths.memoriesDir}. Run \\`hivelore init\\` first.`);\n process.exitCode = 1;\n return;\n }\n\n // Check team/module scope first to give a helpful error\n const teamAndModule = await loadMemoriesFromDir(paths.memoriesDir);\n const alreadyShared = teamAndModule.find(\n (m) =>\n m.memory.frontmatter.id === id &&\n (m.memory.frontmatter.scope === \"team\" || m.memory.frontmatter.scope === \"module\"),\n );\n if (alreadyShared) {\n const fm = alreadyShared.memory.frontmatter;\n ui.warn(\n `\"${id}\" is already in ${fm.scope} scope (status=${fm.status}).`,\n );\n if (fm.status !== \"validated\") {\n ui.info(`→ run \\`hivelore memory approve ${id}\\` to validate it`);\n }\n return;\n }\n\n const all = await loadMemoriesFromDir(paths.personalDir);\n const found = all.find((m) => m.memory.frontmatter.id === id);\n if (!found) {\n ui.error(`No personal memory with id \"${id}\". (Promotion only applies to personal scope.)`);\n process.exitCode = 1;\n return;\n }\n\n const updated = {\n frontmatter: {\n ...found.memory.frontmatter,\n scope: \"team\" as const,\n status: \"proposed\" as const,\n },\n body: found.memory.body,\n };\n\n const newPath = memoryFilePath(paths, \"team\", updated.frontmatter.id);\n await mkdir(path.dirname(newPath), { recursive: true });\n await writeFile(newPath, serializeMemory(updated), \"utf8\");\n await unlink(found.filePath);\n\n ui.success(`Promoted ${id} to team scope (status=proposed)`);\n ui.info(`Now at ${path.relative(root, newPath)}`);\n console.log(ui.dim(`→ next: hivelore memory approve ${id} (validate for team use)`));\n });\n}\n","import { existsSync } from \"node:fs\";\nimport { writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n findProjectRoot,\n resolveHaivePaths,\n serializeMemory,\n} from \"@hivelore/core\";\nimport { loadMemoriesFromDir } from \"../utils/fs.js\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface ApproveOptions {\n all?: boolean;\n pending?: boolean;\n dir?: string;\n}\n\nexport function registerMemoryApprove(memory: Command): void {\n memory\n .command(\"approve [id]\")\n .description(\"Mark a memory as 'validated'. Use --all to bulk-approve all proposed/draft memories.\")\n .option(\"--all\", \"approve all proposed and draft memories at once\")\n .option(\"--pending\", \"approve all memories with status 'proposed'\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (id: string | undefined, opts: ApproveOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.memoriesDir)) {\n ui.error(`No .ai/memories at ${root}.`);\n process.exitCode = 1;\n return;\n }\n\n const all = await loadMemoriesFromDir(paths.memoriesDir);\n\n // Bulk mode\n if (opts.all || opts.pending) {\n const candidates = all.filter((m) => {\n const s = m.memory.frontmatter.status;\n if (opts.all) return s === \"proposed\" || s === \"draft\";\n return s === \"proposed\";\n });\n if (candidates.length === 0) {\n ui.info(opts.all ? \"No draft or proposed memories to approve.\" : \"No proposed memories to approve.\");\n return;\n }\n let count = 0;\n for (const found of candidates) {\n const next = {\n // CLI approval is the human surface → record human provenance.\n frontmatter: { ...found.memory.frontmatter, status: \"validated\" as const, validated_by: \"human\" as const },\n body: found.memory.body,\n };\n await writeFile(found.filePath, serializeMemory(next), \"utf8\");\n count++;\n }\n ui.success(`Approved ${count} memor${count === 1 ? \"y\" : \"ies\"} (status=validated)`);\n return;\n }\n\n // Single mode\n if (!id) {\n ui.error(\"Provide a memory id or use --all / --pending for bulk approval.\");\n process.exitCode = 1;\n return;\n }\n\n const found = all.find((m) => m.memory.frontmatter.id === id);\n if (!found) {\n ui.error(`No memory with id \"${id}\".`);\n process.exitCode = 1;\n return;\n }\n\n const current = found.memory.frontmatter.status;\n if (current === \"validated\") {\n ui.info(`${id} is already validated.`);\n return;\n }\n if (current !== \"proposed\" && current !== \"draft\") {\n ui.warn(`Memory has status \"${current}\"; approve still sets it to validated.`);\n }\n\n const next = {\n frontmatter: { ...found.memory.frontmatter, status: \"validated\" as const, validated_by: \"human\" as const },\n body: found.memory.body,\n };\n await writeFile(found.filePath, serializeMemory(next), \"utf8\");\n ui.success(`Approved ${id} (status=validated, by=human)`);\n ui.info(path.relative(root, found.filePath));\n });\n}\n","import { readFile, writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n findProjectRoot,\n resolveHaivePaths,\n serializeMemory,\n type MemoryType,\n} from \"@hivelore/core\";\nimport { loadMemoriesFromDir } from \"../utils/fs.js\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface UpdateOptions {\n type?: MemoryType;\n title?: string;\n body?: string;\n bodyFile?: string;\n tags?: string;\n paths?: string;\n files?: string;\n symbols?: string;\n commit?: string;\n domain?: string;\n author?: string;\n dir?: string;\n}\n\nexport function registerMemoryUpdate(memory: Command): void {\n memory\n .command(\"update <id>\")\n .description(\"Update body, tags, or anchor of an existing memory (preserves id and usage history)\")\n .option(\"--type <type>\", \"change the memory type (convention | decision | gotcha | architecture | glossary | skill | attempt)\")\n .option(\"--title <text>\", \"new title — replaces the first heading of the body\")\n .option(\"--body <text>\", \"new Markdown body — replaces the existing body\")\n .option(\"--body-file <path>\", \"read new body from a Markdown file — for long content\")\n .option(\"--tags <csv>\", \"new tags, comma-separated — fully replaces existing tags\")\n .option(\"--paths <csv>\", \"new anchor paths, comma-separated\")\n .option(\"--files <csv>\", \"alias for --paths (matches the MCP `files` parameter)\")\n .option(\"--symbols <csv>\", \"new anchor symbols, comma-separated\")\n .option(\"--commit <sha>\", \"new anchor commit SHA\")\n .option(\"--domain <domain>\", \"new domain label\")\n .option(\"--author <author>\", \"new author handle or email\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (id: string, opts: UpdateOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.memoriesDir)) {\n ui.error(`No .ai/memories at ${root}. Run \\`hivelore init\\` first.`);\n process.exitCode = 1;\n return;\n }\n\n const memories = await loadMemoriesFromDir(paths.memoriesDir);\n const loaded = memories.find((m) => m.memory.frontmatter.id === id);\n if (!loaded) {\n ui.error(`No memory with id \"${id}\".`);\n process.exitCode = 1;\n return;\n }\n\n const updated: string[] = [];\n const { frontmatter, body } = loaded.memory;\n\n const newAnchor = { ...frontmatter.anchor };\n const pathsOpt = opts.paths ?? opts.files;\n if (pathsOpt !== undefined) {\n newAnchor.paths = parseCsv(pathsOpt);\n updated.push(\"anchor.paths\");\n }\n if (opts.symbols !== undefined) {\n newAnchor.symbols = parseCsv(opts.symbols);\n updated.push(\"anchor.symbols\");\n }\n if (opts.commit !== undefined) {\n newAnchor.commit = opts.commit;\n updated.push(\"anchor.commit\");\n }\n\n const newFrontmatter = {\n ...frontmatter,\n anchor: newAnchor,\n ...(opts.type !== undefined ? { type: opts.type } : {}),\n ...(opts.tags !== undefined ? { tags: parseCsv(opts.tags) } : {}),\n ...(opts.domain !== undefined ? { domain: opts.domain } : {}),\n ...(opts.author !== undefined ? { author: opts.author } : {}),\n };\n if (opts.type !== undefined) updated.push(\"type\");\n if (opts.tags !== undefined) updated.push(\"tags\");\n if (opts.domain !== undefined) updated.push(\"domain\");\n if (opts.author !== undefined) updated.push(\"author\");\n\n // Body resolution: --body-file > --body > existing body\n let newBody: string;\n if (opts.bodyFile !== undefined) {\n if (!existsSync(opts.bodyFile)) {\n ui.error(`--body-file not found: ${opts.bodyFile}`);\n process.exitCode = 1;\n return;\n }\n newBody = await readFile(opts.bodyFile, \"utf8\");\n updated.push(\"body\");\n } else if (opts.body !== undefined) {\n newBody = opts.body;\n updated.push(\"body\");\n } else {\n newBody = body;\n }\n\n if (opts.title !== undefined) {\n newBody = replaceFirstHeading(newBody, opts.title);\n updated.push(\"title\");\n }\n\n if (updated.length === 0) {\n ui.warn(\"Nothing to update — provide at least one option.\");\n return;\n }\n\n await writeFile(\n loaded.filePath,\n serializeMemory({ frontmatter: newFrontmatter, body: newBody }),\n \"utf8\",\n );\n\n ui.success(`Updated ${path.relative(root, loaded.filePath)}`);\n ui.info(`fields: ${updated.join(\", \")}`);\n });\n}\n\nfunction replaceFirstHeading(body: string, title: string): string {\n const headingRe = /^#\\s+.+$/m;\n const replacement = `# ${title}`;\n if (headingRe.test(body)) {\n return body.replace(headingRe, replacement);\n }\n return `${replacement}\\n\\n${body}`;\n}\n\nfunction parseCsv(value: string): string[] {\n return value.split(\",\").map((s) => s.trim()).filter(Boolean);\n}\n","import { writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n DEFAULT_AUTO_PROMOTE_RULE,\n findProjectRoot,\n getUsage,\n isAutoPromoteEligible,\n loadUsageIndex,\n resolveHaivePaths,\n serializeMemory,\n} from \"@hivelore/core\";\nimport { loadMemoriesFromDir } from \"../utils/fs.js\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface AutoPromoteOptions {\n minReads?: string;\n maxRejections?: string;\n apply?: boolean;\n dir?: string;\n}\n\nexport function registerMemoryAutoPromote(memory: Command): void {\n memory\n .command(\"auto-promote\")\n .description(\"Promote eligible 'proposed' memories to 'validated' based on usage\")\n .option(\"--min-reads <n>\", \"minimum read_count to qualify\", String(DEFAULT_AUTO_PROMOTE_RULE.minReads))\n .option(\n \"--max-rejections <n>\",\n \"memories with more rejections than this are skipped\",\n String(DEFAULT_AUTO_PROMOTE_RULE.maxRejections),\n )\n .option(\"--apply\", \"actually write status=validated to disk (default: dry-run)\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: AutoPromoteOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.memoriesDir)) {\n ui.error(`No .ai/memories at ${root}.`);\n process.exitCode = 1;\n return;\n }\n\n const rule = {\n minReads: Number(opts.minReads ?? DEFAULT_AUTO_PROMOTE_RULE.minReads),\n maxRejections: Number(opts.maxRejections ?? DEFAULT_AUTO_PROMOTE_RULE.maxRejections),\n };\n\n const memories = await loadMemoriesFromDir(paths.memoriesDir);\n const usage = await loadUsageIndex(paths);\n const eligible = memories.filter(({ memory }) =>\n isAutoPromoteEligible(memory.frontmatter, getUsage(usage, memory.frontmatter.id), rule),\n );\n\n if (eligible.length === 0) {\n ui.info(\n `No memories eligible (minReads=${rule.minReads}, maxRejections=${rule.maxRejections}).`,\n );\n return;\n }\n\n let written = 0;\n for (const { memory: mem, filePath } of eligible) {\n const u = getUsage(usage, mem.frontmatter.id);\n console.log(\n `${ui.bold(opts.apply ? \"PROMOTE\" : \"would promote\")} ${mem.frontmatter.id} ${ui.dim(`reads=${u.read_count} rejections=${u.rejected_count}`)}`,\n );\n console.log(` ${ui.dim(path.relative(root, filePath))}`);\n if (opts.apply) {\n const next = {\n // Usage-driven promotion without review → \"auto\" provenance.\n frontmatter: { ...mem.frontmatter, status: \"validated\" as const, validated_by: \"auto\" as const },\n body: mem.body,\n };\n await writeFile(filePath, serializeMemory(next), \"utf8\");\n written++;\n }\n }\n\n const summary = `${eligible.length} eligible`;\n ui.info(opts.apply ? `${summary} · ${written} promoted` : `${summary} · dry-run (use --apply)`);\n });\n}\n","import { spawn } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n findProjectRoot,\n parseMemory,\n resolveHaivePaths,\n} from \"@hivelore/core\";\nimport { loadMemoriesFromDir } from \"../utils/fs.js\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface EditOptions {\n editor?: string;\n dir?: string;\n}\n\nexport function registerMemoryEdit(memory: Command): void {\n memory\n .command(\"edit <id>\")\n .description(\"Open a memory in $EDITOR and re-validate when you save\")\n .option(\"-e, --editor <cmd>\", \"editor command (defaults to $EDITOR or 'vi')\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (id: string, opts: EditOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.memoriesDir)) {\n ui.error(`No .ai/memories at ${root}.`);\n process.exitCode = 1;\n return;\n }\n\n const all = await loadMemoriesFromDir(paths.memoriesDir);\n const found = all.find((m) => m.memory.frontmatter.id === id);\n if (!found) {\n ui.error(`No memory with id \"${id}\".`);\n process.exitCode = 1;\n return;\n }\n\n const editor = opts.editor ?? process.env.EDITOR ?? process.env.VISUAL ?? \"vi\";\n ui.info(`Opening ${path.relative(root, found.filePath)} with ${editor}…`);\n const code = await runEditor(editor, found.filePath);\n if (code !== 0) {\n ui.warn(`Editor exited with status ${code}.`);\n }\n\n try {\n const fresh = await readFile(found.filePath, \"utf8\");\n parseMemory(fresh);\n ui.success(\"Memory still parses cleanly.\");\n } catch (err) {\n ui.error(\n `Memory no longer parses: ${err instanceof Error ? err.message : String(err)}`,\n );\n ui.warn(\"File left as-is on disk; fix it and re-run a parse-aware command to confirm.\");\n process.exitCode = 1;\n }\n });\n}\n\nfunction runEditor(editor: string, file: string): Promise<number> {\n return new Promise((resolve) => {\n const child = spawn(editor, [file], { stdio: \"inherit\" });\n child.on(\"exit\", (code) => resolve(code ?? 0));\n child.on(\"error\", () => resolve(127));\n });\n}\n","import { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n deriveConfidence,\n findProjectRoot,\n getUsage,\n inferModulesFromPaths,\n loadUsageIndex,\n memoryMatchesAnchorPaths,\n resolveHaivePaths,\n} from \"@hivelore/core\";\nimport { loadMemoriesFromDir } from \"../utils/fs.js\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface ForFilesOptions {\n dir?: string;\n}\n\nexport function registerMemoryForFiles(memory: Command): void {\n memory\n .command(\"for-files <files...>\")\n .description(\"Show memories relevant to the given files (anchor overlap, module, domain)\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (files: string[], opts: ForFilesOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.memoriesDir)) {\n ui.error(`No .ai/memories at ${root}.`);\n process.exitCode = 1;\n return;\n }\n\n const all = await loadMemoriesFromDir(paths.memoriesDir);\n const usage = await loadUsageIndex(paths);\n const inferred = inferModulesFromPaths(files);\n\n const byAnchor: typeof all = [];\n const byModule: typeof all = [];\n const byDomain: typeof all = [];\n const seen = new Set<string>();\n\n for (const loaded of all) {\n // session_recap surfaces in briefing last_session — not in for-files\n if (loaded.memory.frontmatter.type === \"session_recap\") continue;\n if (memoryMatchesAnchorPaths(loaded.memory, files)) {\n byAnchor.push(loaded);\n seen.add(loaded.memory.frontmatter.id);\n }\n }\n const pathSegments = extractPathSegments(files);\n\n for (const loaded of all) {\n if (seen.has(loaded.memory.frontmatter.id)) continue;\n if (loaded.memory.frontmatter.type === \"session_recap\") continue;\n const fm = loaded.memory.frontmatter;\n const moduleHit =\n (fm.module && inferred.includes(fm.module)) ||\n fm.tags.some((t) => {\n const tl = t.toLowerCase();\n return pathSegments.has(tl) || pathSegments.has(tl.replace(/[-_]/g, \"\"));\n });\n if (moduleHit) {\n byModule.push(loaded);\n seen.add(fm.id);\n }\n }\n for (const loaded of all) {\n if (seen.has(loaded.memory.frontmatter.id)) continue;\n if (loaded.memory.frontmatter.type === \"session_recap\") continue;\n const domain = loaded.memory.frontmatter.domain;\n if (domain && inferred.includes(domain)) {\n byDomain.push(loaded);\n seen.add(loaded.memory.frontmatter.id);\n }\n }\n\n console.log(ui.dim(`inferred modules: ${inferred.length ? inferred.join(\", \") : \"(none)\"}`));\n printGroup(root, \"anchor overlap\", byAnchor, usage);\n printGroup(root, \"module match\", byModule, usage);\n printGroup(root, \"domain match\", byDomain, usage);\n\n const total = byAnchor.length + byModule.length + byDomain.length;\n ui.info(\n `${total} relevant memor${total === 1 ? \"y\" : \"ies\"} (${byAnchor.length} anchor · ${byModule.length} module · ${byDomain.length} domain)`,\n );\n });\n}\n\nfunction extractPathSegments(files: string[]): Set<string> {\n const GENERIC = new Set([\n \"src\", \"main\", \"java\", \"kotlin\", \"python\", \"go\", \"lib\", \"libs\",\n \"com\", \"org\", \"net\", \"io\", \"app\", \"apps\", \"pkg\", \"internal\",\n \"test\", \"tests\", \"spec\", \"specs\", \"impl\", \"domain\", \"shared\",\n \"resources\", \"static\", \"assets\", \"config\", \"configs\",\n ]);\n const out = new Set<string>();\n for (const file of files) {\n const parts = file.replace(/\\\\/g, \"/\").split(\"/\");\n for (const part of parts) {\n const seg = part.toLowerCase().replace(/\\.[^.]+$/, \"\");\n if (seg.length >= 3 && !GENERIC.has(seg) && /^[a-z]/.test(seg)) {\n out.add(seg);\n for (const sub of seg.split(/[-_]/).filter((s) => s.length >= 3)) {\n out.add(sub);\n }\n }\n }\n }\n return out;\n}\n\nfunction printGroup(\n root: string,\n label: string,\n loaded: Array<Awaited<ReturnType<typeof loadMemoriesFromDir>>[number]>,\n usage: Awaited<ReturnType<typeof loadUsageIndex>>,\n): void {\n if (loaded.length === 0) return;\n console.log(ui.bold(`\\n— ${label} —`));\n for (const { memory: mem, filePath } of loaded) {\n const fm = mem.frontmatter;\n const u = getUsage(usage, fm.id);\n const conf = deriveConfidence(fm, u);\n console.log(`${ui.bold(fm.id)} ${ui.dim(`${fm.scope}/${fm.type}`)} ${ui.bold(conf)}`);\n console.log(` ${ui.dim(path.relative(root, filePath))}`);\n }\n}\n","import { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n findProjectRoot,\n getUsage,\n loadUsageIndex,\n resolveHaivePaths,\n} from \"@hivelore/core\";\nimport { loadMemoriesFromDir } from \"../utils/fs.js\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface HotOptions {\n threshold?: string;\n status?: \"draft\" | \"proposed\";\n dir?: string;\n}\n\nexport function registerMemoryHot(memory: Command): void {\n memory\n .command(\"hot\")\n .description(\n \"List unvalidated memories with high read_count — proven-useful promotion candidates.\\n\\n\" +\n \" Unlike `hivelore memory pending` (which lists ALL draft/proposed by status),\\n\" +\n \" `hot` filters by usage: only memories read ≥N times qualify.\\n\" +\n \" Use it to quickly find memories that agents are already relying on\\n\" +\n \" but that haven't been formally validated yet.\",\n )\n .option(\"--threshold <n>\", \"minimum read_count to qualify (default: 3)\", \"3\")\n .option(\"--status <status>\", \"limit to one status (default: draft + proposed)\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: HotOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.memoriesDir)) {\n ui.error(`No .ai/memories at ${root}.`);\n process.exitCode = 1;\n return;\n }\n const threshold = Math.max(1, Number(opts.threshold ?? 3));\n\n const all = await loadMemoriesFromDir(paths.memoriesDir);\n const usage = await loadUsageIndex(paths);\n const candidates = all\n .filter(({ memory: mem }) => {\n const fm = mem.frontmatter;\n if (opts.status && fm.status !== opts.status) return false;\n if (opts.status === undefined && fm.status !== \"draft\" && fm.status !== \"proposed\") {\n return false;\n }\n return getUsage(usage, fm.id).read_count >= threshold;\n })\n .sort(\n (a, b) =>\n getUsage(usage, b.memory.frontmatter.id).read_count -\n getUsage(usage, a.memory.frontmatter.id).read_count,\n );\n\n if (candidates.length === 0) {\n ui.info(`No hot memories (threshold=${threshold}).`);\n return;\n }\n\n for (const { memory: mem, filePath } of candidates) {\n const fm = mem.frontmatter;\n const u = getUsage(usage, fm.id);\n console.log(\n `${ui.bold(fm.id)} ${ui.dim(`${fm.scope}/${fm.type}`)} ${ui.bold(fm.status)} ${ui.dim(`reads=${u.read_count} rejections=${u.rejected_count}`)}`,\n );\n console.log(` ${ui.dim(path.relative(root, filePath))}`);\n }\n ui.info(\n `${candidates.length} hot (read ≥${threshold}×) — agents rely on these; promote with \\`hivelore memory promote <id>\\`.\\n` +\n ` Tip: \\`hivelore memory pending\\` lists ALL unvalidated memories regardless of read count.`,\n );\n });\n}\n","import { mkdir, writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n buildFrontmatter,\n findProjectRoot,\n memoryFilePath,\n resolveHaivePaths,\n serializeMemory,\n suggestSensorSeed,\n type MemoryScope,\n} from \"@hivelore/core\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface TriedOptions {\n what: string;\n whyFailed: string;\n instead?: string;\n scope?: MemoryScope;\n module?: string;\n tags?: string;\n paths?: string;\n files?: string;\n author?: string;\n dir?: string;\n}\n\nexport function registerMemoryTried(memory: Command): void {\n memory\n .command(\"tried\")\n .description(\n \"Record a FAILED approach — prevents repeated mistakes in future sessions.\\n\\n\" +\n \" This is the most valuable type of negative knowledge. It surfaces FIRST in\\n\" +\n \" get_briefing so agents can't miss it. Auto-validated (no approval cycle).\\n\\n\" +\n \" Use this immediately when you try something and it fails.\\n\\n\" +\n \" Example:\\n\" +\n \" hivelore memory tried \\\\\\\\\\n\" +\n \" --what \\\"importing X with ESM dynamic import\\\" \\\\\\\\\\n\" +\n \" --why-failed \\\"tsup bundles it as CJS, dynamic import fails at runtime\\\" \\\\\\\\\\n\" +\n \" --instead \\\"use static import in the entry file\\\" \\\\\\\\\\n\" +\n \" --paths packages/cli/src/index.ts\\n\",\n )\n .requiredOption(\"--what <text>\", \"what approach was tried (short, descriptive title)\")\n .requiredOption(\"--why-failed <text>\", \"why it failed or should NOT be used (include the exact error if possible)\")\n .option(\"--instead <text>\", \"the correct approach to use instead\")\n .option(\"--scope <scope>\", \"personal | team | module\", \"personal\")\n .option(\"--module <name>\", \"module name (required when scope=module)\")\n .option(\"--tags <csv>\", \"comma-separated tags\")\n .option(\"--paths <csv>\", \"anchor paths, comma-separated\")\n .option(\"--files <csv>\", \"alias for --paths (matches the MCP `files` parameter)\")\n .option(\"--author <author>\", \"author email or handle\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: TriedOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.haiveDir)) {\n ui.error(`No .ai/ found at ${root}. Run \\`hivelore init\\` first.`);\n process.exitCode = 1;\n return;\n }\n\n const slug = opts.what\n .toLowerCase()\n .replace(/[^a-z0-9\\s]/g, \"\")\n .trim()\n .split(/\\s+/)\n .slice(0, 5)\n .join(\"-\");\n\n const baseFm = buildFrontmatter({\n type: \"attempt\",\n slug,\n scope: opts.scope,\n module: opts.module,\n tags: parseCsv(opts.tags),\n paths: parseCsv(opts.paths ?? opts.files),\n author: opts.author,\n });\n // attempt memories are immediately validated — no review cycle needed\n const frontmatter = { ...baseFm, status: \"validated\" as const };\n\n const lines: string[] = [`# ${opts.what}`, \"\"];\n lines.push(`**Why it failed / do NOT use:** ${opts.whyFailed}`);\n if (opts.instead) {\n lines.push(\"\", `**Instead, use:** ${opts.instead}`);\n }\n const body = lines.join(\"\\n\") + \"\\n\";\n\n const file = memoryFilePath(paths, frontmatter.scope, frontmatter.id, frontmatter.module);\n await mkdir(path.dirname(file), { recursive: true });\n\n if (existsSync(file)) {\n ui.error(`Memory already exists at ${file}`);\n process.exitCode = 1;\n return;\n }\n\n await writeFile(file, serializeMemory({ frontmatter, body }), \"utf8\");\n ui.success(`Recorded: ${path.relative(root, file)}`);\n ui.info(`id=${frontmatter.id} type=attempt status=validated (auto-approved)`);\n // A captured attempt closes its loop only once a sensor is VALIDATED via propose_sensor. We no\n // longer auto-write a heuristic warn sensor; surface a candidate SEED (when derivable) instead.\n const seed = frontmatter.anchor.paths.length > 0 ? suggestSensorSeed(body, frontmatter.anchor.paths) : null;\n if (frontmatter.anchor.paths.length === 0) {\n ui.warn(\"No --paths — lesson is briefed but NOT enforced. Add --paths, then call propose_sensor (MCP) to close the loop.\");\n } else if (seed) {\n ui.warn(\"Lesson NOT yet enforced — close the loop with a validated sensor via propose_sensor (MCP).\");\n ui.info(\n ` candidate pattern=${JSON.stringify(seed.pattern)}` +\n (seed.absent ? ` absent=${JSON.stringify(seed.absent)}` : \"\") +\n \" — refine, then validate (silent on current code, fires on the bad example).\",\n );\n } else {\n ui.warn(\n \"Lesson NOT yet enforced and no candidate pattern could be derived. Author a discriminating \" +\n \"sensor (pattern = faulty usage, absent = correct-usage marker) via propose_sensor.\",\n );\n }\n });\n}\n\nfunction parseCsv(value: string | undefined): string[] {\n if (!value) return [];\n return value.split(\",\").map((s) => s.trim()).filter(Boolean);\n}\n","import { readFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n findProjectRoot,\n loadConfig,\n resolveHaivePaths,\n} from \"@hivelore/core\";\nimport {\n SUPPORTED_STACKS,\n autoDetectStacks,\n isValidStack,\n seedStackPack,\n} from \"./init-stack-packs.js\";\nimport { applyAutopilotRepairs } from \"../utils/autopilot.js\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface SeedOptions {\n list?: boolean;\n json?: boolean;\n dir?: string;\n}\n\n/** Best-effort read of the project's dependency map from package.json. */\nasync function readDependencyMap(root: string): Promise<Record<string, string>> {\n try {\n const raw = await readFile(path.join(root, \"package.json\"), \"utf8\");\n const pkg = JSON.parse(raw) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n return { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) };\n } catch {\n return {};\n }\n}\n\nexport function registerMemorySeed(memory: Command): void {\n memory\n .command(\"seed [stack]\")\n .description(\n \"Seed a stack pack of starter memories on demand.\\n\\n\" +\n \" Stack packs are generic framework gotchas/conventions every team using that\\n\" +\n \" stack rediscovers. They are tagged `stack-pack` and kept at BACKGROUND priority\\n\" +\n \" in briefings until you anchor them to a real file or replace them with a\\n\" +\n \" repo-specific note — so they never crowd out your own knowledge.\\n\\n\" +\n \" Examples:\\n\" +\n \" hivelore memory seed # auto-detect stacks from package.json and seed them\\n\" +\n \" hivelore memory seed nestjs # seed a specific stack\\n\" +\n \" hivelore memory seed --list # show supported + auto-detected stacks\\n\" +\n \" hivelore memory seed --list --json\\n\",\n )\n .option(\"--list\", \"list supported stacks (and which are auto-detected here) and exit\")\n .option(\"--json\", \"machine-readable output (use with --list)\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (stack: string | undefined, opts: SeedOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n const deps = await readDependencyMap(root);\n const detected = autoDetectStacks(deps);\n\n // ── --list ──────────────────────────────────────────────────────────\n if (opts.list) {\n if (opts.json) {\n console.log(JSON.stringify({ supported: SUPPORTED_STACKS, detected }, null, 2));\n return;\n }\n ui.info(\"Supported stacks:\");\n for (const s of SUPPORTED_STACKS) {\n const mark = detected.includes(s) ? ui.green(\" ✓ detected here\") : \"\";\n console.log(` • ${s}${mark}`);\n }\n if (detected.length === 0) {\n ui.info(\"No stack auto-detected from package.json — pass a stack name explicitly.\");\n }\n return;\n }\n\n if (!existsSync(paths.haiveDir)) {\n ui.error(`No .ai/ found at ${root}. Run \\`hivelore init\\` first.`);\n process.exitCode = 1;\n return;\n }\n\n // ── Decide which stacks to seed ─────────────────────────────────────\n let stacksToSeed: string[];\n if (stack) {\n if (!isValidStack(stack)) {\n ui.error(`Unknown stack '${stack}'. Supported: ${SUPPORTED_STACKS.join(\", \")}.`);\n ui.info(\"Run `hivelore memory seed --list` to see all stacks.\");\n process.exitCode = 1;\n return;\n }\n stacksToSeed = [stack];\n } else if (detected.length > 0) {\n stacksToSeed = detected;\n ui.info(`Auto-detected from package.json: ${detected.join(\", \")}`);\n } else {\n ui.error(\"No stack auto-detected from package.json.\");\n ui.info(\"Pass a stack name (e.g. `hivelore memory seed nestjs`) or run `hivelore memory seed --list`.\");\n process.exitCode = 1;\n return;\n }\n\n // ── Seed ────────────────────────────────────────────────────────────\n let total = 0;\n const seededStacks: string[] = [];\n for (const s of stacksToSeed) {\n const result = await seedStackPack(paths, s as (typeof SUPPORTED_STACKS)[number]);\n if (result.memories > 0) {\n total += result.memories;\n seededStacks.push(`${s} (${result.memories})`);\n } else {\n ui.info(`Stack pack '${s}': all memories already exist — skipped.`);\n }\n }\n\n if (total === 0) {\n ui.info(\"Nothing new to seed — every memory in the selected pack(s) already exists.\");\n return;\n }\n\n ui.success(`Seeded ${total} starter memor${total === 1 ? \"y\" : \"ies\"}: ${seededStacks.join(\", \")}`);\n ui.info(\"Kept at background priority. Anchor them to a real file (or replace them) to make them high-signal:\");\n ui.info(\" hivelore memory update <id> --paths <key-file> # anchor a seed to a file\");\n\n // Refresh the embeddings index so the new seeds are searchable (autopilot only).\n const config = await loadConfig(paths);\n if (config.autopilot || config.autoRepair?.corpus === true) {\n const repairs = await applyAutopilotRepairs(root, paths, {\n applyConfig: false,\n applyContext: false,\n applyCorpus: true,\n applyCodeMap: false,\n applyCodeSearch: false,\n });\n for (const repair of repairs) ui.info(repair.message);\n }\n });\n}\n","import { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n findProjectRoot,\n getUsage,\n loadUsageIndex,\n resolveHaivePaths,\n} from \"@hivelore/core\";\nimport { loadMemoriesFromDir } from \"../utils/fs.js\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface PendingOptions {\n scope?: \"personal\" | \"team\" | \"module\";\n dir?: string;\n}\n\nexport function registerMemoryPending(memory: Command): void {\n memory\n .command(\"pending\")\n .description(\"List draft and proposed memories awaiting review (sorted by reads desc).\\n\\n draft = created but not yet activated · proposed = promoted, awaiting team validation\")\n .option(\"--scope <scope>\", \"filter by scope (personal | team | module)\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: PendingOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.memoriesDir)) {\n ui.error(`No .ai/memories at ${root}.`);\n process.exitCode = 1;\n return;\n }\n\n const all = await loadMemoriesFromDir(paths.memoriesDir);\n const usage = await loadUsageIndex(paths);\n\n const filterFn = ({ memory: mem }: { memory: { frontmatter: { status: string; scope: string } } }) => {\n if (mem.frontmatter.status !== \"proposed\" && mem.frontmatter.status !== \"draft\") return false;\n if (opts.scope && mem.frontmatter.scope !== opts.scope) return false;\n return true;\n };\n const pending = all.filter(filterFn);\n\n if (pending.length === 0) {\n ui.info(\"No draft or proposed memories awaiting review.\");\n ui.info(\"Drafts are created by `hivelore memory save` without `--status validated`.\");\n return;\n }\n\n pending.sort(\n (a, b) =>\n getUsage(usage, b.memory.frontmatter.id).read_count -\n getUsage(usage, a.memory.frontmatter.id).read_count,\n );\n\n const now = Date.now();\n const drafts = pending.filter((m) => m.memory.frontmatter.status === \"draft\");\n const proposed = pending.filter((m) => m.memory.frontmatter.status === \"proposed\");\n\n if (proposed.length > 0) {\n console.log(ui.bold(`Proposed (${proposed.length}) — awaiting team validation`));\n for (const { memory: mem, filePath } of proposed) {\n const fm = mem.frontmatter;\n const u = getUsage(usage, fm.id);\n const ageDays = Math.floor((now - new Date(fm.created_at).getTime()) / 86_400_000);\n const ageStr = ageDays === 0 ? \"today\" : `${ageDays}d`;\n console.log(\n ` ${ui.bold(fm.id)} ${ui.dim(`${fm.scope}/${fm.type}`)} ${ui.dim(`age=${ageStr} reads=${u.read_count}`)}`,\n );\n console.log(` ${ui.dim(path.relative(root, filePath))}`);\n }\n if (proposed.length > 0) console.log(ui.dim(` → hivelore memory approve <id> or hivelore memory auto-promote`));\n console.log();\n }\n\n if (drafts.length > 0) {\n console.log(ui.bold(`Draft (${drafts.length}) — created but not yet activated`));\n for (const { memory: mem, filePath } of drafts) {\n const fm = mem.frontmatter;\n const u = getUsage(usage, fm.id);\n const ageDays = Math.floor((now - new Date(fm.created_at).getTime()) / 86_400_000);\n const ageStr = ageDays === 0 ? \"today\" : `${ageDays}d`;\n console.log(\n ` ${ui.bold(fm.id)} ${ui.dim(`${fm.scope}/${fm.type}`)} ${ui.dim(`age=${ageStr} reads=${u.read_count}`)}`,\n );\n console.log(` ${ui.dim(path.relative(root, filePath))}`);\n }\n console.log(ui.dim(` → hivelore memory approve <id> (activate) | hivelore memory promote <id> (share with team)`));\n }\n\n ui.info(`${pending.length} total pending (${proposed.length} proposed · ${drafts.length} draft)`);\n });\n}\n","import { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n extractSnippet,\n findProjectRoot,\n literalMatchesAllTokens,\n literalMatchesAnyToken,\n pickSnippetNeedle,\n resolveHaivePaths,\n tokenizeQuery,\n trackReads,\n type MemoryScope,\n} from \"@hivelore/core\";\nimport { loadMemoriesFromDir } from \"../utils/fs.js\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface QueryOptions {\n dir?: string;\n limit?: string;\n scope?: MemoryScope;\n status?: string;\n showRejected?: boolean;\n}\n\nexport function registerMemoryQuery(memory: Command): void {\n memory\n .command(\"search <text>\")\n .alias(\"query\")\n .description(\"Search memories by id, tag, or substring (AND, OR fallback). Mirrors MCP mem_search. Alias: query\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .option(\"--limit <n>\", \"max results\", \"20\")\n .option(\"--scope <scope>\", \"personal | team | module\")\n .option(\"--status <csv>\", \"filter by status (draft,proposed,validated,stale,rejected)\")\n .option(\"--show-rejected\", \"include rejected memories (hidden by default)\")\n .action(async (text: string, opts: QueryOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.memoriesDir)) {\n ui.error(`No memories directory at ${paths.memoriesDir}. Run \\`hivelore init\\` first.`);\n process.exitCode = 1;\n return;\n }\n\n const tokens = tokenizeQuery(text);\n if (tokens.length === 0) {\n ui.warn(\"Empty query — use \\`hivelore memory list\\` to list all memories.\");\n return;\n }\n const statusFilter = opts.status ? opts.status.split(\",\").map((s) => s.trim()) : null;\n const all = await loadMemoriesFromDir(paths.memoriesDir);\n\n const passesFilters = (mem: (typeof all)[number][\"memory\"]) => {\n const fm = mem.frontmatter;\n if (opts.scope && fm.scope !== opts.scope) return false;\n if (!opts.showRejected && !statusFilter && fm.status === \"rejected\") return false;\n if (statusFilter && !statusFilter.includes(fm.status)) return false;\n // session_recap surfaces in briefing as last_session, not in regular search\n if (fm.type === \"session_recap\") return false;\n return true;\n };\n\n const eligible = all.filter(({ memory: mem }) => passesFilters(mem));\n let matches = eligible.filter(({ memory: mem }) => literalMatchesAllTokens(mem, tokens));\n let fallback = false;\n if (matches.length === 0 && tokens.length > 1) {\n matches = eligible.filter(({ memory: mem }) => literalMatchesAnyToken(mem, tokens));\n fallback = true;\n }\n\n const limit = Math.max(1, Number(opts.limit ?? 20));\n const top = matches.slice(0, limit);\n\n if (top.length === 0) {\n ui.info(`No matches for \"${text}\".`);\n return;\n }\n if (fallback) {\n ui.info(`No exact match — showing partial results (OR fallback):`);\n }\n\n const snippetNeedle = pickSnippetNeedle(text);\n for (const { memory: mem, filePath } of top) {\n const fm = mem.frontmatter;\n const statusBadge = ui.statusBadge(fm.status);\n console.log(`${ui.bold(fm.id)} ${ui.dim(fm.scope)} ${statusBadge}`);\n console.log(` ${ui.dim(path.relative(root, filePath))}`);\n const snippet = extractSnippet(mem.body, snippetNeedle);\n if (snippet) console.log(` ${snippet}`);\n }\n console.log(\n ui.dim(`\\n${top.length} of ${matches.length} match${matches.length === 1 ? \"\" : \"es\"}`),\n );\n\n // Track reads for usage stats / decay / hot detection\n const ids = top.map(({ memory: mem }) => mem.frontmatter.id);\n if (ids.length > 0) {\n await trackReads(paths, ids).catch(() => { /* non-fatal */ });\n }\n });\n}\n","import { writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { Command } from \"commander\";\nimport {\n findProjectRoot,\n loadUsageIndex,\n recordRejection,\n resolveHaivePaths,\n saveUsageIndex,\n serializeMemory,\n} from \"@hivelore/core\";\nimport { loadMemoriesFromDir } from \"../utils/fs.js\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface RejectOptions {\n reason?: string;\n dir?: string;\n}\n\nexport function registerMemoryReject(memory: Command): void {\n memory\n .command(\"reject <id>\")\n .description(\"Record a rejection (blocks auto-promotion and lowers confidence)\")\n .option(\"-r, --reason <reason>\", \"why this memory is being rejected\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (id: string, opts: RejectOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.memoriesDir)) {\n ui.error(`No .ai/memories at ${root}.`);\n process.exitCode = 1;\n return;\n }\n\n const memories = await loadMemoriesFromDir(paths.memoriesDir);\n const loaded = memories.find((m) => m.memory.frontmatter.id === id);\n if (!loaded) {\n ui.error(`No memory with id \"${id}\".`);\n process.exitCode = 1;\n return;\n }\n\n await writeFile(\n loaded.filePath,\n serializeMemory({\n frontmatter: {\n ...loaded.memory.frontmatter,\n status: \"rejected\",\n stale_reason: opts.reason ?? loaded.memory.frontmatter.stale_reason ?? null,\n },\n body: loaded.memory.body,\n }),\n \"utf8\",\n );\n\n const idx = await loadUsageIndex(paths);\n recordRejection(idx, id, opts.reason ?? null);\n await saveUsageIndex(paths, idx);\n const u = idx.by_id[id]!;\n ui.success(\n `Rejected ${id} (status=rejected, ${u.rejected_count} rejection${u.rejected_count === 1 ? \"\" : \"s\"})`,\n );\n if (opts.reason) ui.info(`reason: ${opts.reason}`);\n });\n}\n","import { existsSync } from \"node:fs\";\nimport { unlink } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createInterface } from \"node:readline/promises\";\nimport { Command } from \"commander\";\nimport {\n findProjectRoot,\n loadUsageIndex,\n resolveHaivePaths,\n saveUsageIndex,\n} from \"@hivelore/core\";\nimport { loadMemoriesFromDir } from \"../utils/fs.js\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface RmOptions {\n yes?: boolean;\n keepUsage?: boolean;\n dir?: string;\n}\n\nexport function registerMemoryRm(memory: Command): void {\n memory\n .command(\"delete <id>\")\n .alias(\"rm\")\n .description(\"Delete a memory file (and its usage entry by default). Mirrors MCP mem_delete. Alias: rm\")\n .option(\"-y, --yes\", \"skip the confirmation prompt\")\n .option(\"--keep-usage\", \"do not remove the usage.json entry\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (id: string, opts: RmOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.memoriesDir)) {\n ui.error(`No .ai/memories at ${root}.`);\n process.exitCode = 1;\n return;\n }\n\n const all = await loadMemoriesFromDir(paths.memoriesDir);\n const found = all.find((m) => m.memory.frontmatter.id === id);\n if (!found) {\n ui.error(`No memory with id \"${id}\".`);\n process.exitCode = 1;\n return;\n }\n\n const rel = path.relative(root, found.filePath);\n if (!opts.yes) {\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n const answer = (await rl.question(`Delete ${rel}? [y/N] `)).trim().toLowerCase();\n rl.close();\n if (answer !== \"y\" && answer !== \"yes\") {\n ui.info(\"Aborted.\");\n return;\n }\n }\n\n await unlink(found.filePath);\n ui.success(`Deleted ${rel}`);\n\n if (!opts.keepUsage) {\n const idx = await loadUsageIndex(paths);\n if (idx.by_id[id]) {\n delete idx.by_id[id];\n await saveUsageIndex(paths, idx);\n ui.info(\"Removed usage entry\");\n }\n }\n });\n}\n","import { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n deriveConfidence,\n findProjectRoot,\n getUsage,\n loadUsageIndex,\n resolveHaivePaths,\n} from \"@hivelore/core\";\nimport { loadMemoriesFromDir } from \"../utils/fs.js\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface ShowOptions {\n raw?: boolean;\n dir?: string;\n}\n\nexport function registerMemoryShow(memory: Command): void {\n memory\n .command(\"get <id>\")\n .alias(\"show\")\n .description(\"Print a memory's frontmatter, body, and confidence/usage. Mirrors MCP mem_get. Alias: show\")\n .option(\"--raw\", \"print the raw file contents instead of a summary\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (id: string, opts: ShowOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.memoriesDir)) {\n ui.error(`No .ai/memories at ${root}.`);\n process.exitCode = 1;\n return;\n }\n\n const all = await loadMemoriesFromDir(paths.memoriesDir);\n const found = all.find((m) => m.memory.frontmatter.id === id);\n if (!found) {\n ui.error(`No memory with id \"${id}\".`);\n process.exitCode = 1;\n return;\n }\n\n if (opts.raw) {\n console.log(await readFile(found.filePath, \"utf8\"));\n return;\n }\n\n const fm = found.memory.frontmatter;\n const usage = await loadUsageIndex(paths);\n const u = getUsage(usage, fm.id);\n const conf = deriveConfidence(fm, u);\n\n console.log(ui.bold(fm.id));\n console.log(`${ui.dim(\"scope:\")} ${fm.scope}${fm.module ? ` / ${fm.module}` : \"\"}`);\n console.log(`${ui.dim(\"type:\")} ${fm.type}`);\n console.log(`${ui.dim(\"status:\")} ${fm.status} ${ui.dim(\"→ confidence:\")} ${ui.bold(conf)}`);\n console.log(`${ui.dim(\"tags:\")} ${fm.tags.length ? fm.tags.join(\", \") : \"(none)\"}`);\n console.log(`${ui.dim(\"created:\")} ${fm.created_at}`);\n if (fm.verified_at) console.log(`${ui.dim(\"verified:\")} ${fm.verified_at}`);\n if (fm.stale_reason) console.log(`${ui.dim(\"stale:\")} ${fm.stale_reason}`);\n console.log(`${ui.dim(\"reads:\")} ${u.read_count} ${ui.dim(\"rejections:\")} ${u.rejected_count}`);\n console.log(`${ui.dim(\"file:\")} ${path.relative(root, found.filePath)}`);\n if (fm.anchor.paths.length || fm.anchor.symbols.length) {\n console.log(ui.dim(\"anchor:\"));\n if (fm.anchor.commit) console.log(` ${ui.dim(\"commit:\")} ${fm.anchor.commit}`);\n if (fm.anchor.paths.length)\n console.log(` ${ui.dim(\"paths:\")} ${fm.anchor.paths.join(\", \")}`);\n if (fm.anchor.symbols.length)\n console.log(` ${ui.dim(\"symbols:\")} ${fm.anchor.symbols.join(\", \")}`);\n }\n console.log();\n console.log(found.memory.body);\n });\n}\n","import { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n deriveConfidence,\n findProjectRoot,\n getUsage,\n loadUsageIndex,\n resolveHaivePaths,\n} from \"@hivelore/core\";\nimport { loadMemoriesFromDir } from \"../utils/fs.js\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface StatsOptions {\n id?: string;\n dir?: string;\n}\n\nexport function registerMemoryStats(memory: Command): void {\n memory\n .command(\"stats\")\n .description(\"Show usage stats and confidence levels per memory\")\n .option(\"--id <id>\", \"show stats for a single memory id\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: StatsOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.memoriesDir)) {\n ui.error(`No .ai/memories at ${root}. Run \\`hivelore init\\` first.`);\n process.exitCode = 1;\n return;\n }\n\n const all = await loadMemoriesFromDir(paths.memoriesDir);\n const usage = await loadUsageIndex(paths);\n const target = opts.id\n ? all.filter((m) => m.memory.frontmatter.id === opts.id)\n : all;\n\n if (target.length === 0) {\n ui.info(opts.id ? `No memory with id \"${opts.id}\".` : \"No memories.\");\n return;\n }\n\n // Sort by read_count desc to surface the popular ones.\n target.sort(\n (a, b) =>\n getUsage(usage, b.memory.frontmatter.id).read_count -\n getUsage(usage, a.memory.frontmatter.id).read_count,\n );\n\n for (const { memory: mem, filePath } of target) {\n const fm = mem.frontmatter;\n const u = getUsage(usage, fm.id);\n const conf = deriveConfidence(fm, u);\n console.log(\n `${ui.bold(fm.id)} ${ui.dim(`${fm.scope}/${fm.type}`)} ${ui.bold(conf)}`,\n );\n console.log(\n ` ${ui.dim(\"status:\")} ${fm.status} ${ui.dim(\"reads:\")} ${u.read_count} ${ui.dim(\"rejections:\")} ${u.rejected_count}`,\n );\n console.log(` ${ui.dim(path.relative(root, filePath))}`);\n }\n });\n}\n","import { existsSync } from \"node:fs\";\nimport { Command } from \"commander\";\nimport {\n compareImpact,\n computeImpact,\n findProjectRoot,\n getUsage,\n loadUsageIndex,\n resolveHaivePaths,\n summarizeImpact,\n type ImpactScore,\n type ImpactTier,\n} from \"@hivelore/core\";\nimport { loadMemoriesFromDir } from \"../utils/fs.js\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface ImpactOptions {\n id?: string;\n prune?: boolean;\n tier?: string;\n json?: boolean;\n dir?: string;\n}\n\ninterface ImpactRow {\n id: string;\n type: string;\n scope: string;\n status: string;\n impact: ImpactScore;\n}\n\nexport function registerMemoryImpact(memory: Command): void {\n memory\n .command(\"impact\")\n .description(\n \"Score memories by demonstrated utility (reads + applied outcomes + sensor fires \" +\n \"vs rejections, staleness, dormancy) and surface prune candidates.\",\n )\n .option(\"--id <id>\", \"show impact for a single memory id\")\n .option(\"--prune\", \"list only prune candidates (dead weight worth reviewing)\", false)\n .option(\"--tier <tier>\", \"filter to a tier: high | medium | low | dormant\")\n .option(\"--json\", \"emit JSON\", false)\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: ImpactOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.memoriesDir)) {\n ui.error(`No .ai/memories at ${root}. Run \\`hivelore init\\` first.`);\n process.exitCode = 1;\n return;\n }\n\n const all = await loadMemoriesFromDir(paths.memoriesDir);\n const usageIndex = await loadUsageIndex(paths);\n\n let rows: ImpactRow[] = all\n .filter((m) => !opts.id || m.memory.frontmatter.id === opts.id)\n .map(({ memory: mem }) => {\n const fm = mem.frontmatter;\n return {\n id: fm.id,\n type: fm.type,\n scope: fm.scope,\n status: fm.status,\n impact: computeImpact(fm, getUsage(usageIndex, fm.id)),\n };\n });\n\n if (opts.prune) rows = rows.filter((r) => r.impact.pruneCandidate);\n if (opts.tier) {\n const tier = opts.tier as ImpactTier;\n rows = rows.filter((r) => r.impact.tier === tier);\n }\n rows.sort((a, b) => compareImpact(a.impact, b.impact));\n\n const summary = summarizeImpact(all.map((m) => computeImpact(m.memory.frontmatter, getUsage(usageIndex, m.memory.frontmatter.id))));\n\n if (opts.json) {\n console.log(JSON.stringify({ root, summary, rows }, null, 2));\n return;\n }\n\n if (rows.length === 0) {\n ui.info(opts.prune ? \"No prune candidates — every memory earns its keep.\" : \"No memories matched.\");\n return;\n }\n\n console.log(ui.bold(`Hivelore memory impact — ${root}`));\n console.log(\n ui.dim(\n `${summary.total} memories · ${summary.high} high · ${summary.medium} medium · ` +\n `${summary.low} low · ${summary.dormant} dormant · ${summary.prune_candidates} prune candidates`,\n ),\n );\n console.log();\n console.log(`${\"score\".padStart(5)} ${\"tier\".padEnd(7)} ${pad(\"id\", 52)} ${\"prune\".padEnd(5)} signals`);\n console.log(\"─\".repeat(108));\n for (const r of rows) {\n const score = r.impact.score.toFixed(2).padStart(5);\n const tier = tierBadge(r.impact.tier).padEnd(7);\n const prune = r.impact.pruneCandidate ? ui.yellow(\"prune\") : \" \";\n console.log(`${score} ${tier} ${pad(r.id, 52)} ${prune} ${ui.dim(r.impact.signals.join(\", \") || \"no signals\")}`);\n }\n\n if (!opts.prune && summary.prune_candidates > 0) {\n console.log();\n console.log(ui.dim(`Tip: \\`hivelore memory impact --prune\\` lists the ${summary.prune_candidates} prune candidate(s).`));\n }\n });\n}\n\nfunction tierBadge(tier: ImpactTier): string {\n switch (tier) {\n case \"high\": return ui.green(tier);\n case \"medium\": return ui.yellow(tier);\n case \"dormant\": return ui.dim(tier);\n default: return tier; // low\n }\n}\n\nfunction pad(value: string, width: number): string {\n if (value.length <= width) return value.padEnd(width);\n return value.slice(0, width - 1) + \"…\";\n}\n","import { existsSync } from \"node:fs\";\nimport { writeFile } from \"node:fs/promises\";\nimport { Command } from \"commander\";\nimport {\n applyFeedbackAdjustment,\n computeImpact,\n findProjectRoot,\n getUsage,\n loadUsageIndex,\n recordApplied,\n recordRejection,\n recommendFeedbackAdjustment,\n resolveHaivePaths,\n saveUsageIndex,\n serializeMemory,\n} from \"@hivelore/core\";\nimport { loadMemoriesFromDir } from \"../utils/fs.js\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface FeedbackOptions {\n applied?: boolean;\n rejected?: boolean;\n reason?: string;\n json?: boolean;\n dir?: string;\n}\n\nexport function registerMemoryFeedback(memory: Command): void {\n memory\n .command(\"feedback <id>\")\n .description(\n \"Record whether a memory actually helped — the closed-loop utility signal \" +\n \"(mirror of the mem_feedback MCP tool). 'applied' = it steered your work; \" +\n \"'rejected' = it was wrong/unhelpful. Feeds `hivelore memory impact`.\",\n )\n .option(\"--applied\", \"the memory changed what you did (positive signal)\", false)\n .option(\"--rejected\", \"the memory was wrong/outdated/unhelpful (negative signal)\", false)\n .option(\"--reason <text>\", \"why it was rejected (stored on the usage record)\")\n .option(\"--json\", \"emit JSON\", false)\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (id: string, opts: FeedbackOptions) => {\n if (opts.applied === opts.rejected) {\n ui.error(\"Specify exactly one of --applied or --rejected.\");\n process.exitCode = 1;\n return;\n }\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.memoriesDir)) {\n ui.error(`No .ai/memories at ${root}. Run \\`hivelore init\\` first.`);\n process.exitCode = 1;\n return;\n }\n\n const all = await loadMemoriesFromDir(paths.memoriesDir);\n const target = all.find((m) => m.memory.frontmatter.id === id);\n if (!target) {\n ui.error(`No memory with id '${id}'.`);\n process.exitCode = 1;\n return;\n }\n\n const index = await loadUsageIndex(paths);\n const outcome = opts.applied ? \"applied\" : \"rejected\";\n if (opts.applied) recordApplied(index, id);\n else recordRejection(index, id, opts.reason ?? null);\n await saveUsageIndex(paths, index);\n\n const usage = getUsage(index, id);\n const adjustment = opts.rejected\n ? recommendFeedbackAdjustment(target.memory.frontmatter, usage)\n : { action: \"none\" as const, reason: \"No automatic adjustment needed.\" };\n const adjustedFrontmatter = applyFeedbackAdjustment(target.memory.frontmatter, adjustment);\n if (adjustedFrontmatter !== target.memory.frontmatter) {\n target.memory.frontmatter = adjustedFrontmatter;\n await writeFile(target.filePath, serializeMemory(target.memory), \"utf8\");\n }\n const impact = computeImpact(target.memory.frontmatter, usage);\n\n if (opts.json) {\n console.log(JSON.stringify({ id, outcome, usage, impact, feedback_adjustment: adjustment }, null, 2));\n return;\n }\n\n ui.success(`Recorded '${outcome}' for ${id}`);\n ui.info(\n `applied=${usage.applied_count} · rejected=${usage.rejected_count} · read=${usage.read_count} ` +\n `→ impact ${impact.score.toFixed(2)} (${impact.tier})`,\n );\n if (adjustment.action !== \"none\") {\n ui.warn(`Feedback adjustment: ${adjustment.action} — ${adjustment.reason}`);\n }\n });\n}\n","import { writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n findProjectRoot,\n resolveHaivePaths,\n serializeMemory,\n verifyAnchor,\n} from \"@hivelore/core\";\nimport { loadMemoriesFromDir } from \"../utils/fs.js\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface VerifyOptions {\n id?: string;\n all?: boolean;\n update?: boolean;\n json?: boolean;\n dir?: string;\n}\n\ninterface VerifyResultEntry {\n id: string;\n status: \"fresh\" | \"stale\" | \"anchorless\";\n path: string;\n reason?: string;\n possible_renames?: string[];\n}\n\nexport function registerMemoryVerify(memory: Command): void {\n memory\n .command(\"verify\")\n .description(\n \"Check that memory anchor paths still exist in the current codebase.\\n\\n\" +\n \" A memory is 'stale' when its anchored file or symbol was moved, deleted, or renamed.\\n\" +\n \" Stale memories are shown with a warning in get_briefing and should be updated or deleted.\\n\\n\" +\n \" hivelore sync runs this automatically. Use this command for on-demand checks or in CI.\\n\\n\" +\n \" CI recommendation: add 'hivelore memory verify' to your haive-sync.yml PR check job\\n\" +\n \" to catch stale memories before they reach main.\\n\\n\" +\n \" Examples:\\n\" +\n \" hivelore memory verify # check all, report only\\n\" +\n \" hivelore memory verify --update # mark stale/fresh on disk\\n\" +\n \" hivelore memory verify --id 2026-04-28-gotcha-x # check one memory\\n\",\n )\n .option(\"--id <id>\", \"verify a single memory by id\")\n .option(\"--all\", \"verify every memory (default if --id is omitted)\")\n .option(\"--update\", \"write status=stale or status=validated back to disk\")\n .option(\"--json\", \"emit machine-readable JSON (for CI / agents)\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: VerifyOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.memoriesDir)) {\n if (opts.json) {\n console.log(JSON.stringify({ error: \"not-initialized\", root }, null, 2));\n } else {\n ui.error(`No .ai/memories at ${root}. Run \\`hivelore init\\` first.`);\n }\n process.exitCode = 1;\n return;\n }\n\n const all = await loadMemoriesFromDir(paths.memoriesDir);\n const targets = opts.id\n ? all.filter((m) => m.memory.frontmatter.id === opts.id)\n : all;\n\n if (opts.id && targets.length === 0) {\n if (opts.json) {\n console.log(JSON.stringify({ error: \"not-found\", id: opts.id }, null, 2));\n } else {\n ui.error(`No memory with id \"${opts.id}\".`);\n }\n process.exitCode = 1;\n return;\n }\n\n let staleCount = 0;\n let freshCount = 0;\n const anchorlessIds: string[] = [];\n const entries: VerifyResultEntry[] = [];\n let updated = 0;\n\n for (const { memory: mem, filePath } of targets) {\n const result = await verifyAnchor(mem, { projectRoot: root });\n const isAnchored =\n mem.frontmatter.anchor.paths.length > 0 ||\n mem.frontmatter.anchor.symbols.length > 0;\n const rel = path.relative(root, filePath);\n\n if (!isAnchored) {\n anchorlessIds.push(mem.frontmatter.id);\n entries.push({ id: mem.frontmatter.id, status: \"anchorless\", path: rel });\n continue;\n }\n\n if (result.stale) {\n staleCount++;\n entries.push({\n id: mem.frontmatter.id,\n status: \"stale\",\n path: rel,\n reason: result.reason ?? undefined,\n possible_renames: result.possibleRenames,\n });\n if (!opts.json) {\n console.log(`${ui.bold(\"STALE\")} ${mem.frontmatter.id}`);\n console.log(` ${ui.dim(rel)}`);\n console.log(` ${result.reason}`);\n if (result.possibleRenames.length > 0) {\n console.log(` ${ui.yellow(\"Possible renames:\")} ${result.possibleRenames.join(\", \")}`);\n }\n }\n } else {\n freshCount++;\n entries.push({ id: mem.frontmatter.id, status: \"fresh\", path: rel });\n if (!opts.json) console.log(`${ui.dim(\"fresh\")} ${mem.frontmatter.id}`);\n }\n\n if (opts.update) {\n const next = applyVerification(mem, result);\n await writeFile(filePath, serializeMemory(next), \"utf8\");\n updated++;\n }\n }\n\n if (opts.json) {\n console.log(JSON.stringify({\n summary: {\n checked: freshCount + staleCount,\n fresh: freshCount,\n stale: staleCount,\n anchorless: anchorlessIds.length,\n updated,\n },\n results: entries,\n }, null, 2));\n if (staleCount > 0) process.exitCode = 1;\n return;\n }\n\n const summary = [\n `${freshCount} fresh`,\n `${staleCount} stale`,\n `${anchorlessIds.length} anchorless (skipped)`,\n ];\n if (opts.update) summary.push(`${updated} updated on disk`);\n ui.info(summary.join(\" · \"));\n if (anchorlessIds.length > 0) {\n console.log(\n ui.dim(\n `Anchorless memories (no paths/symbols — staleness cannot be detected):\\n` +\n anchorlessIds.map((id) => ` ${id}`).join(\"\\n\") +\n `\\nTip: use \\`hivelore memory update <id> --paths <files>\\` to add anchors.`,\n ),\n );\n }\n });\n}\n\nfunction applyVerification(\n mem: Parameters<typeof serializeMemory>[0],\n result: { stale: boolean; reason: string | null },\n): Parameters<typeof serializeMemory>[0] {\n const verifiedAt = new Date().toISOString();\n if (result.stale) {\n return {\n frontmatter: {\n ...mem.frontmatter,\n status: \"stale\",\n verified_at: verifiedAt,\n stale_reason: result.reason,\n },\n body: mem.body,\n };\n }\n // Reset stale_reason when re-validating; keep validated/proposed status as is,\n // promote draft→validated when verification passes.\n const nextStatus =\n mem.frontmatter.status === \"stale\" || mem.frontmatter.status === \"draft\"\n ? \"validated\"\n : mem.frontmatter.status;\n return {\n frontmatter: {\n ...mem.frontmatter,\n status: nextStatus,\n verified_at: verifiedAt,\n stale_reason: null,\n },\n body: mem.body,\n };\n}\n","import { readFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { Command } from \"commander\";\nimport {\n findProjectRoot,\n resolveHaivePaths,\n} from \"@hivelore/core\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface ImportOptions {\n from: string;\n scope?: \"personal\" | \"team\";\n dir?: string;\n}\n\nexport function registerMemoryImport(memory: Command): void {\n memory\n .command(\"import\")\n .description(\n \"Parse a Markdown file and suggest memories via the import_docs MCP prompt (prints a ready-to-use prompt invocation)\",\n )\n .requiredOption(\"--from <file>\", \"Markdown/text file to import from\")\n .option(\"--scope <scope>\", \"personal | team (default: team)\", \"team\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: ImportOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n\n if (!existsSync(paths.haiveDir)) {\n ui.error(`No .ai/ found at ${root}. Run \\`hivelore init\\` first.`);\n process.exitCode = 1;\n return;\n }\n\n if (!existsSync(opts.from)) {\n ui.error(`File not found: ${opts.from}`);\n process.exitCode = 1;\n return;\n }\n\n const content = await readFile(opts.from, \"utf8\");\n const scope = opts.scope ?? \"team\";\n\n ui.info(`Preparing import from: ${opts.from} (scope=${scope})`);\n ui.info(`Content length: ${content.length} chars`);\n console.log();\n console.log(ui.bold(\"To import via MCP, invoke the `import_docs` prompt with:\"));\n console.log();\n console.log(\n ui.dim(\n JSON.stringify(\n {\n content: content.slice(0, 200) + (content.length > 200 ? \"…\" : \"\"),\n source: opts.from,\n scope,\n },\n null,\n 2,\n ),\n ),\n );\n console.log();\n ui.info(\n \"Or use your AI client to call: import_docs({ content: <file contents>, source: \\\"\" +\n opts.from +\n \"\\\", scope: \\\"\" +\n scope +\n \"\\\" })\",\n );\n });\n}\n","/**\n * hivelore memory import --from-changelog CHANGELOG.md [--package <name>]\n *\n * Parses a CHANGELOG.md file (Keep-a-Changelog format or common variants),\n * extracts breaking changes and notable gotchas from recent versions,\n * and saves them as Hivelore memories.\n *\n * Supports:\n * - Keep a Changelog (https://keepachangelog.com)\n * - Angular commit-based CHANGELOG format\n * - Plain Markdown changelogs with ## headers\n */\nimport { existsSync } from \"node:fs\";\nimport { readFile, mkdir, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n buildFrontmatter,\n findProjectRoot,\n resolveHaivePaths,\n serializeMemory,\n} from \"@hivelore/core\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface ImportChangelogOptions {\n fromChangelog: string;\n package?: string;\n scope?: string;\n versions?: string; // e.g. \"2.0.0,2.1.0\" or \"latest\"\n dir?: string;\n}\n\ninterface ChangelogEntry {\n version: string;\n breaking: string[];\n deprecated: string[];\n removed: string[];\n fixed: string[];\n added: string[];\n}\n\n// ── Parser ─────────────────────────────────────────────────────────────────\n\nfunction parseChangelog(content: string): ChangelogEntry[] {\n const entries: ChangelogEntry[] = [];\n const versionRe = /^#{1,3}\\s+(?:\\[?)([0-9]+\\.[0-9]+[.0-9]*)/m;\n const sections = content.split(/^#{1,3}\\s+/m).slice(1);\n\n for (const section of sections) {\n const versionMatch = section.match(/^(?:\\[?)([0-9]+\\.[0-9]+[.0-9]*)/);\n const version = versionMatch?.[1];\n if (!version) continue;\n\n const entry: ChangelogEntry = {\n version,\n breaking: [],\n deprecated: [],\n removed: [],\n fixed: [],\n added: [],\n };\n\n // Extract sub-sections\n const subSections = section.split(/^#{2,4}\\s+/m);\n for (const sub of subSections) {\n const firstLine = (sub.split(\"\\n\")[0] ?? \"\").toLowerCase().trim();\n const items = sub\n .split(\"\\n\")\n .slice(1)\n .filter((l) => l.trim().startsWith(\"-\") || l.trim().startsWith(\"*\"))\n .map((l) => l.replace(/^[\\s\\-*]+/, \"\").trim())\n .filter(Boolean);\n\n if (/breaking/.test(firstLine)) {\n entry.breaking.push(...items);\n } else if (/deprecated/.test(firstLine)) {\n entry.deprecated.push(...items);\n } else if (/removed/.test(firstLine)) {\n entry.removed.push(...items);\n } else if (/fixed|bug/.test(firstLine)) {\n entry.fixed.push(...items);\n } else if (/added|new|feat/.test(firstLine)) {\n entry.added.push(...items);\n }\n\n // Also scan for BREAKING CHANGE: prefixes in all items (Angular format)\n for (const sub2 of subSections) {\n for (const line of sub2.split(\"\\n\")) {\n const breakingMatch = line.match(/BREAKING CHANGE[S]?:\\s*(.+)/i);\n const breakingText = breakingMatch?.[1]?.trim();\n if (breakingText && !entry.breaking.includes(breakingText)) {\n entry.breaking.push(breakingText);\n }\n }\n }\n }\n\n // If no sub-sections matched, do a raw scan for breaking change indicators\n if (entry.breaking.length === 0) {\n for (const line of section.split(\"\\n\")) {\n if (/breaking|⚠|deprecated|removed/.test(line.toLowerCase())) {\n const item = line.replace(/^[\\s\\-*#]+/, \"\").trim();\n if (item) entry.breaking.push(item);\n }\n }\n }\n\n const hasContent =\n entry.breaking.length > 0 ||\n entry.deprecated.length > 0 ||\n entry.removed.length > 0;\n\n if (hasContent) entries.push(entry);\n }\n\n void versionRe; // used implicitly in section splitting\n return entries;\n}\n\n// ── CLI command ─────────────────────────────────────────────────────────────\n\nexport function registerMemoryImportChangelog(memory: Command): void {\n memory\n .command(\"import-changelog\")\n .description(\n \"Import breaking changes from a CHANGELOG.md as Hivelore memories.\\n\\n\" +\n \" Parses Keep-a-Changelog and Angular commit format changelogs,\\n\" +\n \" extracts breaking changes, deprecations, and removals,\\n\" +\n \" and saves each version's changes as a gotcha memory.\\n\\n\" +\n \" Examples:\\n\" +\n \" hivelore memory import-changelog --from node_modules/@company/sdk/CHANGELOG.md --package @company/sdk\\n\" +\n \" hivelore memory import-changelog --from CHANGELOG.md\\n\" +\n \" hivelore memory import-changelog --from CHANGELOG.md --versions 2.0.0,2.1.0\\n\",\n )\n .requiredOption(\"--from <file>\", \"path to the CHANGELOG.md file\")\n .option(\"--package <name>\", \"name of the package (used in memory title and tags)\")\n .option(\"--scope <scope>\", \"memory scope: team | personal (default: team)\", \"team\")\n .option(\n \"--versions <csv>\",\n \"only import specific versions (comma-separated), or 'latest' for the most recent breaking version\",\n )\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: ImportChangelogOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n\n const changelogPath = path.resolve(root, opts.fromChangelog);\n if (!existsSync(changelogPath)) {\n ui.error(`CHANGELOG not found: ${changelogPath}`);\n process.exitCode = 1;\n return;\n }\n\n const content = await readFile(changelogPath, \"utf8\");\n let entries = parseChangelog(content);\n\n if (entries.length === 0) {\n ui.warn(\"No breaking changes, deprecations, or removals found in the CHANGELOG.\");\n return;\n }\n\n // Filter by versions if specified\n if (opts.versions) {\n if (opts.versions === \"latest\") {\n const latest = entries[0];\n entries = latest ? [latest] : [];\n } else {\n const requested = opts.versions.split(\",\").map((v) => v.trim());\n entries = entries.filter((e) => requested.includes(e.version));\n }\n }\n\n const pkgName = opts.package ?? path.basename(path.dirname(changelogPath));\n const scope = (opts.scope ?? \"team\") as \"team\" | \"personal\";\n const teamDir = path.join(paths.memoriesDir, scope);\n await mkdir(teamDir, { recursive: true });\n\n let saved = 0;\n for (const entry of entries) {\n const lines: string[] = [];\n lines.push(`## ${pkgName} v${entry.version} — Breaking Changes & Deprecations\\n`);\n\n if (entry.breaking.length > 0) {\n lines.push(\"### 🔴 Breaking Changes\\n\");\n for (const item of entry.breaking) lines.push(`- ${item}`);\n lines.push(\"\");\n }\n if (entry.deprecated.length > 0) {\n lines.push(\"### 🟡 Deprecated\\n\");\n for (const item of entry.deprecated) lines.push(`- ${item}`);\n lines.push(\"\");\n }\n if (entry.removed.length > 0) {\n lines.push(\"### ⚫ Removed\\n\");\n for (const item of entry.removed) lines.push(`- ${item}`);\n lines.push(\"\");\n }\n\n lines.push(\n `**Source:** \\`${path.relative(root, changelogPath)}\\` \\n` +\n `**Action:** Update all usages of ${pkgName} if they rely on any of the above.`,\n );\n\n const slug = `changelog-${pkgName.replace(/[^a-z0-9]/gi, \"-\").toLowerCase()}-v${entry.version.replace(/\\./g, \"-\")}`;\n const fm = buildFrontmatter({\n type: \"gotcha\",\n slug,\n scope,\n status: \"validated\",\n tags: [\n \"changelog\",\n \"breaking-change\",\n pkgName.replace(/[^a-z0-9]/gi, \"-\").toLowerCase(),\n `v${entry.version}`,\n ],\n paths: [path.relative(root, changelogPath)],\n topic: `changelog-${pkgName}-${entry.version}`,\n });\n\n await writeFile(\n path.join(teamDir, `${fm.id}.md`),\n serializeMemory({ frontmatter: fm, body: lines.join(\"\\n\") }),\n \"utf8\",\n );\n console.log(ui.green(` ✓ ${fm.id}`));\n saved++;\n }\n\n console.log(\n `\\n${ui.bold(`Imported ${saved} changelog entr${saved === 1 ? \"y\" : \"ies\"} from ${pkgName}`)}`,\n );\n if (saved > 0) {\n console.log(\n ui.dim(` Memories saved to .ai/memories/${scope}/`),\n );\n console.log(\n ui.dim(` Run \\`hivelore briefing --task \"update ${pkgName}\"\\` to see them in context.`),\n );\n }\n });\n}\n","/**\n * hivelore memory digest — generate a Markdown report of memories added/updated\n * within the last N days for bulk review.\n *\n * Usage:\n * hivelore memory digest # last 7 days, team scope\n * hivelore memory digest --days 14 # last 14 days\n * hivelore memory digest --scope all # all scopes\n * hivelore memory digest --out digest.md # write to file instead of stdout\n */\nimport { existsSync } from \"node:fs\";\nimport { writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n deriveConfidence,\n findProjectRoot,\n getUsage,\n loadMemoriesFromDir,\n loadUsageIndex,\n resolveHaivePaths,\n} from \"@hivelore/core\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface DigestOptions {\n days?: string;\n scope?: string;\n out?: string;\n dir?: string;\n}\n\nconst CONFIDENCE_EMOJI: Record<string, string> = {\n unverified: \"⬜\",\n low: \"🟡\",\n trusted: \"🟢\",\n authoritative: \"⭐\",\n stale: \"🔴\",\n};\n\nexport function registerMemoryDigest(program: Command): void {\n program\n .command(\"digest\")\n .description(\n \"Generate a Markdown review digest of recently added or updated memories.\\n\\n\" +\n \" Groups memories by type, shows confidence, status, read count, and anchor info.\\n\" +\n \" Each memory has action checkboxes (approve / reject / keep as-is) for peer review.\\n\\n\" +\n \" Use this to do a bulk weekly review of team memories, or share with teammates\\n\" +\n \" as a pull-request attachment so humans can validate what the AI captured.\\n\\n\" +\n \" Examples:\\n\" +\n \" hivelore memory digest # last 7 days, team scope\\n\" +\n \" hivelore memory digest --days 30 --scope all # last 30 days, all scopes\\n\" +\n \" hivelore memory digest --out review.md # write to file\\n\",\n )\n .option(\"--days <n>\", \"look-back window in days (default: 7)\", \"7\")\n .option(\"--scope <scope>\", \"personal | team | module | all (default: team)\", \"team\")\n .option(\"--out <file>\", \"write digest to a file instead of stdout\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: DigestOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n\n if (!existsSync(paths.memoriesDir)) {\n ui.error(\"No .ai/memories found. Run `hivelore init` first.\");\n process.exitCode = 1;\n return;\n }\n\n const days = Math.max(1, Number(opts.days ?? 7));\n const scopeFilter = opts.scope ?? \"team\";\n const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000);\n\n const all = await loadMemoriesFromDir(paths.memoriesDir);\n const usage = await loadUsageIndex(paths);\n\n const recent = all.filter(({ memory: mem }) => {\n const fm = mem.frontmatter;\n if (fm.type === \"session_recap\") return false;\n if (fm.status === \"rejected\" || fm.status === \"deprecated\") return false;\n if (scopeFilter !== \"all\" && fm.scope !== scopeFilter) return false;\n return new Date(fm.created_at) >= cutoff;\n });\n\n const now = new Date().toISOString().slice(0, 10);\n const lines: string[] = [\n `# Hivelore Memory Digest — ${now}`,\n ``,\n `> **Period:** last ${days} day${days > 1 ? \"s\" : \"\"} | **Scope:** ${scopeFilter} | **Total:** ${recent.length} memor${recent.length === 1 ? \"y\" : \"ies\"}`,\n ``,\n `---`,\n ``,\n ];\n\n if (recent.length === 0) {\n lines.push(`_No new memories in the last ${days} days._`);\n } else {\n // Group by type\n const byType = new Map<string, typeof recent>();\n for (const m of recent) {\n const t = m.memory.frontmatter.type;\n if (!byType.has(t)) byType.set(t, []);\n byType.get(t)!.push(m);\n }\n\n for (const [type, mems] of byType) {\n lines.push(`## ${type.charAt(0).toUpperCase() + type.slice(1)} (${mems.length})`);\n lines.push(``);\n\n for (const { memory: mem } of mems) {\n const fm = mem.frontmatter;\n const u = getUsage(usage, fm.id);\n const confidence = deriveConfidence(fm, u);\n const emoji = CONFIDENCE_EMOJI[confidence] ?? \"⬜\";\n const anchor = fm.anchor.paths.length > 0\n ? `\\`${fm.anchor.paths[0]}\\`` + (fm.anchor.paths.length > 1 ? ` +${fm.anchor.paths.length - 1}` : \"\")\n : \"_no anchor_\";\n\n lines.push(`### ${emoji} \\`${fm.id}\\``);\n lines.push(``);\n lines.push(`| Field | Value |`);\n lines.push(`|---|---|`);\n lines.push(`| **Status** | \\`${fm.status}\\` |`);\n lines.push(`| **Confidence** | ${confidence} |`);\n lines.push(`| **Scope** | ${fm.scope}${fm.module ? `/${fm.module}` : \"\"} |`);\n lines.push(`| **Tags** | ${fm.tags.length > 0 ? fm.tags.map((t) => `\\`${t}\\``).join(\", \") : \"_none_\"} |`);\n lines.push(`| **Anchor** | ${anchor} |`);\n lines.push(`| **Reads** | ${u.read_count} |`);\n lines.push(`| **Created** | ${fm.created_at.slice(0, 10)} |`);\n lines.push(``);\n // First 6 lines of body\n const bodyPreview = mem.body.split(\"\\n\").slice(0, 6).join(\"\\n\").trim();\n lines.push(bodyPreview);\n lines.push(``);\n lines.push(`**Action:** [ ] approve [ ] reject [ ] keep as-is`);\n lines.push(``);\n lines.push(`---`);\n lines.push(``);\n }\n }\n }\n\n lines.push(``);\n lines.push(\n `> _To take action: \\`hivelore memory approve <id>\\`, \\`hivelore memory reject <id>\\`, or open \\`hivelore tui\\` for interactive review._`,\n );\n\n const digest = lines.join(\"\\n\");\n\n if (opts.out) {\n const outPath = path.resolve(process.cwd(), opts.out);\n await writeFile(outPath, digest, \"utf8\");\n ui.success(`Digest written to ${opts.out} (${recent.length} memor${recent.length === 1 ? \"y\" : \"ies\"})`);\n } else {\n console.log(digest);\n }\n });\n}\n","/**\n * hivelore session end — save a structured end-of-session recap.\n *\n * Uses topic-upsert: one recap per scope is kept and updated in-place.\n * get_briefing automatically surfaces the latest recap at the next session start.\n */\nimport { writeFile, mkdir, readFile, rm } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { spawn } from \"node:child_process\";\nimport path from \"node:path\";\nimport { Command, Option } from \"commander\";\nimport {\n buildFrontmatter,\n findProjectRoot,\n loadConfig,\n loadMemoriesFromDir,\n loadPreventionEvents,\n loadUsageIndex,\n memoryFilePath,\n renderCaughtForYou,\n resolveHaivePaths,\n serializeMemory,\n summarizeCaughtForYou,\n writeSessionHandoff,\n type MemoryFrontmatter,\n type MemoryScope,\n} from \"@hivelore/core\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface SessionEndOptions {\n goal?: string;\n accomplished?: string;\n discoveries?: string;\n files?: string;\n next?: string;\n scope?: MemoryScope;\n module?: string;\n dir?: string;\n auto?: boolean;\n quiet?: boolean;\n}\n\ninterface Observation {\n ts: string;\n session_id?: string;\n cwd?: string;\n tool: string;\n summary: string;\n files?: string[];\n failure_hint?: true;\n}\n\nasync function buildAutoRecap(\n paths: ReturnType<typeof resolveHaivePaths>,\n): Promise<{ goal: string; accomplished: string; discoveries?: string; files: string[]; rawCount: number } | null> {\n const obsFile = path.join(paths.haiveDir, \".cache\", \"observations.jsonl\");\n if (!existsSync(obsFile)) return await buildGitAutoRecap(paths);\n const raw = await readFile(obsFile, \"utf8\").catch(() => \"\");\n if (!raw.trim()) return await buildGitAutoRecap(paths);\n const lines = raw.split(\"\\n\").filter(Boolean);\n const obs: Observation[] = [];\n for (const line of lines) {\n try { obs.push(JSON.parse(line) as Observation); } catch { /* skip */ }\n }\n if (obs.length === 0) return await buildGitAutoRecap(paths);\n\n // ── Aggregate tool usage ────────────────────────────────────────────────\n const toolCounts = new Map<string, number>();\n const writeFiles = new Set<string>(); // files that were written/edited\n const readFiles = new Set<string>(); // files that were only read\n for (const o of obs) {\n toolCounts.set(o.tool, (toolCounts.get(o.tool) ?? 0) + 1);\n const isWrite = [\"Edit\", \"Write\", \"NotebookEdit\"].includes(o.tool);\n for (const f of o.files ?? []) {\n const rel = normalizeAnchorPath(paths.root, f);\n if (isWrite) writeFiles.add(rel);\n else readFiles.add(rel);\n }\n }\n // Files in both sets — the write set is authoritative\n for (const f of writeFiles) readFiles.delete(f);\n\n const topTools = [...toolCounts.entries()]\n .sort((a, b) => b[1] - a[1])\n .slice(0, 5)\n .map(([t, c]) => `${t} ×${c}`)\n .join(\", \");\n\n // ── Build accomplished section ─────────────────────────────────────────\n // Prefer git log context (richer than raw tool call list)\n const recentCommits = await runGit(paths.root, [\"log\", \"--oneline\", \"-5\"]).catch(() => \"\");\n const accomplishedParts: string[] = [];\n\n if (writeFiles.size > 0) {\n accomplishedParts.push(\n `**Files modified (${writeFiles.size}):**`,\n ...[...writeFiles].slice(0, 10).map((f) => `- \\`${f}\\``),\n ...(writeFiles.size > 10 ? [`- ...and ${writeFiles.size - 10} more`] : []),\n );\n }\n\n if (recentCommits.trim()) {\n accomplishedParts.push(\"\", \"**Recent commits:**\");\n for (const line of recentCommits.trim().split(\"\\n\").slice(0, 5)) {\n accomplishedParts.push(`- ${line}`);\n }\n }\n\n if (accomplishedParts.length === 0) {\n accomplishedParts.push(`${obs.length} tool calls (${topTools}) — no file writes detected.`);\n }\n\n // ── Discoveries: failures + notable observations ───────────────────────\n const failures = obs.filter((o) => o.failure_hint);\n const discoveriesParts: string[] = [];\n if (failures.length > 0) {\n discoveriesParts.push(\n `⚠️ ${failures.length} failure${failures.length === 1 ? \"\" : \"s\"} detected — call \\`mem_tried\\` for each unresolved one:`,\n ...failures.slice(0, 8).map((o) => `- ${o.summary.slice(0, 180)}`),\n );\n }\n\n const goal = writeFiles.size > 0\n ? `Edited ${writeFiles.size} file${writeFiles.size === 1 ? \"\" : \"s\"} across ${obs.length} tool calls`\n : `Session with ${obs.length} tool calls (${topTools}) — read-only or no writes captured`;\n\n return {\n goal,\n accomplished: accomplishedParts.join(\"\\n\"),\n ...(discoveriesParts.length > 0 ? { discoveries: discoveriesParts.join(\"\\n\") } : {}),\n files: [...writeFiles].slice(0, 12),\n rawCount: obs.length,\n };\n}\n\nasync function buildGitAutoRecap(\n paths: ReturnType<typeof resolveHaivePaths>,\n): Promise<{ goal: string; accomplished: string; discoveries?: string; files: string[]; rawCount: number } | null> {\n const changed = await runGit(paths.root, [\"diff\", \"--name-only\"]).catch(() => \"\");\n const staged = await runGit(paths.root, [\"diff\", \"--cached\", \"--name-only\"]).catch(() => \"\");\n const statusRaw = await runGit(paths.root, [\"status\", \"--porcelain\"]).catch(() => \"\");\n const recentLog = await runGit(paths.root, [\"log\", \"--oneline\", \"-5\"]).catch(() => \"\");\n const diffStat = await runGit(paths.root, [\"diff\", \"--stat\", \"HEAD\"]).catch(() => \"\");\n\n const files = Array.from(new Set(\n [\n ...changed.split(\"\\n\"),\n ...staged.split(\"\\n\"),\n ...statusRaw.split(\"\\n\").map((line) => line.replace(/^[ MADRCU?!]{1,2}\\s+/, \"\")),\n ]\n .map((s) => s.trim())\n .filter(Boolean)\n .filter((file) => !file.startsWith(\".ai/.runtime/\") && !file.startsWith(\".ai/.cache/\")),\n )).sort();\n\n // Parse porcelain status to get modified/added/deleted categories\n const modified: string[] = [];\n const added: string[] = [];\n const deleted: string[] = [];\n for (const line of statusRaw.split(\"\\n\")) {\n const code = line.substring(0, 2).trim();\n const file = line.substring(3).trim().replace(/\".+\"/g, (m) => m.slice(1, -1));\n if (!file || file.startsWith(\".ai/.runtime/\") || file.startsWith(\".ai/.cache/\")) continue;\n if (code === \"D\" || code === \"DD\") deleted.push(file);\n else if (code === \"A\" || code === \"??\") added.push(file);\n else if (file) modified.push(file);\n }\n\n const accomplishedParts: string[] = [];\n if (modified.length > 0) {\n accomplishedParts.push(`**Modified (${modified.length}):**`);\n for (const f of modified.slice(0, 8)) accomplishedParts.push(`- \\`${f}\\``);\n if (modified.length > 8) accomplishedParts.push(`- ...and ${modified.length - 8} more`);\n }\n if (added.length > 0) {\n accomplishedParts.push(`\\n**Added (${added.length}):**`);\n for (const f of added.slice(0, 5)) accomplishedParts.push(`- \\`${f}\\``);\n if (added.length > 5) accomplishedParts.push(`- ...and ${added.length - 5} more`);\n }\n if (deleted.length > 0) {\n accomplishedParts.push(`\\n**Deleted (${deleted.length}):**`);\n for (const f of deleted.slice(0, 5)) accomplishedParts.push(`- \\`${f}\\``);\n }\n\n if (recentLog.trim()) {\n accomplishedParts.push(\"\\n**Recent commits:**\");\n for (const line of recentLog.trim().split(\"\\n\").slice(0, 5)) {\n accomplishedParts.push(`- ${line}`);\n }\n }\n\n if (accomplishedParts.length === 0 && files.length === 0) return null;\n\n if (accomplishedParts.length === 0) {\n accomplishedParts.push(...files.slice(0, 12).map((f) => `- \\`${f}\\``));\n if (files.length > 12) accomplishedParts.push(`- ...and ${files.length - 12} more`);\n }\n\n return {\n goal: files.length > 0\n ? `Session with ${files.length} changed file${files.length === 1 ? \"\" : \"s\"}`\n : `Session with recent commits (no uncommitted changes)`,\n accomplished: accomplishedParts.join(\"\\n\"),\n discoveries: diffStat.trim() ? `Git diff stat:\\n\\`\\`\\`\\n${diffStat.trim()}\\n\\`\\`\\`` : undefined,\n files: files.slice(0, 12),\n rawCount: files.length,\n };\n}\n\nfunction buildRecapBody(opts: {\n goal: string;\n accomplished: string;\n discoveries?: string;\n files?: string;\n next?: string;\n}): string {\n const lines: string[] = [];\n lines.push(`## Goal\\n${opts.goal}`);\n lines.push(`\\n## Accomplished\\n${opts.accomplished}`);\n if (opts.discoveries?.trim()) {\n lines.push(`\\n## Discoveries & surprises\\n${opts.discoveries}`);\n }\n const filesTouched = parseCsv(opts.files);\n if (filesTouched.length > 0) {\n lines.push(`\\n## Files touched\\n${filesTouched.map((f) => `- \\`${f}\\``).join(\"\\n\")}`);\n }\n if (opts.next?.trim()) {\n lines.push(`\\n## Next steps\\n${opts.next}`);\n }\n return lines.join(\"\\n\");\n}\n\nfunction runGit(cwd: string, args: string[]): Promise<string> {\n return new Promise((resolve, reject) => {\n const proc = spawn(\"git\", args, { cwd, stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n let stdout = \"\";\n let stderr = \"\";\n proc.stdout.on(\"data\", (chunk) => { stdout += chunk.toString(); });\n proc.stderr.on(\"data\", (chunk) => { stderr += chunk.toString(); });\n proc.on(\"error\", reject);\n proc.on(\"close\", (code) => {\n if (code === 0) resolve(stdout);\n else reject(new Error(stderr || `git ${args.join(\" \")} exited with code ${code}`));\n });\n });\n}\n\nasync function observationStart(paths: ReturnType<typeof resolveHaivePaths>): Promise<string | null> {\n const obsFile = path.join(paths.haiveDir, \".cache\", \"observations.jsonl\");\n if (!existsSync(obsFile)) return null;\n const raw = await readFile(obsFile, \"utf8\").catch(() => \"\");\n let first: string | null = null;\n for (const line of raw.split(\"\\n\")) {\n if (!line.trim()) continue;\n try {\n const obs = JSON.parse(line) as Partial<Observation>;\n if (typeof obs.ts !== \"string\") continue;\n if (!first || obs.ts < first) first = obs.ts;\n } catch {\n // ignore corrupt observation rows\n }\n }\n return first;\n}\n\nasync function printCaughtForYou(\n paths: ReturnType<typeof resolveHaivePaths>,\n since: string | null,\n quiet: boolean | undefined,\n): Promise<void> {\n if (quiet) return;\n const memories = existsSync(paths.memoriesDir) ? await loadMemoriesFromDir(paths.memoriesDir) : [];\n const usage = await loadUsageIndex(paths);\n const events = await loadPreventionEvents(paths);\n const summary = summarizeCaughtForYou(events, memories, usage, {\n ...(since ? { since } : {}),\n now: new Date(),\n limit: 5,\n });\n const block = renderCaughtForYou(summary);\n if (block) {\n console.log();\n console.log(ui.bold(block));\n }\n}\n\nfunction recapTopic(scope: string, module?: string): string {\n return module ? `session-recap-${scope}-${module}` : `session-recap-${scope}`;\n}\n\nexport function registerSessionEnd(session: Command): void {\n session\n .command(\"end\")\n .description(\n \"Save an end-of-session recap so the NEXT session starts with fresh context.\\n\\n\" +\n \" One recap per scope is kept and updated in-place (topic-upsert). The next\\n\" +\n \" session's get_briefing (or hivelore briefing) shows it at the very top.\\n\\n\" +\n \" In autopilot mode, a minimal recap saves automatically on MCP server exit.\\n\" +\n \" Calling this manually produces a richer, more actionable recap.\\n\\n\" +\n \" Example:\\n\" +\n \" hivelore session end \\\\\\\\\\n\" +\n \" --goal \\\"Add Stripe webhook handler\\\" \\\\\\\\\\n\" +\n \" --accomplished \\\"Implemented webhook endpoint, added idempotency key\\\" \\\\\\\\\\n\" +\n \" --discoveries \\\"Missing .env.example entry for STRIPE_WEBHOOK_SECRET\\\" \\\\\\\\\\n\" +\n \" --files src/payments/WebhookController.ts,src/payments/WebhookService.ts \\\\\\\\\\n\" +\n \" --next \\\"Add integration tests for webhook signature validation\\\"\\n\",\n )\n .option(\"--goal <text>\", \"what you were trying to accomplish (1–2 sentences)\")\n .option(\"--accomplished <text>\", \"what was actually done (bullet list recommended)\")\n // Hidden synonym: agents guess `--summary` for a one-blob recap; map it to --accomplished\n // instead of dead-ending them. Kept out of help so the structured flags stay the documented API.\n .addOption(new Option(\"--summary <text>\", \"alias for --accomplished\").hideHelp())\n .option(\"--discoveries <text>\", \"bugs, surprises, or inconsistencies found during this session\")\n .option(\"--files <csv>\", \"key files touched, comma-separated (used as anchor for staleness detection)\")\n .option(\"--next <text>\", \"what should happen next (for the next session or a teammate)\")\n .option(\"--scope <scope>\", \"personal | team | module (default: personal)\", \"personal\")\n .option(\"--module <name>\", \"module name (required when scope=module)\")\n .option(\"--auto\", \"synthesize the recap from .ai/.cache/observations.jsonl (used by Claude Code SessionEnd hook)\")\n .option(\"--quiet\", \"suppress non-error output (for hook use)\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: SessionEndOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n\n if (!existsSync(paths.haiveDir)) {\n if (opts.auto || opts.quiet) return; // hook context — silently no-op\n ui.error(`No .ai/ found at ${root}. Run \\`hivelore init\\` first.`);\n process.exitCode = 1;\n return;\n }\n\n // Auto mode: derive goal/accomplished/files from captured observations\n let resolvedFiles = opts.files;\n let goal = opts.goal;\n let accomplished = opts.accomplished ?? (opts as { summary?: string }).summary;\n const caughtSince = opts.auto ? await observationStart(paths) : null;\n if (opts.auto) {\n const synth = await buildAutoRecap(paths);\n if (!synth) return; // nothing observed — silently no-op\n goal = goal ?? synth.goal;\n accomplished = accomplished ?? synth.accomplished;\n opts.discoveries = opts.discoveries ?? synth.discoveries;\n if (!resolvedFiles && synth.files.length) resolvedFiles = synth.files.join(\",\");\n }\n\n if (!goal || !accomplished) {\n if (opts.quiet) return;\n ui.error(\"session-end requires --goal and --accomplished (or pass --auto with captured observations).\");\n process.exitCode = 1;\n return;\n }\n\n const scope = opts.scope ?? \"personal\";\n const body = buildRecapBody({\n goal,\n accomplished,\n discoveries: opts.discoveries,\n files: resolvedFiles,\n next: opts.next,\n });\n const topic = recapTopic(scope, opts.module);\n // Normalize to project-relative paths before storing as anchors\n const filesTouched = parseCsv(resolvedFiles).map((p) => normalizeAnchorPath(root, p));\n\n // Warn about paths that don't exist in project\n const missingPaths = filesTouched.filter((p) => !existsSync(path.resolve(root, p)));\n if (missingPaths.length > 0 && !opts.quiet) {\n ui.warn(`Anchor path${missingPaths.length > 1 ? \"s\" : \"\"} not found in project (will be stale):`);\n for (const p of missingPaths) ui.warn(` ✗ ${p}`);\n }\n\n const cleanupObservations = async (): Promise<void> => {\n if (!opts.auto) return;\n const obsFile = path.join(paths.haiveDir, \".cache\", \"observations.jsonl\");\n if (existsSync(obsFile)) await rm(obsFile).catch(() => { /* non-fatal */ });\n };\n\n // ── Auto mode honoring config ───────────────────────────────────\n // When autoSessionRecap=false, an automatic (hook-driven) session end does NOT persist a\n // recap memory into the corpus; it writes an ephemeral NEXT.md handoff instead (if enabled).\n // A manual `hivelore session end --goal ...` is unaffected (explicit recaps are always honored).\n const config = await loadConfig(paths);\n if (opts.auto && config.autoSessionRecap === false) {\n if (config.sessionHandoff) {\n const diffStat = await runGit(root, [\"diff\", \"--stat\", \"HEAD\"]).catch(() => \"\");\n const openThreads = (opts.discoveries ?? \"\")\n .split(\"\\n\")\n .map((s) => s.replace(/^[-*]\\s*/, \"\").trim())\n .filter(Boolean);\n await writeSessionHandoff(root, {\n goal,\n openThreads,\n filesTouched,\n ...(opts.next?.trim() ? { nextSteps: opts.next.trim() } : {}),\n ...(diffStat.trim() ? { diffStat: diffStat.trim() } : {}),\n });\n }\n await cleanupObservations();\n if (!opts.quiet) {\n ui.info(\n config.sessionHandoff\n ? \"Auto recap disabled (autoSessionRecap=false) — wrote ephemeral NEXT.md handoff.\"\n : \"Auto recap disabled (autoSessionRecap=false) — no recap memory written.\",\n );\n }\n return;\n }\n\n // ── Topic upsert ────────────────────────────────────────────────\n if (existsSync(paths.memoriesDir)) {\n const existing = await loadMemoriesFromDir(paths.memoriesDir);\n const topicMatch = existing.find(({ memory }) =>\n memory.frontmatter.topic === topic &&\n memory.frontmatter.scope === scope &&\n (!opts.module || memory.frontmatter.module === opts.module),\n );\n\n if (topicMatch) {\n const fm = topicMatch.memory.frontmatter;\n const revisionCount = (fm.revision_count ?? 0) + 1;\n const newFrontmatter: MemoryFrontmatter = {\n ...fm,\n verified_at: new Date().toISOString(),\n revision_count: revisionCount,\n anchor: {\n ...fm.anchor,\n paths: filesTouched.length ? filesTouched : fm.anchor.paths,\n },\n };\n await writeFile(topicMatch.filePath, serializeMemory({ frontmatter: newFrontmatter, body }), \"utf8\");\n await cleanupObservations();\n if (!opts.quiet) {\n ui.success(`Session recap updated (revision #${revisionCount})`);\n ui.info(`id=${fm.id} file=${path.relative(root, topicMatch.filePath)}`);\n await printCaughtForYou(paths, caughtSince, opts.quiet);\n ui.info(\"Tip: `hivelore stats --export-report` generates a usage JSON suitable for dashboards.\");\n }\n return;\n }\n }\n\n // ── Create first recap ──────────────────────────────────────────\n const frontmatter = buildFrontmatter({\n type: \"session_recap\",\n slug: \"recap\",\n scope,\n module: opts.module,\n tags: [\"session\", \"recap\"],\n paths: filesTouched,\n topic,\n status: \"validated\",\n });\n\n const file = memoryFilePath(paths, frontmatter.scope, frontmatter.id, frontmatter.module);\n await mkdir(path.dirname(file), { recursive: true });\n await writeFile(file, serializeMemory({ frontmatter, body }), \"utf8\");\n await cleanupObservations();\n\n if (!opts.quiet) {\n ui.success(`Session recap created`);\n ui.info(`id=${frontmatter.id} scope=${scope} file=${path.relative(root, file)}`);\n await printCaughtForYou(paths, caughtSince, opts.quiet);\n ui.info(\"Next session: call `get_briefing` — the recap will be surfaced automatically.\");\n ui.info(\"Tip: export a local MCP usage rollup with `hivelore stats --export-report .ai/tool-usage-roi-report.json`.\");\n }\n });\n}\n\nfunction parseCsv(value: string | undefined): string[] {\n if (!value) return [];\n return value.split(\",\").map((s) => s.trim()).filter(Boolean);\n}\n\n/**\n * Convert an absolute or home-relative path to a project-relative path.\n * If the path is already relative, it is returned as-is.\n * Absolute paths outside the project root are kept as-is (external resources).\n */\nexport function normalizeAnchorPath(root: string, filePath: string): string {\n if (!filePath) return filePath;\n // Already relative\n if (!path.isAbsolute(filePath)) return filePath;\n const rel = path.relative(root, filePath);\n // If the relative path goes outside the root (../../..), keep as-is\n if (rel.startsWith(\"..\")) return filePath;\n return rel;\n}\n","/**\n * hivelore snapshot — take or compare an API contract snapshot.\n *\n * hivelore snapshot --contract openapi.yaml --name payment-api\n * hivelore snapshot --contract schema.graphql --format graphql\n * hivelore snapshot --diff --name payment-api\n * hivelore snapshot --list\n */\nimport { existsSync } from \"node:fs\";\nimport { readdir } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n diffContract,\n findProjectRoot,\n loadConfig,\n resolveHaivePaths,\n snapshotContract,\n} from \"@hivelore/core\";\nimport type { ContractFile } from \"@hivelore/core\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface SnapshotOptions {\n contract?: string;\n name?: string;\n format?: string;\n diff?: boolean;\n list?: boolean;\n dir?: string;\n}\n\nexport function registerSnapshot(program: Command): void {\n program\n .command(\"snapshot\")\n .description(\n \"Take or compare an API contract snapshot to detect breaking changes.\\n\\n\" +\n \" A snapshot captures the structure of a contract file (endpoints, types, fields).\\n\" +\n \" Running 'hivelore sync' automatically checks all configured contracts.\\n\" +\n \" This command lets you snapshot or diff a single contract on demand.\\n\\n\" +\n \" Supported formats: openapi, graphql, proto, typescript, json-schema\\n\\n\" +\n \" Examples:\\n\" +\n \" hivelore snapshot --contract docs/openapi.yaml --name payment-api\\n\" +\n \" hivelore snapshot --diff --name payment-api\\n\" +\n \" hivelore snapshot --list\\n\\n\" +\n \" To monitor contracts automatically on hivelore sync, add them to haive.config.json:\\n\" +\n \" { \\\"contractFiles\\\": [{ \\\"name\\\": \\\"payment-api\\\", \\\"path\\\": \\\"docs/openapi.yaml\\\", \\\"format\\\": \\\"openapi\\\" }] }\\n\",\n )\n .option(\"--contract <file>\", \"path to the contract file to snapshot (relative to project root)\")\n .option(\"--name <name>\", \"name for this contract (used in the lock file and memories)\")\n .option(\n \"--format <format>\",\n \"contract format: openapi | graphql | proto | typescript | json-schema (auto-detected if omitted)\",\n )\n .option(\"--diff\", \"compare the contract against its stored snapshot\")\n .option(\"--list\", \"list all stored contract snapshots\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: SnapshotOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n\n if (!existsSync(paths.haiveDir)) {\n ui.error(\"No .ai/ found. Run `hivelore init` first.\");\n process.exitCode = 1;\n return;\n }\n\n // hivelore snapshot --list\n if (opts.list) {\n const contractsDir = path.join(paths.haiveDir, \"contracts\");\n if (!existsSync(contractsDir)) {\n console.log(ui.dim(\"No contract snapshots found.\"));\n return;\n }\n const files = (await readdir(contractsDir)).filter(\n (f) => f.endsWith(\".lock\") && !f.startsWith(\"deps-\"),\n );\n if (files.length === 0) {\n console.log(ui.dim(\"No contract snapshots found.\"));\n return;\n }\n console.log(ui.bold(`Contract snapshots (${files.length}):`));\n for (const f of files) {\n const name = f.replace(\".lock\", \"\");\n console.log(` ${name}`);\n }\n return;\n }\n\n // hivelore snapshot --diff --name <name>\n if (opts.diff) {\n if (!opts.name) {\n // Try all configured contracts\n const config = await loadConfig(paths);\n const contracts = config.contractFiles ?? [];\n if (contracts.length === 0) {\n ui.error(\"--diff requires --name, or configure contractFiles in haive.config.json\");\n process.exitCode = 1;\n return;\n }\n for (const contract of contracts) {\n await runDiff(root, paths.haiveDir, contract);\n }\n return;\n }\n\n // Diff a named contract (need to know path — check config)\n const config = await loadConfig(paths);\n const configured = (config.contractFiles ?? []).find((c) => c.name === opts.name);\n if (!configured && !opts.contract) {\n ui.error(\n `Contract \"${opts.name}\" not found in haive.config.json and --contract not provided.`,\n );\n process.exitCode = 1;\n return;\n }\n const contract: ContractFile = configured ?? {\n name: opts.name!,\n path: opts.contract!,\n format: detectFormat(opts.contract ?? \"\") ?? \"openapi\",\n };\n await runDiff(root, paths.haiveDir, contract);\n return;\n }\n\n // hivelore snapshot --contract <file> [--name <name>] [--format <format>]\n if (!opts.contract) {\n ui.error(\"Provide --contract <file> or use --diff / --list.\");\n process.exitCode = 1;\n return;\n }\n\n const contractPath = opts.contract;\n const name = opts.name ?? path.basename(contractPath, path.extname(contractPath));\n const format =\n (opts.format as ContractFile[\"format\"]) ?? detectFormat(contractPath) ?? \"openapi\";\n\n const contract: ContractFile = { name, path: contractPath, format };\n try {\n const snapshot = await snapshotContract(root, paths.haiveDir, contract);\n console.log(ui.green(`✓ snapshot saved: ${name}`));\n if (snapshot.endpoints) {\n console.log(ui.dim(` ${snapshot.endpoints.length} endpoint(s) captured`));\n }\n if (snapshot.types) {\n console.log(ui.dim(` ${snapshot.types.length} type(s) captured`));\n }\n console.log(ui.dim(` lock: .ai/contracts/${name}.lock`));\n console.log(ui.dim(\" Next hivelore sync will detect changes automatically.\"));\n console.log(\n ui.dim(\n ` Tip: add to haive.config.json → contractFiles to monitor automatically:\\n` +\n ` { \"name\": \"${name}\", \"path\": \"${contractPath}\", \"format\": \"${format}\" }`,\n ),\n );\n } catch (err) {\n ui.error(String(err));\n process.exitCode = 1;\n }\n });\n}\n\nasync function runDiff(\n root: string,\n haiveDir: string,\n contract: ContractFile,\n): Promise<void> {\n try {\n const result = await diffContract(root, haiveDir, contract);\n if (result.unchanged) {\n console.log(ui.green(`✓ ${contract.name}: no changes detected`));\n return;\n }\n const breaking = result.changes.filter((c) => c.severity === \"breaking\");\n const additive = result.changes.filter((c) => c.severity === \"additive\");\n const unknown = result.changes.filter((c) => c.severity === \"unknown\");\n\n console.log(\n ui.bold(`Contract diff: ${contract.name}`) +\n ` — ${breaking.length} breaking · ${additive.length} additive · ${unknown.length} unknown`,\n );\n for (const c of result.changes) {\n const icon = c.severity === \"breaking\" ? \"🔴\" : c.severity === \"additive\" ? \"🟢\" : \"🟡\";\n console.log(` ${icon} ${c.description}`);\n }\n if (breaking.length > 0) {\n console.log(\n ui.yellow(\n \"\\n ⚠ Breaking changes detected — run `hivelore sync` to create a gotcha memory for your team.\",\n ),\n );\n }\n } catch (err) {\n ui.error(`diff failed for ${contract.name}: ${String(err)}`);\n }\n}\n\nfunction detectFormat(filePath: string): ContractFile[\"format\"] | null {\n const ext = path.extname(filePath).toLowerCase();\n const base = path.basename(filePath).toLowerCase();\n if (ext === \".yaml\" || ext === \".yml\" || ext === \".json\") {\n if (base.includes(\"openapi\") || base.includes(\"swagger\")) return \"openapi\";\n if (base.includes(\"schema\") || base.includes(\"graphql\")) return \"graphql\";\n return \"openapi\"; // default for YAML/JSON\n }\n if (ext === \".graphql\" || ext === \".gql\") return \"graphql\";\n if (ext === \".proto\") return \"proto\";\n if (ext === \".d.ts\" || ext === \".ts\") return \"typescript\";\n return null;\n}\n","/**\n * hivelore hub — shared team-knowledge hub operations.\n *\n * hivelore hub pull — import shared memories from the hub into this project\n * hivelore hub push — export this project's shared memories to the hub\n * hivelore hub status — show hub sync status (last pull/push, counts)\n * hivelore hub init <path> — initialize a new hub repo at <path>\n *\n * The hub is a plain git repo with a .ai/ directory.\n * Set hubPath in haive.config.json (relative or absolute path to the hub).\n *\n * Hub memory layout:\n * .ai/memories/shared/<source-project-name>/\n * - memories tagged with the source project name\n * - committed to the hub repo\n *\n * Multiple projects point at the same hub. Each project:\n * - push: writes its `shared`-scoped memories to hub/.ai/memories/shared/<project-name>/\n * - pull: reads from all other projects' shared directories in the hub\n */\nimport { existsSync } from \"node:fs\";\nimport { mkdir, readFile, writeFile, copyFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { spawnSync } from \"node:child_process\";\nimport { Command } from \"commander\";\nimport {\n findProjectRoot,\n loadConfig,\n loadMemoriesFromDir,\n resolveHaivePaths,\n saveConfig,\n serializeMemory,\n} from \"@hivelore/core\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface HubOptions {\n dir?: string;\n commit?: boolean;\n message?: string;\n}\n\nexport function registerHub(program: Command): void {\n const hub = program\n .command(\"hub\")\n .description(\n \"Manage a shared team-knowledge hub — a central repo that multiple projects contribute to and pull from.\\n\\n\" +\n \" The hub is a plain git repo with a .ai/ directory. Each project pushes its\\n\" +\n \" `shared`-scoped memories to the hub and pulls from all other projects.\\n\\n\" +\n \" Setup:\\n\" +\n \" 1. hivelore hub init /path/to/team-hub\\n\" +\n \" 2. Add hubPath to .ai/haive.config.json: { \\\"hubPath\\\": \\\"../team-hub\\\" }\\n\" +\n \" 3. hivelore hub push — publish your shared memories\\n\" +\n \" 4. hivelore hub pull — import other projects' shared memories\\n\\n\" +\n \" Or configure in haive.config.json and hivelore sync handles it automatically.\\n\",\n );\n hub.action(() => hub.help());\n\n // hivelore hub init <path>\n hub\n .command(\"init <hubPath>\")\n .description(\n \"Initialize a new team-knowledge hub repo at <hubPath>.\\n\\n\" +\n \" Creates a git repo with a .ai/ directory structure ready for shared memories.\\n\\n\" +\n \" Example:\\n\" +\n \" hivelore hub init ../team-hub\\n\" +\n \" hivelore hub init /srv/git/team-knowledge\\n\",\n )\n .action(async (hubPath: string) => {\n const absPath = path.resolve(hubPath);\n await mkdir(absPath, { recursive: true });\n\n const gitCheck = spawnSync(\"git\", [\"rev-parse\", \"--git-dir\"], { cwd: absPath });\n if (gitCheck.status !== 0) {\n const init = spawnSync(\"git\", [\"init\"], { cwd: absPath, encoding: \"utf8\" });\n if (init.status !== 0) {\n ui.error(`git init failed: ${init.stderr}`);\n process.exitCode = 1;\n return;\n }\n }\n\n const sharedDir = path.join(absPath, \".ai\", \"memories\", \"shared\");\n await mkdir(sharedDir, { recursive: true });\n await writeFile(\n path.join(absPath, \".ai\", \"README.md\"),\n `# Hivelore Team Knowledge Hub\\n\\n` +\n `This repo is a shared knowledge hub for Hivelore.\\n\\n` +\n `Each project contributes its \\`shared\\`-scoped memories here.\\n` +\n `Other projects pull from it via \\`hivelore hub pull\\`.\\n\\n` +\n `## Structure\\n\\n` +\n \"`\" + \"`.ai/memories/shared/<project-name>/`\\n\\n\" +\n `## Usage\\n\\n` +\n \"```bash\\n\" +\n \"hivelore hub push # publish from a project\\n\" +\n \"hivelore hub pull # import into a project\\n\" +\n \"```\\n\",\n \"utf8\",\n );\n await writeFile(\n path.join(absPath, \".gitignore\"),\n \".ai/.cache/\\n.ai/memories/personal/\\n\",\n \"utf8\",\n );\n\n spawnSync(\"git\", [\"add\", \".\"], { cwd: absPath });\n spawnSync(\"git\", [\"commit\", \"-m\", \"chore: initialize Hivelore team-knowledge hub\"], {\n cwd: absPath,\n encoding: \"utf8\",\n });\n\n console.log(ui.green(`✓ Hub initialized at ${absPath}`));\n console.log(\n ui.dim(\n `\\nNext steps:\\n` +\n ` 1. Add hubPath to your project's .ai/haive.config.json:\\n` +\n ` { \"hubPath\": \"${path.relative(process.cwd(), absPath)}\" }\\n` +\n ` 2. Run \\`hivelore hub push\\` to publish your shared memories\\n` +\n ` 3. Share ${absPath} with teammates (git remote, NFS, etc.)\\n`,\n ),\n );\n });\n\n // hivelore hub push\n hub\n .command(\"push\")\n .description(\n \"Push this project's shared-scoped memories to the hub.\\n\\n\" +\n \" Copies all memories with scope=shared to hub/.ai/memories/shared/<project-name>/.\\n\" +\n \" Optionally commits to the hub repo.\\n\\n\" +\n \" Examples:\\n\" +\n \" hivelore hub push\\n\" +\n \" hivelore hub push --commit\\n\" +\n \" hivelore hub push --commit --message \\\"feat: add payment API contract memories\\\"\\n\",\n )\n .option(\"-d, --dir <dir>\", \"project root\")\n .option(\"--commit\", \"auto-commit to the hub repo after pushing\")\n .option(\"--message <msg>\", \"commit message for the hub (used with --commit)\")\n .action(async (opts: HubOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n const config = await loadConfig(paths);\n\n if (!config.hubPath) {\n ui.error(\n \"hubPath not configured in .ai/haive.config.json.\\n\" +\n \" Add: { \\\"hubPath\\\": \\\"../team-hub\\\" }\\n\" +\n \" Or run: hivelore hub init <path> first.\",\n );\n process.exitCode = 1;\n return;\n }\n\n const hubRoot = path.resolve(root, config.hubPath);\n if (!existsSync(hubRoot)) {\n ui.error(`Hub not found at ${hubRoot}. Run \\`hivelore hub init ${config.hubPath}\\` first.`);\n process.exitCode = 1;\n return;\n }\n\n // Project name = directory name\n const projectName = path.basename(root);\n const destDir = path.join(hubRoot, \".ai\", \"memories\", \"shared\", projectName);\n await mkdir(destDir, { recursive: true });\n\n // Load shared-scoped memories\n const all = await loadMemoriesFromDir(paths.memoriesDir);\n const shared = all.filter(\n ({ memory }) =>\n memory.frontmatter.scope === \"shared\" &&\n memory.frontmatter.status !== \"rejected\" &&\n memory.frontmatter.status !== \"deprecated\" &&\n // Don't push imported memories (avoid echo loops)\n !memory.frontmatter.tags.some((t) => t.startsWith(\"cross-repo:\")),\n );\n\n if (shared.length === 0) {\n ui.warn(\n \"No shared-scoped memories found. Create memories with scope=shared to push to the hub.\\n\" +\n \" Example: hivelore memory add --type architecture --slug my-api --scope shared --body \\\"...\\\"\\n\" +\n \" Or with MCP: mem_save({ scope: 'shared', ... })\",\n );\n return;\n }\n\n let pushed = 0;\n for (const { memory } of shared) {\n const fm = memory.frontmatter;\n const fileName = `${fm.id}.md`;\n const destPath = path.join(destDir, fileName);\n await writeFile(destPath, serializeMemory(memory), \"utf8\");\n pushed++;\n }\n\n console.log(ui.green(`✓ Pushed ${pushed} shared memor${pushed === 1 ? \"y\" : \"ies\"} to hub`));\n console.log(ui.dim(` Location: ${destDir}`));\n\n if (opts.commit) {\n const message =\n opts.message ?? `haive: sync shared memories from ${projectName} (${pushed} memories)`;\n spawnSync(\"git\", [\"add\", path.join(\".ai\", \"memories\", \"shared\", projectName)], {\n cwd: hubRoot,\n });\n const commit = spawnSync(\"git\", [\"commit\", \"-m\", message], {\n cwd: hubRoot,\n encoding: \"utf8\",\n });\n if (commit.status === 0) {\n console.log(ui.green(`✓ Committed to hub: \"${message}\"`));\n } else if (commit.stdout?.includes(\"nothing to commit\")) {\n console.log(ui.dim(\" Hub already up to date — nothing to commit.\"));\n } else {\n ui.warn(`git commit in hub failed: ${commit.stderr}`);\n }\n } else {\n console.log(\n ui.dim(\n \" Tip: use --commit to auto-commit to the hub repo, or commit manually.\",\n ),\n );\n }\n });\n\n // hivelore hub pull\n hub\n .command(\"pull\")\n .description(\n \"Pull shared memories from the hub into this project.\\n\\n\" +\n \" Imports all memories from hub/.ai/memories/shared/ EXCEPT this project's own.\\n\" +\n \" Imported memories land in .ai/memories/shared/<source-project-name>/.\\n\\n\" +\n \" Examples:\\n\" +\n \" hivelore hub pull\\n\",\n )\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: { dir?: string }) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n const config = await loadConfig(paths);\n\n if (!config.hubPath) {\n ui.error(\n \"hubPath not configured in .ai/haive.config.json.\\n\" +\n \" Add: { \\\"hubPath\\\": \\\"../team-hub\\\" }\\n\" +\n \" Or run: hivelore hub init <path> first.\",\n );\n process.exitCode = 1;\n return;\n }\n\n const hubRoot = path.resolve(root, config.hubPath);\n const hubSharedDir = path.join(hubRoot, \".ai\", \"memories\", \"shared\");\n\n if (!existsSync(hubSharedDir)) {\n ui.warn(\"Hub has no shared memories yet. Run `hivelore hub push` from other projects first.\");\n return;\n }\n\n const projectName = path.basename(root);\n const { readdir } = await import(\"node:fs/promises\");\n const projectDirs = (await readdir(hubSharedDir, { withFileTypes: true }))\n .filter((d) => d.isDirectory() && d.name !== projectName)\n .map((d) => d.name);\n\n if (projectDirs.length === 0) {\n console.log(ui.dim(\"No other projects have pushed to the hub yet.\"));\n return;\n }\n\n let totalImported = 0;\n let totalUpdated = 0;\n\n for (const sourceName of projectDirs) {\n const sourceDir = path.join(hubSharedDir, sourceName);\n const destDir = path.join(paths.memoriesDir, \"shared\", sourceName);\n await mkdir(destDir, { recursive: true });\n\n const sourceFiles = (await readdir(sourceDir)).filter((f) => f.endsWith(\".md\"));\n const { loadMemoriesFromDir: loadDir } = await import(\"@hivelore/core\");\n const existingInDest = await loadDir(destDir);\n const existingIds = new Set(existingInDest.map(({ memory }) => memory.frontmatter.id));\n\n for (const file of sourceFiles) {\n const srcPath = path.join(sourceDir, file);\n const destPath = path.join(destDir, file);\n\n // Tag with hub provenance\n const fileContent = await readFile(srcPath, \"utf8\");\n const alreadyTagged = fileContent.includes(`cross-repo:${sourceName}`);\n\n if (!alreadyTagged) {\n // Add provenance tag by copying as-is (the original already has cross-repo tags from push)\n await copyFile(srcPath, destPath);\n } else {\n await copyFile(srcPath, destPath);\n }\n\n const memId = file.replace(\".md\", \"\");\n if (existingIds.has(memId)) {\n totalUpdated++;\n } else {\n totalImported++;\n }\n }\n\n console.log(\n ui.dim(` [${sourceName}]: ${sourceFiles.length} memor${sourceFiles.length === 1 ? \"y\" : \"ies\"} synced`),\n );\n }\n\n console.log(\n ui.green(`✓ Hub pull complete: ${totalImported} new · ${totalUpdated} updated`),\n );\n });\n\n // hivelore hub status\n hub\n .command(\"status\")\n .description(\"Show hub sync status.\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: { dir?: string }) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n const config = await loadConfig(paths);\n\n console.log(ui.bold(\"Hub status\"));\n console.log(\n ` hubPath: ${config.hubPath ? ui.green(config.hubPath) : ui.dim(\"not configured\")}`,\n );\n\n const sharedDir = path.join(paths.memoriesDir, \"shared\");\n if (existsSync(sharedDir)) {\n const { readdir } = await import(\"node:fs/promises\");\n const sources = (await readdir(sharedDir, { withFileTypes: true }))\n .filter((d) => d.isDirectory())\n .map((d) => d.name);\n console.log(`\\n Imported from ${sources.length} source(s):`);\n for (const src of sources) {\n const files = (await readdir(path.join(sharedDir, src))).filter((f) => f.endsWith(\".md\"));\n console.log(` ${src}: ${files.length} memor${files.length === 1 ? \"y\" : \"ies\"}`);\n }\n } else {\n console.log(ui.dim(\" No imported shared memories yet.\"));\n }\n\n // Count outgoing shared memories\n const all = await loadMemoriesFromDir(paths.memoriesDir);\n const outgoing = all.filter(\n ({ memory }) =>\n memory.frontmatter.scope === \"shared\" &&\n !memory.frontmatter.tags.some((t) => t.startsWith(\"cross-repo:\")),\n );\n console.log(`\\n This project's shared memories (ready to push): ${outgoing.length}`);\n if (outgoing.length > 0) {\n console.log(ui.dim(\" Run `hivelore hub push` to publish them to the hub.\"));\n }\n\n void readFile; void writeFile; void saveConfig; // imported for side effects\n });\n}\n","import { Command } from \"commander\";\nimport { existsSync } from \"node:fs\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n aggregateUsage,\n findProjectRoot,\n loadMemoriesFromDir,\n loadUsageIndex,\n parseSince,\n readUsageEvents,\n resolveHaivePaths,\n usageLogSize,\n} from \"@hivelore/core\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface StatsOptions {\n since?: string;\n json?: boolean;\n memoryHits?: boolean;\n exportReport?: string;\n dir?: string;\n}\n\nexport function registerStats(program: Command): void {\n program\n .command(\"stats\")\n .description(\"Show MCP tool-usage stats over a window (e.g. --since 7d).\")\n .option(\"--since <window>\", \"ISO date or relative (e.g. '7d', '24h', '30m')\", \"30d\")\n .option(\"--json\", \"emit JSON instead of human-readable output\", false)\n .option(\"--memory-hits\", \"show top-read memories (which mems are actually being used)\", false)\n .option(\n \"--export-report <path>\",\n \"write a JSON rollup (tools + briefing counts + heuristic ROI hints). Parent dirs are created if needed.\",\n undefined,\n )\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: StatsOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n\n if (opts.exportReport) {\n await writeRoiReport(paths, root, opts.since ?? \"30d\", opts.exportReport);\n return;\n }\n\n if (opts.memoryHits) {\n await renderMemoryHits(paths, opts);\n return;\n }\n\n const size = await usageLogSize(paths);\n if (!size.exists) {\n if (opts.json) {\n console.log(JSON.stringify({ error: \"no_usage_log\" }));\n return;\n }\n ui.warn(\n `No usage log found at ${root}. ` +\n `Stats are populated as the MCP server logs each tool call. ` +\n `Run a session first, then re-check.`,\n );\n return;\n }\n\n const events = await readUsageEvents(paths);\n const since = parseSince(opts.since);\n const aggregate = aggregateUsage(events, since ?? undefined);\n\n if (opts.json) {\n console.log(JSON.stringify(aggregate, null, 2));\n return;\n }\n\n const window = opts.since ?? \"all time\";\n console.log(ui.bold(`Hivelore usage stats (${window})`));\n console.log(\n ` ${ui.dim(\"total calls:\")} ${aggregate.total} ` +\n `${ui.dim(\"unique tools:\")} ${aggregate.by_tool.length} ` +\n `${ui.dim(\"log lines:\")} ${size.lines}`,\n );\n if (aggregate.window_start) {\n console.log(\n ` ${ui.dim(\"window:\")} ${aggregate.window_start.slice(0, 19)} → ${aggregate.window_end?.slice(0, 19)}`,\n );\n }\n if (aggregate.by_tool.length === 0) {\n ui.info(`No events in window. Try a wider --since (current: ${window}).`);\n return;\n }\n console.log();\n console.log(ui.bold(\"Top tools:\"));\n const maxCount = aggregate.by_tool[0]?.count ?? 1;\n for (const t of aggregate.by_tool.slice(0, 20)) {\n const bar = \"█\".repeat(Math.max(1, Math.round((t.count / maxCount) * 30)));\n const pct = ((t.count / aggregate.total) * 100).toFixed(1);\n console.log(\n ` ${t.tool.padEnd(28)} ${ui.green(bar)} ${ui.bold(String(t.count))} ` +\n `${ui.dim(`(${pct}%, last ${t.last_used.slice(0, 19)})`)}`,\n );\n }\n } );\n}\n\nasync function writeRoiReport(\n paths: ReturnType<typeof resolveHaivePaths>,\n root: string,\n sinceRaw: string,\n outRelative: string,\n): Promise<void> {\n const outAbs = path.isAbsolute(outRelative)\n ? path.resolve(outRelative)\n : path.resolve(root, outRelative);\n\n const size = await usageLogSize(paths);\n let events = await readUsageEvents(paths);\n\n let memoryCount = { team: 0, personal: 0, total_skipped_session: 0 };\n if (existsSync(paths.memoriesDir)) {\n const mems = await loadMemoriesFromDir(paths.memoriesDir);\n for (const { memory } of mems) {\n const fm = memory.frontmatter;\n if (fm.type === \"session_recap\") memoryCount.total_skipped_session++;\n else if (fm.scope === \"team\") memoryCount.team++;\n else if (fm.scope === \"personal\") memoryCount.personal++;\n }\n }\n\n const sinceDt = parseSince(sinceRaw) ?? undefined;\n const aggregate = aggregateUsage(events, sinceDt);\n const inWindow = (at: string): boolean =>\n sinceDt === undefined || Date.parse(at) >= sinceDt.getTime();\n\n const briefingCalls = events.filter((e) => inWindow(e.at) && e.tool === \"get_briefing\").length;\n\n let memoryHitsLeader: { id: string; read_count: number } | null = null;\n try {\n const usageIdx = await loadUsageIndex(paths);\n const tops = Object.entries(usageIdx.by_id)\n .map(([id, v]) => ({ id, read_count: v.read_count }))\n .filter((x) => x.read_count > 0)\n .sort((a, b) => b.read_count - a.read_count);\n memoryHitsLeader = tops[0] ?? null;\n } catch {\n memoryHitsLeader = null;\n }\n\n const roiHints = [\n \"Prefer get_briefing(format:'actions') or budget_preset:'quick' for low-risk edits to reduce token pressure.\",\n \"Run `hivelore memory lint` in CI to keep the corpus actionable.\",\n \"Install the haive VS Code extension (packages/vscode) for always-on memory surfacing beside the editor.\",\n ];\n\n if (!size.exists || events.length === 0) {\n ui.warn(\"Usage log missing or empty — report still written with partial data.\");\n events = [];\n }\n\n await mkdir(path.dirname(outAbs), { recursive: true });\n const payload = {\n generated_at: new Date().toISOString(),\n project_root: root,\n window_since: sinceRaw,\n usage_log_meta: size,\n memory_inventory: memoryCount,\n aggregate,\n get_briefing_calls_in_window: briefingCalls,\n top_memory_reads: memoryHitsLeader,\n roi_hints: roiHints,\n };\n\n await writeFile(outAbs, JSON.stringify(payload, null, 2), \"utf8\");\n ui.success(`Wrote ROI / usage rollup → ${outAbs}`);\n}\n\nasync function renderMemoryHits(\n paths: ReturnType<typeof resolveHaivePaths>,\n opts: StatsOptions,\n): Promise<void> {\n const index = await loadUsageIndex(paths);\n const since = parseSince(opts.since ?? \"30d\");\n const sinceMs = since ? new Date(since).getTime() : null;\n const entries = Object.entries(index.by_id)\n .map(([id, usage]) => ({ id, ...usage }))\n .filter((e) => e.read_count > 0)\n .filter((e) => {\n if (!sinceMs || !e.last_read_at) return !sinceMs;\n return new Date(e.last_read_at).getTime() >= sinceMs;\n })\n .sort((a, b) => b.read_count - a.read_count);\n\n if (opts.json) {\n console.log(JSON.stringify({\n window: opts.since ?? \"30d\",\n total_mems_with_hits: entries.length,\n top: entries.slice(0, 50),\n }, null, 2));\n return;\n }\n\n const window = opts.since ?? \"30d\";\n console.log(ui.bold(`Memory hits (${window})`));\n if (entries.length === 0) {\n ui.info(\n `No memory reads recorded in window. Reads are logged when ` +\n `\\`hivelore briefing\\` or \\`hivelore memory search\\` surface a memory.`,\n );\n return;\n }\n console.log(\n ` ${ui.dim(\"memories with hits:\")} ${entries.length} ` +\n `${ui.dim(\"total reads:\")} ${entries.reduce((a, e) => a + e.read_count, 0)}`,\n );\n console.log();\n console.log(ui.bold(\"Top read memories:\"));\n const maxCount = entries[0]!.read_count;\n for (const e of entries.slice(0, 25)) {\n const bar = \"█\".repeat(Math.max(1, Math.round((e.read_count / maxCount) * 20)));\n const lastRead = e.last_read_at?.slice(0, 10) ?? \"?\";\n console.log(\n ` ${ui.bold(String(e.read_count).padStart(4))} ${ui.green(bar.padEnd(20))} ` +\n `${e.id} ${ui.dim(`last: ${lastRead}`)}`,\n );\n }\n const dead = Object.keys(index.by_id).length - entries.length;\n if (dead > 0) {\n console.log();\n ui.info(`${dead} memor${dead === 1 ? \"y\" : \"ies\"} never read in window — candidates for cleanup (run \\`hivelore doctor\\`).`);\n }\n}\n","import { performance } from \"node:perf_hooks\";\nimport { Command } from \"commander\";\nimport {\n estimateTokens,\n findProjectRoot,\n resolveHaivePaths,\n} from \"@hivelore/core\";\nimport {\n antiPatternsCheck,\n codeMapTool,\n codeSearch,\n getBriefing,\n getRecap,\n memRelevantTo,\n} from \"@hivelore/mcp\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface BenchOptions {\n task?: string;\n json?: boolean;\n dir?: string;\n}\n\ninterface ScenarioResult {\n name: string;\n ok: boolean;\n latency_ms: number;\n payload_tokens: number;\n notes: string[];\n}\n\nexport function registerBench(program: Command): void {\n program\n .command(\"selftest\")\n .alias(\"bench\")\n .description(\"Self-test the LOCAL Hivelore install: runs core MCP tools against this project and reports latency + payload size. Different from `benchmark` (which measures Hivelore-vs-plain agent value). Alias: bench\")\n .option(\"-t, --task <task>\", \"task description for ranking-aware tools\", \"audit dependencies for security risks\")\n .option(\"--json\", \"emit JSON instead of a table\", false)\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: BenchOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n const ctx = { paths };\n const task = opts.task ?? \"audit dependencies for security risks\";\n\n const scenarios: Array<() => Promise<ScenarioResult>> = [\n async () => {\n const t0 = performance.now();\n const out = await getBriefing(\n {\n task,\n files: [],\n max_tokens: 4000,\n max_memories: 8,\n include_project_context: true,\n include_module_contexts: true,\n semantic: true,\n include_stale: false,\n track: false,\n format: \"compact\",\n symbols: [],\n min_semantic_score: 0,\n },\n ctx,\n );\n return summarize(\"get_briefing(compact)\", t0, out, [\n out.low_value ? \"low_value (cold-start)\" : `${out.memories.length} memories`,\n `search=${out.search_mode}`,\n ]);\n },\n async () => {\n const t0 = performance.now();\n const out = await codeMapTool({ paths: [], max_files: 40, max_tokens: 2000 }, ctx);\n return summarize(\"code_map(budget=2k)\", t0, out, [\n out.available ? `${out.files.length}/${out.total_files} files` : \"unavailable\",\n out.budget_clipped ? \"clipped\" : \"fits\",\n ]);\n },\n async () => {\n const t0 = performance.now();\n const out = await getRecap({ scope: \"any\" }, ctx);\n return summarize(\"get_recap\", t0, out, [\n out.recap ? `${out.recap.id.slice(0, 30)}…` : \"no recap\",\n ]);\n },\n async () => {\n const t0 = performance.now();\n const out = await memRelevantTo(\n { task, files: [], limit: 8, min_semantic_score: 0.25, format: \"compact\" },\n ctx,\n );\n return summarize(\"mem_relevant_to\", t0, out, [\n `${out.memories.length} memories`,\n `search=${out.search_mode}`,\n ]);\n },\n async () => {\n const t0 = performance.now();\n const out = await codeSearch({ query: task, k: 5, min_score: 0.2 }, ctx);\n return summarize(\"code_search\", t0, out, [\n out.available ? `${out.hits.length} hits` : \"needs index (hivelore index code-search)\",\n ]);\n },\n async () => {\n const t0 = performance.now();\n const out = await antiPatternsCheck({ diff: task, paths: [], limit: 5, semantic: true }, ctx);\n return summarize(\"anti_patterns_check\", t0, out, [\n `${out.warnings.length}/${out.scanned} warn`,\n ]);\n },\n ];\n\n const results: ScenarioResult[] = [];\n for (const run of scenarios) {\n try {\n results.push(await run());\n } catch (err) {\n results.push({\n name: \"(error)\",\n ok: false,\n latency_ms: 0,\n payload_tokens: 0,\n notes: [err instanceof Error ? err.message : String(err)],\n });\n }\n }\n\n if (opts.json) {\n console.log(JSON.stringify({ root, task, scenarios: results }, null, 2));\n return;\n }\n\n console.log(ui.bold(`Hivelore bench — ${root}`));\n console.log(ui.dim(`task: ${task}`));\n console.log();\n console.log(\n `${\"scenario\".padEnd(28)} ${\"latency\".padStart(8)} ${\"tokens\".padStart(7)} notes`,\n );\n console.log(\"─\".repeat(88));\n for (const r of results) {\n const status = r.ok ? ui.green(\"✓\") : ui.red(\"✗\");\n console.log(\n `${status} ${r.name.padEnd(26)} ${`${r.latency_ms.toFixed(0)} ms`.padStart(8)} ${String(r.payload_tokens).padStart(7)} ${r.notes.join(\"; \")}`,\n );\n }\n\n const totalTokens = results.reduce((s, r) => s + r.payload_tokens, 0);\n const totalMs = results.reduce((s, r) => s + r.latency_ms, 0);\n console.log(\"─\".repeat(88));\n console.log(\n `${ui.dim(\"totals:\")} ${`${totalMs.toFixed(0)} ms`.padStart(8)} ${String(totalTokens).padStart(7)}`,\n );\n });\n}\n\nfunction summarize(\n name: string,\n t0: number,\n payload: unknown,\n notes: string[],\n): ScenarioResult {\n return {\n name,\n ok: true,\n latency_ms: performance.now() - t0,\n payload_tokens: estimateTokens(JSON.stringify(payload)),\n notes,\n };\n}\n","import { existsSync } from \"node:fs\";\nimport { readdir, readFile, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport { estimateTokens, findProjectRoot } from \"@hivelore/core\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface BenchmarkOptions {\n dir?: string;\n out?: string;\n json?: boolean;\n}\n\ninterface AgentBenchmarkRow {\n fixture: string;\n group: \"haive\" | \"plain\" | \"unknown\";\n commands: number;\n files_read: number;\n files_modified: number;\n test_iterations: number;\n terminal_failures: number;\n decision_mentions: number;\n report_tokens_est: number;\n haive_impact: boolean;\n}\n\nexport function registerBenchmark(program: Command): void {\n const benchmark = program\n .command(\"benchmark\")\n .description(\"Measure Hivelore's VALUE: paired Hivelore-vs-plain agent runs (correctness, tokens, tools). Different from `selftest` (which only checks local install latency).\");\n\n benchmark\n .command(\"report\")\n .description(\"Summarize BENCHMARK_AGENT_REPORT.md files from a paired Hivelore/plain agent benchmark.\")\n .option(\"-d, --dir <dir>\", \"benchmark root\", \"benchmarks/agent-benchmark\")\n .option(\"--out <file>\", \"write a Markdown report\")\n .option(\"--json\", \"emit JSON\", false)\n .action(async (opts: BenchmarkOptions) => {\n const root = resolveBenchmarkRoot(opts.dir);\n const rows = await collectRows(root);\n const summary = summarizeRows(rows);\n\n if (opts.json) {\n console.log(JSON.stringify({ root, summary, rows }, null, 2));\n return;\n }\n\n const markdown = renderMarkdown(root, summary, rows);\n if (opts.out) {\n const outFile = path.isAbsolute(opts.out) ? opts.out : path.join(root, opts.out);\n await writeFile(outFile, markdown, \"utf8\");\n ui.success(`wrote ${path.relative(process.cwd(), outFile)}`);\n return;\n }\n console.log(markdown);\n });\n\n benchmark\n .command(\"demo\")\n .description(\"Print the recommended protocol for running a Hivelore vs plain agent benchmark.\")\n .action(() => {\n console.log([\n \"# Hivelore Agent Benchmark Demo\",\n \"\",\n \"1. Create paired fixtures: one `*-haive`, one `*-plain`.\",\n \"2. Put the same failing tests in both fixtures.\",\n \"3. Add precise `.ai/memories/team/*.md` policy memories only to the Hivelore fixture.\",\n \"4. Run equal agents in parallel:\",\n \" - Hivelore agents must run `hivelore briefing --files ... --task ...` first.\",\n \" - Plain agents must not read `.ai` or call Hivelore.\",\n \"5. Require every agent to write `BENCHMARK_AGENT_REPORT.md`.\",\n \"6. Run `hivelore benchmark report --dir <benchmark-root> --out RESULTS.md`.\",\n \"\",\n \"Recommended metrics: pass rate, test iterations, files read, files changed, visible artifacts, decision quality, and token proxy.\",\n ].join(\"\\n\"));\n });\n}\n\nfunction resolveBenchmarkRoot(dir: string | undefined): string {\n const candidate = dir ?? \"benchmarks/agent-benchmark\";\n if (path.isAbsolute(candidate)) return candidate;\n const projectRoot = findProjectRoot(process.cwd());\n return path.join(projectRoot, candidate);\n}\n\nasync function collectRows(root: string): Promise<AgentBenchmarkRow[]> {\n if (!existsSync(root)) throw new Error(`Benchmark directory not found: ${root}`);\n const entries = await readdir(root, { withFileTypes: true });\n const rows: AgentBenchmarkRow[] = [];\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n const fixtureDir = path.join(root, entry.name);\n const reportFile = path.join(fixtureDir, \"BENCHMARK_AGENT_REPORT.md\");\n if (!existsSync(reportFile)) continue;\n const report = await readFile(reportFile, \"utf8\");\n rows.push(parseAgentReport(entry.name, report));\n }\n return rows.sort((a, b) => a.fixture.localeCompare(b.fixture));\n}\n\nfunction parseAgentReport(fixture: string, report: string): AgentBenchmarkRow {\n const group = fixture.endsWith(\"-haive\") ? \"haive\" : fixture.endsWith(\"-plain\") ? \"plain\" : \"unknown\";\n return {\n fixture,\n group,\n commands: sectionBulletCount(report, \"Commands\"),\n files_read: sectionBulletCount(report, \"Files Read\"),\n files_modified: sectionBulletCount(report, \"Files Modified\"),\n test_iterations: countMatches(section(report, \"Test Iterations\"), /Iteration\\s+\\d+|^- /gim),\n terminal_failures: countMatches(section(report, \"Terminal Errors\"), /fail|error|not raised|exited with code 1/gi),\n decision_mentions: sectionBulletCount(report, \"Key Decisions\"),\n report_tokens_est: estimateTokens(report),\n haive_impact: /Hivelore Memory Impact[\\s\\S]*?\\b(yes|directly|changed|shaped|confirmed)\\b/i.test(report),\n };\n}\n\nfunction summarizeRows(rows: AgentBenchmarkRow[]) {\n const byGroup = (group: AgentBenchmarkRow[\"group\"]) => rows.filter((r) => r.group === group);\n return {\n fixtures: rows.length,\n haive: summarizeGroup(byGroup(\"haive\")),\n plain: summarizeGroup(byGroup(\"plain\")),\n };\n}\n\nfunction summarizeGroup(rows: AgentBenchmarkRow[]) {\n const sum = (key: keyof AgentBenchmarkRow): number =>\n rows.reduce((total, row) => total + Number(row[key] ?? 0), 0);\n return {\n fixtures: rows.length,\n commands: sum(\"commands\"),\n files_read: sum(\"files_read\"),\n files_modified: sum(\"files_modified\"),\n test_iterations: sum(\"test_iterations\"),\n terminal_failures: sum(\"terminal_failures\"),\n decision_mentions: sum(\"decision_mentions\"),\n report_tokens_est: sum(\"report_tokens_est\"),\n haive_impact_count: rows.filter((r) => r.haive_impact).length,\n };\n}\n\nfunction renderMarkdown(\n root: string,\n summary: ReturnType<typeof summarizeRows>,\n rows: AgentBenchmarkRow[],\n): string {\n const lines = [\n \"# Hivelore Agent Benchmark Report\",\n \"\",\n `Benchmark root: \\`${root}\\``,\n \"\",\n \"## Summary\",\n \"\",\n \"| Group | Fixtures | Commands | Files read | Files modified | Test iterations | Terminal failures | Decision mentions | Report tokens (est, report only) | Hivelore impact |\",\n \"| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |\",\n groupLine(\"Hivelore\", summary.haive),\n groupLine(\"Plain\", summary.plain),\n \"\",\n \"## Fixtures\",\n \"\",\n \"| Fixture | Group | Commands | Files read | Files modified | Test iterations | Terminal failures | Decisions | Report tokens (est, report only) | Hivelore impact |\",\n \"| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | --- |\",\n ...rows.map((row) =>\n `| \\`${row.fixture}\\` | ${row.group} | ${row.commands} | ${row.files_read} | ${row.files_modified} | ${row.test_iterations} | ${row.terminal_failures} | ${row.decision_mentions} | ${row.report_tokens_est} | ${row.haive_impact ? \"yes\" : \"no\"} |`,\n ),\n \"\",\n \"## Reading\",\n \"\",\n \"`Report tokens (est)` estimates the size of the agent's WRITTEN REPORT only — a verbosity proxy, NOT\",\n \"the agent's total token consumption. For real per-agent token/latency, capture your runner's telemetry\",\n \"(e.g. subagent token counts) separately; this report can't see model billing.\",\n \"Use this report to compare relative effort and decision quality, then pair it with final test results and a human review of the diffs.\",\n \"\",\n ];\n return lines.join(\"\\n\");\n}\n\nfunction groupLine(label: string, group: ReturnType<typeof summarizeGroup>): string {\n return `| ${label} | ${group.fixtures} | ${group.commands} | ${group.files_read} | ${group.files_modified} | ${group.test_iterations} | ${group.terminal_failures} | ${group.decision_mentions} | ${group.report_tokens_est} | ${group.haive_impact_count} |`;\n}\n\nfunction sectionBulletCount(markdown: string, title: string): number {\n return countMatches(section(markdown, title), /^- |^\\d+\\.\\s/gm);\n}\n\nfunction section(markdown: string, title: string): string {\n const re = new RegExp(`##\\\\s+[^\\\\n]*${escapeRegExp(title)}[^\\\\n]*\\\\n([\\\\s\\\\S]*?)(?=\\\\n##\\\\s+|$)`, \"i\");\n return re.exec(markdown)?.[1] ?? \"\";\n}\n\nfunction countMatches(text: string, re: RegExp): number {\n return [...text.matchAll(re)].length;\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n","import { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n aggregateRetrieval,\n aggregateSensors,\n appendEvalHistory,\n buildReport,\n compareGatePrecision,\n compareEvalReports,\n computeGatePrecision,\n computeEvalTrend,\n findProjectRoot,\n loadConfig,\n loadEvalHistory,\n loadPreventionEvents,\n loadUsageIndex,\n overallScore,\n resolveHaivePaths,\n scoreRetrievalCase,\n scoreSensorCase,\n synthesizeSelfEvalCases,\n type EvalDelta,\n type EvalReport,\n type EvalSpec,\n type GatePrecision,\n type GatePrecisionDelta,\n type RetrievalCase,\n type RetrievalCaseResult,\n type SensorCase,\n type SensorCaseResult,\n} from \"@hivelore/core\";\nimport { antiPatternsCheck, getBriefing } from \"@hivelore/mcp\";\nimport { loadMemoriesFromDir } from \"../utils/fs.js\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface EvalOptions {\n spec?: string;\n semanticOnly?: boolean;\n top?: string;\n json?: boolean;\n out?: string;\n failUnder?: string;\n failUnderCatchRate?: string;\n failUnderGatePrecision?: string;\n baseline?: boolean;\n compare?: boolean;\n baselineFile?: string;\n failOnRegression?: boolean;\n regressionGate?: boolean;\n record?: boolean;\n trend?: boolean;\n ref?: string;\n dir?: string;\n}\n\ninterface BaselineSnapshot {\n saved_at: string;\n k: number;\n spec_source: string;\n report: EvalReport;\n gate_precision?: GatePrecision;\n}\n\ninterface ResolvedEvalSpec {\n spec: EvalSpec;\n source: string;\n /** Cases synthesized from the repo's own anchored memories — self-referential (a sanity floor, not ground truth). */\n synthesized: number;\n /** Hand-labeled cases from a spec file — independent ground truth. */\n authored: number;\n}\n\nexport function registerEval(program: Command): void {\n program\n .command(\"eval\")\n .description(\n \"Rigorous, repeatable quality eval: do the right memories surface (retrieval) and \" +\n \"do the right sensors fire (catch-rate)? Emits a numeric 0–100 score. \" +\n \"Uses .ai/eval cases via --spec, or auto-synthesizes cases from anchored memories.\",\n )\n .option(\"--spec <file>\", \"JSON eval spec ({ retrieval: [...], sensors: [...] })\")\n .option(\"--semantic-only\", \"self-eval probes by title alone (no anchor files) — harder retrieval\", false)\n .option(\"-k, --top <n>\", \"briefing top-k considered a hit\", \"8\")\n .option(\"--json\", \"emit JSON\", false)\n .option(\"--out <file>\", \"write a Markdown report\")\n .option(\"--fail-under <score>\", \"exit non-zero if the overall score is below this (0–100) — for CI gates\")\n .option(\"--fail-under-catch-rate <pct>\", \"exit non-zero if sensor catch-rate is below this percentage\")\n .option(\"--fail-under-gate-precision <pct>\", \"exit non-zero if gate precision is below this percentage\")\n .option(\"--baseline\", \"save this run as the baseline (.ai/eval/baseline.json) for future --compare\", false)\n .option(\"--compare\", \"diff this run against the saved baseline and print the delta\", false)\n .option(\"--baseline-file <path>\", \"baseline file to read/write (default: .ai/eval/baseline.json)\")\n .option(\"--fail-on-regression\", \"with --compare, exit non-zero if the score dropped vs the baseline\", false)\n .option(\"--regression-gate\", \"CI-safe gate: compare against the baseline IF one exists (fail on regression), else no-op\", false)\n .option(\"--record\", \"append this run's score to .ai/.cache/eval-history.jsonl (trend the harness over time)\", false)\n .option(\"--trend\", \"print the recorded score trend (sparkline + latest/best/delta) and exit\", false)\n .option(\"--ref <ref>\", \"version/commit label stored with a --record run\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: EvalOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.memoriesDir)) {\n ui.error(`No .ai/memories at ${root}. Run \\`hivelore init\\` first.`);\n process.exitCode = 1;\n return;\n }\n\n // ── Trend view: read-only, no scoring run needed ─────────────────────\n if (opts.trend) {\n const trend = computeEvalTrend(await loadEvalHistory(paths));\n if (opts.json) {\n console.log(JSON.stringify(trend, null, 2));\n return;\n }\n if (trend.runs === 0) {\n ui.info(\"No eval history yet. Run `hivelore eval --record` to start trending the harness.\");\n return;\n }\n const spark = trend.recent.map((s) => \"▁▂▃▄▅▆▇█\"[Math.min(7, Math.round((s / 100) * 7))]).join(\"\");\n const arrow = trend.regressed ? ui.red(\"▼\") : (trend.delta ?? 0) > 0 ? ui.green(\"▲\") : ui.dim(\"=\");\n console.log(ui.bold(\"Hivelore eval trend\"));\n console.log(` ${spark} latest ${arrow} ${trend.latest}/100 ${ui.dim(`(best ${trend.best}, ${trend.runs} run${trend.runs === 1 ? \"\" : \"s\"})`)}`);\n return;\n }\n const k = Math.max(1, parseInt(opts.top ?? \"8\", 10) || 8);\n const ctx = { paths };\n\n const resolvedSpec = await resolveSpec(opts, root, paths.memoriesDir);\n const spec = resolvedSpec.spec;\n if ((spec.retrieval?.length ?? 0) === 0 && (spec.sensors?.length ?? 0) === 0) {\n ui.warn(\"No eval cases (no anchored memories and no --spec). Nothing to score.\");\n return;\n }\n\n // ── Retrieval cases ──────────────────────────────────────────────────\n let retrievalAgg = null;\n if (spec.retrieval && spec.retrieval.length > 0) {\n const results: RetrievalCaseResult[] = [];\n for (const c of spec.retrieval) {\n const surfaced = await runRetrieval(c, k, ctx);\n results.push(scoreRetrievalCase(c.name, c.expect_ids, surfaced));\n }\n retrievalAgg = aggregateRetrieval(results);\n }\n\n // ── Sensor cases ─────────────────────────────────────────────────────\n let sensorAgg = null;\n if (spec.sensors && spec.sensors.length > 0) {\n const results: SensorCaseResult[] = [];\n for (const c of spec.sensors) {\n const fired = await runSensorCase(c, ctx);\n results.push(scoreSensorCase(c.name, c.expect_fire_ids, fired));\n }\n sensorAgg = aggregateSensors(results);\n }\n\n const report = buildReport(retrievalAgg, sensorAgg);\n // Honesty: when the run mixes independent (authored) and self-referential (synthesized) cases,\n // a blended headline can read as ground truth. Compute the authored-ONLY score from the cases\n // that did NOT come from self-synthesis (no re-run — reuse the per-case results):\n // • retrieval: the slice after the synthesized retrieval cases (synthesis only makes retrieval);\n // • sensors: ALL sensor cases (they only ever come from the hand-authored spec).\n const authoredRetrievalCases = retrievalAgg ? retrievalAgg.cases.slice(resolvedSpec.synthesized) : [];\n const authoredRetrievalAgg = authoredRetrievalCases.length > 0 ? aggregateRetrieval(authoredRetrievalCases) : null;\n const authoredScore =\n resolvedSpec.authored > 0 && resolvedSpec.synthesized > 0 && (authoredRetrievalAgg || sensorAgg)\n ? overallScore(authoredRetrievalAgg, sensorAgg)\n : null;\n const [usage, preventionEvents, config] = await Promise.all([\n loadUsageIndex(paths),\n loadPreventionEvents(paths),\n loadConfig(paths),\n ]);\n const gatePrecision = computeGatePrecision(\n preventionEvents,\n usage,\n config.enforcement?.antiPatternGate ?? \"anchored\",\n );\n\n // ── Record to history (trend the harness over releases) ───────────────\n if (opts.record) {\n await appendEvalHistory(paths, {\n at: new Date().toISOString(),\n score: report.score,\n ...(report.retrieval ? { mean_recall: report.retrieval.mean_recall, mrr: report.retrieval.mrr } : {}),\n ...(report.sensors ? { catch_rate: report.sensors.catch_rate } : {}),\n ...(opts.ref ? { ref: opts.ref } : {}),\n }).catch(() => { /* best-effort telemetry */ });\n if (!opts.json) ui.success(`Recorded eval score ${report.score}/100 to history.`);\n }\n\n const baselineFile = opts.baselineFile\n ? (path.isAbsolute(opts.baselineFile) ? opts.baselineFile : path.join(root, opts.baselineFile))\n : path.join(root, \".ai\", \"eval\", \"baseline.json\");\n\n // ── Save baseline ─────────────────────────────────────────────────────\n if (opts.baseline) {\n const snapshot: BaselineSnapshot = {\n saved_at: new Date().toISOString(),\n k,\n spec_source: resolvedSpec.source,\n report,\n gate_precision: gatePrecision,\n };\n await mkdir(path.dirname(baselineFile), { recursive: true });\n await writeFile(baselineFile, JSON.stringify(snapshot, null, 2), \"utf8\");\n if (!opts.json) ui.success(`Saved baseline (score ${report.score}/100) → ${path.relative(root, baselineFile)}`);\n }\n\n // ── Compare against baseline ──────────────────────────────────────────\n // `--regression-gate` is the CI-safe variant: it compares only when a baseline\n // exists and otherwise no-ops, so it can be dropped into any pipeline unconditionally.\n let delta: EvalDelta | null = null;\n let gateDelta: GatePrecisionDelta | null = null;\n if (opts.compare || opts.regressionGate) {\n if (!existsSync(baselineFile)) {\n if (opts.regressionGate) {\n if (!opts.json) ui.info(`No baseline at ${path.relative(root, baselineFile)} — regression gate skipped. Run \\`hivelore eval --baseline\\` to enable it.`);\n } else {\n ui.error(`No baseline at ${path.relative(root, baselineFile)}. Run \\`hivelore eval --baseline\\` first.`);\n process.exitCode = 1;\n return;\n }\n } else {\n const snapshot = JSON.parse(await readFile(baselineFile, \"utf8\")) as BaselineSnapshot;\n delta = compareEvalReports(snapshot.report, report);\n if (snapshot.gate_precision) {\n gateDelta = compareGatePrecision(snapshot.gate_precision, gatePrecision);\n }\n }\n }\n\n if (opts.json) {\n console.log(JSON.stringify({\n root,\n k,\n spec_source: resolvedSpec.source,\n provenance: {\n synthesized: resolvedSpec.synthesized,\n authored: resolvedSpec.authored,\n ...(authoredScore !== null ? { authored_score: authoredScore } : {}),\n },\n report,\n gate_precision: gatePrecision,\n ...(delta ? { delta } : {}),\n ...(gateDelta ? { gate_delta: gateDelta } : {}),\n }, null, 2));\n applyExitGates(opts, report, delta, gatePrecision, gateDelta);\n return;\n }\n\n // Honesty: a score built only from self-synthesized cases is a sanity floor, not proof the\n // harness helps on real, independently-labeled tasks. Say so out loud rather than letting the\n // number read as ground truth.\n if (resolvedSpec.authored === 0 && resolvedSpec.synthesized > 0) {\n ui.warn(\n `All ${resolvedSpec.synthesized} case(s) are self-synthesized from your own memories (self-referential). ` +\n \"Add hand-labeled cases in .ai/eval/spec.json, or run `hivelore eval --spec <file>`, for an independent score.\",\n );\n }\n\n if (delta) {\n console.log(renderDelta(delta));\n }\n if (gateDelta) {\n console.log(renderGateDelta(gateDelta));\n }\n\n const md = renderMarkdown(root, k, resolvedSpec, report, gatePrecision, authoredScore);\n if (opts.out) {\n const outFile = path.isAbsolute(opts.out) ? opts.out : path.join(root, opts.out);\n await writeFile(outFile, md, \"utf8\");\n ui.success(`wrote ${path.relative(process.cwd(), outFile)}`);\n } else {\n console.log(md);\n }\n\n applyExitGates(opts, report, delta, gatePrecision, gateDelta);\n });\n}\n\nfunction parsePctThreshold(label: string, raw: string | undefined): number | null {\n if (raw === undefined) return null;\n const n = Number(raw);\n if (Number.isNaN(n)) {\n ui.error(`${label} expects a number, got \"${raw}\"`);\n process.exitCode = 1;\n return null;\n }\n return n > 1 ? n / 100 : n;\n}\n\n/** CI gates: fail the build on absolute floors or metric regressions. */\nfunction applyExitGates(\n opts: EvalOptions,\n report: EvalReport,\n delta: EvalDelta | null,\n gatePrecision: GatePrecision,\n gateDelta: GatePrecisionDelta | null,\n): void {\n if (opts.failUnder !== undefined) {\n const threshold = Number(opts.failUnder);\n if (Number.isNaN(threshold)) {\n ui.error(`--fail-under expects a number, got \"${opts.failUnder}\"`);\n process.exitCode = 1;\n } else if (report.score < threshold) {\n ui.error(`eval score ${report.score} is below --fail-under ${threshold}`);\n process.exitCode = 1;\n }\n }\n const catchRateFloor = parsePctThreshold(\"--fail-under-catch-rate\", opts.failUnderCatchRate);\n if (catchRateFloor !== null && report.sensors && report.sensors.catch_rate < catchRateFloor) {\n ui.error(`sensor catch-rate ${Math.round(report.sensors.catch_rate * 100)}% is below --fail-under-catch-rate ${Math.round(catchRateFloor * 100)}%`);\n process.exitCode = 1;\n }\n const gatePrecisionFloor = parsePctThreshold(\"--fail-under-gate-precision\", opts.failUnderGatePrecision);\n if (\n gatePrecisionFloor !== null &&\n gatePrecision.precision !== null &&\n gatePrecision.precision < gatePrecisionFloor\n ) {\n ui.error(`gate precision ${Math.round(gatePrecision.precision * 100)}% is below --fail-under-gate-precision ${Math.round(gatePrecisionFloor * 100)}%`);\n process.exitCode = 1;\n }\n if ((opts.failOnRegression || opts.regressionGate) && delta?.regressed) {\n ui.error(`eval score regressed ${delta.score.baseline} → ${delta.score.current} (Δ ${delta.score.delta}) vs baseline`);\n process.exitCode = 1;\n }\n if ((opts.failOnRegression || opts.regressionGate) && delta?.catch_rate?.delta !== undefined && delta.catch_rate.delta < 0) {\n ui.error(`sensor catch-rate regressed ${delta.catch_rate.baseline} → ${delta.catch_rate.current} (Δ ${delta.catch_rate.delta}) vs baseline`);\n process.exitCode = 1;\n }\n if ((opts.failOnRegression || opts.regressionGate) && gateDelta?.regressed) {\n ui.error(\"gate precision regressed vs baseline (more false-positive rejections or lower precision)\");\n process.exitCode = 1;\n }\n}\n\nfunction fmtDelta(label: string, m: { baseline: number; current: number; delta: number } | null): string | null {\n if (!m) return null;\n const sign = m.delta > 0 ? \"+\" : \"\";\n const arrow = m.delta > 0 ? ui.green(\"▲\") : m.delta < 0 ? ui.red(\"▼\") : ui.dim(\"=\");\n return ` ${arrow} ${label.padEnd(12)} ${m.baseline} → ${m.current} ${ui.dim(`(${sign}${m.delta})`)}`;\n}\n\nfunction renderDelta(delta: EvalDelta): string {\n const verdict = delta.regressed ? ui.red(\"REGRESSED\") : delta.improved ? ui.green(\"IMPROVED\") : ui.dim(\"UNCHANGED\");\n const lines = [ui.bold(`Eval vs baseline — ${verdict}`)];\n for (const line of [\n fmtDelta(\"score\", delta.score),\n fmtDelta(\"mean recall\", delta.mean_recall),\n fmtDelta(\"mrr\", delta.mrr),\n fmtDelta(\"catch-rate\", delta.catch_rate),\n ]) {\n if (line) lines.push(line);\n }\n return lines.join(\"\\n\");\n}\n\nfunction renderGateDelta(delta: GatePrecisionDelta): string {\n const verdict = delta.regressed ? ui.red(\"REGRESSED\") : ui.dim(\"UNCHANGED\");\n const lines = [ui.bold(`Gate precision vs baseline — ${verdict}`)];\n const precisionDelta =\n delta.precision.delta === null ? \"n/a\" : `${delta.precision.delta > 0 ? \"+\" : \"\"}${delta.precision.delta}`;\n const rejectionDelta =\n delta.rejections.delta === null ? \"n/a\" : `${delta.rejections.delta > 0 ? \"+\" : \"\"}${delta.rejections.delta}`;\n lines.push(` precision ${delta.precision.baseline ?? \"n/a\"} → ${delta.precision.current ?? \"n/a\"} ${ui.dim(`(${precisionDelta})`)}`);\n lines.push(` rejections ${delta.rejections.baseline ?? \"n/a\"} → ${delta.rejections.current ?? \"n/a\"} ${ui.dim(`(${rejectionDelta})`)}`);\n return lines.join(\"\\n\");\n}\n\nfunction countCases(spec: EvalSpec): number {\n return (spec.retrieval?.length ?? 0) + (spec.sensors?.length ?? 0);\n}\n\nasync function resolveSpec(opts: EvalOptions, root: string, memoriesDir: string): Promise<ResolvedEvalSpec> {\n if (opts.spec) {\n const file = path.resolve(opts.spec);\n const raw = await readFile(file, \"utf8\");\n const spec = JSON.parse(raw) as EvalSpec;\n // --spec uses ONLY the hand-labeled cases: a true independent-ground-truth run, no self-referential synthesis.\n return { spec, source: file, synthesized: 0, authored: countCases(spec) };\n }\n const defaultSpec = path.join(root, \".ai\", \"eval\", \"spec.json\");\n if (existsSync(defaultSpec)) {\n const raw = await readFile(defaultSpec, \"utf8\");\n const explicit = JSON.parse(raw) as EvalSpec;\n const memories = await loadMemoriesFromDir(memoriesDir);\n const synthesized = synthesizeSelfEvalCases(memories, { includeFiles: !opts.semanticOnly });\n return {\n spec: {\n retrieval: [...synthesized, ...(explicit.retrieval ?? [])],\n sensors: explicit.sensors ?? [],\n },\n source: \".ai/eval/spec.json + synthesized anchored retrieval\",\n synthesized: synthesized.length,\n authored: countCases(explicit),\n };\n }\n const memories = await loadMemoriesFromDir(memoriesDir);\n const synthesized = synthesizeSelfEvalCases(memories, { includeFiles: !opts.semanticOnly });\n return {\n spec: { retrieval: synthesized },\n source: \"synthesized anchored retrieval\",\n synthesized: synthesized.length,\n authored: 0,\n };\n}\n\nasync function runRetrieval(\n c: RetrievalCase,\n k: number,\n ctx: { paths: ReturnType<typeof resolveHaivePaths> },\n): Promise<string[]> {\n const out = await getBriefing(\n {\n task: c.task,\n files: c.files ?? [],\n symbols: c.symbols ?? [],\n max_tokens: 6000,\n max_memories: k,\n include_project_context: false,\n include_module_contexts: false,\n semantic: true,\n include_stale: false,\n track: false,\n format: \"compact\",\n min_semantic_score: 0,\n },\n ctx,\n );\n return out.memories.map((m) => m.id);\n}\n\nasync function runSensorCase(\n c: SensorCase,\n ctx: { paths: ReturnType<typeof resolveHaivePaths> },\n): Promise<string[]> {\n const out = await antiPatternsCheck(\n { diff: c.diff, paths: c.paths ?? [], limit: 50, semantic: false },\n ctx,\n );\n return out.warnings.filter((w) => w.reasons.includes(\"sensor\")).map((w) => w.id);\n}\n\nfunction pct(n: number): string {\n return `${Math.round(n * 100)}%`;\n}\n\nfunction renderMarkdown(\n root: string,\n k: number,\n resolved: ResolvedEvalSpec,\n report: ReturnType<typeof buildReport>,\n gatePrecision: GatePrecision,\n authoredScore: number | null,\n): string {\n const provenance =\n resolved.authored === 0\n ? `${resolved.synthesized} synthesized (self-referential — sanity floor, not ground truth)`\n : resolved.synthesized === 0\n ? `${resolved.authored} authored (independent ground truth)`\n : `${resolved.authored} authored (independent) + ${resolved.synthesized} synthesized (self-referential)`;\n const lines = [\n \"# Hivelore eval report\",\n \"\",\n `Project: \\`${root}\\` · top-k: ${k}`,\n `Spec: ${resolved.source}`,\n `Cases: ${provenance}`,\n \"\",\n // Honesty: the HEADLINE is the independent (authored) score when the run mixes in self-referential\n // synthesized cases — so 100/100 from cases the harness wrote about itself can't read as ground truth.\n `## Overall score: ${authoredScore !== null ? authoredScore : report.score}/100${authoredScore !== null ? \" (authored-only, independent ground truth)\" : \"\"}`,\n \"\",\n ];\n\n // Show the blended number as a secondary, clearly-labelled sanity floor — never the headline.\n if (authoredScore !== null) {\n lines.push(\n `> Blended with ${resolved.synthesized} self-referential synthesized case(s): **${report.score}/100** ` +\n `(a self-referential sanity floor, NOT ground truth — the headline above is the independent score).`,\n \"\",\n );\n }\n\n if (report.retrieval) {\n const r = report.retrieval;\n lines.push(\n \"## Retrieval\",\n \"\",\n `- cases: ${r.cases.length}`,\n `- mean recall: ${pct(r.mean_recall)} ${\"— did the expected memory make the top-k? (the metric that matters)\"}`,\n `- mean precision: ${pct(r.mean_precision)} ${\"— top-k precision (expected ÷ k surfaced); low by design when ~1 is expected per case, NOT a quality defect; excluded from the headline score\"}`,\n `- MRR: ${r.mrr.toFixed(3)} — how high the expected memory was ranked`,\n \"\",\n );\n const misses = r.cases.filter((c) => c.misses.length > 0);\n if (misses.length > 0) {\n lines.push(`### ${misses.length} retrieval miss(es)`, \"\");\n for (const c of misses.slice(0, 25)) {\n lines.push(`- \\`${c.name}\\` — expected not in top-${k}`);\n }\n lines.push(\"\");\n }\n }\n\n if (report.sensors) {\n const s = report.sensors;\n lines.push(\"## Sensors\", \"\", `- cases: ${s.cases.length}`, `- catch-rate: ${pct(s.catch_rate)}`, \"\");\n const misses = s.cases.filter((c) => c.misses.length > 0);\n if (misses.length > 0) {\n lines.push(`### ${misses.length} sensor miss(es)`, \"\");\n for (const c of misses.slice(0, 25)) {\n lines.push(`- \\`${c.name}\\` — sensor did not fire (expected: ${c.misses.join(\", \")})`);\n }\n lines.push(\"\");\n }\n }\n\n lines.push(\n \"## Gate precision\",\n \"\",\n `- precision: ${gatePrecision.precision === null ? \"n/a\" : pct(gatePrecision.precision)}`,\n `- useful outcomes: ${gatePrecision.useful}`,\n `- rejected as false-positive/noise: ${gatePrecision.rejections}`,\n \"\",\n );\n\n lines.push(\n \"## Reading\",\n \"\",\n \"Retrieval recall = share of expected memories that surfaced in the briefing top-k.\",\n \"MRR rewards ranking the right memory high. Catch-rate = share of known-bad diffs a sensor flagged.\",\n \"Run in CI to fail the build on a ranking/sensor regression.\",\n \"\",\n );\n return lines.join(\"\\n\");\n}\n","import { mkdir, writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n aggregateUsage,\n buildFrontmatter,\n findProjectRoot,\n loadConfig,\n loadMemoriesFromDir,\n memoryFilePath,\n parseSince,\n readUsageEvents,\n resolveHaivePaths,\n serializeMemory,\n} from \"@hivelore/core\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface SuggestOptions {\n since?: string;\n min?: string;\n json?: boolean;\n dir?: string;\n autoSave?: boolean;\n topN?: string;\n scope?: \"personal\" | \"team\";\n}\n\nconst SEARCH_TOOLS = new Set([\n \"mem_search\",\n \"code_search\",\n \"mem_relevant_to\",\n \"get_briefing\",\n]);\n\nconst SYNTHETIC_QUERY_RE = /\\b(auto-promote-marker|local enforcement smoke|cli-test-session)\\b/i;\n\nexport function isSyntheticSuggestionQuery(query: string): boolean {\n return SYNTHETIC_QUERY_RE.test(query);\n}\n\ninterface QuerySuggestion {\n query: string;\n count: number;\n tools: string[];\n last_used: string;\n reason: string;\n inferred_type: \"architecture\" | \"convention\" | \"decision\" | \"gotcha\";\n}\n\nexport function registerMemorySuggest(memory: Command): void {\n memory\n .command(\"suggest\")\n .description(\n \"Suggest memories to create based on recurring search queries in the usage log.\\n\\n\" +\n \" Use --auto-save to save the top-N suggestions using the project defaults.\\n\" +\n \" In autopilot, suggestions land as validated team records; in manual mode they stay draft.\",\n )\n .option(\"--since <window>\", \"ISO date or relative (e.g. '7d', '24h')\", \"30d\")\n .option(\"--min <count>\", \"minimum repeat count to surface a query\", \"2\")\n .option(\"--top-n <n>\", \"with --auto-save, draft this many top suggestions\", \"3\")\n .option(\"--scope <scope>\", \"with --auto-save, scope of saved memories (personal | team; default: config default)\")\n .option(\"--auto-save\", \"save top-N suggestions as memories on disk\", false)\n .option(\"--json\", \"emit JSON instead of human-readable output\", false)\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: SuggestOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n const events = await readUsageEvents(paths);\n if (events.length === 0) {\n if (opts.json) {\n console.log(JSON.stringify({ suggestions: [] }));\n return;\n }\n ui.warn(\"No usage log entries yet. Suggestions appear after the MCP server records some calls.\");\n return;\n }\n\n const since = parseSince(opts.since);\n const minCount = Math.max(1, parseInt(opts.min ?? \"2\", 10));\n const cutoff = since ? since.getTime() : 0;\n\n const queries = new Map<string, { count: number; tools: Set<string>; last: string }>();\n for (const e of events) {\n if (cutoff && Date.parse(e.at) < cutoff) continue;\n if (!SEARCH_TOOLS.has(e.tool)) continue;\n const key = (e.summary ?? \"\").toLowerCase().trim();\n if (!key) continue;\n if (isSyntheticSuggestionQuery(key)) continue;\n const prior = queries.get(key);\n if (prior) {\n prior.count++;\n prior.tools.add(e.tool);\n if (e.at > prior.last) prior.last = e.at;\n } else {\n queries.set(key, { count: 1, tools: new Set([e.tool]), last: e.at });\n }\n }\n\n const suggestions: QuerySuggestion[] = [...queries.entries()]\n .filter(([, v]) => v.count >= minCount)\n .map(([query, v]) => ({\n query,\n count: v.count,\n tools: [...v.tools].sort(),\n last_used: v.last,\n reason: chooseReason(v.tools, v.count),\n inferred_type: inferType(v.tools, query),\n }))\n .sort((a, b) => b.count - a.count);\n\n // ── Auto-save flow ────────────────────────────────────────────────────\n if (opts.autoSave) {\n const config = await loadConfig(paths);\n const topN = Math.max(1, parseInt(opts.topN ?? \"3\", 10));\n const scope: \"personal\" | \"team\" =\n opts.scope === \"personal\" || opts.scope === \"team\"\n ? opts.scope\n : config.defaultScope ?? \"personal\";\n const status = config.defaultStatus === \"validated\" ? \"validated\" : \"draft\";\n const top = suggestions.slice(0, topN);\n if (top.length === 0) {\n ui.warn(`No suggestions met --min=${minCount} — nothing to save.`);\n return;\n }\n const created: Array<{ id: string; file: string; query: string }> = [];\n const skipped: Array<{ query: string; reason: string }> = [];\n const existing = existsSync(paths.memoriesDir)\n ? await loadMemoriesFromDir(paths.memoriesDir)\n : [];\n\n for (const s of top) {\n const slug = slugify(s.query);\n if (!slug) {\n skipped.push({ query: s.query, reason: \"could not derive a slug\" });\n continue;\n }\n // Avoid overwriting an existing memory with similar slug.\n const dup = existing.find(({ memory }) => memory.frontmatter.id.endsWith(`-${slug}`));\n if (dup) {\n skipped.push({ query: s.query, reason: `similar memory already exists (${dup.memory.frontmatter.id})` });\n continue;\n }\n const fm = buildFrontmatter({\n type: s.inferred_type,\n slug,\n scope,\n tags: [\"auto-suggested\", ...s.tools],\n paths: [],\n symbols: [],\n status,\n });\n const body = renderTemplate(s, fm.id, status);\n const file = memoryFilePath(paths, fm.scope, fm.id, fm.module);\n await mkdir(path.dirname(file), { recursive: true });\n if (existsSync(file)) {\n skipped.push({ query: s.query, reason: `file already exists at ${path.relative(root, file)}` });\n continue;\n }\n await writeFile(file, serializeMemory({ frontmatter: fm, body }), \"utf8\");\n created.push({ id: fm.id, file: path.relative(root, file), query: s.query });\n }\n\n if (opts.json) {\n console.log(JSON.stringify({ created, skipped }, null, 2));\n return;\n }\n for (const c of created) {\n ui.success(`${status === \"validated\" ? \"Saved\" : \"Drafted\"} ${c.id} → ${c.file}`);\n console.log(` ${ui.dim(\"from query:\")} ${truncate(c.query, 60)}`);\n }\n for (const s of skipped) {\n ui.warn(`Skipped: ${truncate(s.query, 50)} — ${s.reason}`);\n }\n if (created.length > 0) {\n console.log();\n if (status === \"validated\") {\n ui.info(\"Autopilot defaults applied: suggestions are status=validated and active.\");\n } else {\n ui.info(\"Drafts are status=draft — edit them, then run `hivelore memory promote <id>`.\");\n }\n }\n return;\n }\n\n // ── Read-only listing flow ───────────────────────────────────────────\n if (opts.json) {\n console.log(JSON.stringify({ window: opts.since, suggestions }, null, 2));\n return;\n }\n\n const totals = aggregateUsage(events, since ?? undefined);\n console.log(ui.bold(`Hivelore memory suggestions (${opts.since ?? \"all time\"})`));\n console.log(\n ui.dim(`scanned ${totals.total} events, ${suggestions.length} repeated queries (≥${minCount})`),\n );\n console.log();\n if (suggestions.length === 0) {\n ui.info(\"No recurring searches yet — nothing to suggest.\");\n return;\n }\n for (const s of suggestions.slice(0, 30)) {\n console.log(\n ` ${ui.bold(`×${s.count}`)} ${ui.dim(`[${s.tools.join(\",\")}]`)} ${truncate(s.query, 70)}`,\n );\n console.log(` ${ui.dim(\"→\")} ${s.reason}`);\n }\n console.log();\n ui.info(\"Run with --auto-save to save the top-3 using the project defaults.\");\n });\n}\n\nfunction chooseReason(tools: Set<string>, count: number): string {\n if (tools.has(\"code_search\")) {\n return `${count} agents searched the code for this — consider mem_save (architecture/decision) capturing where it lives.`;\n }\n if (tools.has(\"mem_search\") || tools.has(\"mem_relevant_to\")) {\n return `${count} agents asked but the memory layer had no clear answer — consider mem_save (convention/decision/gotcha).`;\n }\n return `${count} agents asked the briefing for this — consider promoting the answer to a team memory.`;\n}\n\nfunction inferType(tools: Set<string>, query: string): QuerySuggestion[\"inferred_type\"] {\n const q = query.toLowerCase();\n if (q.includes(\"bug\") || q.includes(\"error\") || q.includes(\"crash\") || q.includes(\"trap\")) return \"gotcha\";\n if (q.includes(\"decid\") || q.includes(\"why\") || q.includes(\"choose\") || q.includes(\"vs \")) return \"decision\";\n if (tools.has(\"code_search\") && (q.includes(\"where\") || q.includes(\"location\") || q.includes(\"structure\"))) {\n return \"architecture\";\n }\n return \"convention\";\n}\n\nfunction renderTemplate(s: QuerySuggestion, id: string, status: \"draft\" | \"validated\"): string {\n const nextStep = status === \"validated\"\n ? `This record is already active because project autopilot defaults set status=validated. Replace the template body with the actual answer when known.`\n : `Then run \\`hivelore memory promote ${id}\\` to move it into team review.`;\n return [\n `# Auto-drafted from recurring searches`,\n ``,\n `> This memory was drafted by \\`hivelore memory suggest --auto-save\\` because`,\n `> agents searched for this **${s.count} times** in the recent window`,\n `> via ${s.tools.join(\", \")}.`,\n ``,\n `## Query`,\n ``,\n `> ${s.query}`,\n ``,\n `## What to fill in`,\n ``,\n `Replace this section with the actual answer the team keeps re-discovering:`,\n ``,\n `- **What** — the convention / decision / gotcha (1-3 sentences)`,\n `- **Why** — the rationale or root cause`,\n `- **How to apply** — what an agent should do when this comes up again`,\n ``,\n nextStep,\n ].join(\"\\n\");\n}\n\nfunction slugify(s: string): string {\n return s\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 60);\n}\n\nfunction truncate(text: string, max: number): string {\n if (text.length <= max) return text;\n return text.slice(0, max - 1) + \"…\";\n}\n","import { existsSync } from \"node:fs\";\nimport { writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n findProjectRoot,\n getUsage,\n retirementSignal,\n loadConfig,\n loadMemoriesFromDir,\n loadUsageIndex,\n resolveHaivePaths,\n serializeMemory,\n} from \"@hivelore/core\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface ArchiveOptions {\n since?: string;\n type?: string;\n unread?: boolean;\n apply?: boolean;\n json?: boolean;\n dir?: string;\n}\n\ninterface Candidate {\n id: string;\n type: string;\n status: string;\n last_seen: string;\n reason: string;\n filePath: string;\n}\n\nconst MS_PER_DAY = 24 * 60 * 60 * 1000;\n\nexport function registerMemoryArchive(memory: Command): void {\n memory\n .command(\"archive\")\n .description(\n \"Archive obsolete memories: marks status='deprecated' for memories not read in N days\\n\" +\n \" whose anchored paths have all disappeared (or have no anchor at all).\\n\\n\" +\n \" Defaults to a DRY RUN — pass --apply to actually rewrite files.\\n\" +\n \" Targets `attempt` memories by default since they age the fastest.\\n\\n\" +\n \" Recover later with `hivelore memory edit <id>` to set status back to validated.\",\n )\n .option(\"--since <window>\", \"minimum age since last read (e.g. '180d', '6m'). Default: enforcement.decayAfterDays or 180d\")\n .option(\"--type <type>\", \"limit to a memory type (default 'attempt'). Pass 'all' to scan all types.\", \"attempt\")\n .option(\"--unread\", \"decay by unread-age ALONE (ignore anchor status) — more aggressive corpus hygiene\", false)\n .option(\"--apply\", \"actually rewrite files (default: dry run)\", false)\n .option(\"--json\", \"emit JSON instead of human-readable output\", false)\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: ArchiveOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.memoriesDir)) {\n ui.error(`No .ai/memories at ${root}. Run \\`hivelore init\\` first.`);\n process.exitCode = 1;\n return;\n }\n\n const config = await loadConfig(paths);\n const defaultWindow = config.enforcement?.decayAfterDays\n ? `${config.enforcement.decayAfterDays}d`\n : \"180d\";\n const minDays = parseDays(opts.since ?? defaultWindow);\n if (minDays === null) {\n ui.error(`Invalid --since value: ${opts.since}. Use formats like '180d', '6m', '1y'.`);\n process.exitCode = 1;\n return;\n }\n const cutoff = Date.now() - minDays * MS_PER_DAY;\n\n const all = await loadMemoriesFromDir(paths.memoriesDir);\n const usage = await loadUsageIndex(paths);\n const typeFilter = opts.type === \"all\" ? null : (opts.type ?? \"attempt\");\n\n const candidates: Candidate[] = [];\n for (const { memory: mem, filePath } of all) {\n const fm = mem.frontmatter;\n if (typeFilter && fm.type !== typeFilter) continue;\n // Never auto-decay session recaps or memories pinned for human review.\n if (fm.type === \"session_recap\" || fm.requires_human_approval) continue;\n // Skip already-archived states.\n if (fm.status === \"deprecated\" || fm.status === \"rejected\") continue;\n const retired = retirementSignal(fm, mem.body);\n // Anchorless OR all anchored paths gone OR all anchored symbols missing\n const hasAnyAnchor = fm.anchor.paths.length + fm.anchor.symbols.length > 0;\n const allPathsGone = fm.anchor.paths.length > 0\n && fm.anchor.paths.every((p) => !existsSync(path.join(paths.root, p)));\n const isAnchorless = !hasAnyAnchor;\n // Default mode requires the knowledge to be unanchored or its code to have vanished.\n // --unread is the aggressive path: decay on unread-age alone, regardless of anchor state.\n if (!retired.retired && !opts.unread && !isAnchorless && !allPathsGone) continue;\n // Age check\n const u = getUsage(usage, fm.id);\n const lastSeen = u.last_read_at ?? fm.created_at;\n if (!retired.retired && Date.parse(lastSeen) >= cutoff) continue;\n\n const reason = retired.retired\n ? `retired lifecycle signal: ${retired.reason ?? \"unknown\"}`\n : isAnchorless\n ? `anchorless and not read since ${lastSeen.slice(0, 10)}`\n : allPathsGone\n ? `all ${fm.anchor.paths.length} anchored path(s) missing and not read since ${lastSeen.slice(0, 10)}`\n : `not read since ${lastSeen.slice(0, 10)} (unread decay)`;\n candidates.push({\n id: fm.id,\n type: fm.type,\n status: fm.status,\n last_seen: lastSeen,\n reason,\n filePath,\n });\n }\n\n if (opts.json) {\n console.log(JSON.stringify({\n dry_run: !opts.apply,\n window_days: minDays,\n candidates: candidates.length,\n archived: opts.apply ? candidates.length : 0,\n items: candidates,\n }, null, 2));\n } else {\n const header = opts.apply ? \"Archiving\" : \"Would archive\";\n console.log(ui.bold(`${header} ${candidates.length} memor${candidates.length === 1 ? \"y\" : \"ies\"} (older than ${minDays}d, type=${typeFilter ?? \"all\"})`));\n if (candidates.length === 0) {\n ui.info(\"Nothing to archive — all memories are anchored or read recently.\");\n return;\n }\n for (const c of candidates) {\n console.log(` ${ui.dim(c.last_seen.slice(0, 10))} ${c.id} ${ui.dim(`(${c.type})`)} — ${c.reason}`);\n }\n }\n\n if (!opts.apply) {\n if (!opts.json) {\n console.log();\n ui.info(\"Dry run — pass --apply to mark these as deprecated on disk.\");\n }\n return;\n }\n\n // Apply: rewrite each file with status=deprecated.\n let archived = 0;\n let failed = 0;\n for (const c of candidates) {\n const found = all.find(({ filePath }) => filePath === c.filePath);\n if (!found) continue;\n const fm = { ...found.memory.frontmatter, status: \"deprecated\" as const };\n try {\n await writeFile(c.filePath, serializeMemory({ frontmatter: fm, body: found.memory.body }), \"utf8\");\n archived++;\n } catch (err) {\n if (!opts.json) {\n ui.error(`Failed to archive ${c.id}: ${err instanceof Error ? err.message : String(err)}`);\n }\n failed++;\n }\n }\n if (!opts.json) {\n ui.success(`Archived ${archived} memor${archived === 1 ? \"y\" : \"ies\"}${failed > 0 ? ` (${failed} failed)` : \"\"}`);\n }\n });\n}\n\nfunction parseDays(input: string): number | null {\n const m = input.match(/^(\\d+)([dmy])$/);\n if (!m) return null;\n const n = parseInt(m[1] ?? \"0\", 10);\n const unit = m[2] ?? \"d\";\n if (unit === \"d\") return n;\n if (unit === \"m\") return n * 30;\n if (unit === \"y\") return n * 365;\n return null;\n}\n","import { existsSync, statSync } from \"node:fs\";\nimport { readFile, stat, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { execFileSync, execSync } from \"node:child_process\";\nimport { Command } from \"commander\";\nimport {\n applyAutopilotRepairs,\n projectContextVersionStatus,\n type AutopilotRepair,\n} from \"../utils/autopilot.js\";\nimport { lintMemoriesAsync } from \"./memory-lint.js\";\nimport { isSyntheticSuggestionQuery } from \"./memory-suggest.js\";\n\ndeclare const __HAIVE_VERSION__: string;\nimport {\n codeMapPath,\n countSourceFilesOnDisk,\n extractReferencedPaths,\n sensorPatternBrittleness,\n sensorSelfCheck,\n findProjectRoot,\n getUsage,\n isStackPackSeed,\n loadCodeMap,\n loadConfig,\n loadMemoriesFromDir,\n loadUsageIndex,\n readUsageEvents,\n resolveHaivePaths,\n type LoadedMemory,\n type SensorTarget,\n type UsageEvent,\n} from \"@hivelore/core\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface DoctorOptions {\n json?: boolean;\n dir?: string;\n fix?: boolean;\n dryRun?: boolean;\n}\n\ntype Severity = \"info\" | \"warn\" | \"error\";\ntype DoctorSection =\n | \"Protection\"\n | \"Agent coverage\"\n | \"Context quality\"\n | \"Corpus health\"\n | \"Harness coverage\"\n | \"Index health\"\n | \"Next actions\";\n\ninterface Finding {\n severity: Severity;\n code: string;\n message: string;\n fix?: string;\n section?: DoctorSection;\n coverage_percent?: number;\n}\n\ninterface DoctorScores {\n protection_score: number;\n context_quality_score: number;\n corpus_quality_score: number;\n harness_coverage_score: number;\n}\n\nconst MS_PER_DAY = 24 * 60 * 60 * 1000;\n\nexport function registerDoctor(program: Command): void {\n program\n .command(\"doctor\")\n .description(\n \"Analyze the local Hivelore setup and emit actionable recommendations.\\n\\n\" +\n \" Inspects: project-context status, memory health (stale/anchorless/decay/pending),\\n\" +\n \" code-map freshness, usage log signals (low-hit briefings, repeated empty searches).\\n\\n\" +\n \" Read-only by default. Pass --fix to apply safe autopilot repairs.\",\n )\n .option(\"--json\", \"emit JSON instead of human-readable output\", false)\n .option(\"--fix\", \"include suggested fix commands in human output\", false)\n .option(\"--dry-run\", \"with --fix, show delegated repairs without applying them\", false)\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: DoctorOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n const findings: Finding[] = [];\n const repairs: AutopilotRepair[] = [];\n const config = await loadConfig(paths);\n\n // ── 1. Init state ─────────────────────────────────────────────────────\n if (!existsSync(paths.haiveDir)) {\n findings.push({\n severity: \"error\",\n code: \"not-initialized\",\n message: \".ai/ directory missing — Hivelore is not initialized in this project.\",\n fix: \"hivelore init\",\n });\n return emit(findings, opts);\n }\n\n if (opts.fix && !opts.dryRun) {\n repairs.push(\n ...await applyAutopilotRepairs(root, paths, {\n applyConfig: true,\n applyContext: true,\n applyCorpus: true,\n applyCodeMap: true,\n applyCodeSearch: true,\n forceCodeMap: true,\n }),\n );\n }\n\n // ── 2. Project context ────────────────────────────────────────────────\n if (!existsSync(paths.projectContext)) {\n findings.push({\n severity: \"warn\",\n code: \"no-project-context\",\n message: \".ai/project-context.md is missing.\",\n fix: \"hivelore init\",\n });\n } else {\n const { readFile } = await import(\"node:fs/promises\");\n const content = await readFile(paths.projectContext, \"utf8\");\n const isTemplate = content.includes(\"TODO — high-level overview\") ||\n content.includes(\"Generated by `hivelore init`\");\n if (isTemplate) {\n findings.push({\n severity: \"warn\",\n code: \"template-context\",\n message: \"project-context.md still contains the default template — get_briefing returns little value until filled.\",\n fix: \"Invoke the bootstrap_project MCP prompt from your AI client.\",\n });\n } else {\n // Grounding: a FILLED context that cites file paths which don't exist on disk is ungrounded\n // (hallucinated or stale) — the failure mode of LLM-generated context. Flag low-grounded ones.\n const referenced = extractReferencedPaths(content);\n const missing = referenced.filter((p) => !existsSync(path.resolve(root, p)));\n const grounded = referenced.length - missing.length;\n if (referenced.length >= 3 && grounded / referenced.length < 0.5) {\n findings.push({\n severity: \"warn\",\n code: \"project-context-ungrounded\",\n section: \"Context quality\" as DoctorSection,\n message:\n `project-context.md cites ${referenced.length} file path(s) but ${missing.length} don't exist on disk ` +\n `(e.g. ${missing.slice(0, 3).join(\", \")}) — it looks ungrounded or stale, not written from the real code.`,\n fix: \"Regenerate via the bootstrap_project MCP prompt, or fix the stale paths.\",\n });\n }\n }\n const versionStatus = await projectContextVersionStatus(root, paths);\n if (versionStatus.mismatch) {\n findings.push({\n severity: \"warn\",\n code: \"project-context-version-mismatch\",\n message:\n `.ai/project-context.md version metadata (${versionStatus.currentVersion ?? \"missing\"}) ` +\n `does not match package.json (${versionStatus.expectedVersion}).`,\n fix: \"hivelore doctor --fix\",\n });\n }\n }\n\n // ── 3. Memories ───────────────────────────────────────────────────────\n const memories: LoadedMemory[] = existsSync(paths.memoriesDir)\n ? await loadMemoriesFromDir(paths.memoriesDir)\n : [];\n const now = Date.now();\n\n if (memories.length === 0) {\n findings.push({\n severity: \"info\",\n code: \"no-memories\",\n message: \"No memories yet. Capture knowledge as agents work via mem_save / mem_observe / mem_tried.\",\n });\n } else {\n const usage = await loadUsageIndex(paths);\n\n const stale = memories.filter((m) => m.memory.frontmatter.status === \"stale\");\n if (stale.length > 0) {\n findings.push({\n severity: \"warn\",\n code: \"stale-memories\",\n message: `${stale.length} memor${stale.length === 1 ? \"y\" : \"ies\"} marked stale (anchored code drifted).`,\n fix: \"hivelore memory verify --update # re-check anchors\\nhaive memory edit <id> # manually refresh body\",\n });\n }\n\n const proposed = memories.filter((m) => m.memory.frontmatter.status === \"proposed\");\n if (proposed.length > 0) {\n findings.push({\n severity: \"info\",\n code: \"pending-review\",\n message: `${proposed.length} memor${proposed.length === 1 ? \"y is\" : \"ies are\"} proposed and awaiting validation.`,\n fix: \"hivelore memory pending # list them\\nhaive memory auto-promote # promote those with high read_count\",\n });\n }\n\n // Drafts older than 30 days — likely forgotten, never activated\n const OLD_DRAFT_DAYS = 30;\n const oldDrafts = memories.filter((m) => {\n if (m.memory.frontmatter.status !== \"draft\") return false;\n const age = (now - Date.parse(m.memory.frontmatter.created_at)) / MS_PER_DAY;\n return age > OLD_DRAFT_DAYS;\n });\n if (oldDrafts.length > 0) {\n const ids = oldDrafts.slice(0, 4).map((m) => m.memory.frontmatter.id).join(\", \");\n const more = oldDrafts.length > 4 ? ` (+${oldDrafts.length - 4} more)` : \"\";\n findings.push({\n severity: \"warn\",\n code: \"stale-draft-memories\",\n message:\n `${oldDrafts.length} draft memor${oldDrafts.length === 1 ? \"y has\" : \"ies have\"} been in draft status for 30+ days: ${ids}${more}`,\n fix: \"hivelore memory approve <id> # activate\\nhaive memory delete <id> # or delete if obsolete\",\n });\n }\n\n // Anchorless = no paths AND no symbols → cannot detect drift automatically\n // (skill, glossary, session_recap are procedure/reference types that don't need code anchors)\n const policyMemories = memories.filter((m) => !isStackPackSeed(m.memory.frontmatter));\n const anchorless = policyMemories.filter((m) =>\n m.memory.frontmatter.anchor.paths.length === 0 &&\n m.memory.frontmatter.anchor.symbols.length === 0 &&\n m.memory.frontmatter.type !== \"session_recap\" &&\n m.memory.frontmatter.type !== \"glossary\" &&\n m.memory.frontmatter.type !== \"skill\"\n );\n const stackSeeds = memories.filter((m) => isStackPackSeed(m.memory.frontmatter));\n if (anchorless.length / Math.max(policyMemories.length, 1) > 0.3) {\n findings.push({\n severity: \"warn\",\n code: \"anchorless-majority\",\n message: `${anchorless.length}/${policyMemories.length} repo-specific memories have no anchor path/symbol — staleness undetectable.`,\n fix: \"Add `paths:` + `symbols:` to mem_save calls to enable hivelore memory verify.\",\n });\n } else if (stackSeeds.length > 0 && policyMemories.length === 0) {\n findings.push({\n severity: \"info\",\n code: \"stack-pack-seeds\",\n message: `${stackSeeds.length} starter stack memor${stackSeeds.length === 1 ? \"y is\" : \"ies are\"} present as generic background guidance.`,\n fix: \"Replace or anchor stack-pack seeds when they become repo-specific policy.\",\n });\n }\n\n // Decay candidates: validated memories not read in 180 days\n const decayCandidates = memories.filter((m) => {\n if (m.memory.frontmatter.status !== \"validated\") return false;\n const u = getUsage(usage, m.memory.frontmatter.id);\n const last = u.last_read_at ?? m.memory.frontmatter.created_at;\n return (now - Date.parse(last)) / MS_PER_DAY > 180;\n });\n if (decayCandidates.length > 0) {\n findings.push({\n severity: \"info\",\n code: \"decay-candidates\",\n message: `${decayCandidates.length} validated memor${decayCandidates.length === 1 ? \"y has\" : \"ies have\"} not been read in 180+ days — confidence is decaying.`,\n fix: \"hivelore memory archive --type all --since 365d # dry run\",\n });\n }\n }\n\n const lintReport = await lintMemoriesAsync(root);\n if (lintReport.findings.length > 0) {\n const warnCount = lintReport.findings.filter((finding) => finding.severity === \"warn\").length;\n const errorCount = lintReport.findings.filter((finding) => finding.severity === \"error\").length;\n const severity: Severity = errorCount > 0 ? \"error\" : warnCount > 0 ? \"warn\" : \"info\";\n findings.push({\n severity,\n code: \"memory-lint-findings\",\n message:\n `memory lint reports ${lintReport.findings.length} finding${lintReport.findings.length === 1 ? \"\" : \"s\"} ` +\n `(${errorCount} error, ${warnCount} warn, ${lintReport.findings.length - errorCount - warnCount} info).`,\n fix: \"hivelore memory lint --fix --apply\",\n });\n }\n\n // Corpus hygiene: brittle sensors (over-fit to line numbers/literals) silently rot and inflate\n // the \"active protection\" count. Surface them so they can be rewritten or retired.\n const brittleSensors = memories.filter((m) => {\n const s = m.memory.frontmatter.sensor;\n return s?.kind === \"regex\" && s.pattern && sensorPatternBrittleness(s.pattern);\n }).length;\n if (brittleSensors > 0) {\n findings.push({\n severity: \"info\",\n code: \"memory-brittle-sensors\",\n message: `${brittleSensors} sensor(s) look brittle (hardcoded line numbers/literals) — they won't hard-block and may not fire on real diffs.`,\n fix: \"hivelore sensors list # review the ⚠ brittle entries, then rewrite or retire them\",\n });\n }\n\n // Honest protection signal: Hivelore's headline claim is \"blocks the repeat\". If every sensor is\n // warn-only, enforcement is *advisory*, not blocking — say so (and pull down protection_score)\n // rather than letting the pitch outrun the config. Either promote a trusted sensor, or stop\n // claiming enforcement. Counts toward the Protection section.\n const sensorMemories = memories.filter((m) => m.memory.frontmatter.sensor);\n const blockSensors = sensorMemories.filter(\n (m) => m.memory.frontmatter.sensor?.severity === \"block\",\n ).length;\n if (sensorMemories.length > 0 && blockSensors === 0) {\n findings.push({\n severity: \"warn\",\n code: \"sensors-no-hard-block\",\n section: \"Protection\" as DoctorSection,\n message:\n `${sensorMemories.length} sensor(s) defined but 0 hard-block (all warn-only) — enforcement is ` +\n `effectively advisory. The \"blocks the repeat\" guarantee isn't true until a trusted sensor is promoted.`,\n fix: \"hivelore sensors list # then `hivelore sensors promote <id>` for a trusted, non-brittle sensor — or retire the noise\",\n });\n }\n\n // Self-validation: a block sensor that matches the CURRENT (presumed-correct) code false-positives\n // on every commit. It shouldn't be trusted as protection — surface it so it's fixed or demoted.\n const firesOnCurrent: string[] = [];\n for (const m of sensorMemories) {\n const s = m.memory.frontmatter.sensor;\n if (!s || s.kind !== \"regex\" || s.severity !== \"block\" || !s.pattern) continue;\n const anchorPaths = s.paths.length > 0 ? s.paths : m.memory.frontmatter.anchor.paths;\n const targets: SensorTarget[] = [];\n for (const rel of anchorPaths) {\n const abs = path.resolve(root, rel);\n if (!existsSync(abs)) continue;\n try { targets.push({ path: rel, content: await readFile(abs, \"utf8\") }); } catch { /* skip */ }\n }\n if (targets.length === 0) continue;\n if (!sensorSelfCheck(s, { currentTargets: targets, badExamples: [] }).silent_on_current) {\n firesOnCurrent.push(m.memory.frontmatter.id);\n }\n }\n if (firesOnCurrent.length > 0) {\n findings.push({\n severity: \"warn\",\n code: \"sensor-fires-on-current\",\n section: \"Protection\" as DoctorSection,\n message:\n `${firesOnCurrent.length} block sensor(s) match the CURRENT code — they false-positive on every ` +\n `commit and can't be trusted as protection: ${firesOnCurrent.slice(0, 3).join(\", \")}` +\n `${firesOnCurrent.length > 3 ? \", …\" : \"\"}.`,\n fix: \"Make the pattern discriminating (add an 'absent' companion), or demote: `hivelore sensors promote <id> --severity warn`\",\n });\n }\n\n // ── 4. Code-map freshness ─────────────────────────────────────────────\n const codeMap = await loadCodeMap(paths);\n if (!codeMap) {\n findings.push({\n severity: \"warn\",\n code: \"no-code-map\",\n message: \"No code-map found — code_map MCP tool and symbol_locations are unavailable.\",\n fix: \"hivelore index code\",\n });\n } else {\n const cmFile = codeMapPath(paths);\n const cmStat = await stat(cmFile);\n const ageDays = (now - cmStat.mtimeMs) / MS_PER_DAY;\n const indexedCount = Object.keys(codeMap.files).length;\n if (ageDays > 14) {\n findings.push({\n severity: \"warn\",\n code: \"stale-code-map\",\n message: `code-map is ${Math.round(ageDays)} days old (${indexedCount} files indexed).`,\n fix: \"hivelore index code # or rely on the post-merge git hook\",\n });\n }\n // Detect a near-empty code-map: many source files on disk but few indexed (untracked source\n // or a structure the indexer missed). Silent before — on a real monorepo it indexed 2/1400+.\n const onDisk = await countSourceFilesOnDisk(root);\n if (onDisk >= 20 && indexedCount < onDisk * 0.5) {\n findings.push({\n severity: \"warn\",\n code: \"code-map-near-empty\",\n message: `code-map indexed ${indexedCount} file(s) but ~${onDisk} source file(s) are on disk — most of your code is NOT indexed (untracked source, or nested repos the indexer can't reach).`,\n fix: \"hivelore index code # if files are untracked, commit them or check nested-repo setup\",\n });\n }\n }\n\n findings.push(...await collectHarnessCoverageFindings(codeMap, memories));\n findings.push(...await collectSemanticIndexFindings(paths, config, memories.length, codeMap));\n\n // ── 5. Usage log signals ──────────────────────────────────────────────\n const events = await readUsageEvents(paths);\n if (events.length === 0) {\n findings.push({\n severity: \"info\",\n code: \"no-usage-log\",\n message: \"No usage log entries — MCP server hasn't recorded any calls yet, or this project hasn't been used by an agent.\",\n });\n } else {\n // Count searches that likely returned little (heuristic: same query repeated 3+ times)\n const queryRepeats = new Map<string, number>();\n for (const e of events) {\n if (!isSearchTool(e.tool)) continue;\n const key = (e.summary ?? \"\").toLowerCase().trim();\n if (!key) continue;\n if (isSyntheticSuggestionQuery(key)) continue;\n queryRepeats.set(key, (queryRepeats.get(key) ?? 0) + 1);\n }\n const repeated = [...queryRepeats.entries()].filter(([, n]) => n >= 3);\n if (repeated.length > 0) {\n findings.push({\n severity: \"info\",\n code: \"recurring-searches\",\n message: `${repeated.length} query${repeated.length === 1 ? \"\" : \"ies\"} repeated 3+ times — agents keep asking the same things.`,\n fix: `hivelore memory suggest --auto-save --top-n ${Math.min(5, repeated.length)}`,\n });\n }\n\n // Code-map calls that errored (returned 0 files even though indexed)\n const codeMapCalls = events.filter((e) => e.tool === \"code_map\").length;\n const briefingCalls = events.filter((e) => e.tool === \"get_briefing\").length;\n if (codeMapCalls > 0 && memories.length > 0) {\n // we only have summaries, not output; this stays informational\n findings.push({\n severity: \"info\",\n code: \"tool-mix\",\n message: `${briefingCalls} get_briefing call${briefingCalls === 1 ? \"\" : \"s\"}, ${codeMapCalls} code_map call${codeMapCalls === 1 ? \"\" : \"s\"} recorded.`,\n });\n }\n }\n\n // ── 6. Config sanity ──────────────────────────────────────────────────\n if (config.enforcement?.requireBriefingFirst) {\n const claudeSettings = path.join(root, \".claude\", \"settings.local.json\");\n let hasClaudeEnforcement = false;\n if (existsSync(claudeSettings)) {\n try {\n const { readFile } = await import(\"node:fs/promises\");\n const raw = await readFile(claudeSettings, \"utf8\");\n hasClaudeEnforcement =\n raw.includes(\"hivelore enforce session-start\") &&\n raw.includes(\"hivelore enforce pre-tool-use\");\n } catch {\n hasClaudeEnforcement = false;\n }\n }\n if (!hasClaudeEnforcement) {\n findings.push({\n severity: \"info\",\n code: \"claude-enforcement-hooks-missing\",\n message: \"Hivelore enforcement is enabled, but project-scoped Claude Code hooks are not installed.\",\n fix: \"hivelore install-hooks claude --scope project\",\n });\n }\n }\n if (!config.autoSessionEnd) {\n findings.push({\n severity: \"info\",\n code: \"no-autopilot\",\n message: \"Autopilot is OFF — session recaps are not auto-saved on shutdown.\",\n fix: \"Edit .ai/haive.config.json: set autoSessionEnd: true (or re-run `hivelore init` without --manual).\",\n });\n }\n\n // ── 7. Installation / integration version sanity ──────────────────────\n findings.push(...await collectInstallFindings(root, __HAIVE_VERSION__));\n findings.push(...await collectToolchainFindings(root));\n\n // ── 8. Legacy standalone haive-mcp ──────────────────────────────────────\n // MCP runs inside `hivelore mcp --stdio` — updating @hivelore/cli is enough.\n // Warn only if an old global haive-mcp exists and disagrees with CLI.\n try {\n const legacyRaw = execSync(\"haive-mcp --version\", {\n encoding: \"utf8\",\n timeout: 3000,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n }).trim();\n const cliVersion = __HAIVE_VERSION__;\n if (legacyRaw && legacyRaw !== cliVersion) {\n findings.push({\n severity: \"warn\",\n code: \"legacy-haive-mcp-stale\",\n message:\n `Standalone haive-mcp on PATH is v${legacyRaw} but the CLI is v${cliVersion}. ` +\n `MCP is now bundled in the hivelore CLI itself — switch your client configs to ` +\n `command \"hivelore\" + args [\"mcp\", \"--stdio\"], then uninstall @hivelore/mcp.`,\n fix:\n `# 1. Run hivelore init to regenerate MCP configs pointing to bundled server:\\n` +\n `hivelore init\\n` +\n `# 2. Optionally remove the now-redundant standalone package:\\n` +\n `npm uninstall -g @hivelore/mcp`,\n });\n }\n } catch {\n // haive-mcp not on PATH — expected when using bundled MCP via haive only\n }\n\n // ── 9. Legacy haive-mcp references in project MCP config files ──────────\n // Scan .mcp.json / .cursor/mcp.json / .vscode/mcp.json for old command references.\n {\n const configPaths = [\n path.join(root, \".mcp.json\"),\n path.join(root, \".cursor\", \"mcp.json\"),\n path.join(root, \".vscode\", \"mcp.json\"),\n ];\n const staleConfigs: string[] = [];\n for (const cfgPath of configPaths) {\n if (!existsSync(cfgPath)) continue;\n try {\n const raw = await readFile(cfgPath, \"utf8\");\n if (raw.includes('\"haive-mcp\"') || raw.includes(\"'haive-mcp'\")) {\n staleConfigs.push(path.relative(root, cfgPath));\n if (opts.fix && !opts.dryRun) {\n const updated = raw\n .replace(/\"command\"\\s*:\\s*\"haive-mcp\"/g, '\"command\": \"hivelore\"')\n .replace(/\"args\"\\s*:\\s*\\[\\]/g, '\"args\": [\"mcp\", \"--stdio\"]');\n await writeFile(cfgPath, updated, \"utf8\");\n }\n }\n } catch { /* ignore unreadable config */ }\n }\n if (staleConfigs.length > 0) {\n findings.push({\n severity: \"warn\",\n code: \"legacy-mcp-config\",\n message:\n `${staleConfigs.length} MCP config file${staleConfigs.length === 1 ? \"\" : \"s\"} still reference the old \"haive-mcp\" command: ` +\n staleConfigs.join(\", \") +\n `. Run \\`hivelore doctor --fix\\` to auto-migrate to the bundled server.`,\n fix: \"hivelore doctor --fix\",\n section: \"Protection\" as DoctorSection,\n });\n }\n }\n\n if (repairs.length > 0) {\n findings.push({\n severity: \"info\",\n code: \"autopilot-repairs-applied\",\n message: repairs.map((repair) => repair.message).join(\" \"),\n section: \"Next actions\",\n });\n }\n\n emit(findings, opts, repairs);\n });\n}\n\nfunction emit(findings: Finding[], opts: DoctorOptions, repairs: AutopilotRepair[] = []): void {\n const classified = findings.map((finding) => ({\n ...finding,\n section: finding.section ?? sectionForFinding(finding),\n }));\n const scores = computeDoctorScores(classified);\n if (opts.json) {\n console.log(JSON.stringify({\n scores,\n findings: classified,\n sections: groupBySection(classified),\n next_actions: nextActions(classified),\n repairs,\n fix_mode: opts.fix ? opts.dryRun ? \"dry-run\" : \"apply\" : \"off\",\n }, null, 2));\n return;\n }\n if (classified.length === 0) {\n ui.success(repairs.length > 0 ? \"Hivelore doctor — autopilot repairs applied.\" : \"Hivelore doctor — no issues found.\");\n return;\n }\n console.log(ui.bold(`Hivelore doctor — ${classified.length} finding${classified.length === 1 ? \"\" : \"s\"}`));\n console.log(\n ui.dim(\n ` protection=${scores.protection_score} ` +\n `context=${scores.context_quality_score} ` +\n `corpus=${scores.corpus_quality_score} ` +\n `harness-coverage=${scores.harness_coverage_score}%`,\n ),\n );\n console.log();\n\n const sectionOrder: DoctorSection[] = [\n \"Protection\",\n \"Agent coverage\",\n \"Context quality\",\n \"Corpus health\",\n \"Harness coverage\",\n \"Index health\",\n \"Next actions\",\n ];\n const severityOrder: Severity[] = [\"error\", \"warn\", \"info\"];\n for (const section of sectionOrder) {\n const sectionFindings = classified.filter((f) => f.section === section);\n if (sectionFindings.length === 0) continue;\n console.log(ui.bold(section));\n for (const sev of severityOrder) {\n for (const f of sectionFindings.filter((x) => x.severity === sev)) {\n const icon = sev === \"error\" ? ui.red(\"✗\") : sev === \"warn\" ? ui.yellow(\"⚠\") : ui.dim(\"ℹ\");\n console.log(`${icon} ${ui.bold(f.code)} ${f.message}`);\n if (opts.fix && f.fix) {\n for (const line of f.fix.split(\"\\n\")) {\n console.log(` ${ui.dim(opts.dryRun ? \"would run:\" : \"$\")} ${line}`);\n }\n }\n }\n }\n console.log();\n }\n\n if (repairs.length > 0) {\n console.log(ui.bold(\"Autopilot repairs applied\"));\n for (const repair of repairs) console.log(` ${ui.dim(\"✓\")} ${repair.message}`);\n console.log();\n }\n\n const actions = nextActions(classified);\n if (actions.length > 0) {\n console.log(ui.bold(\"Next actions\"));\n for (const action of actions.slice(0, 5)) console.log(` ${ui.dim(\"$\")} ${action}`);\n } else if (!opts.fix && classified.some((f) => f.fix)) {\n ui.info(\"Re-run with --fix to see suggested commands.\");\n }\n}\n\nfunction sectionForFinding(finding: Finding): DoctorSection {\n if (\n finding.code.includes(\"haive\") ||\n finding.code.includes(\"integration\") ||\n finding.code.includes(\"claude\") ||\n finding.code.includes(\"autopilot\")\n ) return \"Agent coverage\";\n if (\n finding.code.includes(\"context\") ||\n finding.code.includes(\"briefing\") ||\n finding.code.includes(\"search\")\n ) return \"Context quality\";\n if (finding.code.includes(\"harness-coverage\")) return \"Harness coverage\";\n if (finding.code.includes(\"code-map\") || finding.code.includes(\"index\")) return \"Index health\";\n if (\n finding.code.includes(\"memory\") ||\n finding.code.includes(\"anchor\") ||\n finding.code.includes(\"pending\") ||\n finding.code.includes(\"decay\")\n ) return \"Corpus health\";\n if (finding.severity === \"error\") return \"Protection\";\n return \"Next actions\";\n}\n\nfunction computeDoctorScores(findings: Finding[]): DoctorScores {\n const scoreFor = (sections: DoctorSection[]): number => {\n const scoped = findings.filter((f) => sections.includes(f.section ?? sectionForFinding(f)));\n const penalty = scoped.reduce((sum, f) => {\n if (f.severity === \"error\") return sum + 35;\n if (f.severity === \"warn\") return sum + 15;\n return sum + 4;\n }, 0);\n return Math.max(0, 100 - penalty);\n };\n const coverageFinding = findings.find((f) => f.code === \"harness-coverage\");\n const harnessCoverageScore = coverageFinding?.coverage_percent ?? 0;\n return {\n protection_score: scoreFor([\"Protection\", \"Agent coverage\"]),\n context_quality_score: scoreFor([\"Context quality\", \"Index health\"]),\n corpus_quality_score: scoreFor([\"Corpus health\"]),\n harness_coverage_score: harnessCoverageScore,\n };\n}\n\nfunction groupBySection(findings: Finding[]): Record<DoctorSection, Finding[]> {\n const out: Record<DoctorSection, Finding[]> = {\n \"Protection\": [],\n \"Agent coverage\": [],\n \"Context quality\": [],\n \"Corpus health\": [],\n \"Harness coverage\": [],\n \"Index health\": [],\n \"Next actions\": [],\n };\n for (const finding of findings) out[finding.section ?? sectionForFinding(finding)].push(finding);\n return out;\n}\n\nfunction nextActions(findings: Finding[]): string[] {\n return [...new Set(findings.flatMap((finding) => finding.fix ? finding.fix.split(\"\\n\") : []))]\n .filter(Boolean);\n}\n\n/**\n * Files that are low-value anchoring targets: test files, build configs, and type\n * declaration files don't represent production logic worth protecting with memories.\n * Excluding them from the denominator makes the coverage percentage meaningful.\n */\nfunction isLowValueCoverageFile(file: string): boolean {\n const lower = file.toLowerCase();\n const base = lower.split(\"/\").pop() ?? lower;\n if (lower.includes(\".test.\") || lower.includes(\".spec.\")) return true;\n if (lower.includes(\"/__tests__/\") || lower.includes(\"/test/\") || lower.includes(\"/tests/\")) return true;\n if (lower.endsWith(\".d.ts\")) return true;\n if (base === \"tsup.config.ts\" || base === \"vitest.config.ts\" || base === \"jest.config.ts\") return true;\n if (base.endsWith(\".config.ts\") || base.endsWith(\".config.js\")) return true;\n if (base === \"vite.config.ts\" || base === \"vite.config.js\") return true;\n return false;\n}\n\nasync function collectHarnessCoverageFindings(\n codeMap: Awaited<ReturnType<typeof loadCodeMap>>,\n memories: LoadedMemory[],\n): Promise<Finding[]> {\n if (!codeMap) return [];\n const allFiles = Object.keys(codeMap.files);\n // Exclude test files and build configs from the denominator — only production\n // source files are meaningful anchor targets for harness coverage.\n const codeFiles = allFiles.filter((f) => !isLowValueCoverageFile(f));\n const total = codeFiles.length;\n if (total === 0) return [];\n\n const validatedWithAnchors = memories.filter(\n (m) =>\n (m.memory.frontmatter.status === \"validated\" || m.memory.frontmatter.status === \"proposed\") &&\n m.memory.frontmatter.anchor.paths.length > 0,\n );\n\n const coveredFiles = new Set<string>();\n for (const m of validatedWithAnchors) {\n for (const anchorPath of m.memory.frontmatter.anchor.paths) {\n const normalized = anchorPath.replace(/^\\/+/, \"\");\n for (const codeFile of codeFiles) {\n if (\n codeFile === normalized ||\n codeFile.startsWith(normalized + \"/\") ||\n normalized.startsWith(codeFile + \"/\")\n ) {\n coveredFiles.add(codeFile);\n }\n }\n }\n }\n\n const covered = coveredFiles.size;\n const pct = Math.round((covered / total) * 100);\n\n // Top uncovered files — prefer root-level and common source directories\n const uncovered = codeFiles\n .filter((f) => !coveredFiles.has(f))\n .sort((a, b) => {\n // Prefer shorter paths (key modules tend to be near the root)\n const depthA = a.split(\"/\").length;\n const depthB = b.split(\"/\").length;\n if (depthA !== depthB) return depthA - depthB;\n return a.localeCompare(b);\n })\n .slice(0, 5);\n\n const coverageDesc =\n pct < 10 && total > 10\n ? \"Low coverage — add memory anchors on key modules to improve harness enforcement.\"\n : pct < 50\n ? \"Partial coverage — useful but not yet broad enough to call the harness mature.\"\n : pct < 80\n ? \"Good coverage — critical modules are increasingly protected.\"\n : \"Good harness coverage.\";\n\n const uncoveredHint = uncovered.length > 0\n ? `\\n Top uncovered: ${uncovered.map((f) => `\\`${f}\\``).join(\", \")}`\n : \"\";\n\n const findings: Finding[] = [];\n findings.push({\n severity: \"info\",\n code: \"harness-coverage\",\n coverage_percent: pct,\n message:\n `${covered}/${total} code-map files have validated memory anchors (${pct}%). ` +\n coverageDesc + uncoveredHint,\n fix: pct < 50 && total > 10\n ? `hivelore memory save --type gotcha|convention|architecture --paths <key-file> --scope team`\n : undefined,\n section: \"Harness coverage\",\n });\n\n return findings;\n}\n\nasync function collectSemanticIndexFindings(\n paths: ReturnType<typeof resolveHaivePaths>,\n config: Awaited<ReturnType<typeof loadConfig>>,\n memoryCount: number,\n codeMap: Awaited<ReturnType<typeof loadCodeMap>>,\n): Promise<Finding[]> {\n const findings: Finding[] = [];\n const autoWantsCodeSearch = Boolean(config.autopilot || config.autoRepair?.codeSearch);\n let mod: typeof import(\"@hivelore/embeddings\");\n try {\n mod = await import(\"@hivelore/embeddings\");\n } catch {\n findings.push({\n severity: autoWantsCodeSearch ? \"warn\" : \"info\",\n code: \"embeddings-unavailable\",\n message:\n \"@hivelore/embeddings is not available, so get_briefing falls back to lexical ranking and code_search cannot run.\",\n fix: \"npm install -g @hivelore/cli@latest\\nhaive embeddings status\",\n section: \"Index health\",\n });\n return findings;\n }\n\n if (memoryCount > 0) {\n const stat = await mod.indexStat(paths).catch(() => ({ exists: false, count: 0 }));\n if (!stat.exists || stat.count === 0) {\n findings.push({\n severity: \"warn\",\n code: \"semantic-memory-index-missing\",\n message:\n \"Memory embeddings index is missing or empty; get_briefing will report literal_fallback instead of semantic ranking.\",\n fix: \"hivelore embeddings index\",\n section: \"Index health\",\n });\n }\n }\n\n if (autoWantsCodeSearch || codeMap) {\n const codeIndex = await mod.loadCodeIndex(paths).catch(() => null);\n if (!codeIndex || codeIndex.entries.length === 0) {\n findings.push({\n severity: autoWantsCodeSearch ? \"warn\" : \"info\",\n code: \"code-search-index-missing\",\n message:\n \"Code-search embeddings index is missing or empty; MCP code_search is unavailable until it is built.\",\n fix: \"hivelore index code-search\",\n section: \"Index health\",\n });\n } else if (codeMap && codeIndex.source_generated_at !== codeMap.generated_at) {\n findings.push({\n severity: \"info\",\n code: \"code-search-index-outdated\",\n message:\n \"Code-search embeddings index was built from an older code-map; semantic code search may miss recent symbols.\",\n fix: \"hivelore index code-search\",\n section: \"Index health\",\n });\n }\n }\n\n return findings;\n}\n\nfunction isSearchTool(name: string): boolean {\n return [\"mem_search\", \"code_search\", \"mem_relevant_to\", \"get_briefing\"].includes(name);\n}\n\nasync function collectInstallFindings(root: string, expectedVersion: string): Promise<Finding[]> {\n const findings: Finding[] = [];\n\n findings.push(...await collectWorkspaceVersionFindings(root, expectedVersion));\n findings.push(...await collectDistFreshnessFindings(root, expectedVersion));\n\n const haiveBins = listHaiveBins();\n if (haiveBins.length === 0) {\n findings.push({\n severity: \"warn\",\n code: \"haive-not-on-path\",\n message: \"No `hivelore` (or legacy `haive`) binary was found on PATH. Hooks and MCP configs that call it may fail.\",\n fix: `npm install -g @hivelore/cli@${expectedVersion}`,\n });\n } else {\n const first = haiveBins[0]!;\n const firstVersion = versionForBinary(first);\n if (firstVersion && firstVersion !== expectedVersion) {\n findings.push({\n severity: \"warn\",\n code: \"path-haive-version-mismatch\",\n message: `PATH resolves the CLI to ${first} (${firstVersion}), but this build expects ${expectedVersion}.`,\n fix: `npm install -g @hivelore/cli@${expectedVersion}\\nwhich -a hivelore haive`,\n });\n }\n const skewed = haiveBins\n .map((bin) => ({ bin, version: versionForBinary(bin) }))\n .filter((item) => item.version && item.version !== expectedVersion);\n if (skewed.length > 0) {\n findings.push({\n severity: \"info\",\n code: \"multiple-haive-binaries\",\n message:\n `Found ${haiveBins.length} hivelore/haive binar${haiveBins.length === 1 ? \"y\" : \"ies\"} on PATH; ` +\n `${skewed.length} do not match ${expectedVersion}.`,\n fix: \"Remove stale global installs or ensure hooks call the intended `hivelore` binary.\",\n });\n }\n }\n\n const integrationFiles = [\n \".git/hooks/pre-commit\",\n \".git/hooks/pre-push\",\n \".claude/settings.local.json\",\n \".mcp.json\",\n \".cursor/mcp.json\",\n \".vscode/mcp.json\",\n ];\n // Dedupe by binary: the same broken/stale path is usually referenced by several integration files\n // (pre-commit, pre-push, .mcp.json…). Emit ONE finding per unique binary that lists the files,\n // instead of one per occurrence (which produced 3× identical warnings).\n const missingBins = new Map<string, Set<string>>();\n const staleBins = new Map<string, { version: string; files: Set<string> }>();\n for (const rel of integrationFiles) {\n const file = path.join(root, rel);\n if (!existsSync(file)) continue;\n const text = await readFile(file, \"utf8\").catch(() => \"\");\n for (const bin of extractAbsoluteHaiveBins(text)) {\n const version = versionForBinary(bin);\n if (!version) {\n (missingBins.get(bin) ?? missingBins.set(bin, new Set()).get(bin)!).add(rel);\n } else if (version !== expectedVersion) {\n const entry = staleBins.get(bin) ?? staleBins.set(bin, { version, files: new Set() }).get(bin)!;\n entry.files.add(rel);\n }\n }\n }\n for (const [bin, files] of missingBins) {\n findings.push({\n severity: \"warn\",\n code: \"integration-haive-binary-missing\",\n message: `${[...files].join(\", \")} reference ${bin}, but it could not be executed.`,\n fix: \"Run `hivelore agent setup --no-global` or `hivelore enforce install` to rewrite project integrations.\",\n });\n }\n for (const [bin, { version, files }] of staleBins) {\n findings.push({\n severity: \"warn\",\n code: \"integration-haive-version-mismatch\",\n message: `${[...files].join(\", \")} reference ${bin} (${version}), but current Hivelore is ${expectedVersion}.`,\n fix: \"Run `hivelore agent setup --no-global` and `hivelore enforce install` to refresh stale paths.\",\n });\n }\n\n return findings;\n}\n\nasync function collectToolchainFindings(root: string): Promise<Finding[]> {\n const findings: Finding[] = [];\n const pkg = await readJson<{ packageManager?: string; scripts?: Record<string, string> }>(\n path.join(root, \"package.json\"),\n );\n const wantsPnpm = pkg?.packageManager?.startsWith(\"pnpm@\") ||\n Object.values(pkg?.scripts ?? {}).some((script) => /\\bpnpm\\b/.test(script));\n if (!wantsPnpm) return findings;\n\n const expected = pkg?.packageManager?.replace(/^pnpm@/, \"\") ?? \"9.14.2\";\n if (!commandExists(\"pnpm\", [\"--version\"])) {\n const corepackAvailable = commandExists(\"corepack\", [\"--version\"]);\n findings.push({\n severity: \"warn\",\n code: \"pnpm-not-on-path\",\n message:\n `This workspace uses pnpm${expected ? ` ${expected}` : \"\"}, but no pnpm binary is available on PATH. ` +\n `Local build/test commands may fail even though CI works.`,\n fix: corepackAvailable\n ? `corepack prepare pnpm@${expected} --activate`\n : `npx pnpm@${expected} install --frozen-lockfile`,\n section: \"Agent coverage\",\n });\n }\n return findings;\n}\n\nasync function collectDistFreshnessFindings(root: string, expectedVersion: string): Promise<Finding[]> {\n const findings: Finding[] = [];\n const isHaiveWorkspace =\n [\"hivelore-monorepo\", \"haive-monorepo\"].includes((await readJson<{ name?: string }>(path.join(root, \"package.json\")))?.name ?? \"\");\n if (!isHaiveWorkspace) return findings;\n\n const cliDist = path.join(root, \"packages/cli/dist/index.js\");\n if (!existsSync(cliDist)) {\n findings.push({\n severity: \"warn\",\n code: \"workspace-dist-missing\",\n message: \"packages/cli/dist/index.js is missing; local Hivelore smoke commands cannot reflect source changes.\",\n fix: \"pnpm -r build\",\n section: \"Agent coverage\",\n });\n return findings;\n }\n\n const distVersion = versionForNodeEntrypoint(cliDist);\n if (distVersion && distVersion !== expectedVersion) {\n findings.push({\n severity: \"warn\",\n code: \"workspace-dist-version-mismatch\",\n message:\n `packages/cli/dist/index.js reports ${distVersion}, but this source build expects ${expectedVersion}. ` +\n `Run a fresh workspace build after pull before trusting local doctor/enforce output.`,\n fix: \"pnpm -r build\\npnpm check:artifacts\",\n section: \"Agent coverage\",\n });\n }\n\n const sourceFiles = [\n \"packages/core/src/index.ts\",\n \"packages/mcp/src/server.ts\",\n \"packages/cli/src/index.ts\",\n ].map((rel) => path.join(root, rel)).filter(existsSync);\n if (sourceFiles.length > 0) {\n const distMtime = statSync(cliDist).mtimeMs;\n const newestSource = Math.max(...sourceFiles.map((file) => statSync(file).mtimeMs));\n if (newestSource > distMtime + 1000) {\n findings.push({\n severity: \"info\",\n code: \"workspace-dist-older-than-source\",\n message:\n \"Built CLI artifacts are older than key source files; rebuild before running release smoke checks.\",\n fix: \"pnpm -r build\\npnpm check:artifacts\",\n section: \"Agent coverage\",\n });\n }\n }\n\n return findings;\n}\n\nasync function collectWorkspaceVersionFindings(root: string, expectedVersion: string): Promise<Finding[]> {\n const findings: Finding[] = [];\n const rootPkg = await readJson<{ name?: string; version?: string }>(path.join(root, \"package.json\"));\n const workspacePackages = [\n \"packages/core/package.json\",\n \"packages/embeddings/package.json\",\n \"packages/cli/package.json\",\n \"packages/mcp/package.json\",\n ];\n const existing = (await Promise.all(workspacePackages.map(async (rel) => ({\n rel,\n pkg: await readJson<{ name?: string; version?: string }>(path.join(root, rel)),\n })))).filter((item) => item.pkg);\n\n const isHaiveWorkspace = rootPkg?.name === \"hivelore-monorepo\" || rootPkg?.name === \"haive-monorepo\" ||\n existing.some((item) => item.pkg?.name?.startsWith(\"@hivelore/\"));\n if (!isHaiveWorkspace) return findings;\n\n if (rootPkg?.version && rootPkg.version !== expectedVersion) {\n findings.push({\n severity: \"warn\",\n code: \"repo-root-version-mismatch\",\n message: `Root package.json is ${rootPkg.version}, but the active Hivelore build is ${expectedVersion}.`,\n fix: `Update root package.json to ${expectedVersion} before tagging/publishing.`,\n section: \"Agent coverage\",\n });\n }\n\n const skewed = existing.filter((item) => item.pkg?.version !== expectedVersion);\n if (skewed.length > 0) {\n findings.push({\n severity: \"warn\",\n code: \"workspace-package-version-mismatch\",\n message:\n `Workspace package version skew: ` +\n skewed.map((item) => `${item.rel}=${item.pkg?.version ?? \"missing\"}`).join(\", \") +\n `; expected ${expectedVersion}.`,\n fix: `Bump @hivelore/core, @hivelore/embeddings, @hivelore/cli and @hivelore/mcp to ${expectedVersion}.`,\n section: \"Agent coverage\",\n });\n }\n\n findings.push(...collectGlobalHivemoduleFindings(expectedVersion));\n return findings;\n}\n\nfunction collectGlobalHivemoduleFindings(expectedVersion: string): Finding[] {\n try {\n const raw = execSync(\n \"npm list -g --depth=0 --json @hivelore/cli @hivelore/mcp @hivelore/core @hivelore/embeddings\",\n { encoding: \"utf8\", timeout: 5000, stdio: [\"ignore\", \"pipe\", \"ignore\"] },\n );\n const parsed = JSON.parse(raw) as { dependencies?: Record<string, { version?: string }> };\n const deps = parsed.dependencies ?? {};\n const important = [\"@hivelore/cli\", \"@hivelore/mcp\"];\n const staleImportant = important\n .map((name) => ({ name, version: deps[name]?.version }))\n .filter((item) => item.version && item.version !== expectedVersion);\n const staleTopLevel = [\"@hivelore/core\", \"@hivelore/embeddings\"]\n .map((name) => ({ name, version: deps[name]?.version }))\n .filter((item) => item.version && item.version !== expectedVersion);\n const findings: Finding[] = [];\n if (staleImportant.length > 0) {\n findings.push({\n severity: \"warn\",\n code: \"global-haive-version-mismatch\",\n message:\n `Global Hivelore CLI/MCP package skew: ` +\n staleImportant.map((item) => `${item.name}@${item.version}`).join(\", \") +\n `; expected ${expectedVersion}.`,\n fix: `npm install -g @hivelore/cli@${expectedVersion} @hivelore/mcp@${expectedVersion}`,\n section: \"Agent coverage\",\n });\n }\n if (staleTopLevel.length > 0) {\n findings.push({\n severity: \"info\",\n code: \"global-haive-top-level-stale\",\n message:\n `Older top-level global packages are installed but may be unused: ` +\n staleTopLevel.map((item) => `${item.name}@${item.version}`).join(\", \") +\n `. Active CLI/MCP dependencies should still be checked by hivelore --version and haive-mcp --version.`,\n fix: \"npm uninstall -g @hivelore/core @hivelore/embeddings\",\n section: \"Agent coverage\",\n });\n }\n return findings;\n } catch {\n return [];\n }\n}\n\nasync function readJson<T>(file: string): Promise<T | null> {\n if (!existsSync(file)) return null;\n try {\n return JSON.parse(await readFile(file, \"utf8\")) as T;\n } catch {\n return null;\n }\n}\n\nfunction listHaiveBins(): string[] {\n // Transition: the CLI ships both `hivelore` (primary) and `haive` (legacy alias) bins.\n const found: string[] = [];\n for (const name of [\"hivelore\", \"haive\"]) {\n try {\n found.push(...execSync(`which -a ${name}`, {\n encoding: \"utf8\",\n timeout: 3000,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n })\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter(Boolean));\n } catch { /* not on PATH under this name */ }\n }\n return found;\n}\n\nfunction versionForBinary(bin: string): string | null {\n try {\n const out = execFileSync(bin, [\"--version\"], {\n encoding: \"utf8\",\n timeout: 3000,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n }).trim();\n return out.match(/\\d+\\.\\d+\\.\\d+/)?.[0] ?? null;\n } catch {\n return null;\n }\n}\n\nfunction versionForNodeEntrypoint(file: string): string | null {\n try {\n const out = execFileSync(process.execPath, [file, \"--version\"], {\n encoding: \"utf8\",\n timeout: 3000,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n }).trim();\n return out.match(/\\d+\\.\\d+\\.\\d+/)?.[0] ?? null;\n } catch {\n return null;\n }\n}\n\nfunction commandExists(command: string, args: string[]): boolean {\n try {\n execFileSync(command, args, {\n encoding: \"utf8\",\n timeout: 3000,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n });\n return true;\n } catch {\n return false;\n }\n}\n\nfunction extractAbsoluteHaiveBins(text: string): string[] {\n const out = new Set<string>();\n const re = /([\"'\\s])((?:\\/[^\"'\\s]+)*\\/haive)\\b/g;\n let match: RegExpExecArray | null;\n while ((match = re.exec(text))) {\n const p = match[2];\n if (!p) continue;\n // Skip paths that are directories — a haive binary is a file, not a folder.\n // This prevents env-var values like HAIVE_PROJECT_ROOT being mistaken for binaries.\n try {\n if (statSync(p).isDirectory()) continue;\n } catch {\n // Path does not exist — still add so we can report it as missing\n }\n out.add(p);\n }\n return [...out].sort();\n}\n","import { existsSync } from \"node:fs\";\nimport { Command } from \"commander\";\nimport {\n findProjectRoot,\n loadMemoriesFromDir,\n parseSince,\n readUsageEvents,\n resolveHaivePaths,\n type UsageEvent,\n} from \"@hivelore/core\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface PlaybackOptions {\n since?: string;\n json?: boolean;\n dir?: string;\n sessionGap?: string;\n limit?: string;\n}\n\ninterface SessionBucket {\n index: number;\n start: string;\n end: string;\n duration_minutes: number;\n events: number;\n tools_count: Record<string, number>;\n briefing_tasks: string[];\n memories_created_since: number;\n /** memories that exist now but didn't at session start */\n new_memories: string[];\n}\n\nconst MS_PER_MINUTE = 60_000;\n\nexport function registerPlayback(program: Command): void {\n program\n .command(\"playback\")\n .description(\n \"Replay past sessions from the usage log. For each session, show:\\n\" +\n \" - tool calls (what kind, how many)\\n\" +\n \" - briefing tasks asked\\n\" +\n \" - memories that have been created since then (that the session didn't have)\\n\\n\" +\n \" Useful to ask 'would today's haive have helped past me on this task?'\",\n )\n .option(\"--since <window>\", \"limit to events in this window (e.g. '7d')\", \"30d\")\n .option(\"--session-gap <minutes>\", \"minutes of inactivity that splits a session\", \"30\")\n .option(\"--limit <n>\", \"show at most this many sessions (newest first)\", \"10\")\n .option(\"--json\", \"emit JSON instead of human-readable output\", false)\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: PlaybackOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n\n const events = await readUsageEvents(paths);\n if (events.length === 0) {\n if (opts.json) {\n console.log(JSON.stringify({ sessions: [] }));\n return;\n }\n ui.warn(\"No usage log entries yet.\");\n return;\n }\n\n const since = parseSince(opts.since);\n const cutoff = since ? since.getTime() : 0;\n const filtered = cutoff > 0\n ? events.filter((e) => Date.parse(e.at) >= cutoff)\n : events;\n\n const gapMs = Math.max(1, parseInt(opts.sessionGap ?? \"30\", 10)) * MS_PER_MINUTE;\n const sessions = bucketSessions(filtered, gapMs);\n\n // Load memories and pre-index by created_at to compute \"new memories since\" deltas.\n const all = existsSync(paths.memoriesDir) ? await loadMemoriesFromDir(paths.memoriesDir) : [];\n const memByCreatedAt = all\n .filter(({ memory }) => memory.frontmatter.type !== \"session_recap\")\n .map(({ memory }) => ({ id: memory.frontmatter.id, at: Date.parse(memory.frontmatter.created_at) }))\n .sort((a, b) => a.at - b.at);\n\n const enriched: SessionBucket[] = sessions.map((s, i) => {\n const startMs = Date.parse(s.start);\n const newer = memByCreatedAt.filter((m) => m.at > startMs);\n return {\n index: i,\n start: s.start,\n end: s.end,\n duration_minutes: (Date.parse(s.end) - startMs) / MS_PER_MINUTE,\n events: s.events.length,\n tools_count: countTools(s.events),\n briefing_tasks: s.events\n .filter((e) => e.tool === \"get_briefing\" && e.summary)\n .map((e) => e.summary!)\n .slice(0, 5),\n memories_created_since: newer.length,\n new_memories: newer.slice(0, 5).map((m) => m.id),\n };\n });\n\n // Sort newest first and apply limit\n enriched.sort((a, b) => Date.parse(b.start) - Date.parse(a.start));\n const limit = Math.max(1, parseInt(opts.limit ?? \"10\", 10));\n const shown = enriched.slice(0, limit);\n\n if (opts.json) {\n console.log(JSON.stringify({\n window: opts.since,\n session_gap_minutes: gapMs / MS_PER_MINUTE,\n total_sessions: enriched.length,\n sessions: shown,\n }, null, 2));\n return;\n }\n\n console.log(ui.bold(`Hivelore playback — ${enriched.length} session(s) over ${opts.since ?? \"all time\"}`));\n console.log();\n for (const s of shown) {\n console.log(\n `${ui.bold(`Session ${s.index + 1}`)} ${ui.dim(s.start.slice(0, 19) + \" → \" + s.end.slice(11, 19))}` +\n ` ${ui.dim(`(${Math.round(s.duration_minutes)}m, ${s.events} call${s.events === 1 ? \"\" : \"s\"})`)}`,\n );\n const toolList = Object.entries(s.tools_count)\n .sort((a, b) => b[1] - a[1])\n .slice(0, 5)\n .map(([t, n]) => `${t}×${n}`)\n .join(\", \");\n if (toolList) console.log(` ${ui.dim(\"tools:\")} ${toolList}`);\n if (s.briefing_tasks.length > 0) {\n console.log(` ${ui.dim(\"briefings asked:\")}`);\n for (const t of s.briefing_tasks) {\n console.log(` • ${truncate(t, 80)}`);\n }\n }\n if (s.memories_created_since > 0) {\n console.log(\n ` ${ui.green(\"⤴\")} ${s.memories_created_since} memor${s.memories_created_since === 1 ? \"y has\" : \"ies have\"} been created since this session ` +\n ui.dim(`— newer haive could have answered better`),\n );\n for (const id of s.new_memories) {\n console.log(` + ${ui.dim(id)}`);\n }\n }\n console.log();\n }\n });\n}\n\nfunction bucketSessions(events: UsageEvent[], gapMs: number): Array<{ start: string; end: string; events: UsageEvent[] }> {\n if (events.length === 0) return [];\n const sorted = [...events].sort((a, b) => Date.parse(a.at) - Date.parse(b.at));\n const buckets: Array<{ start: string; end: string; events: UsageEvent[] }> = [];\n let current: { start: string; end: string; events: UsageEvent[] } | null = null;\n for (const e of sorted) {\n if (!current) {\n current = { start: e.at, end: e.at, events: [e] };\n continue;\n }\n if (Date.parse(e.at) - Date.parse(current.end) > gapMs) {\n buckets.push(current);\n current = { start: e.at, end: e.at, events: [e] };\n } else {\n current.events.push(e);\n current.end = e.at;\n }\n }\n if (current) buckets.push(current);\n return buckets;\n}\n\nfunction countTools(events: UsageEvent[]): Record<string, number> {\n const out: Record<string, number> = {};\n for (const e of events) out[e.tool] = (out[e.tool] ?? 0) + 1;\n return out;\n}\n\nfunction truncate(text: string, max: number): string {\n if (text.length <= max) return text;\n return text.slice(0, max - 1) + \"…\";\n}\n","import { spawn } from \"node:child_process\";\nimport { Command } from \"commander\";\nimport {\n antiPatternGateParams,\n findProjectRoot,\n loadConfig,\n resolveHaivePaths,\n} from \"@hivelore/core\";\nimport { preCommitCheck } from \"@hivelore/mcp\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface PrecommitOptions {\n blockOn?: \"any\" | \"high-confidence\" | \"never\";\n noSemantic?: boolean;\n anchoredBlocks?: boolean;\n json?: boolean;\n dir?: string;\n paths?: string[];\n}\n\nexport function registerPrecommit(program: Command): void {\n program\n .command(\"precommit\")\n .description(\n \"Run a pre-commit safety check (manual variant of `hivelore enforce check --stage pre-commit`):\\n\" +\n \" scans `git diff --cached` against known anti-patterns,\\n\" +\n \" surfaces conventions/decisions anchored to touched files, and warns about stale anchored memories.\\n\\n\" +\n \" Wire it into git as: `.git/hooks/pre-commit` running `hivelore precommit` (exit 1 = block).\\n\\n\" +\n \" Examples:\\n\" +\n \" hivelore precommit # auto-detects staged diff\\n\" +\n \" hivelore precommit --block-on any # block on any warning, not just high-confidence\\n\" +\n \" hivelore precommit --paths src/auth.ts src/db.ts # explicit paths instead of git diff\",\n )\n .option(\n \"--block-on <mode>\",\n \"'any' | 'high-confidence' | 'never' (report only). Default: derived from enforcement.antiPatternGate.\",\n )\n .option(\"--no-semantic\", \"disable semantic search in anti-patterns matching\")\n .option(\n \"--no-anchored-blocks\",\n \"do not block on anchored, diff-corroborated anti-patterns (only block on very strong semantic matches)\",\n )\n .option(\"--json\", \"emit JSON instead of human-readable output\", false)\n .option(\"--paths <paths...>\", \"explicit paths to check (skips git diff)\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: PrecommitOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n const ctx = { paths };\n\n // Derive the gate behavior from project config so this command matches the\n // installed git hook (`hivelore enforce check`). Explicit flags still override:\n // --block-on <mode> overrides the gate's block_on\n // --no-anchored-blocks forces anchored_blocks off (the only explicit opt-out)\n const config = await loadConfig(paths);\n const gate = config.enforcement?.antiPatternGate ?? \"anchored\";\n const gateParams = antiPatternGateParams(gate);\n const blockOn = opts.blockOn ?? gateParams.block_on;\n const anchoredBlocks = opts.anchoredBlocks === false ? false : gateParams.anchored_blocks;\n\n let diff = \"\";\n let touchedPaths: string[] = opts.paths ?? [];\n\n if (touchedPaths.length === 0) {\n // Auto-detect from git\n try {\n diff = await runCommand(\"git\", [\"diff\", \"--cached\"], root);\n if (!diff.trim()) {\n if (opts.json) {\n console.log(JSON.stringify({\n should_block: false,\n summary: {\n anti_patterns: 0,\n blocking_warnings: 0,\n review_warnings: 0,\n info_warnings: 0,\n relevant_memories: 0,\n stale_anchors: 0,\n },\n warnings: [],\n relevant_memories: [],\n stale_anchors: [],\n notice: \"No staged changes — nothing to check.\",\n }, null, 2));\n return;\n }\n ui.warn(\"No staged changes — nothing to check. Stage with `git add` first.\");\n return;\n }\n const nameOnly = await runCommand(\"git\", [\"diff\", \"--cached\", \"--name-only\"], root);\n touchedPaths = nameOnly.split(\"\\n\").map((s) => s.trim()).filter(Boolean);\n } catch (err) {\n ui.error(`git diff failed: ${err instanceof Error ? err.message : String(err)}`);\n process.exit(1);\n }\n }\n\n const result = await preCommitCheck({\n diff: diff || undefined,\n paths: touchedPaths,\n block_on: blockOn,\n anchored_blocks: anchoredBlocks,\n semantic: opts.noSemantic ? false : true,\n }, ctx);\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n process.exit(result.should_block ? 1 : 0);\n }\n\n console.log(ui.bold(`Hivelore precommit — ${touchedPaths.length} file(s)`));\n console.log(\n ui.dim(\n ` anti-patterns: ${result.summary.anti_patterns} ` +\n `blocking: ${result.summary.blocking_warnings ?? result.summary.anti_patterns} ` +\n `review: ${result.summary.review_warnings ?? 0} ` +\n `info: ${result.summary.info_warnings ?? 0} ` +\n `relevant memories: ${result.summary.relevant_memories} ` +\n `stale anchors: ${result.summary.stale_anchors}`,\n ),\n );\n console.log();\n\n const blocking = result.warnings.filter((w) => w.level === \"blocking\");\n const review = result.warnings.filter((w) => w.level === \"review\");\n const info = result.warnings.filter((w) => w.level === \"info\");\n\n printWarnings(\"Blocking anti-patterns\", blocking, \"error\");\n printWarnings(\"Review anti-patterns\", review.slice(0, 8), \"warn\");\n if (info.length > 0) {\n console.log(\n ui.dim(\n `${info.length} weak anti-pattern signal${info.length === 1 ? \"\" : \"s\"} hidden. ` +\n \"Use --json to inspect FYI matches.\",\n ),\n );\n console.log();\n }\n\n if (result.relevant_memories.length > 0) {\n console.log(ui.bold(\"📌 Relevant conventions/decisions:\"));\n for (const m of result.relevant_memories) {\n console.log(` • ${m.id} ${ui.dim(`(${m.type}, ${m.confidence})`)}`);\n }\n console.log();\n }\n\n if (result.stale_anchors.length > 0) {\n console.log(ui.bold(\"🕒 Stale anchored memories:\"));\n for (const s of result.stale_anchors) {\n console.log(` • ${s.id}`);\n if (s.body_preview) console.log(` ${ui.dim(s.body_preview)}`);\n }\n console.log();\n }\n\n if (result.should_block) {\n ui.error(`Blocking commit (gate=${gate}, block_on=${blockOn}). Address the warnings above or pass --block-on never to bypass.`);\n process.exit(1);\n }\n\n if (result.warnings.length === 0 && result.stale_anchors.length === 0) {\n ui.success(\"No anti-patterns or stale anchors found.\");\n } else {\n ui.success(\"Check passed (block_on threshold not met).\");\n }\n });\n}\n\nfunction printWarnings(\n title: string,\n warnings: Array<{\n id: string;\n type: string;\n confidence: string;\n body_preview: string;\n reasons: string[];\n rationale?: string;\n affected_files?: string[];\n repair_command?: string;\n }>,\n tone: \"error\" | \"warn\",\n): void {\n if (warnings.length === 0) return;\n console.log(ui.bold(tone === \"error\" ? `✗ ${title}:` : `⚠ ${title}:`));\n for (const w of warnings) {\n const marker = tone === \"error\" ? ui.red(\"✗\") : ui.yellow(\"⚠\");\n console.log(` ${marker} ${w.id} ${ui.dim(`(${w.type}, ${w.confidence})`)}`);\n for (const line of w.body_preview.split(\"\\n\").slice(0, 3)) {\n console.log(` ${ui.dim(line)}`);\n }\n console.log(` ${ui.dim(\"reasons:\")} ${w.reasons.join(\", \")}`);\n if (w.affected_files && w.affected_files.length > 0) {\n console.log(` ${ui.dim(\"files:\")} ${w.affected_files.slice(0, 4).join(\", \")}`);\n }\n if (w.rationale) console.log(` ${ui.dim(\"why shown:\")} ${w.rationale}`);\n if (w.repair_command) console.log(` ${ui.dim(\"repair:\")} ${w.repair_command}`);\n }\n console.log();\n}\n\nfunction runCommand(cmd: string, args: string[], cwd: string): Promise<string> {\n return new Promise((resolve, reject) => {\n const proc = spawn(cmd, args, { cwd, stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n let stdout = \"\";\n let stderr = \"\";\n proc.stdout.on(\"data\", (chunk) => { stdout += chunk.toString(); });\n proc.stderr.on(\"data\", (chunk) => { stderr += chunk.toString(); });\n proc.on(\"error\", reject);\n proc.on(\"close\", (code) => {\n if (code === 0) resolve(stdout);\n else reject(new Error(stderr || `${cmd} exited with code ${code}`));\n });\n });\n}\n","/**\n * Curated onboarding: print high-signal team memories in read order — no MCP required.\n * Also prints a corpus-summary block so returning devs can see the current harness state at a glance.\n */\nimport { existsSync } from \"node:fs\";\nimport { Command } from \"commander\";\nimport {\n findProjectRoot,\n loadMemoriesFromDir,\n resolveHaivePaths,\n} from \"@hivelore/core\";\nimport { ui } from \"../utils/ui.js\";\n\nconst TYPE_RANK: Record<string, number> = {\n skill: 0,\n decision: 1,\n architecture: 2,\n convention: 3,\n glossary: 4,\n gotcha: 5,\n attempt: 6,\n};\n\ninterface WelcomeOpts {\n limit?: string;\n dir?: string;\n}\n\nexport function registerWelcome(program: Command): void {\n program\n .command(\"welcome\")\n .description(\n \"Onboarding checklist: ranks validated/proposed **team** memories by type.\\n\" +\n \"Use after `hivelore init` so new devs skim institutional knowledge quickly.\\n\\n\" +\n \" hivelore welcome\\n\" +\n \" hivelore welcome --limit 15\\n\",\n )\n .option(\"--limit <n>\", \"maximum memories listed\", \"20\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: WelcomeOpts) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.memoriesDir)) {\n ui.error(`No memories at ${paths.memoriesDir}. Run 'hivelore init' first.`);\n process.exitCode = 1;\n return;\n }\n\n const all = await loadMemoriesFromDir(paths.memoriesDir);\n const team = all.filter(\n ({ memory }) =>\n memory.frontmatter.scope === \"team\" &&\n memory.frontmatter.status !== \"rejected\" &&\n memory.frontmatter.status !== \"deprecated\" &&\n memory.frontmatter.status !== \"stale\" &&\n memory.frontmatter.type !== \"session_recap\",\n );\n\n team.sort((a, b) => {\n const ta = TYPE_RANK[a.memory.frontmatter.type] ?? 99;\n const tb = TYPE_RANK[b.memory.frontmatter.type] ?? 99;\n if (ta !== tb) return ta - tb;\n const sta = a.memory.frontmatter.status === \"validated\" ? 0 : 1;\n const stb = b.memory.frontmatter.status === \"validated\" ? 0 : 1;\n if (sta !== stb) return sta - stb;\n return b.memory.frontmatter.created_at.localeCompare(a.memory.frontmatter.created_at);\n });\n\n const cap = Math.max(1, Math.min(500, Number(opts.limit) || 20));\n const pick = team.slice(0, cap);\n\n // ── Corpus summary ───────────────────────────────────────────────────\n const totalAll = all.length;\n const validated = all.filter(({ memory }) => memory.frontmatter.status === \"validated\").length;\n const withSensor = all.filter(({ memory }) => memory.frontmatter.sensor != null).length;\n const drafts = all.filter(({ memory }) => memory.frontmatter.status === \"draft\").length;\n const proposed = all.filter(({ memory }) => memory.frontmatter.status === \"proposed\").length;\n\n const summaryLines: string[] = [\n ` Corpus : ${totalAll} memories (${validated} validated, ${drafts + proposed} pending review)`,\n ` Sensors : ${withSensor} active`,\n ];\n const summaryWidth = Math.max(...summaryLines.map((l) => l.length), 44);\n const bar = \"─\".repeat(summaryWidth + 2);\n console.log(ui.bold(`┌${bar}┐`));\n console.log(ui.bold(`│`) + ` Hivelore corpus`.padEnd(summaryWidth + 1) + ui.bold(`│`));\n console.log(ui.bold(`├${bar}┤`));\n for (const line of summaryLines) {\n console.log(ui.bold(`│`) + line.padEnd(summaryWidth + 2) + ui.bold(`│`));\n }\n console.log(ui.bold(`└${bar}┘`));\n console.log();\n // ────────────────────────────────────────────────────────────────────\n\n console.log(ui.bold(`Hivelore welcome — ${pick.length} team memories (${root})`));\n console.log(ui.dim(`Next: invoke get_briefing with your task or run 'hivelore briefing --task \"…\"'`));\n\n if (pick.length === 0) {\n ui.warn(\"No team memories yet — add some with 'hivelore memory save' or promote personal ones.\");\n return;\n }\n\n let i = 1;\n for (const { memory } of pick) {\n const fm = memory.frontmatter;\n const head = memory.body.match(/^#\\s+(.+)/m)?.[1]?.trim();\n const line = head ?? fm.id;\n console.log(\n `${String(i).padStart(2, \" \")} ${fm.type.padEnd(12)} ${fm.status.padEnd(10)} ${ui.dim(fm.id)}\\n ${line}`,\n );\n i++;\n }\n });\n}\n","import { Command } from \"commander\";\nimport { MemoryTypeSchema, suggestTopicKey } from \"@hivelore/core\";\nimport { ui } from \"../utils/ui.js\";\n\nexport function registerMemorySuggestTopic(memory: Command): void {\n memory\n .command(\"suggest-topic\")\n .description(\"Suggest a stable topic key (topic-upsert) from type + title phrase\")\n .requiredOption(\n \"--type <type>\",\n \"convention | decision | gotcha | architecture | glossary | attempt | session_recap\",\n )\n .argument(\"<title>\", \"Short title or phrase to slugify\")\n .action((title: string, opts: { type: string }) => {\n const parsed = MemoryTypeSchema.safeParse(opts.type);\n if (!parsed.success) {\n ui.error(`Invalid type: ${opts.type}`);\n process.exit(1);\n }\n const suggestion = suggestTopicKey(parsed.data, title);\n console.log(JSON.stringify({ type: parsed.data, ...suggestion }, null, 2));\n });\n}\n","import path from \"node:path\";\nimport { Command } from \"commander\";\nimport { resolveProjectInfo } from \"@hivelore/core\";\n\nexport function registerResolveProject(program: Command): void {\n program\n .command(\"resolve-project\")\n .description(\n \"Print JSON for Hivelore project root resolution (HAIVE_PROJECT_ROOT, markers, .ai layout).\",\n )\n .option(\"-d, --dir <dir>\", \"working directory\", process.cwd())\n .action((opts: { dir: string }) => {\n const info = resolveProjectInfo({ cwd: path.resolve(opts.dir) });\n console.log(JSON.stringify({ ok: true, info }, null, 2));\n });\n}\n","import { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n appendRuntimeJournalEntry,\n findProjectRoot,\n readRuntimeJournalTail,\n resolveHaivePaths,\n type RuntimeJournalEntry,\n} from \"@hivelore/core\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface JournalAppendOpts {\n kind: string;\n dir?: string;\n}\n\nexport function registerRuntime(program: Command): void {\n const runtime = program\n .command(\"runtime\")\n .description(\n \"Local-only .ai/.runtime helpers (not versioned team memory). See session-journal.ndjson.\",\n );\n\n const journal = runtime\n .command(\"journal\")\n .description(\"Append or read the machine-local session journal (NDJSON)\");\n\n journal\n .command(\"append\")\n .description(\"Append one JSON line to .ai/.runtime/session-journal.ndjson\")\n .argument(\"<message>\", \"short text to log\")\n .option(\"-k, --kind <kind>\", \"note | session_end | mcp\", \"note\")\n .option(\"-d, --dir <dir>\", \"project root\", process.cwd())\n .action(async (message: string, opts: JournalAppendOpts) => {\n const root = path.resolve(opts.dir ?? process.cwd());\n const paths = resolveHaivePaths(findProjectRoot(root));\n const raw = opts.kind ?? \"note\";\n const kind = ([\"note\", \"session_end\", \"mcp\"].includes(raw)\n ? raw\n : \"note\") as RuntimeJournalEntry[\"kind\"];\n await appendRuntimeJournalEntry(paths, { kind, message });\n ui.success(`Appended to ${path.relative(root, paths.runtimeDir)}/session-journal.ndjson`);\n });\n\n journal\n .command(\"tail\")\n .description(\"Print the last N entries from the runtime session journal as JSON\")\n .option(\"-n, --limit <n>\", \"number of lines\", \"30\")\n .option(\"-d, --dir <dir>\", \"project root\", process.cwd())\n .action(async (opts: { limit: string; dir?: string }) => {\n const root = path.resolve(opts.dir ?? process.cwd());\n const paths = resolveHaivePaths(findProjectRoot(root));\n const limit = Math.min(500, Math.max(1, parseInt(opts.limit, 10) || 30));\n if (!existsSync(paths.haiveDir)) {\n ui.error(\"No .ai/ — run `hivelore init` first.\");\n process.exitCode = 1;\n return;\n }\n const entries = await readRuntimeJournalTail(paths, limit);\n if (entries.length === 0) {\n ui.info(\"Journal empty or missing.\");\n return;\n }\n console.log(JSON.stringify({ entries, count: entries.length }, null, 2));\n });\n}\n","import { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n collectTimelineEntries,\n findProjectRoot,\n resolveHaivePaths,\n} from \"@hivelore/core\";\nimport { loadMemoriesFromDir } from \"../utils/fs.js\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface TimelineOpts {\n id?: string;\n topic?: string;\n limit: string;\n dir?: string;\n}\n\nexport function registerMemoryTimeline(memory: Command): void {\n memory\n .command(\"timeline\")\n .description(\n \"List related memories chronologically (topic, related_ids, anchors) — same logic as MCP mem_timeline.\",\n )\n .option(\"--id <id>\", \"seed memory id\")\n .option(\"--topic <key>\", \"filter by frontmatter.topic (use without --id for topic-only)\")\n .option(\"-n, --limit <n>\", \"max entries\", \"30\")\n .option(\"-d, --dir <dir>\", \"project root\", process.cwd())\n .action(async (opts: TimelineOpts) => {\n if (!opts.id && !opts.topic) {\n ui.error(\"Provide --id and/or --topic.\");\n process.exitCode = 1;\n return;\n }\n const root = path.resolve(opts.dir ?? process.cwd());\n const paths = resolveHaivePaths(findProjectRoot(root));\n if (!existsSync(paths.memoriesDir)) {\n ui.error(\"No memories — run `hivelore init`.\");\n process.exitCode = 1;\n return;\n }\n const limit = Math.min(100, Math.max(1, parseInt(opts.limit, 10) || 30));\n const all = await loadMemoriesFromDir(paths.memoriesDir);\n const { entries, notice } = collectTimelineEntries(all, {\n memoryId: opts.id,\n topic: opts.topic,\n limit,\n });\n if (notice) ui.warn(notice);\n console.log(JSON.stringify({ entries, total: entries.length }, null, 2));\n });\n}\n","import { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n findLexicalConflictPairs,\n findTopicStatusConflictPairs,\n findProjectRoot,\n resolveHaivePaths,\n} from \"@hivelore/core\";\nimport { loadMemoriesFromDir } from \"../utils/fs.js\";\nimport { ui } from \"../utils/ui.js\";\n\ntype MemType = \"decision\" | \"architecture\" | \"convention\" | \"gotcha\";\n\ninterface CandOpts {\n sinceDays: string;\n types: string;\n minJaccard: string;\n maxPairs: string;\n maxScan: string;\n maxTopicPairs: string;\n dir?: string;\n}\n\nfunction parseTypes(csv: string): MemType[] {\n const allowed: MemType[] = [\"decision\", \"architecture\", \"convention\", \"gotcha\"];\n const parts = csv.split(\",\").map((s) => s.trim().toLowerCase());\n const out = parts.filter((p): p is MemType => allowed.includes(p as MemType));\n return out.length ? out : [\"decision\", \"architecture\"];\n}\n\nexport function registerMemoryConflictCandidates(memory: Command): void {\n memory\n .command(\"conflict-candidates\")\n .description(\n \"Heuristic conflict candidates (lexical Jaccard + same-topic validated/rejected pairs) — aligns with MCP mem_conflict_candidates.\",\n )\n .option(\"-d, --dir <dir>\", \"project root\", process.cwd())\n .option(\"--since-days <n>\", \"only memories created within N days (lexical scan)\", \"365\")\n .option(\n \"--types <csv>\",\n \"decision,architecture,convention,gotcha (lexical scan)\",\n \"decision,architecture\",\n )\n .option(\"--min-jaccard <x>\", \"minimum Jaccard for lexical pairs\", \"0.45\")\n .option(\"--max-pairs <n>\", \"cap lexical pairs\", \"20\")\n .option(\"--max-scan <n>\", \"max memories scanned (lexical)\", \"500\")\n .option(\"--max-topic-pairs <n>\", \"cap topic/status pairs\", \"20\")\n .action(async (opts: CandOpts) => {\n const root = path.resolve(opts.dir ?? process.cwd());\n const paths = resolveHaivePaths(findProjectRoot(root));\n if (!existsSync(paths.memoriesDir)) {\n ui.error(\"No memories — run `hivelore init`.\");\n process.exitCode = 1;\n return;\n }\n\n const sinceDays = Math.max(1, parseInt(opts.sinceDays, 10) || 365);\n const minJaccard = parseFloat(opts.minJaccard) || 0.45;\n const maxPairs = Math.min(100, Math.max(1, parseInt(opts.maxPairs, 10) || 20));\n const maxScan = Math.min(2000, Math.max(1, parseInt(opts.maxScan, 10) || 500));\n const maxTopicPairs = Math.min(100, Math.max(1, parseInt(opts.maxTopicPairs, 10) || 20));\n\n const all = await loadMemoriesFromDir(paths.memoriesDir);\n const lexical = findLexicalConflictPairs(all, {\n sinceDays,\n types: parseTypes(opts.types),\n minJaccard,\n maxPairs,\n maxScan,\n });\n const topicStatusPairs = findTopicStatusConflictPairs(all, maxTopicPairs);\n\n console.log(\n JSON.stringify(\n {\n pairs: lexical.pairs,\n topic_status_pairs: topicStatusPairs,\n scanned: lexical.scanned,\n truncated: lexical.truncated,\n },\n null,\n 2,\n ),\n );\n });\n}\n","import { execFile, execFileSync, spawn } from \"node:child_process\";\nimport { existsSync, statSync } from \"node:fs\";\nimport { chmod, mkdir, readFile, readdir, rm, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { Command } from \"commander\";\nimport {\n antiPatternGateParams,\n assessBootstrapState,\n isSensorScannablePath,\n findProjectRoot,\n loadCodeMap,\n renderBootstrapChecklist,\n findUncapturedFailures,\n handoffAgeMs,\n hasRecentBriefingMarker,\n isFreshIsoDate,\n isRetiredMemory,\n loadConfig,\n loadMemoriesFromDir,\n memoryMatchesAnchorPaths,\n readRecentBriefingMarker,\n recordPreventionHits,\n resolveBriefingBudget,\n resolveHaivePaths,\n runSensors,\n saveConfig,\n selectCommandSensors,\n sensorTargetsFromDiff,\n SESSION_RECAP_TTL_MS,\n verifyAnchor,\n writeBriefingMarker,\n type AntiPatternGate,\n type CommandSensorSpec,\n type LoadedMemory,\n type HaiveConfig,\n} from \"@hivelore/core\";\nimport { getBriefing, preCommitCheck } from \"@hivelore/mcp\";\nimport { ui } from \"../utils/ui.js\";\nimport { installClaudeHooksAtPath, defaultClaudeSettingsPath } from \"../utils/claude-hooks.js\";\nimport { applyAutopilotRepairs } from \"../utils/autopilot.js\";\n\ndeclare const __HAIVE_VERSION__: string;\n\nconst execFileAsync = promisify(execFile);\n\nconst MAX_STDIN_BYTES = 256 * 1024;\nconst ENFORCE_HOOK_MARKER = \"# Hivelore enforcement hook\";\n\ninterface HookPayload {\n cwd?: string;\n session_id?: string;\n prompt?: string;\n tool_name?: string;\n tool_input?: Record<string, unknown>;\n}\n\ninterface EnforceOptions {\n dir?: string;\n task?: string;\n source?: string;\n sessionId?: string;\n json?: boolean;\n stage?: \"local\" | \"pre-commit\" | \"pre-push\" | \"ci\";\n strict?: boolean;\n claude?: boolean;\n git?: boolean;\n ci?: boolean;\n explain?: boolean;\n}\n\ninterface FinishOptions {\n dir?: string;\n json?: boolean;\n explain?: boolean;\n}\n\ninterface EnforcementFinding {\n severity: \"ok\" | \"info\" | \"warn\" | \"error\";\n code: string;\n message: string;\n fix?: string;\n impact?: number;\n reason?: string;\n affected_files?: string[];\n memory_ids?: string[];\n}\n\ninterface EnforcementScore {\n score: number;\n threshold: number;\n checks: {\n total: number;\n ok: number;\n warn: number;\n error: number;\n };\n}\n\ninterface EnforcementReport {\n root: string;\n initialized: boolean;\n mode: \"off\" | \"advisory\" | \"strict\";\n score: EnforcementScore;\n should_block: boolean;\n findings: EnforcementFinding[];\n categories: {\n blocking: EnforcementFinding[];\n review: EnforcementFinding[];\n info: EnforcementFinding[];\n };\n}\n\nexport function registerEnforce(program: Command): void {\n const enforce = program\n .command(\"enforce\")\n .description(\n \"Agent-agnostic enforcement helpers: install policy gates, report status, and block unsafe workflows.\",\n );\n\n enforce\n .command(\"install\")\n .description(\"Install Hivelore enforcement across MCP config, git hooks, CI template, and supported client hooks.\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .option(\"--no-git\", \"skip git pre-commit/pre-push enforcement hooks\")\n .option(\"--no-claude\", \"skip Claude Code hooks\")\n .option(\"--no-ci\", \"skip GitHub Actions enforcement workflow\")\n .action(async (opts: EnforceOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n await mkdir(paths.haiveDir, { recursive: true });\n const current = await loadConfig(paths);\n await saveConfig(paths, {\n ...current,\n enforcement: {\n ...current.enforcement,\n mode: \"strict\",\n requireBriefingFirst: true,\n requireSessionRecap: true,\n requireMemoryVerify: true,\n blockStaleDecisionChanges: true,\n requireDecisionCoverage: true,\n scoreThreshold: 85,\n cleanupGeneratedArtifacts: true,\n toolProfile: \"enforcement\",\n policyPacks: [\"architecture\", \"gotchas\", \"security\", \"domain\", \"release\"],\n },\n });\n ui.success(\"Hivelore strict enforcement enabled in .ai/haive.config.json\");\n\n if (opts.git !== false) await installGitEnforcement(root);\n if (opts.ci !== false) await installCiEnforcement(root);\n if (opts.claude !== false) {\n try {\n const result = await installClaudeHooksAtPath(defaultClaudeSettingsPath(\"project\", root));\n ui.success(`${result.created ? \"Created\" : \"Patched\"} Claude Code hooks (${path.relative(root, result.settingsPath)})`);\n } catch (err) {\n ui.warn(`Claude Code hooks not installed: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n\n ui.info(\"Agent-agnostic gates are now active at workflow level: MCP, git, CI, and optional client hooks.\");\n ui.info(\"Use `hivelore run -- <agent command>` for agents that do not expose blocking hooks.\");\n });\n\n enforce\n .command(\"status\")\n .description(\"Show whether this project has agent-agnostic Hivelore enforcement installed.\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .option(\"--explain\", \"group findings by blocking/review/info and show repair commands\", false)\n .option(\"--json\", \"emit JSON\", false)\n .action(async (opts: EnforceOptions) => {\n const report = await buildEnforcementReport(opts.dir, \"local\");\n printReport(report, Boolean(opts.json), Boolean(opts.explain));\n if (report.should_block) process.exitCode = 1;\n });\n\n enforce\n .command(\"check\")\n .description(\"Run the Hivelore policy gate. Intended for pre-commit, pre-push, wrappers, and any agent client.\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .option(\"--stage <stage>\", \"local | pre-commit | pre-push | ci\", \"local\")\n .option(\"--explain\", \"group findings by blocking/review/info and show repair commands\", false)\n .option(\"--json\", \"emit JSON\", false)\n .action(async (opts: EnforceOptions) => {\n const report = await buildEnforcementReport(opts.dir, opts.stage ?? \"local\");\n printReport(report, Boolean(opts.json), Boolean(opts.explain));\n if (report.should_block) process.exit(2);\n });\n\n enforce\n .command(\"cleanup\")\n .description(\"Remove generated Hivelore runtime/cache artifacts that should not appear in commits.\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .option(\"--dry-run\", \"print what would be removed without deleting\", false)\n .action(async (opts: EnforceOptions & { dryRun?: boolean }) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n const cacheDir = path.join(paths.haiveDir, \".cache\");\n if (existsSync(cacheDir)) {\n if (opts.dryRun) ui.info(`would clean ${path.relative(root, cacheDir)} (preserving .gitignore)`);\n else {\n const removed = await cleanupCacheDir(cacheDir);\n ui.success(`cleaned ${path.relative(root, cacheDir)}${removed > 0 ? ` (${removed} item${removed === 1 ? \"\" : \"s\"} removed)` : \"\"}`);\n }\n }\n if (existsSync(paths.runtimeDir)) {\n if (opts.dryRun) ui.info(`would clean ${path.relative(root, paths.runtimeDir)} (preserving briefing markers)`);\n else {\n const removed = await cleanupRuntimeDir(paths.runtimeDir);\n ui.success(`cleaned ${path.relative(root, paths.runtimeDir)}${removed > 0 ? ` (${removed} item${removed === 1 ? \"\" : \"s\"} removed)` : \"\"}`);\n }\n }\n });\n\n enforce\n .command(\"ci\")\n .description(\"CI entrypoint: fail if the repository violates Hivelore enforcement policy.\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .option(\"--explain\", \"group findings by blocking/review/info and show repair commands\", false)\n .option(\"--json\", \"emit JSON\", false)\n .action(async (opts: EnforceOptions) => {\n const report = await buildEnforcementReport(opts.dir, \"ci\");\n printReport(report, Boolean(opts.json), Boolean(opts.explain));\n if (report.should_block) process.exit(2);\n });\n\n enforce\n .command(\"finish\")\n .alias(\"completion\")\n .description(\n \"Final agent-exit gate: verify the git sync/release protocol before reporting a task done.\",\n )\n .option(\"-d, --dir <dir>\", \"project root\")\n .option(\"--explain\", \"group findings by blocking/review/info and show repair commands\", false)\n .option(\"--json\", \"emit JSON\", false)\n .action(async (opts: FinishOptions) => {\n const report = await buildFinishReport(opts.dir);\n printReport(report, Boolean(opts.json), Boolean(opts.explain));\n if (report.should_block) {\n if (!opts.json) printNextRequiredAction(report);\n process.exit(2);\n }\n });\n\n enforce\n .command(\"commit-msg <msgfile>\")\n .description(\n \"git commit-msg hook: block a CI-skip directive in a commit that also changes shippable code \" +\n \"(GitHub scans the whole message and would skip CI for the entire push). `.ai/`-only sync commits are allowed.\",\n )\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (msgfile: string, opts: EnforceOptions) => {\n const root = findProjectRoot(opts.dir);\n const verdict = await checkCommitMessageSkipCi(root, msgfile);\n if (verdict.block) {\n ui.error(verdict.message);\n process.exit(1);\n }\n });\n\n enforce\n .command(\"session-start\")\n .description(\"Claude Code SessionStart hook: inject briefing and write a local briefing marker.\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .option(\"--task <text>\", \"task text to rank memories\")\n .option(\"--source <name>\", \"marker source\", \"claude-session-start\")\n .option(\"--session-id <id>\", \"agent session id\")\n .action(async (opts: EnforceOptions) => {\n const payload = await readHookPayload();\n const root = resolveRoot(opts.dir, payload);\n if (!root) return;\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.haiveDir)) return;\n await mkdir(paths.runtimeDir, { recursive: true });\n const sessionId = opts.sessionId ?? payload.session_id;\n const task = opts.task ?? payload.prompt ?? \"Start an AI coding session in this Hivelore-initialized project.\";\n await applyLightweightRepairs(root, paths);\n\n const budget = resolveBriefingBudget(\"quick\", {\n max_tokens: 2500,\n max_memories: 5,\n include_module_contexts: false,\n });\n const briefing = await getBriefing(\n {\n task,\n files: [],\n max_tokens: budget.max_tokens,\n max_memories: budget.max_memories,\n include_project_context: true,\n include_module_contexts: budget.include_module_contexts,\n semantic: true,\n include_stale: false,\n track: true,\n format: \"actions\",\n symbols: [],\n min_semantic_score: 0.25,\n budget_preset: \"quick\",\n },\n { paths },\n );\n await writeBriefingMarker(paths, {\n sessionId,\n task,\n source: opts.source ?? \"claude-session-start\",\n memoryIds: briefing.memories.map((m) => m.id),\n });\n\n console.log(\"Hivelore briefing loaded. Agents must consult this before editing.\");\n if (briefing.last_session) {\n console.log(`\\n## Last session\\n${briefing.last_session.body.slice(0, 1200)}`);\n }\n if (briefing.project_context?.content) {\n console.log(`\\n## Project context\\n${briefing.project_context.content.slice(0, 1800)}`);\n }\n if (briefing.memories.length > 0) {\n console.log(\"\\n## Relevant memories\");\n for (const memory of briefing.memories.slice(0, 6)) {\n console.log(`\\n### ${memory.id} (${memory.scope}/${memory.type}, ${memory.confidence})`);\n console.log(memory.body.slice(0, 1000));\n }\n }\n for (const warning of briefing.setup_warnings) {\n console.log(`\\n[setup warning] ${warning}`);\n }\n });\n\n enforce\n .command(\"pre-tool-use\")\n .description(\"Claude Code PreToolUse hook: surface the relevant team policy for the edited file (advise; configurable to block).\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: EnforceOptions) => {\n const payload = await readHookPayload();\n const root = resolveRoot(opts.dir, payload);\n if (!root) return;\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.haiveDir)) return;\n if (!isWriteLikeTool(payload)) return;\n\n const config = await loadConfig(paths);\n if (config.enforcement?.requireBriefingFirst === false) return;\n const gate = config.enforcement?.preEditGate ?? \"advise\";\n\n const targetFiles = extractToolPaths(payload, root);\n const hasMarker = await hasRecentBriefingMarker(paths, payload.session_id);\n const missing = targetFiles.length > 0\n ? await missingRequiredMemoriesForFiles(paths, targetFiles, payload.session_id)\n : [];\n\n // Clean pass: a recent briefing exists and the touched files carry no un-surfaced policy.\n if (hasMarker && missing.length === 0) return;\n\n // Auto-resolve: record the relevant policy for the touched files into the briefing marker so\n // the agent gets credit for it AND the commit-time decision-coverage gate accumulates coverage\n // as the agent edits — no separate `hivelore briefing` command needed.\n if (targetFiles.length > 0) {\n await recordFilesIntoBriefingMarker(paths, targetFiles, missing, payload.session_id)\n .catch(() => { /* best-effort */ });\n }\n\n const contextText = buildPreEditContext(payload.tool_name ?? \"write tool\", targetFiles, missing, hasMarker);\n\n if (gate === \"block\") {\n // Legacy strict behaviour: block — but with the actual content and no separate command.\n // The relevant policy is already recorded, so simply re-issuing the edit passes.\n console.error(\n contextText +\n \"\\n\\nThe relevant context is now recorded — re-issue the same edit to proceed \" +\n \"(no `hivelore briefing` command needed). To make this advisory instead of blocking, set \" +\n '`{ \"enforcement\": { \"preEditGate\": \"advise\" } }` in .ai/haive.config.json.',\n );\n process.exit(2);\n }\n\n // advise (default): inject the context into the agent and ALLOW the edit — zero round-trip.\n // Commit-time decision-coverage + CI enforcement remain the hard backstops.\n emitPreToolUseContext(contextText);\n });\n}\n\n/**\n * Record the validated policy memories anchored to the touched files into the briefing marker,\n * unioned with whatever is already there. Mirrors what `hivelore briefing --files` records, so the\n * commit-time decision-coverage gate accumulates coverage as the agent edits (no broad re-briefing).\n */\nasync function recordFilesIntoBriefingMarker(\n paths: ReturnType<typeof resolveHaivePaths>,\n files: string[],\n missing: LoadedMemory[],\n sessionId?: string,\n): Promise<void> {\n const existing = await readRecentBriefingMarker(paths, sessionId);\n const ids = new Set<string>(existing?.memory_ids ?? []);\n for (const { memory } of missing) ids.add(memory.frontmatter.id);\n await writeBriefingMarker(paths, {\n sessionId,\n task: existing?.task ?? \"pre-edit auto-briefing\",\n source: \"haive-pre-edit\",\n files,\n memoryIds: [...ids],\n });\n}\n\n/** Build the context block surfaced to the agent at edit time (the actual memory bodies). */\nfunction buildPreEditContext(\n tool: string,\n files: string[],\n missing: LoadedMemory[],\n hasMarker: boolean,\n): string {\n const lines: string[] = [\"Hivelore — relevant team policy for this edit\", `Tool: ${tool}`];\n if (files.length > 0) lines.push(`Files: ${files.slice(0, 6).join(\", \")}`);\n if (missing.length > 0) {\n lines.push(\"\", \"Consult these before editing (anchored to the files you are touching):\");\n for (const { memory } of missing.slice(0, 5)) {\n const fm = memory.frontmatter;\n lines.push(\"\", `### ${fm.id} (${fm.scope}/${fm.type})`, memory.body.trim().slice(0, 900));\n }\n } else if (!hasMarker) {\n lines.push(\n \"\",\n \"No team briefing was loaded yet this session. Proceeding — but for substantive work call \" +\n \"get_briefing / mem_relevant_to for richer context.\",\n );\n }\n return lines.join(\"\\n\");\n}\n\n/** Emit a Claude Code PreToolUse hook result that injects context for the model WITHOUT blocking. */\nfunction emitPreToolUseContext(text: string): void {\n console.log(\n JSON.stringify({\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n additionalContext: text,\n },\n }),\n );\n}\n\nasync function buildFinishReport(dir: string | undefined): Promise<EnforcementReport> {\n const root = findProjectRoot(dir);\n const paths = resolveHaivePaths(root);\n const initialized = existsSync(paths.haiveDir);\n const config = initialized ? await loadConfig(paths) : {};\n const mode = config.enforcement?.mode ?? \"strict\";\n const findings: EnforcementFinding[] = [];\n\n if (!initialized) {\n return withCategories({\n root,\n initialized,\n mode,\n score: buildScore([], config.enforcement?.scoreThreshold),\n should_block: true,\n findings: [{\n severity: \"error\",\n code: \"not-initialized\",\n message: \"This repository is not initialized with Hivelore.\",\n fix: \"Run `hivelore init` or `hivelore enforce install`.\",\n impact: 100,\n }],\n });\n }\n\n findings.push(...await checkFailureCapture(paths, config));\n // First-agent bootstrap: declaring the task done with a still-cold knowledge layer means the first\n // agent never paid the baseline that later agents depend on. Evaluated as \"code present\" (true) so a\n // codebase blocks; the assessment returns ready on its own for repos with no code areas.\n findings.push(...await checkBootstrapComplete(paths, config, true));\n\n const status = await getGitSyncStatus(root);\n if (!status.available) {\n findings.push({\n severity: \"error\",\n code: \"git-unavailable\",\n message: \"Git status could not be inspected, so Hivelore cannot verify the exit protocol.\",\n fix: \"Run `git status` manually, then commit/push according to the Hivelore git-sync protocol.\",\n impact: 100,\n });\n return finishReport(root, initialized, mode, findings, config);\n }\n\n const shippableDirty = status.dirtyFiles.filter(isShippablePath);\n if (status.dirtyFiles.length > 0) {\n findings.push({\n severity: \"error\",\n code: shippableDirty.length > 0 ? \"git-sync-uncommitted-shippable\" : \"git-sync-uncommitted-changes\",\n message: shippableDirty.length > 0\n ? `${shippableDirty.length} shippable file(s) are modified but not committed.`\n : `${status.dirtyFiles.length} file(s) are modified but not committed.`,\n fix: shippableDirty.length > 0\n ? \"Bump the lockstep package version if needed, then `git add`, `git commit`, `git tag vX.Y.Z`, `git push && git push origin vX.Y.Z` (not `--tags`).\"\n : \"Commit and push these changes before reporting the task done.\",\n reason: \"The multi-agent git-sync decision requires agents to leave completed work committed and pushed, not as a local diff.\",\n affected_files: status.dirtyFiles.slice(0, 12),\n impact: 100,\n });\n return finishReport(root, initialized, mode, findings, config);\n }\n\n findings.push({\n severity: \"ok\",\n code: \"git-worktree-clean\",\n message: \"No uncommitted worktree changes remain.\",\n });\n\n if (!status.upstream) {\n findings.push({\n severity: \"warn\",\n code: \"git-sync-no-upstream\",\n message: \"This branch has no upstream, so Hivelore cannot verify that commits/tags were pushed.\",\n fix: \"Set an upstream with `git push -u origin <branch>`.\",\n impact: 15,\n });\n return finishReport(root, initialized, mode, findings, config);\n }\n\n if (status.behind > 0) {\n findings.push({\n severity: \"error\",\n code: \"git-sync-behind-upstream\",\n message: `This branch is ${status.behind} commit(s) behind ${status.upstream}.`,\n fix: \"Run `git pull --ff-only` and resolve any conflicts before finishing.\",\n impact: 40,\n });\n }\n\n if (status.ahead > 0) {\n findings.push({\n severity: \"error\",\n code: \"git-sync-unpushed-commits\",\n message: `This branch is ${status.ahead} commit(s) ahead of ${status.upstream}.`,\n fix: \"Run `git push` before reporting the task done.\",\n reason: \"The multi-agent git-sync decision requires agents to push completed commits.\",\n impact: 60,\n });\n } else {\n findings.push({\n severity: \"ok\",\n code: \"git-sync-pushed\",\n message: `Branch is not ahead of ${status.upstream}.`,\n });\n }\n\n const releaseChangedFiles = status.releaseChangedFiles ?? status.changedSinceUpstream;\n const releaseBaseRef = status.releaseBaseRef ?? status.upstream;\n const shippableChanged = releaseChangedFiles.filter(isShippablePath);\n if (shippableChanged.length === 0) {\n findings.push({\n severity: \"ok\",\n code: \"release-version-not-required\",\n message: \"No shippable package code changed since upstream; no version/tag required.\",\n });\n findings.push(...await verifyGithubActionsForHead(root, status));\n return finishReport(root, initialized, mode, findings, config);\n }\n\n findings.push({\n severity: \"info\",\n code: \"release-shippable-changes\",\n message: `${shippableChanged.length} shippable file(s) changed since ${releaseBaseRef}.`,\n affected_files: shippableChanged.slice(0, 12),\n });\n\n // Release discipline (version bump + tag) is a HARD gate only on the configured release branch.\n // On feature/* or an integration branch like `develop`, the bump/tag happen when releasing from\n // that branch — so here the same findings are advisory (warn), never blocking the agent's exit.\n const releaseBranch = config.enforcement?.releaseBranch ?? \"main\";\n const onReleaseBranch = !status.branch || status.branch === releaseBranch;\n const releaseSeverity: EnforcementFinding[\"severity\"] = onReleaseBranch ? \"error\" : \"warn\";\n const offBranchNote = onReleaseBranch\n ? \"\"\n : ` (advisory on '${status.branch}'; enforced when releasing from '${releaseBranch}')`;\n\n const versionState = await inspectReleaseVersionState(root, releaseBaseRef);\n if (!versionState.lockstep) {\n findings.push({\n severity: \"error\",\n code: \"release-version-not-lockstep\",\n message: `Publishable package versions are not in lockstep: ${versionState.localVersionsLabel}.`,\n fix: \"Set root, core, cli, mcp, and embeddings package.json versions to the same X.Y.Z.\",\n impact: 60,\n });\n return finishReport(root, initialized, mode, findings, config);\n }\n\n const version = versionState.version;\n if (!version) {\n findings.push({\n severity: \"error\",\n code: \"release-version-unreadable\",\n message: \"Could not read the lockstep package version.\",\n fix: \"Verify package.json files are valid JSON.\",\n impact: 60,\n });\n return finishReport(root, initialized, mode, findings, config);\n }\n\n if (versionState.baseVersion && compareSemver(version, versionState.baseVersion) <= 0) {\n findings.push({\n severity: releaseSeverity,\n code: \"release-version-missing\",\n message: `Shippable code changed, but version stayed at ${version} (base: ${versionState.baseVersion})${offBranchNote}.`,\n fix: \"Bump the lockstep package version (patch by default), commit the bump, tag it, then push code and tags.\",\n impact: onReleaseBranch ? 70 : 0,\n });\n } else {\n findings.push({\n severity: \"ok\",\n code: \"release-version-bumped\",\n message: versionState.baseVersion\n ? `Lockstep version bumped from ${versionState.baseVersion} to ${version}.`\n : `Lockstep version is ${version}.`,\n });\n }\n\n const tag = `v${version}`;\n const localTagAtHead = await tagPointsAtHead(root, tag);\n if (!localTagAtHead) {\n findings.push({\n severity: releaseSeverity,\n code: \"release-tag-missing\",\n message: `Expected git tag ${tag} to point at HEAD${offBranchNote}.`,\n fix: `Run \\`git tag ${tag}\\` after committing the version bump.`,\n impact: onReleaseBranch ? 50 : 0,\n });\n } else {\n findings.push({\n severity: \"ok\",\n code: \"release-tag-present\",\n message: `Tag ${tag} points at HEAD.`,\n });\n }\n\n const remoteTag = await remoteTagExists(root, tag);\n if (remoteTag === false) {\n findings.push({\n severity: releaseSeverity,\n code: \"release-tag-unpushed\",\n message: `Tag ${tag} is not present on the remote${offBranchNote}.`,\n fix: `Run \\`git push origin ${tag}\\` (avoid \\`git push --tags\\` — it fails on pre-existing divergent tags).`,\n impact: onReleaseBranch ? 50 : 0,\n });\n } else if (remoteTag === true) {\n findings.push({\n severity: \"ok\",\n code: \"release-tag-pushed\",\n message: `Tag ${tag} exists on the remote.`,\n });\n } else {\n findings.push({\n severity: \"warn\",\n code: \"release-tag-remote-unverified\",\n message: `Could not verify whether tag ${tag} exists on the remote.`,\n fix: `Run \\`git push origin ${tag}\\` if you have not already (avoid \\`git push --tags\\`).`,\n impact: 10,\n });\n }\n\n findings.push(...await verifyGithubActionsForHead(root, status));\n return finishReport(root, initialized, mode, findings, config);\n}\n\n/**\n * Failure-capture gate: hard failures observed this session (`hivelore observe` tagged them\n * `failure_hint`) that were never written down as a lesson are a silent-repeat risk. Surface them\n * (gate=warn, default) or block finish (gate=block). A failure is \"captured\" once an attempt/gotcha\n * lesson was recorded after it. Off by config opt-out — the signal has false positives (a `grep`\n * that finds nothing exits non-zero), so the default is advisory, not blocking.\n */\nasync function checkFailureCapture(\n paths: ReturnType<typeof resolveHaivePaths>,\n config: HaiveConfig,\n): Promise<EnforcementFinding[]> {\n const gate = config.enforcement?.failureCaptureGate ?? \"warn\";\n if (gate === \"off\") return [];\n\n const obsFile = path.join(paths.haiveDir, \".cache\", \"observations.jsonl\");\n if (!existsSync(obsFile)) return [];\n\n const failures: { ts: string; tool: string; summary: string }[] = [];\n try {\n const raw = await readFile(obsFile, \"utf8\");\n for (const line of raw.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n try {\n const o = JSON.parse(trimmed) as { ts?: string; tool?: string; summary?: string; failure_hint?: boolean };\n if (o.failure_hint && o.ts) failures.push({ ts: o.ts, tool: o.tool ?? \"?\", summary: o.summary ?? \"\" });\n } catch { /* skip corrupt line */ }\n }\n } catch {\n return [];\n }\n if (failures.length === 0) return [];\n\n const memories = existsSync(paths.memoriesDir) ? await loadMemoriesFromDir(paths.memoriesDir) : [];\n const captureTimes = memories\n .filter(({ memory }) => [\"attempt\", \"gotcha\"].includes(memory.frontmatter.type))\n .map(({ memory }) => memory.frontmatter.created_at);\n\n const uncaptured = findUncapturedFailures(failures, captureTimes);\n if (uncaptured.length === 0) {\n return [{\n severity: \"ok\",\n code: \"failure-capture-clean\",\n message: \"No uncaptured hard failures from this session.\",\n }];\n }\n\n return [{\n severity: gate === \"block\" ? \"error\" : \"info\",\n code: \"uncaptured-failures\",\n message: `${uncaptured.length} hard failure(s) this session were never captured as a lesson (mem_tried).`,\n fix: \"Call `mem_tried` (or `hivelore memory tried`) for each real failure so the next session doesn't repeat it. False positives (e.g. a grep that found nothing) can be ignored.\",\n reason: \"Harness ratchet: a mistake that isn't written down gets re-introduced. Set enforcement.failureCaptureGate to 'off' to disable, or 'block' to hard-fail.\",\n affected_files: uncaptured.slice(0, 8).map((f) => `${f.tool}: ${f.summary}`.slice(0, 100)),\n ...(gate === \"block\" ? { impact: 30 } : {}),\n }];\n}\n\nfunction finishReport(\n root: string,\n initialized: boolean,\n mode: EnforcementReport[\"mode\"],\n findings: EnforcementFinding[],\n config: HaiveConfig,\n): EnforcementReport {\n const score = buildScore(findings, config.enforcement?.scoreThreshold);\n const hasErrors = findings.some((f) => f.severity === \"error\");\n return withCategories({\n root,\n initialized,\n mode,\n score,\n should_block: mode === \"strict\" && hasErrors,\n findings,\n });\n}\n\nexport async function runWithEnforcement(\n command: string,\n args: string[],\n opts: { dir?: string; task?: string },\n): Promise<void> {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.haiveDir)) {\n ui.error(`No .ai/ found at ${root}. Run \\`hivelore init\\` first.`);\n process.exit(1);\n }\n\n const sessionId = `haive-run-${process.pid}-${Date.now()}`;\n const task = opts.task ?? `Run agent command: ${[command, ...args].join(\" \")}`;\n await writeBriefingMarker(paths, {\n sessionId,\n task,\n source: \"haive-run\",\n });\n const briefingFile = await writeWrapperBriefing(paths, sessionId, task);\n\n const before = await buildEnforcementReport(root, \"local\", sessionId);\n const blocking = before.findings.filter((f) => f.severity === \"error\" && f.code !== \"session-recap-missing\");\n if (blocking.length > 0) {\n printReport({ ...before, should_block: true, findings: blocking }, false);\n process.exit(2);\n }\n\n ui.info(`Hivelore briefing marker created for wrapped agent session: ${sessionId}`);\n ui.info(`Briefing written to ${path.relative(root, briefingFile)} and exported as HAIVE_BRIEFING_FILE`);\n const child = spawn(command, args, {\n cwd: root,\n stdio: \"inherit\",\n env: {\n ...process.env,\n HAIVE_PROJECT_ROOT: root,\n HAIVE_SESSION_ID: sessionId,\n HAIVE_BRIEFING_FILE: briefingFile,\n HAIVE_ENFORCEMENT: \"strict\",\n HAIVE_TOOL_PROFILE: process.env.HAIVE_TOOL_PROFILE ?? \"enforcement\",\n },\n });\n await new Promise<void>((resolve, reject) => {\n child.on(\"error\", reject);\n child.on(\"close\", (code, signal) => {\n if (signal) process.exit(128);\n process.exitCode = code ?? 0;\n resolve();\n });\n });\n}\n\nasync function writeWrapperBriefing(\n paths: ReturnType<typeof resolveHaivePaths>,\n sessionId: string,\n task: string,\n): Promise<string> {\n await applyLightweightRepairs(paths.root, paths);\n const budget = resolveBriefingBudget(\"quick\", {\n max_tokens: 2500,\n max_memories: 5,\n include_module_contexts: false,\n });\n const briefing = await getBriefing({\n task,\n files: [],\n max_tokens: budget.max_tokens,\n max_memories: budget.max_memories,\n include_project_context: true,\n include_module_contexts: budget.include_module_contexts,\n semantic: true,\n include_stale: false,\n track: true,\n format: \"actions\",\n symbols: [],\n min_semantic_score: 0.25,\n budget_preset: \"quick\",\n }, { paths });\n await writeBriefingMarker(paths, {\n sessionId,\n task,\n source: \"haive-run\",\n memoryIds: briefing.memories.map((m) => m.id),\n });\n const dir = path.join(paths.runtimeDir, \"enforcement\", \"briefings\");\n await mkdir(dir, { recursive: true });\n const file = path.join(dir, `${sessionId}.md`);\n const parts = [\n \"# Hivelore Briefing\",\n \"\",\n `Task: ${task}`,\n \"\",\n ];\n if (briefing.last_session) parts.push(\"## Last Session\", briefing.last_session.body.trim(), \"\");\n if (briefing.project_context?.content) parts.push(\"## Project Context\", briefing.project_context.content.trim(), \"\");\n if (briefing.memories.length > 0) {\n parts.push(\"## Relevant Memories\");\n for (const memory of briefing.memories) {\n parts.push(\"\", `### ${memory.id}`, memory.body.trim());\n }\n }\n if (briefing.setup_warnings.length > 0) {\n parts.push(\"\", \"## Setup Warnings\", ...briefing.setup_warnings.map((w) => `- ${w}`));\n }\n await writeFile(file, parts.join(\"\\n\") + \"\\n\", \"utf8\");\n return file;\n}\n\nconst PRODUCTION_CODE_EXT = /\\.(ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|kt|swift|rb|php|cs|cpp|cc|c|h|hpp|vue|svelte)$/i;\n/** A changed path that represents real product source (not .ai/, docs, config, or generated artifacts). */\nfunction looksLikeProductionCode(file: string): boolean {\n const f = file.replace(/^\\/+/, \"\");\n if (f.startsWith(\".ai/\") || f.startsWith(\".github/\")) return false;\n if (isGeneratedArtifact(f)) return false;\n if (/\\.(test|spec)\\.[cm]?[jt]sx?$/.test(f)) return false;\n if (/(^|\\/)(test|tests|__tests__|__mocks__|e2e|fixtures)(\\/|$)/.test(f)) return false;\n return PRODUCTION_CODE_EXT.test(f);\n}\n\n/**\n * First-agent bootstrap gate. Forces the very first agent on a cold corpus to fill the knowledge layer\n * (project-context, module contexts, anchored memories + a sensor per main code area) before its\n * commit/finish can pass. The trigger is the corpus state (all committed artifacts → identical in CI),\n * so it self-clears and is silent for every later agent. Block only bites when production code changes;\n * docs/config-only commits are downgraded to a warning.\n */\nasync function checkBootstrapComplete(\n paths: ReturnType<typeof resolveHaivePaths>,\n config: HaiveConfig,\n productionCodeChanged: boolean,\n): Promise<EnforcementFinding[]> {\n const gate = config.enforcement?.bootstrapGate ?? \"block\";\n if (gate === \"off\") return [];\n\n let projectContextRaw = \"\";\n try { projectContextRaw = await readFile(paths.projectContext, \"utf8\"); } catch { /* absent */ }\n\n const memories = existsSync(paths.memoriesDir) ? await loadMemoriesFromDir(paths.memoriesDir) : [];\n const codeMap = await loadCodeMap(paths);\n const codeFiles = codeMap ? Object.keys(codeMap.files) : [];\n\n let existingModules: string[] = [];\n try {\n const entries = await readdir(paths.modulesContextDir, { withFileTypes: true });\n existingModules = entries.filter((e) => e.isDirectory()).map((e) => e.name);\n } catch { /* no modules dir yet */ }\n\n const assessment = assessBootstrapState({ projectContextRaw, memories, codeFiles, existingModules });\n\n if (assessment.state === \"ready\") {\n return [{\n severity: \"ok\",\n code: \"bootstrap-complete\",\n message: `Repo knowledge layer is ready — ${assessment.metrics.mainAreas} main area(s) covered by memories and sensors.`,\n }];\n }\n\n // Only enforce where there are genuine main code areas — otherwise (tiny / docs / config-only repo)\n // there is nothing for later coding agents to rely on, so the gate is advisory (info, no score penalty).\n const hasCodeAreas = assessment.metrics.mainAreas > 0;\n const blocking = gate === \"block\" && hasCodeAreas && productionCodeChanged;\n const severity: EnforcementFinding[\"severity\"] = blocking ? \"error\" : hasCodeAreas ? \"warn\" : \"info\";\n return [{\n severity,\n code: \"bootstrap-incomplete\",\n message:\n `First-agent bootstrap ${blocking ? \"REQUIRED\" : \"pending\"} — the repo knowledge layer is ${assessment.state}; ` +\n `later agents will rely on it. Close these gaps:\\n${renderBootstrapChecklist(assessment)}`,\n fix: \"Invoke the bootstrap_repo MCP prompt — it drives project-context, module contexts, anchored memories, and propose_sensor for each main area. (Override: enforcement.bootstrapGate, or `git commit --no-verify`.)\",\n impact: blocking ? 40 : severity === \"warn\" ? 5 : 0,\n }];\n}\n\nasync function buildEnforcementReport(\n dir: string | undefined,\n stage: \"local\" | \"pre-commit\" | \"pre-push\" | \"ci\",\n sessionId?: string,\n): Promise<EnforcementReport> {\n const root = findProjectRoot(dir);\n const paths = resolveHaivePaths(root);\n const initialized = existsSync(paths.haiveDir);\n const config = initialized ? await loadConfig(paths) : {};\n if (initialized) {\n await applyLightweightRepairs(root, paths);\n // Atomic release commit: when the repair re-syncs the project-context version\n // header to package.json, stage it so it lands in THIS commit instead of drifting\n // into a later `chore: hivelore sync [skip ci]` tip — which would skip CI for the whole\n // push (decision 2026-06-02-decision-atomic-release-commit-and-skip-ci-tip).\n if (stage === \"pre-commit\") await stageResyncedArtifacts(root, paths);\n }\n const mode = config.enforcement?.mode ?? \"strict\";\n const findings: EnforcementFinding[] = [];\n\n if (!initialized) {\n return withCategories({\n root,\n initialized,\n mode,\n score: buildScore([], config.enforcement?.scoreThreshold),\n should_block: true,\n findings: [{\n severity: \"error\",\n code: \"not-initialized\",\n message: \"This repository is not initialized with Hivelore.\",\n fix: \"Run `hivelore init` or `hivelore enforce install`.\",\n impact: 100,\n }],\n });\n }\n\n if (mode === \"off\") {\n return withCategories({\n root,\n initialized,\n mode,\n score: buildScore([], config.enforcement?.scoreThreshold),\n should_block: false,\n findings: [{ severity: \"info\", code: \"enforcement-off\", message: \"Hivelore enforcement is disabled.\" }],\n });\n }\n\n findings.push(...await inspectIntegrationVersions(root, __HAIVE_VERSION__));\n\n if (config.enforcement?.requireBriefingFirst !== false && stage !== \"ci\") {\n const hasBriefing = await hasRecentBriefingMarker(paths, sessionId);\n findings.push(hasBriefing\n ? { severity: \"ok\", code: \"briefing-loaded\", message: \"A recent Hivelore briefing marker exists.\" }\n : {\n severity: \"error\",\n code: \"briefing-missing\",\n message: \"No recent Hivelore briefing marker was found for this workflow.\",\n fix: \"Run `hivelore briefing --task \\\"...\\\"`, `hivelore enforce session-start`, or wrap the agent with `hivelore run -- <agent>`.\",\n impact: 35,\n });\n }\n\n if (config.enforcement?.requireSessionRecap !== false && (stage === \"pre-push\" || stage === \"ci\")) {\n const hasRecap = await hasRecentSessionRecap(paths);\n findings.push(hasRecap\n ? { severity: \"ok\", code: \"session-recap-present\", message: \"A recent session_recap memory exists.\" }\n : stage === \"ci\"\n ? {\n severity: \"warn\",\n code: \"session-recap-missing\",\n message: \"No recent session_recap memory was found. CI reports this as a warning because personal recaps are usually not committed.\",\n fix: \"Run `hivelore session end --scope team --goal ... --accomplished ...` if you want a team recap visible in CI.\",\n impact: 5,\n }\n : {\n severity: \"error\",\n code: \"session-recap-missing\",\n message: \"No recent session_recap memory was found.\",\n fix: \"Run `hivelore session end --goal ... --accomplished ...` before pushing.\",\n impact: 20,\n });\n }\n\n if (config.enforcement?.requireMemoryVerify !== false) {\n findings.push(...await verifyMemoryPolicy(paths, config));\n }\n\n if (config.enforcement?.requireDecisionCoverage !== false) {\n findings.push(...await verifyDecisionCoverage(paths, stage, sessionId));\n }\n\n if (stage === \"pre-commit\" || stage === \"ci\") {\n findings.push(...await runPrecommitPolicy(paths, config.enforcement?.antiPatternGate ?? \"anchored\", stage));\n } else if (stage === \"local\") {\n // The diff-scan layer (anti-pattern matcher + regex/command sensors) runs only at\n // pre-commit/ci — by design, so a bare `enforce check` preview stays fast and quiet on\n // config/docs work. Say so explicitly: otherwise a clean `local` run reads as \"your diff\n // passed the sensor gate\", which it did not evaluate. The installed git hook uses pre-commit.\n findings.push({\n severity: \"info\",\n code: \"antipattern-gate-deferred\",\n message:\n \"Anti-pattern + sensor diff scan is NOT evaluated in --stage local (this is a preview). \" +\n \"It runs in the installed git hook (--stage pre-commit) and in CI (--stage ci).\",\n fix: \"To scan the staged diff now: `hivelore sensors check`, or `hivelore enforce check --stage pre-commit`.\",\n });\n }\n\n if (config.enforcement?.cleanupGeneratedArtifacts !== false) {\n findings.push(...await findGeneratedArtifacts(paths));\n }\n\n {\n const changed = await getChangedFiles(root, stage).catch(() => [] as string[]);\n findings.push(...await checkBootstrapComplete(paths, config, changed.some(looksLikeProductionCode)));\n }\n\n const score = buildScore(findings, config.enforcement?.scoreThreshold);\n if (score.score < score.threshold) {\n findings.push({\n severity: \"error\",\n code: \"enforcement-score-below-threshold\",\n message: `Enforcement score ${score.score}% is below required threshold ${score.threshold}%.`,\n fix: \"Load the relevant briefing, address policy findings, then rerun `hivelore enforce check`.\",\n impact: 0,\n });\n }\n\n const hasErrors = findings.some((f) => f.severity === \"error\");\n return withCategories({\n root,\n initialized,\n mode,\n score: buildScore(findings, config.enforcement?.scoreThreshold),\n should_block: mode === \"strict\" && hasErrors,\n findings,\n });\n}\n\nfunction withCategories(report: Omit<EnforcementReport, \"categories\">): EnforcementReport {\n return {\n ...report,\n categories: {\n blocking: report.findings.filter((f) => f.severity === \"error\"),\n review: report.findings.filter((f) => f.severity === \"warn\"),\n info: report.findings.filter((f) => f.severity === \"info\" || f.severity === \"ok\"),\n },\n };\n}\n\nasync function hasRecentSessionRecap(paths: ReturnType<typeof resolveHaivePaths>): Promise<boolean> {\n // An ephemeral NEXT.md handoff also satisfies continuity (autoSessionRecap=false setups).\n const handoffAge = await handoffAgeMs(paths.root);\n if (handoffAge !== null && handoffAge < SESSION_RECAP_TTL_MS) return true;\n if (!existsSync(paths.memoriesDir)) return false;\n const all = await loadMemoriesFromDir(paths.memoriesDir);\n return all.some(({ memory }) => {\n const fm = memory.frontmatter;\n const freshnessDate = fm.verified_at ?? fm.created_at;\n return fm.type === \"session_recap\" &&\n fm.status !== \"rejected\" &&\n isFreshIsoDate(freshnessDate, SESSION_RECAP_TTL_MS);\n });\n}\n\nasync function verifyMemoryPolicy(\n paths: ReturnType<typeof resolveHaivePaths>,\n config: HaiveConfig,\n): Promise<EnforcementFinding[]> {\n if (!existsSync(paths.memoriesDir)) return [];\n const all = await loadMemoriesFromDir(paths.memoriesDir);\n const findings: EnforcementFinding[] = [];\n const staleImportant: string[] = [];\n let verified = 0;\n\n for (const { memory } of all) {\n const fm = memory.frontmatter;\n const anchored = fm.anchor.paths.length > 0 || fm.anchor.symbols.length > 0;\n if (!anchored || fm.status === \"rejected\" || fm.status === \"deprecated\") continue;\n verified++;\n if (fm.status === \"stale\") {\n if ([\"decision\", \"gotcha\", \"architecture\", \"convention\"].includes(fm.type)) {\n staleImportant.push(fm.id);\n }\n continue;\n }\n if (config.enforcement?.blockStaleDecisionChanges !== false && [\"decision\", \"gotcha\"].includes(fm.type)) {\n const result = await verifyAnchor(memory, { projectRoot: paths.root });\n if (result.stale) staleImportant.push(fm.id);\n }\n }\n\n findings.push({\n severity: \"ok\",\n code: \"memory-verify-ran\",\n message: `Checked ${verified} anchored memories for stale enforcement policy.`,\n });\n\n if (staleImportant.length > 0) {\n findings.push({\n severity: \"error\",\n code: \"stale-important-memories\",\n message: `${staleImportant.length} important anchored memories are stale: ${staleImportant.slice(0, 8).join(\", \")}`,\n fix: \"Run `hivelore memory verify --update`, then update or delete stale decisions/gotchas before merging.\",\n impact: 40,\n });\n }\n return findings;\n}\n\nasync function verifyDecisionCoverage(\n paths: ReturnType<typeof resolveHaivePaths>,\n stage: \"local\" | \"pre-commit\" | \"pre-push\" | \"ci\",\n sessionId?: string,\n): Promise<EnforcementFinding[]> {\n if (!existsSync(paths.memoriesDir)) return [];\n // Exclude Hivelore-generated artifacts: the agent doesn't author them, so requiring decision\n // coverage for them is pure friction (and blocked release commits over repair-touched files).\n const changedFiles = (await getChangedFiles(paths.root, stage)).filter((f) => !isGeneratedArtifact(f));\n if (changedFiles.length === 0) {\n return [{ severity: \"info\", code: \"decision-coverage-no-changes\", message: \"No changed files to match against policy memories.\" }];\n }\n\n const all = await loadMemoriesFromDir(paths.memoriesDir);\n const changedSet = new Set(changedFiles);\n const policyTypes = new Set([\"decision\", \"gotcha\", \"architecture\", \"convention\"]);\n const relevant = all\n .filter(({ memory }) => {\n const fm = memory.frontmatter;\n if (!policyTypes.has(fm.type)) return false;\n if (fm.status !== \"validated\") return false;\n return memoryMatchesAnchorPaths(memory, changedFiles);\n });\n\n if (relevant.length === 0) {\n return [{\n severity: \"ok\",\n code: \"decision-coverage-none-required\",\n message: `No anchored decisions or policies matched ${changedFiles.length} changed file(s).`,\n }];\n }\n\n const marker = await readRecentBriefingMarker(paths, sessionId);\n if (stage === \"ci\" && !marker) {\n return [{\n severity: \"ok\",\n code: \"decision-coverage-ci-pass\",\n message:\n `CI surfaced ${relevant.length} relevant anchored decision/polic${relevant.length === 1 ? \"y\" : \"ies\"} ` +\n `for ${changedFiles.length} changed file(s). Runtime briefing markers are local-only and are not expected on GitHub Actions.`,\n memory_ids: relevant.slice(0, 20).map(({ memory }) => memory.frontmatter.id),\n affected_files: changedFiles.slice(0, 10),\n }];\n }\n\n const consulted = new Set(marker?.memory_ids ?? []);\n // Self-authored exemption: a policy memory whose OWN backing file is in this changeset is being\n // written/edited by the committer — requiring it to be pre-surfaced in a briefing is pure friction\n // (you cannot brief a memory you are creating in the same commit). Treat it as covered.\n const missing = relevant\n .filter(({ memory, filePath }) => {\n if (consulted.has(memory.frontmatter.id)) return false;\n if (changedSet.has(path.relative(paths.root, filePath))) return false;\n return true;\n })\n .map(({ memory }) => memory);\n if (missing.length === 0) {\n return [{\n severity: \"ok\",\n code: \"decision-coverage-pass\",\n message: `Relevant decisions/policies were surfaced for ${changedFiles.length} changed file(s): ${relevant.length}/${relevant.length}.`,\n }];\n }\n\n // Auto-brief (default on): instead of blocking with \"run a briefing first\", the gate surfaces the\n // relevant policies itself and records them in the session marker — feedforward at commit time with\n // zero manual step (the harness iterates the loop, not the human). Strict teams set\n // enforcement.autoBrief=false to keep the legacy \"must brief before commit\" hard gate.\n if (stage === \"pre-commit\" || stage === \"pre-push\") {\n const cfg = await loadConfig(paths).catch(() => ({}) as HaiveConfig);\n if (cfg.enforcement?.autoBrief !== false) {\n await writeBriefingMarker(paths, {\n sessionId,\n source: \"haive-autobrief\",\n task: \"decision-coverage auto-surfaced at commit\",\n memoryIds: relevant.map(({ memory }) => memory.frontmatter.id),\n files: changedFiles,\n }).catch(() => { /* best-effort: marker is runtime-local */ });\n return [{\n severity: \"ok\",\n code: \"decision-coverage-autosurfaced\",\n message:\n `Surfaced ${relevant.length} relevant decision/policy memor${relevant.length === 1 ? \"y\" : \"ies\"} ` +\n `for ${changedFiles.length} changed file(s) at commit time` +\n (missing.length > 0 ? ` (${missing.length} not previously briefed — now recorded)` : \"\") +\n \". Set enforcement.autoBrief=false to require a manual briefing first.\",\n memory_ids: relevant.slice(0, 12).map(({ memory }) => memory.frontmatter.id),\n affected_files: changedFiles.slice(0, 10),\n }];\n }\n }\n\n return [{\n severity: stage === \"local\" ? \"warn\" : \"error\",\n code: \"decision-coverage-missing\",\n message: `${missing.length}/${relevant.length} relevant anchored decisions/policies were not present in the latest briefing: ${missing.slice(0, 6).map((m) => m.frontmatter.id).join(\", \")}`,\n fix: `Run \\`hivelore briefing --files \"${changedFiles.slice(0, 12).join(\",\")}\" --max-memories 60 --task \"...\"\\` before committing (briefings now accumulate, so several smaller briefings also work).`,\n reason: \"Changed files overlap validated anchored policy memories that were not recorded in the latest briefing marker.\",\n affected_files: changedFiles.slice(0, 10),\n memory_ids: missing.slice(0, 10).map((m) => m.frontmatter.id),\n impact: Math.min(35, 10 + missing.length * 5),\n }];\n}\n\nasync function runPrecommitPolicy(\n paths: ReturnType<typeof resolveHaivePaths>,\n gate: AntiPatternGate,\n stage: \"pre-commit\" | \"ci\",\n): Promise<EnforcementFinding[]> {\n if (gate === \"off\") {\n return [{ severity: \"info\", code: \"precommit-policy-off\", message: \"Anti-pattern gate is disabled (enforcement.antiPatternGate=off).\" }];\n }\n const snapshot = await getPolicyDiffSnapshot(paths.root, stage);\n const touchedPaths = snapshot.paths;\n if (touchedPaths.length === 0) {\n const code = stage === \"ci\" ? \"no-ci-diff-changes\" : \"no-staged-changes\";\n const message = stage === \"ci\"\n ? \"No changed files found for CI policy diff.\"\n : \"No staged changes found for pre-commit policy.\";\n return [{ severity: \"info\", code, message }];\n }\n // The gate→params mapping lives in @hivelore/core so the git-hook path and the\n // standalone `hivelore precommit` command can never drift apart.\n const { block_on, anchored_blocks } = antiPatternGateParams(gate);\n const result = await preCommitCheck({\n diff: snapshot.diff,\n paths: touchedPaths,\n block_on,\n anchored_blocks,\n semantic: true,\n }, { paths });\n\n // Deterministic regex sensors — the precise/computational layer. Previously these\n // only ran via the standalone `hivelore sensors check` and never on a real commit\n // (see 2026-06-03-gotcha-regex-sensors-orphaned-from-precommit-gate). Run them here\n // so a promoted block sensor actually blocks and warn sensors surface in the gate,\n // covering convention/architecture sensors the fuzzy anti-pattern matcher skips.\n const sensorFindings = await runSensorGate(paths, snapshot.diff);\n\n // Review-level anti-patterns must stay VISIBLE in the gate output even when nothing blocks.\n // History (see 2026-05-07-attempt-strict-precommit-gate-on-haive): making them block spammed\n // config-only commits — so they were silenced entirely, and `enforce check` reported a clean\n // pass while `hivelore precommit` showed \"you are about to repeat a documented failed approach\".\n // Middle ground: ONE aggregated warn finding (bounded score impact, never blocks) that points\n // at `hivelore precommit` for the full detail. Sensor-driven review warnings are excluded — the\n // sensor gate below already emits a dedicated finding per sensor hit.\n const reviewWarnings = result.warnings.filter(\n (w) => w.level === \"review\" && !w.reasons.includes(\"sensor\"),\n );\n const reviewFinding: EnforcementFinding[] = reviewWarnings.length > 0\n ? [{\n severity: \"warn\",\n code: \"anti-pattern-review\",\n message:\n `${reviewWarnings.length} documented lesson(s) plausibly match this diff — review before committing: ` +\n reviewWarnings\n .slice(0, 3)\n .map((w) => `${w.id} (${w.reasons.join(\"+\")})`)\n .join(\", \") +\n (reviewWarnings.length > 3 ? \", …\" : \"\"),\n fix: \"Run `hivelore precommit` for the matched lines and repair commands; update the code, or retire the memory if it no longer applies.\",\n memory_ids: reviewWarnings.slice(0, 10).map((w) => w.id),\n impact: 5,\n }]\n : [];\n\n if (!result.should_block) {\n return [\n {\n severity: \"ok\",\n code: \"precommit-policy-pass\",\n message: `${stage === \"ci\" ? \"CI\" : \"Pre-commit\"} policy passed for ${touchedPaths.length} changed file(s).`,\n },\n ...reviewFinding,\n ...sensorFindings,\n ];\n }\n // Name the culprits: a CI failure that says \"1 blocking anti-pattern\" without the memory id\n // is undebuggable from the workflow log (lived on the v0.29.12 release push).\n const blockingWarnings = result.warnings.filter((w) => w.level === \"blocking\");\n const blockingDetail = blockingWarnings\n .slice(0, 5)\n .map((w) => `${w.id} (${w.reasons.join(\"+\")}${w.sensor_severity ? `, sensor=${w.sensor_severity}` : \"\"})`)\n .join(\", \");\n return [\n {\n severity: \"error\",\n code: \"precommit-policy-block\",\n message:\n `Pre-commit policy matched ${result.summary.blocking_warnings ?? result.summary.anti_patterns} blocking anti-pattern(s), ${result.summary.stale_anchors} stale anchor(s)` +\n (blockingDetail ? `: ${blockingDetail}` : \"\") +\n (result.stale_anchors.length > 0 ? ` — stale: ${result.stale_anchors.slice(0, 5).map((s) => s.id).join(\", \")}` : \"\") + \".\",\n fix: \"Review the Hivelore warnings, then update the code or the relevant memories.\",\n memory_ids: blockingWarnings.slice(0, 10).map((w) => w.id),\n impact: 45,\n },\n ...reviewFinding,\n ...sensorFindings,\n ];\n}\n\n/**\n * Run the repo's regex sensors against the staged diff and turn hits into findings:\n * a `block`-severity sensor → error (fails the gate); a `warn` sensor → warn (visible,\n * non-blocking). Read-only and best-effort: a sensor bug must never break a commit.\n */\nasync function runSensorGate(\n paths: ReturnType<typeof resolveHaivePaths>,\n diff: string,\n): Promise<EnforcementFinding[]> {\n if (!diff || !existsSync(paths.memoriesDir)) return [];\n try {\n const loaded = await loadMemoriesFromDir(paths.memoriesDir);\n const scannable = loaded\n .map((l) => l.memory)\n .filter((m) => Boolean(m.frontmatter.sensor) && !isRetiredMemory(m.frontmatter, m.body));\n if (scannable.length === 0) return [];\n\n // Only scan real code targets — never Hivelore-owned/`.ai/` files (self-match guard).\n const targets = sensorTargetsFromDiff(diff).filter((t) => isSensorScannablePath(t.path));\n if (targets.length === 0) return [];\n\n const findings: EnforcementFinding[] = [];\n const seen = new Set<string>();\n const firedIds = new Set<string>();\n\n // ── Computational layer 1: deterministic regex sensors ──\n const regexSensorMemories = scannable.filter((m) => m.frontmatter.sensor!.kind === \"regex\");\n const hits = regexSensorMemories.length > 0 ? runSensors(regexSensorMemories, targets) : [];\n for (const hit of hits) {\n if (seen.has(hit.memory_id)) continue;\n seen.add(hit.memory_id);\n firedIds.add(hit.memory_id);\n const where = hit.file ? ` (${hit.file})` : \"\";\n if (hit.severity === \"block\") {\n findings.push({\n severity: \"error\",\n code: \"sensor-block\",\n message: `Block sensor fired — ${hit.memory_id}: ${hit.message}${where}`,\n fix: \"Remove the flagged pattern, or run `hivelore sensors check` to inspect the match.\",\n impact: 45,\n });\n } else {\n findings.push({\n severity: \"warn\",\n code: \"sensor-warn\",\n message: `Sensor flagged ${hit.memory_id}: ${hit.message}${where}`,\n fix: \"Review the flagged line; `hivelore sensors check` shows the matched code.\",\n impact: 5,\n });\n }\n }\n\n // ── Computational layer 2: shell/test command sensors (a regex can't express) ──\n // OFF by default — they execute arbitrary repo-authored commands. Opt in per-repo with\n // enforcement.runCommandSensors=true (mirrors `hivelore sensors check --commands`).\n const config = await loadConfig(paths).catch(() => null);\n if (config?.enforcement?.runCommandSensors === true) {\n const changedPaths = targets.map((t) => t.path).filter(Boolean);\n for (const spec of selectCommandSensors(scannable, changedPaths)) {\n if (seen.has(spec.memory_id)) continue;\n const failed = await runGateCommandSensor(spec, paths.root);\n if (!failed) continue;\n seen.add(spec.memory_id);\n firedIds.add(spec.memory_id);\n if (spec.severity === \"block\") {\n findings.push({\n severity: \"error\",\n code: \"sensor-block\",\n message: `Block command sensor fired — ${spec.memory_id}: ${spec.message} (command: ${spec.command})`,\n fix: \"Fix the condition the command checks, or run `hivelore sensors check --commands` to inspect it.\",\n impact: 45,\n });\n } else {\n findings.push({\n severity: \"warn\",\n code: \"sensor-warn\",\n message: `Command sensor flagged ${spec.memory_id}: ${spec.message}`,\n fix: \"Review the failing command; `hivelore sensors check --commands` re-runs it.\",\n impact: 5,\n });\n }\n }\n }\n\n // OUTCOME measurement — the formerly-missing leg of the loop. A sensor firing in the gate is a\n // prevention event (a documented mistake intercepted before it landed). Funnel through THE shared\n // recorder so the installed git-hook gate finally records what it blocks — debounced, so it can't\n // double-count with a prior `sensors check` / `anti_patterns_check` on the same diff.\n if (firedIds.size > 0) {\n await recordPreventionHits(paths, [...firedIds], \"sensor\").catch(() => { /* best-effort telemetry */ });\n }\n\n return findings;\n } catch {\n return []; // best-effort: never break the gate on a sensor error\n }\n}\n\n/**\n * Run one shell/test sensor command in the gate. Returns true when the command FAILS (non-zero exit) —\n * the \"bad state is present\" signal. Timeout/spawn errors also count as a hit. Never throws; mirrors\n * `runCommandSensor` in `sensors.ts`.\n */\nasync function runGateCommandSensor(spec: CommandSensorSpec, root: string): Promise<boolean> {\n try {\n await execFileAsync(\"bash\", [\"-c\", spec.command], { cwd: root, timeout: 120_000, maxBuffer: 8 * 1024 * 1024 });\n return false;\n } catch {\n return true;\n }\n}\n\nasync function findGeneratedArtifacts(paths: ReturnType<typeof resolveHaivePaths>): Promise<EnforcementFinding[]> {\n const dirty = await runCommand(\"git\", [\"status\", \"--short\", \"--untracked-files=all\"], paths.root).catch(() => \"\");\n const generated = dirty\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter(Boolean)\n .filter((line) =>\n isGeneratedArtifactStatusLine(line) ||\n line.includes(\"__pycache__/\") ||\n line.endsWith(\".pyc\"),\n );\n if (generated.length === 0) {\n return [{ severity: \"ok\", code: \"generated-artifacts-clean\", message: \"No generated runtime/cache artifacts are visible to git.\" }];\n }\n return [{\n severity: \"warn\",\n code: \"generated-artifacts-visible\",\n message: `${generated.length} generated artifact(s) are visible in git status.`,\n fix: \"Run `hivelore enforce cleanup`, update .gitignore, or remove test/runtime outputs before committing.\",\n impact: 10,\n }];\n}\n\nfunction isGeneratedArtifactStatusLine(line: string): boolean {\n const file = line.replace(/^[ MADRCU?!]{1,2}\\s+/, \"\").trim();\n if (file === \".ai/.cache/.gitignore\") return false;\n if (file === \".ai/.runtime/.gitignore\" || file === \".ai/.runtime/README.md\") return false;\n if (file.startsWith(\".ai/.runtime/enforcement/briefings/\")) return false;\n return file.startsWith(\".ai/.cache/\") || file.startsWith(\".ai/.runtime/\");\n}\n\nasync function cleanupRuntimeDir(runtimeDir: string): Promise<number> {\n let removed = 0;\n await mkdir(runtimeDir, { recursive: true });\n const entries = await readdir(runtimeDir, { withFileTypes: true }).catch(() => []);\n for (const entry of entries) {\n if (entry.name === \".gitignore\" || entry.name === \"README.md\") continue;\n if (entry.name === \"enforcement\") {\n removed += await cleanupEnforcementDir(path.join(runtimeDir, entry.name));\n continue;\n }\n await rm(path.join(runtimeDir, entry.name), { recursive: true, force: true });\n removed++;\n }\n await writeFile(path.join(runtimeDir, \".gitignore\"), \"*\\n!.gitignore\\n!README.md\\n\", \"utf8\");\n if (!existsSync(path.join(runtimeDir, \"README.md\"))) {\n await writeFile(\n path.join(runtimeDir, \"README.md\"),\n \"# .ai/.runtime — disposable local layer\\n\\nRuntime data is local. Hivelore cleanup preserves briefing markers so enforcement state remains valid.\\n\",\n \"utf8\",\n );\n }\n return removed;\n}\n\nasync function cleanupCacheDir(cacheDir: string): Promise<number> {\n let removed = 0;\n await mkdir(cacheDir, { recursive: true });\n const entries = await readdir(cacheDir, { withFileTypes: true }).catch(() => []);\n for (const entry of entries) {\n if (entry.name === \".gitignore\") continue;\n await rm(path.join(cacheDir, entry.name), { recursive: true, force: true });\n removed++;\n }\n await writeFile(path.join(cacheDir, \".gitignore\"), \"*\\n!.gitignore\\n\", \"utf8\");\n return removed;\n}\n\nasync function cleanupEnforcementDir(enforcementDir: string): Promise<number> {\n let removed = 0;\n const entries = await readdir(enforcementDir, { withFileTypes: true }).catch(() => []);\n for (const entry of entries) {\n if (entry.name === \"briefings\") continue;\n await rm(path.join(enforcementDir, entry.name), { recursive: true, force: true });\n removed++;\n }\n return removed;\n}\n\nasync function inspectIntegrationVersions(\n root: string,\n expectedVersion: string,\n): Promise<EnforcementFinding[]> {\n const files = [\n \".git/hooks/pre-commit\",\n \".git/hooks/pre-push\",\n \".claude/settings.local.json\",\n \".mcp.json\",\n \".cursor/mcp.json\",\n \".vscode/mcp.json\",\n ];\n const findings: EnforcementFinding[] = [];\n // Dedupe by binary: one finding per unique stale/broken path (listing the files that reference it),\n // not one per occurrence across pre-commit/pre-push/.mcp.json/etc.\n const missingBins = new Map<string, Set<string>>();\n const staleBins = new Map<string, { version: string; files: Set<string> }>();\n for (const rel of files) {\n const file = path.join(root, rel);\n if (!existsSync(file)) continue;\n const text = await readFile(file, \"utf8\").catch(() => \"\");\n for (const bin of extractAbsoluteHaiveBins(text)) {\n const version = versionForBinary(bin);\n if (!version) {\n (missingBins.get(bin) ?? missingBins.set(bin, new Set()).get(bin)!).add(rel);\n } else if (version !== expectedVersion) {\n const entry = staleBins.get(bin) ?? staleBins.set(bin, { version, files: new Set() }).get(bin)!;\n entry.files.add(rel);\n }\n }\n }\n for (const [bin, fileSet] of missingBins) {\n findings.push({\n severity: \"warn\",\n code: \"integration-haive-binary-missing\",\n message: `${[...fileSet].join(\", \")} reference ${bin}, but that binary could not be executed.`,\n fix: \"Run `hivelore agent setup --no-global` or `hivelore enforce install` to refresh project integrations.\",\n impact: 0,\n });\n }\n for (const [bin, { version, files: fileSet }] of staleBins) {\n findings.push({\n severity: \"warn\",\n code: \"integration-haive-version-mismatch\",\n message: `${[...fileSet].join(\", \")} reference Hivelore ${version} at ${bin}; current Hivelore is ${expectedVersion}.`,\n fix: \"Run `hivelore agent setup --no-global` and `hivelore enforce install` to repair stale hooks/configs.\",\n impact: 0,\n });\n }\n if (findings.length === 0) {\n return [{\n severity: \"ok\",\n code: \"integration-version-check\",\n message: \"No stale absolute Hivelore binary paths were found in project hooks/MCP configs.\",\n }];\n }\n return findings;\n}\n\nfunction extractAbsoluteHaiveBins(text: string): string[] {\n const out = new Set<string>();\n const re = /([\"'\\s])((?:\\/[^\"'\\s]+)*\\/haive)\\b/g;\n let match: RegExpExecArray | null;\n while ((match = re.exec(text))) {\n const p = match[2];\n if (!p) continue;\n // Skip directories — a haive binary is a file, not a folder.\n // Prevents HAIVE_PROJECT_ROOT env values from being mistaken for binaries.\n try {\n if (statSync(p).isDirectory()) continue;\n } catch {\n // Path does not exist — still report as missing binary\n }\n out.add(p);\n }\n return [...out].sort();\n}\n\nfunction versionForBinary(bin: string): string | null {\n try {\n const out = execFileSync(bin, [\"--version\"], {\n encoding: \"utf8\",\n timeout: 3000,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n }).trim();\n return out.match(/\\d+\\.\\d+\\.\\d+/)?.[0] ?? null;\n } catch {\n return null;\n }\n}\n\nasync function getChangedFiles(\n root: string,\n stage: \"local\" | \"pre-commit\" | \"pre-push\" | \"ci\",\n): Promise<string[]> {\n if (stage === \"ci\") {\n return (await getPolicyDiffSnapshot(root, \"ci\")).paths;\n }\n if (stage === \"pre-commit\") {\n return normalizeChangedFileList(\n await runCommand(\"git\", [\"diff\", \"--cached\", \"--name-only\"], root).catch(() => \"\"),\n );\n }\n const files = new Set<string>();\n for (const args of [[\"diff\", \"--cached\", \"--name-only\"], [\"diff\", \"--name-only\"]]) {\n for (const file of normalizeChangedFileList(await runCommand(\"git\", args, root).catch(() => \"\"))) {\n files.add(file);\n }\n }\n return [...files];\n}\n\ninterface PolicyDiffSnapshot {\n diff: string;\n paths: string[];\n source: string;\n}\n\nasync function getPolicyDiffSnapshot(\n root: string,\n stage: \"pre-commit\" | \"ci\",\n): Promise<PolicyDiffSnapshot> {\n if (stage === \"pre-commit\") {\n const diff = await runCommand(\"git\", [\"diff\", \"--cached\"], root).catch(() => \"\");\n const names = await runCommand(\"git\", [\"diff\", \"--cached\", \"--name-only\"], root).catch(() => \"\");\n return { diff, paths: normalizeChangedFileList(names), source: \"staged\" };\n }\n\n const range = await resolveCiDiffRange(root);\n if (range) {\n const diff = await runCommand(\"git\", [\"diff\", range], root).catch(() => \"\");\n const names = await runCommand(\"git\", [\"diff\", \"--name-only\", range], root).catch(() => \"\");\n return { diff, paths: normalizeChangedFileList(names), source: range };\n }\n\n return { diff: \"\", paths: [], source: \"none\" };\n}\n\nasync function resolveCiDiffRange(root: string): Promise<string | null> {\n const explicitBase = cleanGitSha(process.env.HAIVE_BASE_SHA ?? process.env.HAIVE_BASE_REF);\n const explicitHead = cleanGitSha(process.env.HAIVE_HEAD_SHA ?? process.env.GITHUB_SHA) ?? \"HEAD\";\n if (explicitBase && await gitCommitExists(root, explicitBase)) {\n return `${explicitBase}...${explicitHead}`;\n }\n\n const eventRange = await resolveGithubEventRange(root);\n if (eventRange) return eventRange;\n\n const baseRef = process.env.GITHUB_BASE_REF?.trim();\n if (baseRef) {\n const remoteRef = `origin/${baseRef}`;\n if (await gitCommitExists(root, remoteRef)) return `${remoteRef}...${explicitHead}`;\n }\n\n if (await gitCommitExists(root, \"origin/main\")) return `origin/main...${explicitHead}`;\n if (await gitCommitExists(root, \"origin/master\")) return `origin/master...${explicitHead}`;\n if (await gitCommitExists(root, \"HEAD^\")) return `HEAD^..${explicitHead}`;\n return null;\n}\n\nasync function resolveGithubEventRange(root: string): Promise<string | null> {\n const eventPath = process.env.GITHUB_EVENT_PATH;\n if (!eventPath || !existsSync(eventPath)) return null;\n try {\n const event = JSON.parse(await readFile(eventPath, \"utf8\")) as {\n before?: string;\n after?: string;\n pull_request?: {\n base?: { sha?: string };\n head?: { sha?: string };\n };\n };\n const prBase = cleanGitSha(event.pull_request?.base?.sha);\n const prHead = cleanGitSha(event.pull_request?.head?.sha ?? event.after ?? process.env.GITHUB_SHA) ?? \"HEAD\";\n if (prBase && await gitCommitExists(root, prBase)) return `${prBase}...${prHead}`;\n\n const pushBase = cleanGitSha(event.before);\n const pushHead = cleanGitSha(event.after ?? process.env.GITHUB_SHA) ?? \"HEAD\";\n if (pushBase && await gitCommitExists(root, pushBase)) return `${pushBase}..${pushHead}`;\n } catch {\n return null;\n }\n return null;\n}\n\nfunction cleanGitSha(value: string | undefined): string | null {\n const trimmed = value?.trim();\n if (!trimmed || /^0+$/.test(trimmed)) return null;\n return trimmed;\n}\n\nasync function gitCommitExists(root: string, ref: string): Promise<boolean> {\n try {\n await runCommand(\"git\", [\"rev-parse\", \"--verify\", `${ref}^{commit}`], root);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction normalizeChangedFileList(raw: string): string[] {\n return raw.split(\"\\n\")\n .map((s) => s.trim())\n .filter(Boolean)\n .filter((file) =>\n !file.startsWith(\".ai/.runtime/\") &&\n !file.startsWith(\".ai/.cache/\") &&\n !file.startsWith(\".ai/.usage/\") &&\n file !== \".ai/.usage/tool-usage.jsonl\"\n );\n}\n\ninterface GitSyncStatus {\n available: boolean;\n branch?: string;\n upstream?: string;\n ahead: number;\n behind: number;\n dirtyFiles: string[];\n changedSinceUpstream: string[];\n releaseBaseRef?: string;\n releaseChangedFiles?: string[];\n}\n\ninterface GithubActionsRun {\n conclusion?: string | null;\n databaseId?: number;\n name?: string;\n status?: string;\n workflowName?: string;\n}\n\nasync function getGitSyncStatus(root: string): Promise<GitSyncStatus> {\n const dirty = (await runCommand(\"git\", [\"status\", \"--short\", \"--untracked-files=all\"], root).catch(() => \"\"))\n .split(\"\\n\")\n .map((line) => statusLineToPath(line.trim()))\n .filter(Boolean)\n .filter((file) => normalizeChangedFileList(file).length > 0);\n const branch = (await runCommand(\"git\", [\"branch\", \"--show-current\"], root).catch(() => \"\")).trim() || undefined;\n const upstream = (await runCommand(\"git\", [\"rev-parse\", \"--abbrev-ref\", \"--symbolic-full-name\", \"@{u}\"], root).catch(() => \"\")).trim() || undefined;\n if (!branch && !upstream) {\n const inside = (await runCommand(\"git\", [\"rev-parse\", \"--is-inside-work-tree\"], root).catch(() => \"\")).trim();\n if (inside !== \"true\") return { available: false, ahead: 0, behind: 0, dirtyFiles: [], changedSinceUpstream: [] };\n }\n\n let ahead = 0;\n let behind = 0;\n let changedSinceUpstream: string[] = [];\n let releaseBaseRef: string | undefined;\n let releaseChangedFiles: string[] | undefined;\n if (upstream) {\n const counts = (await runCommand(\"git\", [\"rev-list\", \"--left-right\", \"--count\", `${upstream}...HEAD`], root).catch(() => \"\")).trim();\n const [behindRaw, aheadRaw] = counts.split(/\\s+/);\n behind = Number.parseInt(behindRaw ?? \"0\", 10) || 0;\n ahead = Number.parseInt(aheadRaw ?? \"0\", 10) || 0;\n changedSinceUpstream = normalizeChangedFileList(\n await runCommand(\"git\", [\"diff\", \"--name-only\", `${upstream}...HEAD`], root).catch(() => \"\"),\n );\n if (changedSinceUpstream.length > 0) {\n releaseBaseRef = upstream;\n releaseChangedFiles = changedSinceUpstream;\n }\n }\n\n if (!releaseChangedFiles || releaseChangedFiles.length === 0) {\n const hasParent = (await runCommand(\"git\", [\"rev-parse\", \"--verify\", \"--quiet\", \"HEAD^\"], root).catch(() => \"\")).trim().length > 0;\n if (hasParent) {\n const changedSinceParent = normalizeChangedFileList(\n await runCommand(\"git\", [\"diff\", \"--name-only\", \"HEAD^..HEAD\"], root).catch(() => \"\"),\n );\n if (changedSinceParent.length > 0) {\n releaseBaseRef = \"HEAD^\";\n releaseChangedFiles = changedSinceParent;\n }\n }\n }\n\n return {\n available: true,\n branch,\n upstream,\n ahead,\n behind,\n dirtyFiles: dirty,\n changedSinceUpstream,\n ...(releaseBaseRef ? { releaseBaseRef } : {}),\n ...(releaseChangedFiles ? { releaseChangedFiles } : {}),\n };\n}\n\nfunction statusLineToPath(line: string): string {\n const body = line.replace(/^[ MADRCU?!]{1,2}\\s+/, \"\").trim();\n const renamed = body.match(/.+ -> (.+)$/);\n return renamed?.[1]?.trim() ?? body;\n}\n\nconst VERSION_FILES = [\n \"package.json\",\n \"packages/core/package.json\",\n \"packages/cli/package.json\",\n \"packages/mcp/package.json\",\n \"packages/embeddings/package.json\",\n] as const;\n\nconst SHIPPABLE_PATH_PREFIXES = [\n \"packages/core/src/\",\n \"packages/cli/src/\",\n \"packages/mcp/src/\",\n \"packages/embeddings/src/\",\n];\n\nfunction isShippablePath(file: string): boolean {\n return SHIPPABLE_PATH_PREFIXES.some((prefix) => file.startsWith(prefix)) ||\n VERSION_FILES.includes(file as (typeof VERSION_FILES)[number]);\n}\n\n/** Directives that make GitHub Actions skip a whole push (matched on the cleaned message). */\nconst CI_SKIP_DIRECTIVE = /\\[skip ci\\]|\\[ci skip\\]|\\[no ci\\]|\\[skip actions\\]|\\*\\*\\*NO_CI\\*\\*\\*|skip-checks: *true/i;\n\n/**\n * commit-msg prevention for the skip-ci footgun: GitHub scans the ENTIRE commit message\n * (subject + body) for a CI-skip directive and then skips CI for the whole push. Blocking such a\n * directive ONLY when the commit also carries shippable code keeps legitimate `.ai/`-only sync\n * commits (which correctly use [skip ci]) working. Comment lines (`#…`, stripped by git) are\n * ignored so merely discussing the directive in a comment never blocks.\n */\nasync function checkCommitMessageSkipCi(\n root: string,\n msgfile: string,\n): Promise<{ block: boolean; message: string }> {\n const file = path.isAbsolute(msgfile) ? msgfile : path.join(root, msgfile);\n const raw = await readFile(file, \"utf8\").catch(() => \"\");\n const cleaned = raw\n .split(\"\\n\")\n .filter((line) => !line.startsWith(\"#\"))\n .join(\"\\n\");\n if (!CI_SKIP_DIRECTIVE.test(cleaned)) return { block: false, message: \"\" };\n\n const staged = (await runCommand(\"git\", [\"diff\", \"--cached\", \"--name-only\"], root).catch(() => \"\"))\n .split(\"\\n\")\n .map((s) => s.trim())\n .filter(Boolean);\n const shippable = staged.filter(isShippablePath);\n if (shippable.length === 0) return { block: false, message: \"\" };\n\n return {\n block: true,\n message:\n \"This commit message contains a CI-skip directive ([skip ci] / [ci skip] / [no ci]) but the commit changes shippable code:\\n\" +\n shippable.slice(0, 6).map((f) => ` - ${f}`).join(\"\\n\") +\n (shippable.length > 6 ? `\\n …and ${shippable.length - 6} more` : \"\") +\n \"\\nGitHub scans the whole commit message and would skip CI for the ENTIRE push — your code would land untested.\\n\" +\n \"Fix: reword the message so it does not contain the literal directive (e.g. write 'skip-ci'), or move the\\n\" +\n \"skip-ci sync into a separate `.ai/`-only commit.\",\n };\n}\n\ninterface ReleaseVersionState {\n lockstep: boolean;\n version?: string;\n baseVersion?: string;\n localVersionsLabel: string;\n}\n\nasync function inspectReleaseVersionState(root: string, upstream: string): Promise<ReleaseVersionState> {\n const localEntries = await Promise.all(VERSION_FILES.map(async (file) => [file, await readPackageVersion(root, file)] as const));\n const localVersions = new Map(localEntries);\n const unique = new Set([...localVersions.values()].filter(Boolean));\n const version = unique.size === 1 ? [...unique][0] : undefined;\n const localVersionsLabel = VERSION_FILES\n .map((file) => `${file}=${localVersions.get(file) ?? \"unreadable\"}`)\n .join(\", \");\n\n const baseVersion = await readPackageVersionAtRef(root, upstream, \"package.json\");\n return {\n lockstep: unique.size === 1 && localVersions.size === VERSION_FILES.length,\n ...(version ? { version } : {}),\n ...(baseVersion ? { baseVersion } : {}),\n localVersionsLabel,\n };\n}\n\nasync function readPackageVersion(root: string, relPath: string): Promise<string | undefined> {\n try {\n const data = JSON.parse(await readFile(path.join(root, relPath), \"utf8\")) as { version?: unknown };\n return typeof data.version === \"string\" ? data.version : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function readPackageVersionAtRef(root: string, ref: string, relPath: string): Promise<string | undefined> {\n try {\n const raw = await runCommand(\"git\", [\"show\", `${ref}:${relPath}`], root);\n const data = JSON.parse(raw) as { version?: unknown };\n return typeof data.version === \"string\" ? data.version : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction compareSemver(a: string, b: string): number {\n const pa = a.split(/[.-]/).map((part) => Number.parseInt(part, 10) || 0);\n const pb = b.split(/[.-]/).map((part) => Number.parseInt(part, 10) || 0);\n const len = Math.max(pa.length, pb.length, 3);\n for (let i = 0; i < len; i++) {\n const diff = (pa[i] ?? 0) - (pb[i] ?? 0);\n if (diff !== 0) return diff;\n }\n return 0;\n}\n\nasync function tagPointsAtHead(root: string, tag: string): Promise<boolean> {\n const tags = await runCommand(\"git\", [\"tag\", \"--points-at\", \"HEAD\"], root).catch(() => \"\");\n return tags.split(\"\\n\").map((line) => line.trim()).includes(tag);\n}\n\nasync function remoteTagExists(root: string, tag: string): Promise<boolean | null> {\n const branch = (await runCommand(\"git\", [\"branch\", \"--show-current\"], root).catch(() => \"\")).trim();\n const branchRemote = branch\n ? (await runCommand(\"git\", [\"config\", \"--get\", `branch.${branch}.remote`], root).catch(() => \"\")).trim()\n : \"\";\n const hasOrigin = (await runCommand(\"git\", [\"config\", \"--get\", \"remote.origin.url\"], root).catch(() => \"\")).trim().length > 0;\n const remote = branchRemote || (hasOrigin ? \"origin\" : \"\");\n if (!remote) return null;\n try {\n const out = await runCommand(\"git\", [\"ls-remote\", \"--tags\", remote, `refs/tags/${tag}`], root);\n return out.trim().length > 0;\n } catch {\n return null;\n }\n}\n\nasync function verifyGithubActionsForHead(\n root: string,\n status: GitSyncStatus,\n): Promise<EnforcementFinding[]> {\n if (!status.upstream) return [];\n if (status.ahead > 0) {\n return [{\n severity: \"info\",\n code: \"github-actions-waiting-for-push\",\n message: \"GitHub Actions verification waits until HEAD is pushed.\",\n }];\n }\n\n const remote = await githubRemoteForCurrentBranch(root);\n if (!remote) {\n return [{\n severity: \"info\",\n code: \"github-actions-not-applicable\",\n message: \"No GitHub remote was detected; GitHub Actions pipeline verification was skipped.\",\n }];\n }\n\n const sha = (await runCommand(\"git\", [\"rev-parse\", \"HEAD\"], root).catch(() => \"\")).trim();\n if (!sha) {\n return [{\n severity: \"error\",\n code: \"github-actions-head-unreadable\",\n message: \"Could not read HEAD SHA for GitHub Actions verification.\",\n fix: \"Run `git rev-parse HEAD`, then verify GitHub Actions manually before finishing.\",\n impact: 30,\n }];\n }\n\n let runs: GithubActionsRun[];\n try {\n const raw = await runCommand(\"gh\", [\n \"run\",\n \"list\",\n \"--commit\",\n sha,\n \"--limit\",\n \"50\",\n \"--json\",\n \"conclusion,databaseId,name,status,workflowName\",\n ], root);\n runs = JSON.parse(raw) as GithubActionsRun[];\n } catch {\n return [{\n severity: \"error\",\n code: \"github-actions-unverified\",\n message: \"Could not verify GitHub Actions runs for HEAD.\",\n fix: \"Install/authenticate GitHub CLI, then run `gh run list --commit $(git rev-parse HEAD)` and ensure every workflow is successful before finishing.\",\n reason: `Detected GitHub remote ${remote}, but Hivelore could not query workflow runs.`,\n impact: 50,\n }];\n }\n\n if (runs.length === 0) {\n // Pinpoint the most common cause: GitHub scans the WHOLE HEAD commit message (subject AND\n // body) for a CI-skip directive and then skips the entire push — even when it carries code.\n const headMsg = (await runCommand(\"git\", [\"log\", \"-1\", \"--pretty=%B\"], root).catch(() => \"\")).trim();\n if (/\\[skip ci\\]|\\[ci skip\\]|\\[no ci\\]|\\*\\*\\*NO_CI\\*\\*\\*|skip-checks: *true/i.test(headMsg)) {\n return [{\n severity: \"error\",\n code: \"github-actions-skipped-by-message\",\n message: \"No GitHub Actions runs for HEAD because the HEAD commit message contains a CI-skip directive ([skip ci] / [ci skip] / [no ci]) — this skips the WHOLE push, including code.\",\n fix: \"Reword the HEAD commit so its message (subject AND body) does not contain the literal skip-ci directive — write it as 'skip-ci'. Then re-push, or trigger CI manually with `gh workflow run <workflow.yml> --ref <branch>`.\",\n reason: \"GitHub scans the entire commit message; a code commit whose message includes a skip-ci directive silently skips CI for the whole push.\",\n impact: 60,\n }];\n }\n return [{\n severity: \"error\",\n code: \"github-actions-runs-missing\",\n message: \"No GitHub Actions runs were found for HEAD.\",\n fix: \"Wait for GitHub to create the workflow runs, or verify that the push was not skipped by a skip-ci head commit; rerun `hivelore enforce finish` after the runs appear.\",\n impact: 50,\n }];\n }\n\n const pending = runs.filter((run) => run.status !== \"completed\");\n if (pending.length > 0) {\n return [{\n severity: \"error\",\n code: \"github-actions-pending\",\n message: `${pending.length}/${runs.length} GitHub Actions workflow run(s) for HEAD are still pending: ${formatGithubRunNames(pending)}.`,\n fix: \"Wait for the runs to finish (`gh run watch <run-id> --exit-status`), then rerun `hivelore enforce finish`.\",\n impact: 50,\n }];\n }\n\n const failed = runs.filter((run) => run.conclusion !== \"success\");\n const failedCore = failed.filter((run) => !isExternalTransientWorkflow(run));\n const failedExternal = failed.filter((run) => isExternalTransientWorkflow(run));\n\n if (failedCore.length > 0) {\n return [{\n severity: \"error\",\n code: \"github-actions-failed\",\n message: `${failedCore.length}/${runs.length} GitHub Actions workflow run(s) for HEAD did not pass: ${formatGithubRunNames(failedCore)}.`,\n fix: \"Inspect the failed run logs with `gh run view <run-id> --log`, fix the issue, push the fix, then rerun `hivelore enforce finish`.\",\n impact: 80,\n }];\n }\n\n if (failedExternal.length > 0) {\n // Don't let a flaky external integration (e.g. SonarQube network/timeout) masquerade as a\n // product regression. Hivelore's principle is zero hard dependency on the user's environment, so\n // external workflows are advisory: surfaced as info, never blocking `finish`.\n return [{\n severity: \"info\",\n code: \"github-actions-external-transient\",\n message: `${failedExternal.length} external/transient workflow run(s) for HEAD did not pass (non-blocking): ${formatGithubRunNames(failedExternal)}. All core workflows passed.`,\n fix: \"External integrations can fail on transient network/timeout. Re-run with `gh run rerun <run-id>` if you want them green — not required to finish.\",\n }];\n }\n\n return [{\n severity: \"ok\",\n code: \"github-actions-pass\",\n message: `All ${runs.length} GitHub Actions workflow run(s) for HEAD completed successfully.`,\n }];\n}\n\n/** External integrations whose failures are advisory (flaky network/timeout), not product\n * regressions. Matched by workflow name so it works regardless of file naming. */\nfunction isExternalTransientWorkflow(run: GithubActionsRun): boolean {\n const label = `${run.workflowName ?? \"\"} ${run.name ?? \"\"}`.toLowerCase();\n return /\\bsonar(qube|cloud)?\\b|\\bcodeql\\b|\\bsnyk\\b|\\bcodecov\\b/.test(label);\n}\n\nasync function githubRemoteForCurrentBranch(root: string): Promise<string | null> {\n const branch = (await runCommand(\"git\", [\"branch\", \"--show-current\"], root).catch(() => \"\")).trim();\n const branchRemote = branch\n ? (await runCommand(\"git\", [\"config\", \"--get\", `branch.${branch}.remote`], root).catch(() => \"\")).trim()\n : \"\";\n const remoteName = branchRemote || \"origin\";\n const remoteUrl = (await runCommand(\"git\", [\"config\", \"--get\", `remote.${remoteName}.url`], root).catch(() => \"\")).trim();\n if (!isGithubRemoteUrl(remoteUrl)) return null;\n return remoteUrl;\n}\n\nfunction isGithubRemoteUrl(url: string): boolean {\n return /(^git@github\\.com:|github\\.com[/:])/.test(url);\n}\n\nfunction formatGithubRunNames(runs: GithubActionsRun[]): string {\n return runs\n .slice(0, 6)\n .map((run) => {\n const label = run.workflowName ?? run.name ?? \"workflow\";\n return run.databaseId ? `${label}#${run.databaseId}` : label;\n })\n .join(\", \");\n}\n\nfunction buildScore(findings: EnforcementFinding[], threshold = 80): EnforcementScore {\n const checks = {\n total: findings.length,\n ok: findings.filter((f) => f.severity === \"ok\").length,\n warn: findings.filter((f) => f.severity === \"warn\").length,\n error: findings.filter((f) => f.severity === \"error\").length,\n };\n const penalty = findings.reduce((sum, f) => {\n if (f.severity === \"error\") return sum + (f.impact ?? 25);\n if (f.severity === \"warn\") return sum + (f.impact ?? 8);\n return sum;\n }, 0);\n return {\n score: Math.max(0, Math.min(100, 100 - penalty)),\n threshold,\n checks,\n };\n}\n\nasync function installGitEnforcement(root: string): Promise<void> {\n const hooksDir = path.join(root, \".git\", \"hooks\");\n if (!existsSync(path.join(root, \".git\"))) {\n ui.warn(\"No .git directory found; git enforcement hooks skipped.\");\n return;\n }\n await mkdir(hooksDir, { recursive: true });\n // Resolve the CLI with a legacy fallback: developers with an older global install only have\n // the `haive` alias on PATH; the hook must not silently no-op for them.\n const resolveCli = `_hivelore() {\n if command -v hivelore >/dev/null 2>&1; then hivelore \"$@\"\n elif command -v haive >/dev/null 2>&1; then haive \"$@\"\n else return 0\n fi\n}`;\n const hooks = [\n {\n name: \"pre-commit\",\n body: `#!/bin/sh\n${ENFORCE_HOOK_MARKER}\n${resolveCli}\n_hivelore enforce check --stage pre-commit --dir . || exit $?\n`,\n },\n {\n name: \"pre-push\",\n body: `#!/bin/sh\n${ENFORCE_HOOK_MARKER}\n${resolveCli}\n_hivelore enforce check --stage pre-push --dir . || exit $?\n`,\n },\n {\n name: \"commit-msg\",\n body: `#!/bin/sh\n${ENFORCE_HOOK_MARKER}\n${resolveCli}\n_hivelore enforce commit-msg \"$1\" --dir . || exit $?\n`,\n },\n ];\n for (const hook of hooks) {\n const file = path.join(hooksDir, hook.name);\n if (existsSync(file)) {\n const current = await readFile(file, \"utf8\").catch(() => \"\");\n if (current.includes(ENFORCE_HOOK_MARKER)) {\n await writeFile(file, hook.body, \"utf8\");\n } else {\n await writeFile(file, `${current.trimEnd()}\\n\\n${hook.body}`, \"utf8\");\n }\n } else {\n await writeFile(file, hook.body, \"utf8\");\n }\n await chmod(file, 0o755);\n }\n ui.success(\"Installed blocking git enforcement hooks: pre-commit, pre-push, commit-msg\");\n}\n\nasync function installCiEnforcement(root: string): Promise<void> {\n const workflowPath = path.join(root, \".github\", \"workflows\", \"haive-enforcement.yml\");\n await mkdir(path.dirname(workflowPath), { recursive: true });\n if (existsSync(workflowPath)) {\n ui.info(\"GitHub Actions enforcement workflow already exists — skipped\");\n return;\n }\n await writeFile(workflowPath, `name: haive-enforcement\n\non:\n pull_request:\n push:\n branches: [main, master]\n\njobs:\n haive-enforcement:\n runs-on: ubuntu-latest\n permissions:\n contents: read\n steps:\n - uses: actions/checkout@v4\n with:\n fetch-depth: 0\n - uses: actions/setup-node@v4\n with:\n node-version: '20'\n - name: Install Hivelore\n run: npm install -g @hivelore/cli\n - name: Enforce Hivelore policy\n env:\n HAIVE_BASE_SHA: \\${{ github.event.pull_request.base.sha || github.event.before }}\n HAIVE_HEAD_SHA: \\${{ github.event.pull_request.head.sha || github.sha }}\n run: hivelore enforce ci\n`, \"utf8\");\n ui.success(`Created ${path.relative(root, workflowPath)}`);\n}\n\nfunction printReport(report: EnforcementReport, json: boolean, explain = false): void {\n if (json) {\n console.log(JSON.stringify(report, null, 2));\n return;\n }\n console.log(ui.bold(`Hivelore enforcement — ${report.mode}`));\n console.log(ui.dim(` root: ${report.root}`));\n console.log(ui.dim(` score: ${report.score.score}% / threshold ${report.score.threshold}%`));\n\n if (explain) {\n printFindingGroup(\"Blocking\", report.categories.blocking, \"error\");\n printFindingGroup(\"Review\", report.categories.review, \"warn\");\n printFindingGroup(\"Info\", report.categories.info, \"info\");\n } else {\n for (const finding of report.findings) printFinding(finding);\n }\n if (report.should_block) ui.error(\"Hivelore enforcement gate failed.\");\n else ui.success(\"Hivelore enforcement gate passed.\");\n}\n\nfunction printFindingGroup(\n title: string,\n findings: EnforcementFinding[],\n tone: \"error\" | \"warn\" | \"info\",\n): void {\n if (findings.length === 0) return;\n console.log();\n const heading = tone === \"error\" ? ui.red(title) : tone === \"warn\" ? ui.yellow(title) : ui.bold(title);\n console.log(ui.bold(`${heading} (${findings.length})`));\n const scoreFinding = findings.find((f) => f.code === \"enforcement-score-below-threshold\");\n for (const finding of findings.filter((f) => f.code !== \"enforcement-score-below-threshold\")) {\n printFinding(finding, true);\n }\n if (scoreFinding) printFinding(scoreFinding, true);\n}\n\nfunction printFinding(finding: EnforcementFinding, explain = false): void {\n const marker = finding.severity === \"error\"\n ? ui.red(\"✗\")\n : finding.severity === \"warn\"\n ? ui.yellow(\"⚠\")\n : finding.severity === \"ok\"\n ? ui.green(\"✓\")\n : ui.dim(\"•\");\n console.log(`${marker} ${finding.code}: ${finding.message}`);\n if (explain && finding.reason) console.log(ui.dim(` why: ${finding.reason}`));\n if (explain && finding.affected_files?.length) console.log(ui.dim(` files: ${finding.affected_files.join(\", \")}`));\n if (explain && finding.memory_ids?.length) console.log(ui.dim(` memories: ${finding.memory_ids.join(\", \")}`));\n if (finding.fix) console.log(ui.dim(`${explain ? \" repair: \" : \" fix: \"}${finding.fix}`));\n}\n\n/**\n * Turn the blocking report into one guided next step. Findings are produced in protocol order\n * (worktree clean → synced → version bumped → tag → push → CI), so the first blocking finding\n * with a fix IS the next required action. Surfacing it removes the \"assemble the steps yourself\"\n * burden that makes the exit protocol error-prone.\n */\nfunction printNextRequiredAction(report: EnforcementReport): void {\n const blocker = report.findings.find((f) => f.severity === \"error\" && f.fix);\n if (!blocker) return;\n console.log(\"\");\n console.log(ui.bold(\"→ NEXT REQUIRED ACTION\") + ui.dim(` (${blocker.code})`));\n for (const line of blocker.fix!.split(\"\\n\")) console.log(` ${line}`);\n}\n\nasync function applyLightweightRepairs(\n root: string,\n paths: ReturnType<typeof resolveHaivePaths>,\n): Promise<void> {\n await applyAutopilotRepairs(root, paths, {\n applyConfig: false,\n applyContext: true,\n applyCorpus: true,\n applyCodeMap: false,\n applyCodeSearch: true,\n }).catch(() => { /* lightweight repair is best-effort */ });\n}\n\nasync function readHookPayload(): Promise<HookPayload> {\n const raw = await readStdin(MAX_STDIN_BYTES);\n if (!raw.trim()) return {};\n try {\n return JSON.parse(raw) as HookPayload;\n } catch {\n return {};\n }\n}\n\nfunction resolveRoot(dir: string | undefined, payload: HookPayload): string | null {\n try {\n return findProjectRoot(dir ?? payload.cwd);\n } catch {\n return null;\n }\n}\n\nfunction isWriteLikeTool(payload: HookPayload): boolean {\n const tool = payload.tool_name ?? \"\";\n if ([\"Edit\", \"Write\", \"MultiEdit\", \"NotebookEdit\"].includes(tool)) return true;\n if (tool !== \"Bash\") return false;\n const command = String(payload.tool_input?.[\"command\"] ?? \"\");\n return /\\b(rm|mv|cp|mkdir|touch|tee|sed|perl|python|node|npm|pnpm|yarn|git)\\b/.test(command) ||\n />{1,2}/.test(command);\n}\n\nfunction extractToolPaths(payload: HookPayload, root: string): string[] {\n const input = payload.tool_input ?? {};\n const values: unknown[] = [\n input[\"file_path\"],\n input[\"path\"],\n input[\"notebook_path\"],\n ];\n if (Array.isArray(input[\"file_paths\"])) values.push(...input[\"file_paths\"]);\n if (Array.isArray(input[\"files\"])) values.push(...input[\"files\"]);\n\n if (payload.tool_name === \"MultiEdit\" && Array.isArray(input[\"edits\"])) {\n for (const edit of input[\"edits\"]) {\n if (edit && typeof edit === \"object\" && \"file_path\" in edit) {\n values.push((edit as { file_path?: unknown }).file_path);\n }\n }\n }\n\n const out = new Set<string>();\n for (const value of values) {\n if (typeof value !== \"string\" || !value.trim()) continue;\n out.add(normalizeToolPath(value, root));\n }\n return [...out].filter(Boolean).sort();\n}\n\nfunction normalizeToolPath(file: string, root: string): string {\n const normalized = file.replace(/\\\\/g, \"/\");\n if (!path.isAbsolute(normalized)) return normalized.replace(/^\\.\\//, \"\");\n return path.relative(root, normalized).replace(/\\\\/g, \"/\");\n}\n\nasync function missingRequiredMemoriesForFiles(\n paths: ReturnType<typeof resolveHaivePaths>,\n files: string[],\n sessionId?: string,\n): Promise<LoadedMemory[]> {\n if (!existsSync(paths.memoriesDir)) return [];\n const marker = await readRecentBriefingMarker(paths, sessionId);\n const consulted = new Set(marker?.memory_ids ?? []);\n const policyTypes = new Set([\"decision\", \"gotcha\", \"architecture\", \"convention\", \"attempt\"]);\n const all = await loadMemoriesFromDir(paths.memoriesDir);\n return all\n .filter(({ memory }) => {\n const fm = memory.frontmatter;\n if (!policyTypes.has(fm.type)) return false;\n if (fm.status !== \"validated\") return false;\n if (consulted.has(fm.id)) return false;\n return memoryMatchesAnchorPaths(memory, files);\n })\n .map(({ memory, filePath }) => ({ memory, filePath }));\n}\n\n/**\n * Hivelore-generated `.ai/` artifacts that the agent never authors — they are re-synced by the\n * lightweight repair (version header, code-map) or are pure telemetry. Requiring a human-reviewed\n * \"decision\" to cover them is friction with no value, and it caused the gate to block release\n * commits whose only \"uncovered\" change was a repair-touched artifact. Excluded from\n * decision-coverage's notion of \"changed files\". Source code and real `.ai/memories/*` still count.\n */\nfunction isGeneratedArtifact(file: string): boolean {\n if (file === \".ai/project-context.md\" || file === \".ai/code-map.json\") return true;\n if (file.startsWith(\".ai/.cache/\") || file.startsWith(\".ai/.runtime/\") || file.startsWith(\".ai/.usage/\")) return true;\n return false;\n}\n\nasync function readStdin(maxBytes: number): Promise<string> {\n if (process.stdin.isTTY) return \"\";\n return await new Promise((resolve) => {\n const chunks: Buffer[] = [];\n let total = 0;\n let done = false;\n const finish = (): void => {\n if (done) return;\n done = true;\n resolve(Buffer.concat(chunks).toString(\"utf8\"));\n };\n process.stdin.on(\"data\", (c: Buffer) => {\n total += c.length;\n if (total > maxBytes) {\n process.stdin.destroy();\n finish();\n return;\n }\n chunks.push(c);\n });\n process.stdin.on(\"end\", finish);\n process.stdin.on(\"error\", finish);\n setTimeout(finish, 2000);\n });\n}\n\n/**\n * Stage `.ai/` artifacts that a pre-commit lightweight repair just re-synced\n * (currently the project-context version header) so the release commit is atomic.\n * Best-effort — never blocks a commit. Scoped to the project-context file so it does\n * not sweep in telemetry churn (e.g. the tool-usage log) that belongs in a later sync.\n */\n/** Machine-local `.ai/` subtrees that must NOT enter the release commit — they belong in a\n * separate later `chore: hivelore sync` push (telemetry, runtime markers, derived caches). */\nconst ATOMIC_STAGE_EXCLUDE = [\"/.usage/\", \"/.runtime/\", \"/.cache/\"];\n\nasync function stageResyncedArtifacts(\n root: string,\n paths: ReturnType<typeof resolveHaivePaths>,\n): Promise<void> {\n // Stage every tracked `.ai/` file the lightweight repair just re-synced (project-context\n // version header, auto-promoted/re-validated memories, code-map) so the release commit is\n // atomic and the haive-sync workflow has nothing left to commit as a `[skip ci]` tip.\n // `git diff --name-only` lists only tracked files with UNSTAGED changes, relative to the repo\n // root — exactly the repair output. Telemetry subtrees are excluded on purpose.\n const aiRel = path.relative(root, paths.haiveDir);\n const out = await runCommand(\"git\", [\"diff\", \"--name-only\", \"--\", aiRel], root).catch(() => \"\");\n const toStage = out\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter(Boolean)\n .filter((file) => !ATOMIC_STAGE_EXCLUDE.some((excl) => `/${file}`.includes(excl)));\n if (toStage.length === 0) return;\n await runCommand(\"git\", [\"add\", \"--\", ...toStage], root).catch(() => { /* best-effort */ });\n}\n\nfunction runCommand(cmd: string, args: string[], cwd: string): Promise<string> {\n return new Promise((resolve, reject) => {\n const proc = spawn(cmd, args, { cwd, stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n let stdout = \"\";\n let stderr = \"\";\n proc.stdout.on(\"data\", (chunk) => { stdout += chunk.toString(); });\n proc.stderr.on(\"data\", (chunk) => { stderr += chunk.toString(); });\n proc.on(\"error\", reject);\n proc.on(\"close\", (code) => {\n if (code === 0) resolve(stdout);\n else reject(new Error(stderr || `${cmd} exited with code ${code}`));\n });\n });\n}\n","import { Command } from \"commander\";\nimport { runWithEnforcement } from \"./enforce.js\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface RunOptions {\n dir?: string;\n task?: string;\n}\n\nexport function registerRun(program: Command): void {\n program\n .command(\"run\")\n .description(\"Run any AI agent command inside a Hivelore-enforced session.\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .option(\"--task <text>\", \"task text used for the Hivelore briefing marker\")\n .allowUnknownOption(true)\n .argument(\"[cmd]\", \"agent command to run\")\n .argument(\"[args...]\", \"agent command arguments\")\n .action(async (cmd: string | undefined, args: string[], opts: RunOptions) => {\n if (!cmd) {\n ui.error(\"Usage: hivelore run -- <agent command> [args...]\");\n process.exit(1);\n }\n await runWithEnforcement(cmd, args, opts);\n });\n}\n","import { execFile } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { chmod, mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { Command } from \"commander\";\nimport {\n extractSensorExamples,\n findProjectRoot,\n isRetiredMemory,\n judgeProposedSensor,\n loadConfig,\n loadMemoriesFromDir,\n recordPreventionHits,\n resolveHaivePaths,\n runSensors,\n selectCommandSensors,\n sensorPatternBrittleness,\n sensorSelfCheck,\n scannableSensorTargets,\n serializeMemory,\n type CommandSensorSpec,\n type Memory,\n type Sensor,\n} from \"@hivelore/core\";\nimport { readPresumedCorrectTargets } from \"@hivelore/mcp\";\nimport { ui } from \"../utils/ui.js\";\n\nconst exec = promisify(execFile);\n\ninterface SensorsListOptions {\n json?: boolean;\n dir?: string;\n}\n\ninterface SensorsCheckOptions {\n diffFile?: string;\n json?: boolean;\n commands?: boolean;\n dir?: string;\n}\n\ninterface SensorsExportOptions {\n format?: \"grep\" | \"eslint\";\n outDir?: string;\n dir?: string;\n}\n\ninterface SensorsPromoteOptions {\n severity?: \"warn\" | \"block\";\n yes?: boolean;\n force?: boolean;\n dir?: string;\n}\n\ninterface SensorsProposeOptions {\n pattern: string;\n absent?: string;\n badExample?: string;\n severity?: string;\n message?: string;\n flags?: string;\n paths?: string;\n dir?: string;\n}\n\nexport function registerSensors(program: Command): void {\n const sensors = program\n .command(\"sensors\")\n .description(\"Operate executable sensors derived from Hivelore memories\");\n\n sensors\n .command(\"list\")\n .description(\"List memories carrying executable sensors\")\n .option(\"--json\", \"emit JSON\", false)\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: SensorsListOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n const rows = await sensorRows(paths);\n if (opts.json) {\n console.log(JSON.stringify(rows, null, 2));\n return;\n }\n if (rows.length === 0) {\n ui.warn(\"No sensors found.\");\n return;\n }\n const brittleCount = rows.filter((r) => \"brittle\" in r && r.brittle).length;\n console.log(\n ui.bold(`Hivelore sensors — ${rows.length}`) +\n (brittleCount > 0 ? ui.yellow(` (${brittleCount} brittle — see ⚠)`) : \"\"),\n );\n for (const row of rows) {\n const brittle = \"brittle\" in row ? row.brittle : undefined;\n console.log(\n ` • ${row.id} ${ui.dim(`(${row.kind}, ${row.severity})`)} ` +\n `${row.pattern ?? row.command ?? \"\"}`,\n );\n if (\"absent\" in row && row.absent) console.log(` ${ui.dim(\"only when missing:\")} ${row.absent}`);\n if (row.paths.length > 0) console.log(` ${ui.dim(\"paths:\")} ${row.paths.join(\", \")}`);\n if (row.last_fired) console.log(` ${ui.dim(\"last fired:\")} ${row.last_fired}`);\n if (brittle) console.log(` ${ui.yellow(\"⚠ brittle:\")} ${brittle} — consider rewriting or retiring this sensor`);\n }\n });\n\n sensors\n .command(\"check\")\n .description(\n \"Run regex sensors against a diff (the deterministic/computational layer); defaults to `git diff --cached`.\\n\" +\n \" Diff-scan layers: `sensors check` (regex) and `anti_patterns_check` (memory match) are components;\\n\" +\n \" `pre_commit_check` combines them; `hivelore enforce check` is THE gate that runs at commit.\",\n )\n .option(\"--diff-file <path>\", \"read unified diff from a file instead of staged changes\")\n .option(\"--json\", \"emit JSON\", false)\n .option(\"--commands\", \"ALSO execute shell/test sensors (runs repo-authored commands)\", false)\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: SensorsCheckOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n const memories = await runnableSensorMemories(paths);\n const diff = opts.diffFile\n ? await readFile(path.resolve(root, opts.diffFile), \"utf8\")\n : await stagedDiff(root);\n // Never scan `.ai/` or Hivelore-owned files — a memory body quotes the very pattern it\n // documents and would self-fire (mirrors the git-hook gate in enforce.ts).\n const targets = scannableSensorTargets(diff);\n const hits = runSensors(memories, targets);\n\n // ── Command (shell/test) sensors — the deterministic check a regex can't express ──\n // OFF by default: they execute arbitrary repo-authored commands. Opt in per-run with\n // `--commands` or per-repo with `enforcement.runCommandSensors: true`.\n const config = await loadConfig(paths);\n const runCommands = opts.commands || config.enforcement?.runCommandSensors === true;\n const changedPaths = targets.map((t) => t.path).filter(Boolean);\n const allSensorMemories = await runnableSensorMemories(paths, false);\n const commandSpecs = selectCommandSensors(allSensorMemories, changedPaths);\n const commandHits: Array<{ memory_id: string; severity: \"warn\" | \"block\"; message: string; matched_line: string }> = [];\n const commandSkipped: string[] = [];\n if (commandSpecs.length > 0 && runCommands) {\n for (const spec of commandSpecs) {\n const failed = await runCommandSensor(spec, root);\n if (failed) {\n commandHits.push({\n memory_id: spec.memory_id,\n severity: spec.severity,\n message: spec.message,\n matched_line: `command failed: ${spec.command}`,\n });\n }\n }\n } else if (commandSpecs.length > 0) {\n for (const spec of commandSpecs) commandSkipped.push(spec.memory_id);\n }\n\n // Outcome measurement: a sensor firing on a real diff is a *prevention* event — the encoded\n // lesson intercepted a known mistake before it landed. THE shared recorder bumps impact\n // (debounced) and logs the event, identically to the git-hook gate and the MCP anti-pattern gate.\n const firedIds = [...new Set([...hits, ...commandHits].map((hit) => hit.memory_id))];\n await recordPreventionHits(paths, firedIds, \"sensor\");\n\n const output = {\n scanned: memories.length,\n hits: hits.map((hit) => ({\n memory_id: hit.memory_id,\n file: hit.file,\n severity: hit.severity,\n message: hit.message,\n matched_line: hit.matched_line,\n })),\n command_hits: commandHits,\n command_skipped: commandSkipped,\n };\n if (opts.json) {\n console.log(JSON.stringify(output, null, 2));\n } else {\n const total = hits.length + commandHits.length;\n console.log(ui.bold(`Hivelore sensors check — ${total} hit(s), ${memories.length} regex + ${commandSpecs.length} command sensor(s)`));\n for (const hit of hits) {\n const marker = hit.severity === \"block\" ? ui.red(\"✗\") : ui.yellow(\"⚠\");\n console.log(` ${marker} ${hit.memory_id} ${ui.dim(`(${hit.severity})`)}`);\n if (hit.file) console.log(` ${ui.dim(\"file:\")} ${hit.file}`);\n console.log(` ${hit.message}`);\n if (hit.matched_line) console.log(` ${ui.dim(hit.matched_line)}`);\n }\n for (const hit of commandHits) {\n const marker = hit.severity === \"block\" ? ui.red(\"✗\") : ui.yellow(\"⚠\");\n console.log(` ${marker} ${hit.memory_id} ${ui.dim(`(${hit.severity}, command)`)}`);\n console.log(` ${hit.message}`);\n console.log(` ${ui.dim(hit.matched_line)}`);\n }\n if (commandSkipped.length > 0) {\n console.log(ui.dim(` ${commandSkipped.length} command sensor(s) not run — pass --commands or set enforcement.runCommandSensors.`));\n }\n }\n if ([...hits, ...commandHits].some((hit) => hit.severity === \"block\")) process.exitCode = 1;\n });\n\n sensors\n .command(\"promote\")\n .description(\"Promote or demote an existing memory sensor severity\")\n .argument(\"<memory-id>\", \"memory id carrying the sensor\")\n .option(\"--severity <severity>\", \"block | warn\", \"block\")\n .option(\"--yes\", \"confirm promotion to block severity\", false)\n .option(\"--force\", \"promote even a brittle sensor (line-number/literal patterns) to block\", false)\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (id: string, opts: SensorsPromoteOptions) => {\n const severity = opts.severity ?? \"block\";\n if (severity !== \"block\" && severity !== \"warn\") {\n ui.error(\"--severity must be block or warn\");\n process.exitCode = 1;\n return;\n }\n if (severity === \"block\" && !opts.yes) {\n ui.error(\"Promoting a sensor to block makes the gate hard-fail. Re-run with --yes to confirm.\");\n process.exitCode = 1;\n return;\n }\n\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n const loaded = existsSync(paths.memoriesDir) ? await loadMemoriesFromDir(paths.memoriesDir) : [];\n const found = loaded.find(({ memory }) => memory.frontmatter.id === id);\n if (!found) {\n ui.error(`No memory found with id ${id}`);\n process.exitCode = 1;\n return;\n }\n const sensor = found.memory.frontmatter.sensor;\n if (!sensor) {\n ui.error(`Memory ${id} does not carry a sensor.`);\n process.exitCode = 1;\n return;\n }\n\n // Don't let a brittle pattern become a hard gate — that's how false-positive blocks train\n // agents to ignore the gate (an existential failure mode). Require --force to override.\n const brittle = sensor.kind === \"regex\" && sensor.pattern ? sensorPatternBrittleness(sensor.pattern) : null;\n if (severity === \"block\" && brittle && !opts.force) {\n ui.error(`Refusing to block on a brittle sensor (${brittle}). Rewrite the pattern, or pass --force.`);\n process.exitCode = 1;\n return;\n }\n\n // Self-validation gate: a sensor may only hard-block once it proves it discriminates — it must\n // be SILENT on the current (presumed-correct) code, and ideally FIRE on the lesson's bad example.\n // A sensor that matches correct code is precisely what trains agents to ignore the gate.\n if (severity === \"block\" && sensor.kind === \"regex\" && !opts.force) {\n const anchorPaths = sensor.paths.length > 0 ? sensor.paths : found.memory.frontmatter.anchor.paths;\n // HEAD-first: the working tree may still contain the very bad pattern being documented.\n const currentTargets = await readPresumedCorrectTargets(root, anchorPaths);\n const check = sensorSelfCheck(sensor, {\n currentTargets,\n badExamples: extractSensorExamples(found.memory.body),\n });\n if (currentTargets.length > 0 && !check.silent_on_current) {\n ui.error(\n `Refusing to block: this sensor fires on the CURRENT (presumed-correct) code in ` +\n `${check.fired_on.join(\", \")} — it would false-positive on every commit. ` +\n `Make it discriminating (add an 'absent' companion), fix the current code, or pass --force.`,\n );\n process.exitCode = 1;\n return;\n }\n if (check.fires_on_bad === true) {\n ui.success(\"Self-check passed: fires on the lesson's bad example, silent on current code.\");\n } else if (check.fires_on_bad === false) {\n ui.warn(\n \"Self-check: the sensor did NOT fire on the bad example in the lesson — it may not catch the \" +\n \"mistake. Promoting anyway (it is at least silent on the current code).\",\n );\n } else if (currentTargets.length > 0) {\n ui.info(\"Self-check: silent on current code (no bad example in the lesson to confirm firing).\");\n }\n }\n\n const next = {\n frontmatter: {\n ...found.memory.frontmatter,\n sensor: { ...sensor, severity },\n },\n body: found.memory.body,\n };\n await writeFile(found.filePath, serializeMemory(next), \"utf8\");\n ui.success(`Updated ${id}: sensor severity=${severity}`);\n if (sensor.pattern) ui.info(`pattern=${JSON.stringify(sensor.pattern)}`);\n ui.info(`message=${sensor.message}`);\n });\n\n sensors\n .command(\"propose\")\n .description(\n \"Propose a discriminating sensor for a memory — you write the pattern, Hivelore validates it before\\n\" +\n \" trusting it to block. Mirrors the MCP `propose_sensor` tool (the agent-authored path).\\n\\n\" +\n \" A `block` proposal is accepted ONLY if it is not brittle, stays SILENT on the current code,\\n\" +\n \" and FIRES on the bad example. Rejected proposals are not written — fix and re-run.\\n\\n\" +\n \" Example:\\n\" +\n \" hivelore sensors propose <memory-id> \\\\\\n\" +\n \" --pattern 'stripe\\\\.paymentIntents\\\\.create' --absent 'idempotencyKey' \\\\\\n\" +\n \" --bad-example 'stripe.paymentIntents.create({ amount })'\",\n )\n .argument(\"<memory-id>\", \"memory id to attach the sensor to\")\n .requiredOption(\"--pattern <regex>\", \"regex matching the FAULTY usage\")\n .option(\"--absent <regex>\", \"regex for the CORRECT-usage marker (makes it discriminate)\")\n .option(\"--bad-example <code>\", \"a snippet that SHOULD match (else examples are read from the lesson)\")\n .option(\"--severity <severity>\", \"block | warn\", \"block\")\n .option(\"--message <text>\", \"fix message shown when it fires\")\n .option(\"--flags <flags>\", \"regex flags (e.g. i)\")\n .option(\"--paths <csv>\", \"override scope paths (defaults to the memory anchors)\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (id: string, opts: SensorsProposeOptions) => {\n const severity = opts.severity === \"warn\" ? \"warn\" : \"block\";\n try { new RegExp(opts.pattern, opts.flags ?? \"\"); if (opts.absent) new RegExp(opts.absent, opts.flags ?? \"\"); }\n catch (err) { ui.error(`Invalid regex: ${String(err)}`); process.exitCode = 1; return; }\n\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n const loaded = existsSync(paths.memoriesDir) ? await loadMemoriesFromDir(paths.memoriesDir) : [];\n const found = loaded.find(({ memory }) => memory.frontmatter.id === id);\n if (!found) { ui.error(`No memory found with id ${id}`); process.exitCode = 1; return; }\n\n const anchorPaths = opts.paths\n ? opts.paths.split(\",\").map((s) => s.trim()).filter(Boolean)\n : found.memory.frontmatter.anchor.paths;\n // HEAD-first: the working tree may still contain the very bad pattern being documented.\n const currentTargets = await readPresumedCorrectTargets(root, anchorPaths);\n const badExamples = [\n ...(opts.badExample ? [opts.badExample] : []),\n ...extractSensorExamples(found.memory.body),\n ];\n\n const sensor: Sensor = {\n kind: \"regex\",\n pattern: opts.pattern,\n ...(opts.absent ? { absent: opts.absent } : {}),\n ...(opts.flags ? { flags: opts.flags } : {}),\n paths: anchorPaths,\n message: opts.message?.trim() || deriveProposedMessage(found.memory.body, opts.pattern, opts.absent),\n severity,\n autogen: false,\n last_fired: null,\n };\n\n const verdict = judgeProposedSensor(sensor, { currentTargets, badExamples });\n if (!verdict.accepted) {\n ui.error(`Rejected (${verdict.reason}).`);\n if (verdict.reason === \"fires-on-current\") {\n ui.warn(`Fires on the CURRENT correct code in: ${verdict.self_check.fired_on.join(\", \")}. Add/tighten --absent, then re-run.`);\n } else if (verdict.reason === \"missed-bad-example\") {\n ui.warn(\"Did not match the bad example — the pattern won't catch the mistake. Adjust --pattern, then re-run.\");\n } else if (verdict.reason === \"brittle\") {\n ui.warn(`Pattern is brittle (${verdict.brittle}). Use a durable pattern, then re-run.`);\n }\n process.exitCode = 1;\n return;\n }\n\n await writeFile(found.filePath, serializeMemory({ frontmatter: { ...found.memory.frontmatter, sensor }, body: found.memory.body }), \"utf8\");\n ui.success(`Sensor accepted (${severity}) on ${id}`);\n ui.info(`pattern=${JSON.stringify(opts.pattern)}${opts.absent ? ` absent=${JSON.stringify(opts.absent)}` : \"\"}`);\n ui.info(\n `self-check: silent on current=${verdict.self_check.silent_on_current}` +\n (verdict.self_check.fires_on_bad === null ? \"; no bad example tested\" : `; fires on bad=${verdict.self_check.fires_on_bad}`),\n );\n });\n\n sensors\n .command(\"export\")\n .description(\"Export regex sensors into .ai/generated for external toolchains\")\n .option(\"--format <format>\", \"grep | eslint\", \"grep\")\n .option(\"--out-dir <dir>\", \"output directory\", \".ai/generated\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: SensorsExportOptions) => {\n const format = opts.format ?? \"grep\";\n if (format !== \"grep\" && format !== \"eslint\") {\n ui.error(\"--format must be grep or eslint\");\n process.exitCode = 1;\n return;\n }\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n const rows = await sensorRows(paths);\n const outDir = path.resolve(root, opts.outDir ?? \".ai/generated\");\n await mkdir(outDir, { recursive: true });\n const outPath = path.join(outDir, format === \"grep\" ? \"haive-sensors-grep.sh\" : \"haive-sensors-eslint.json\");\n const content = format === \"grep\" ? renderGrepScript(rows) : JSON.stringify({ sensors: rows }, null, 2) + \"\\n\";\n await writeFile(outPath, content, \"utf8\");\n if (format === \"grep\") await chmod(outPath, 0o755);\n ui.success(`Exported ${rows.length} sensor(s): ${path.relative(root, outPath)}`);\n });\n}\n\n/** Default sensor message for a CLI-proposed sensor when --message is omitted. */\nfunction deriveProposedMessage(body: string, pattern: string, absent?: string): string {\n const instead = body.match(/\\*\\*Instead,\\s*use:\\*\\*\\s*([^\\n]+)/i)?.[1]?.trim();\n if (absent) {\n const base = `${pattern} without ${absent}`;\n return instead ? `${base} — ${instead}` : `${base} — add the required companion.`;\n }\n const heading = body\n .split(\"\\n\")\n .map((l) => l.replace(/^#+\\s*/, \"\").trim())\n .find((l) => l.length > 0 && !l.startsWith(\"---\"));\n return heading?.slice(0, 180) || `Avoid ${pattern}.`;\n}\n\nasync function sensorRows(paths: ReturnType<typeof resolveHaivePaths>) {\n const memories = await runnableSensorMemories(paths, false);\n return memories.map((memory) => {\n const sensor = memory.frontmatter.sensor!;\n const brittle = sensor.kind === \"regex\" && sensor.pattern ? sensorPatternBrittleness(sensor.pattern) : null;\n return {\n id: memory.frontmatter.id,\n kind: sensor.kind,\n severity: sensor.severity,\n pattern: sensor.pattern,\n absent: sensor.absent,\n command: sensor.command,\n paths: sensor.paths.length > 0 ? sensor.paths : memory.frontmatter.anchor.paths,\n message: sensor.message,\n autogen: sensor.autogen,\n last_fired: sensor.last_fired,\n ...(brittle ? { brittle } : {}),\n };\n });\n}\n\nasync function runnableSensorMemories(\n paths: ReturnType<typeof resolveHaivePaths>,\n regexOnly = true,\n): Promise<Memory[]> {\n if (!existsSync(paths.memoriesDir)) return [];\n const loaded = await loadMemoriesFromDir(paths.memoriesDir);\n return loaded\n .map(({ memory }) => memory)\n .filter((memory) => {\n const sensor = memory.frontmatter.sensor;\n if (!sensor) return false;\n if (regexOnly && sensor.kind !== \"regex\") return false;\n return !isRetiredMemory(memory.frontmatter, memory.body);\n });\n}\n\n/**\n * Run one shell/test sensor command. Returns true when the command FAILS (non-zero exit) — that is\n * the \"the bad state is present\" signal. A timeout or spawn error counts as a failure too (the check\n * couldn't confirm the good state). Never throws.\n */\nasync function runCommandSensor(spec: CommandSensorSpec, root: string): Promise<boolean> {\n try {\n await exec(\"bash\", [\"-c\", spec.command], { cwd: root, timeout: 120_000, maxBuffer: 8 * 1024 * 1024 });\n return false; // exit 0 → good state, no hit\n } catch {\n return true; // non-zero exit / timeout / spawn error → hit\n }\n}\n\nasync function stagedDiff(root: string): Promise<string> {\n try {\n const { stdout } = await exec(\"git\", [\"diff\", \"--cached\"], { cwd: root });\n return stdout;\n } catch (err) {\n throw new Error(`git diff --cached failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nfunction renderGrepScript(rows: Awaited<ReturnType<typeof sensorRows>>): string {\n const lines = [\n \"#!/usr/bin/env bash\",\n \"set -euo pipefail\",\n \"status=0\",\n \"\",\n ];\n for (const row of rows.filter((item) => item.kind === \"regex\" && item.pattern)) {\n const paths = row.paths.length > 0 ? row.paths : [\".\"];\n for (const p of paths) {\n lines.push(`if grep -RInE -- ${shellQuote(row.pattern!)} ${shellQuote(p)}; then`);\n lines.push(` echo ${shellQuote(`Hivelore sensor ${row.id}: ${row.message}`)}`);\n if (row.severity === \"block\") lines.push(\" status=1\");\n lines.push(\"fi\");\n lines.push(\"\");\n }\n }\n lines.push(\"exit $status\", \"\");\n return lines.join(\"\\n\");\n}\n\nfunction shellQuote(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n}\n","/**\n * CI USAGE — integrate hivelore ingest in your pipeline:\n *\n * # ESLint / any SARIF emitter\n * eslint --format @microsoft/eslint-formatter-sarif --output-file eslint.sarif src/\n * hivelore ingest --from sarif eslint.sarif --scope team --min-severity major\n *\n * # SonarQube file export\n * hivelore ingest --from sonar sonar-issues.json --scope team --min-severity major\n *\n * # SonarQube live API (no file needed — Node 18+)\n * hivelore ingest --from sonar-api \\\n * --sonar-url \"$SONAR_HOST_URL\" --sonar-token \"$SONAR_TOKEN\" \\\n * --sonar-component my_project --min-severity major\n *\n * # Dry-run to preview without writing\n * hivelore ingest --from sarif report.sarif --dry-run\n *\n * Exit codes: 0 = success (even when nothing new), 1 = bad args or unreadable report.\n * New memories are status=proposed; a human validates them with `hivelore memory pending`.\n */\nimport { existsSync } from \"node:fs\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n draftsFromFindings,\n filterNewDrafts,\n findProjectRoot,\n loadMemoriesFromDir,\n memoryFilePath,\n parseFindings,\n resolveHaivePaths,\n serializeMemory,\n type FindingSeverity,\n type MemoryDraft,\n} from \"@hivelore/core\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface IngestOptions {\n from?: \"sarif\" | \"sonar\" | \"sonar-api\" | \"eslint\" | \"npm-audit\";\n dryRun?: boolean;\n scope?: \"personal\" | \"team\" | \"module\";\n module?: string;\n type?: \"gotcha\" | \"convention\";\n minSeverity?: FindingSeverity;\n includeStylistic?: boolean;\n limit?: string;\n author?: string;\n json?: boolean;\n sonarUrl?: string;\n sonarToken?: string;\n sonarComponent?: string;\n sonarBranch?: string;\n dir?: string;\n}\n\nconst SEVERITIES: FindingSeverity[] = [\"info\", \"minor\", \"major\", \"critical\", \"blocker\"];\n\nexport function registerIngest(program: Command): void {\n program\n .command(\"ingest\")\n .description(\n \"Ingest scanner findings (SonarQube / SARIF) as proposed, anchored memories with sensors.\\n\\n\" +\n \" Closes the review↔memory loop: a real defect a scanner found becomes a `gotcha`/`convention`\\n\" +\n \" memory anchored to the file, pre-filled with a conservative `warn` sensor, so the next agent\\n\" +\n \" is steered away from it. Drafts are status=proposed; a human validates/promotes them.\\n\\n\" +\n \" `sonar-api` fetches issues live over plain HTTPS from any SonarQube/SonarCloud instance —\\n\" +\n \" no MCP or special setup required, just a URL + token you provide (or SONAR_HOST_URL /\\n\" +\n \" SONAR_TOKEN env). If you don't use it, file-based ingest works exactly the same.\\n\\n\" +\n \" Example:\\n\" +\n \" hivelore ingest --from eslint eslint-report.json --min-severity major\\n\" +\n \" hivelore ingest --from npm-audit audit.json --scope team\\n\" +\n \" hivelore ingest --from sarif report.sarif --dry-run\\n\" +\n \" hivelore ingest --from sonar sonar-issues.json --scope team --min-severity major\\n\" +\n \" hivelore ingest --from sonar-api --sonar-component my_project --min-severity major\\n\\n\" +\n \" Generate the input reports:\\n\" +\n \" eslint -f json -o eslint-report.json . # --from eslint\\n\" +\n \" npm audit --json > audit.json # --from npm-audit\\n\",\n )\n .argument(\"[file]\", \"path to the findings report JSON (required for --from sarif|sonar|eslint|npm-audit)\")\n .requiredOption(\"--from <format>\", \"report format: sarif | sonar | sonar-api | eslint | npm-audit\")\n .option(\"--dry-run\", \"show what would be created without writing\", false)\n .option(\"--scope <scope>\", \"memory scope: personal | team | module\", \"team\")\n .option(\"--module <name>\", \"module name (required when scope=module)\")\n .option(\"--type <type>\", \"memory type: gotcha | convention\", \"gotcha\")\n .option(\"--min-severity <severity>\", \"ignore findings below this severity (info|minor|major|critical|blocker)\")\n .option(\"--include-stylistic\", \"also ingest auto-fixable stylistic rules (semi/quotes/prefer-const…); off by default as low-value noise\", false)\n .option(\"--limit <n>\", \"cap the number of memories created\")\n .option(\"--author <author>\", \"author email or handle\")\n .option(\"--json\", \"emit JSON\", false)\n .option(\"--sonar-url <url>\", \"SonarQube base URL for --from sonar-api (or env SONAR_HOST_URL)\")\n .option(\"--sonar-token <token>\", \"SonarQube token for --from sonar-api (or env SONAR_TOKEN)\")\n .option(\"--sonar-component <key>\", \"SonarQube project/component key for --from sonar-api\")\n .option(\"--sonar-branch <branch>\", \"optional SonarQube branch for --from sonar-api\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (file: string | undefined, opts: IngestOptions) => {\n const format = opts.from;\n const VALID_FORMATS = [\"sarif\", \"sonar\", \"sonar-api\", \"eslint\", \"npm-audit\"] as const;\n if (!format || !(VALID_FORMATS as readonly string[]).includes(format)) {\n ui.error(`--from must be one of: ${VALID_FORMATS.join(\", \")}`);\n process.exitCode = 1;\n return;\n }\n if (opts.type && opts.type !== \"gotcha\" && opts.type !== \"convention\") {\n ui.error(\"--type must be gotcha or convention\");\n process.exitCode = 1;\n return;\n }\n if (opts.minSeverity && !SEVERITIES.includes(opts.minSeverity)) {\n ui.error(`--min-severity must be one of: ${SEVERITIES.join(\", \")}`);\n process.exitCode = 1;\n return;\n }\n\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.haiveDir)) {\n ui.error(`No .ai/ found at ${root}. Run \\`hivelore init\\` first.`);\n process.exitCode = 1;\n return;\n }\n\n // `sonar-api` parses with the same Sonar reader; only the source differs (HTTP vs file).\n const parseFormat: \"sarif\" | \"sonar\" | \"eslint\" | \"npm-audit\" =\n format === \"sonar-api\" ? \"sonar\" : format;\n\n let raw: string;\n if (format === \"sonar-api\") {\n const fetched = await fetchSonarIssues(opts);\n if (!fetched.ok) {\n ui.error(fetched.error);\n process.exitCode = 1;\n return;\n }\n raw = fetched.json;\n } else {\n if (!file) {\n ui.error(`--from ${format} needs a report file argument, e.g. \\`hivelore ingest --from ${format} report.json\\`.`);\n process.exitCode = 1;\n return;\n }\n const reportPath = path.resolve(root, file);\n if (!existsSync(reportPath)) {\n ui.error(`Report file not found: ${reportPath}`);\n process.exitCode = 1;\n return;\n }\n try {\n raw = await readFile(reportPath, \"utf8\");\n } catch (err) {\n ui.error(`Could not read ${reportPath}: ${err instanceof Error ? err.message : String(err)}`);\n process.exitCode = 1;\n return;\n }\n }\n\n let drafts: MemoryDraft[];\n let findingsCount = 0;\n try {\n const findings = parseFindings(parseFormat, raw, { cwd: root });\n findingsCount = findings.length;\n drafts = draftsFromFindings(findings, {\n type: opts.type ?? \"gotcha\",\n scope: opts.scope ?? \"team\",\n module: opts.module,\n author: opts.author,\n ...(opts.minSeverity ? { minSeverity: opts.minSeverity } : {}),\n ...(opts.includeStylistic ? { includeStylistic: true } : {}),\n ...(opts.limit ? { limit: Math.max(0, Number.parseInt(opts.limit, 10) || 0) } : {}),\n });\n } catch (err) {\n ui.error(`Failed to parse ${format} report: ${err instanceof Error ? err.message : String(err)}`);\n process.exitCode = 1;\n return;\n }\n\n // Cross-run dedup: skip findings already ingested (same `ingest:<key>` topic).\n const existing = existsSync(paths.memoriesDir) ? await loadMemoriesFromDir(paths.memoriesDir) : [];\n const existingTopics = new Set(\n existing.map(({ memory }) => memory.frontmatter.topic).filter((t): t is string => Boolean(t)),\n );\n const fresh = filterNewDrafts(drafts, existingTopics);\n const skipped = drafts.length - fresh.length;\n\n if (opts.json) {\n const created: string[] = [];\n if (!opts.dryRun) {\n for (const draft of fresh) created.push(await writeDraft(paths, draft));\n }\n console.log(\n JSON.stringify(\n {\n format,\n findings: findingsCount,\n parsed: drafts.length,\n filtered_low_value: Math.max(0, findingsCount - drafts.length),\n new: fresh.length,\n skipped_existing: skipped,\n dry_run: Boolean(opts.dryRun),\n drafts: fresh.map((d) => ({\n id: d.frontmatter.id,\n topic: d.topic,\n path: d.finding.path,\n rule: d.finding.ruleId,\n severity: d.finding.severity,\n has_sensor: d.has_sensor,\n })),\n },\n null,\n 2,\n ),\n );\n return;\n }\n\n const filteredLowValue = Math.max(0, findingsCount - drafts.length);\n console.log(\n ui.bold(\n `Hivelore ingest (${format}) — ${findingsCount} finding(s), ${fresh.length} new` +\n (filteredLowValue > 0 ? `, ${filteredLowValue} low-value/stylistic filtered` : \"\") +\n (skipped > 0 ? `, ${skipped} already ingested` : \"\"),\n ),\n );\n if (fresh.length === 0) {\n ui.info(\"Nothing to ingest.\");\n return;\n }\n\n for (const draft of fresh) {\n const sensorTag = draft.has_sensor ? ui.dim(\" +sensor\") : \"\";\n console.log(\n ` • ${draft.finding.ruleId} ${ui.dim(`(${draft.finding.severity})`)} → ${draft.finding.path}${sensorTag}`,\n );\n if (opts.dryRun) console.log(` ${ui.dim(\"would create:\")} ${draft.frontmatter.id}`);\n }\n\n if (opts.dryRun) {\n ui.info(`Dry run — nothing written. Re-run without --dry-run to create ${fresh.length} proposed memory(ies).`);\n return;\n }\n\n let created = 0;\n for (const draft of fresh) {\n await writeDraft(paths, draft);\n created++;\n }\n ui.success(`Created ${created} proposed memory(ies) under ${path.relative(root, paths.memoriesDir)}/`);\n ui.info(\"Review with `hivelore memory pending`; promote sensors with `hivelore sensors promote <id> --yes`.\");\n });\n}\n\nasync function writeDraft(paths: ReturnType<typeof resolveHaivePaths>, draft: MemoryDraft): Promise<string> {\n const file = memoryFilePath(paths, draft.frontmatter.scope, draft.frontmatter.id, draft.frontmatter.module);\n await mkdir(path.dirname(file), { recursive: true });\n await writeFile(file, serializeMemory({ frontmatter: draft.frontmatter, body: draft.body }), \"utf8\");\n return file;\n}\n\ntype SonarFetchResult = { ok: true; json: string } | { ok: false; error: string };\n\n/**\n * Fetch open issues from any SonarQube / SonarCloud instance over plain HTTPS, using the\n * SonarQube Web API (`/api/issues/search`). This is deliberately MCP-free and dependency-free\n * (Node's built-in fetch) so Hivelore works on any project: credentials are supplied by the user\n * via flags or env, and when they are absent this returns a clear error instead of crashing —\n * file-based ingest (`--from sonar|sarif`) is always available regardless.\n */\nasync function fetchSonarIssues(opts: IngestOptions): Promise<SonarFetchResult> {\n const baseUrl = (opts.sonarUrl ?? process.env.SONAR_HOST_URL ?? \"\").trim().replace(/\\/+$/, \"\");\n const token = (opts.sonarToken ?? process.env.SONAR_TOKEN ?? \"\").trim();\n const component = (opts.sonarComponent ?? \"\").trim();\n\n if (!baseUrl) {\n return { ok: false, error: \"--from sonar-api needs --sonar-url (or env SONAR_HOST_URL).\" };\n }\n if (!token) {\n return { ok: false, error: \"--from sonar-api needs --sonar-token (or env SONAR_TOKEN).\" };\n }\n if (!component) {\n return { ok: false, error: \"--from sonar-api needs --sonar-component <projectKey>.\" };\n }\n if (typeof fetch !== \"function\") {\n return { ok: false, error: \"global fetch is unavailable — Node 18+ is required for --from sonar-api.\" };\n }\n\n const params = new URLSearchParams({ componentKeys: component, resolved: \"false\", ps: \"500\" });\n if (opts.sonarBranch) params.set(\"branch\", opts.sonarBranch);\n const url = `${baseUrl}/api/issues/search?${params.toString()}`;\n\n try {\n const res = await fetch(url, {\n headers: { Authorization: `Bearer ${token}`, Accept: \"application/json\" },\n });\n if (!res.ok) {\n const hint = res.status === 401 || res.status === 403 ? \" (check the token and its permissions)\" : \"\";\n return { ok: false, error: `SonarQube API returned ${res.status} ${res.statusText}${hint}.` };\n }\n const json = await res.text();\n return { ok: true, json };\n } catch (err) {\n return {\n ok: false,\n error: `Could not reach SonarQube at ${baseUrl}: ${err instanceof Error ? err.message : String(err)}. File-based ingest (--from sonar) still works.`,\n };\n }\n}\n","import { existsSync } from \"node:fs\";\nimport { Command } from \"commander\";\nimport {\n buildDashboard,\n findProjectRoot,\n loadConfig,\n loadMemoriesFromDir,\n loadPreventionEvents,\n loadUsageIndex,\n resolveHaivePaths,\n type DashboardReport,\n} from \"@hivelore/core\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface DashboardOptions {\n json?: boolean;\n top?: string;\n dormantDays?: string;\n dir?: string;\n}\n\nexport function registerDashboard(program: Command): void {\n program\n .command(\"dashboard\")\n .description(\n \"Non-interactive observability snapshot of the memory corpus.\\n\\n\" +\n \" One-shot rollup an agent or CI can read (unlike `hivelore tui`, no TTY needed):\\n\" +\n \" inventory, impact tiers + top memories, sensors (and which ones fired),\\n\" +\n \" health (stale / anchorless / pending / prune candidates), decay, and corpus weight.\\n\" +\n \" Use --json to pipe it into other tooling.\",\n )\n .option(\"--json\", \"emit the full report as JSON\", false)\n .option(\"--top <n>\", \"rows per top-list\", \"10\")\n .option(\"--dormant-days <n>\", \"dormancy window for impact scoring\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: DashboardOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.haiveDir)) {\n ui.error(`No .ai/ found at ${root}. Run \\`hivelore init\\` first.`);\n process.exitCode = 1;\n return;\n }\n\n const memories = existsSync(paths.memoriesDir) ? await loadMemoriesFromDir(paths.memoriesDir) : [];\n const usage = await loadUsageIndex(paths);\n const preventionEvents = await loadPreventionEvents(paths);\n const config = await loadConfig(paths);\n const top = Math.max(1, Number.parseInt(opts.top ?? \"10\", 10) || 10);\n const dormantDays = opts.dormantDays ? Number.parseInt(opts.dormantDays, 10) : undefined;\n const report = buildDashboard(memories, usage, {\n top,\n preventionEvents,\n antiPatternGate: config.enforcement?.antiPatternGate ?? \"anchored\",\n ...(dormantDays !== undefined && Number.isFinite(dormantDays) ? { dormantDays } : {}),\n });\n\n if (opts.json) {\n console.log(JSON.stringify(report, null, 2));\n return;\n }\n\n renderDashboard(report);\n });\n}\n\nfunction renderDashboard(r: DashboardReport): void {\n const { inventory: inv, impact, sensors, health, decay, corpus, prevention, gate_precision: gate } = r;\n\n console.log(ui.bold(\"Hivelore dashboard\"));\n console.log(\n ` ${ui.dim(\"corpus:\")} ${inv.total} policy memor${inv.total === 1 ? \"y\" : \"ies\"} ` +\n `(${inv.active} active, ${inv.retired} retired) · ${inv.session_recaps} recap(s) · ` +\n `~${corpus.est_tokens.toLocaleString()} tokens`,\n );\n console.log(` ${ui.dim(\"scopes:\")} ${formatCounts(inv.by_scope)}`);\n console.log(` ${ui.dim(\"types: \")} ${formatCounts(inv.by_type)}`);\n\n // ── Value vs cost (the honest one-line answer to \"is Hivelore earning its keep?\") ──\n console.log();\n console.log(ui.bold(\"Value\") + ui.dim(\" (what Hivelore demonstrably earned — vs its per-task cost)\"));\n const blocked = prevention.trend.last_30d;\n const demonstrated = impact.high;\n console.log(\n ` ${blocked > 0 ? ui.green(`${blocked} repeat${blocked === 1 ? \"\" : \"s\"} blocked (30d)`) : \"0 repeats blocked (30d)\"}` +\n ` · ${demonstrated} high-impact memor${demonstrated === 1 ? \"y\" : \"ies\"} (applied/prevented)` +\n ` · ${inv.active} active polic${inv.active === 1 ? \"y\" : \"ies\"} surfaceable`,\n );\n console.log(\n ui.dim(\n \" Cost is real: the briefing adds context to every task; the payoff is downstream (defects/incidents avoided), not the agent's token bill.\",\n ),\n );\n\n // ── Prevention (outcome) ──\n console.log();\n console.log(ui.bold(\"Prevention\") + ui.dim(\" (caught-for-you outcome)\"));\n console.log(\n ` ${prevention.trend.last_30d} catch${prevention.trend.last_30d === 1 ? \"\" : \"es\"} in 30d` +\n ` · ${prevention.recurrence.recurring_count} recurrence${prevention.recurrence.recurring_count === 1 ? \"\" : \"s\"} to review` +\n ` · ${prevention.trend.last_7d} in 7d`,\n );\n console.log(\n ` ${prevention.total_events > 0 ? ui.green(`${prevention.total_events} total catch event(s)`) : \"0 total catch events\"}` +\n ` · ${prevention.memories_with_catches} memor${prevention.memories_with_catches === 1 ? \"y\" : \"ies\"} with catches` +\n ` ${ui.dim(\"weekly\")} [${prevention.trend.weekly.join(\" \")}]`,\n );\n for (const p of prevention.top.slice(0, 5)) {\n console.log(\n ` ${ui.green(\"✓\")} ${p.prevented_count}× ${p.id}` +\n (p.last_prevented_at ? ui.dim(` last ${p.last_prevented_at.slice(0, 10)}`) : \"\"),\n );\n }\n if (prevention.recurrence.recurring_count > 0) {\n for (const r of prevention.recurrence.top.slice(0, 5)) {\n console.log(` ${ui.yellow(\"↻\")} ${r.distinct_days} days · ${r.catches}× ${r.id}`);\n }\n }\n\n // ── Gate precision (inferential signal quality) ──\n console.log();\n console.log(ui.bold(\"Gate precision\") + ui.dim(\" (is the anti-pattern gate real or noisy?)\"));\n const precisionLabel =\n gate.precision === null\n ? ui.dim(\"no signal yet\")\n : gate.precision >= 0.7\n ? ui.green(`${Math.round(gate.precision * 100)}%`)\n : ui.yellow(`${Math.round(gate.precision * 100)}%`);\n console.log(\n ` ${precisionLabel} precision · ${gate.useful} useful (sensor ${gate.sensor_catches} · anti-pattern ${gate.anti_pattern_catches}) · ` +\n `${gate.rejections > 0 ? ui.yellow(`${gate.rejections} rejected`) : \"0 rejected\"}`,\n );\n if (gate.suggestion) {\n ui.info(`Tuning: set enforcement.antiPatternGate=\"${gate.suggestion.recommended}\" — ${gate.suggestion.reason}`);\n }\n\n // ── Impact ──\n console.log();\n console.log(ui.bold(\"Impact\"));\n console.log(\n ` ${ui.green(`high ${impact.high}`)} · ${ui.yellow(`medium ${impact.medium}`)} · ` +\n `low ${impact.low} · ${ui.dim(`dormant ${impact.dormant}`)} · ` +\n `${impact.prune_candidates > 0 ? ui.red(`prune ${impact.prune_candidates}`) : \"prune 0\"}`,\n );\n if (impact.top.length > 0) {\n console.log(ui.dim(\" top by demonstrated utility:\"));\n for (const row of impact.top.filter((x) => x.score > 0).slice(0, 8)) {\n console.log(\n ` ${tierMark(row.tier)} ${row.score.toFixed(2)} ${row.id}` +\n (row.signals.length ? ui.dim(` [${row.signals.join(\", \")}]`) : \"\"),\n );\n }\n }\n\n // ── Sensors ──\n console.log();\n console.log(ui.bold(\"Sensors\"));\n console.log(\n ` ${sensors.total} total · ${sensors.block} block · ${sensors.warn} warn · ` +\n `${ui.dim(`${sensors.autogen} autogen`)} · ${sensors.fired > 0 ? ui.green(`${sensors.fired} fired`) : \"0 fired\"}`,\n );\n for (const s of sensors.recently_fired.slice(0, 5)) {\n const marker = s.severity === \"block\" ? ui.red(\"✗\") : ui.yellow(\"⚠\");\n console.log(` ${marker} ${s.id} ${ui.dim(`last fired ${s.last_fired.slice(0, 10)}`)}`);\n }\n\n // ── Health ──\n console.log();\n console.log(ui.bold(\"Health\"));\n console.log(\n ` stale ${warnNum(health.stale)} · anchorless ${warnNum(health.anchorless)} · ` +\n `pending ${health.pending} · prune candidates ${warnNum(health.prune_candidates)}`,\n );\n if (health.anchorless > 0) {\n ui.info(\"Anchorless validated decisions/gotchas can't detect drift — add `paths`/`symbols`.\");\n }\n\n // ── Decay ──\n console.log();\n console.log(ui.bold(`Decay (>${decay.decay_days}d)`));\n console.log(` ${decay.decaying} decaying memor${decay.decaying === 1 ? \"y\" : \"ies\"}`);\n for (const d of decay.top_dormant.slice(0, 5)) {\n const last = d.last_read_at ? d.last_read_at.slice(0, 10) : \"never read\";\n console.log(` ${ui.dim(String(d.age_days).padStart(4) + \"d\")} ${d.id} ${ui.dim(`(${last})`)}`);\n }\n if (health.prune_candidates > 0 || decay.decaying > 0) {\n console.log();\n ui.info(\"Review low-value memories with `hivelore memory impact` and `hivelore memory lint`.\");\n }\n}\n\nfunction formatCounts(map: Record<string, number>): string {\n const entries = Object.entries(map).sort((a, b) => b[1] - a[1]);\n if (entries.length === 0) return \"none\";\n return entries.map(([k, v]) => `${k} ${v}`).join(\", \");\n}\n\nfunction tierMark(tier: string): string {\n if (tier === \"high\") return ui.green(\"●\");\n if (tier === \"medium\") return ui.yellow(\"●\");\n if (tier === \"dormant\") return ui.dim(\"○\");\n return \"·\";\n}\n\nfunction warnNum(n: number): string {\n return n > 0 ? ui.yellow(String(n)) : String(n);\n}\n","import { execFile } from \"node:child_process\";\nimport { cp, readFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { Command } from \"commander\";\nimport { findProjectRoot } from \"@hivelore/core\";\nimport { ui } from \"../utils/ui.js\";\n\nconst exec = promisify(execFile);\n\ninterface DevLinkOptions {\n dir?: string;\n json?: boolean;\n}\n\n/**\n * Copy the repo's freshly-built `dist/` into the globally-installed `@hivelore/*` so the `haive`\n * binary (and the MCP server / git hooks that shell out to it) run your LOCAL code — without an\n * npm publish cycle. Codifies the hot-swap recipe that was previously a copy-paste shell snippet,\n * including the nested `@hivelore/core` copies that pnpm workspaces require.\n */\nexport function registerDevLink(program: Command): void {\n const dev = program.commands.find((c) => c.name() === \"dev\") ?? program.command(\"dev\").description(\"Developer utilities for working on Hivelore itself.\");\n dev\n .command(\"link\")\n .description(\"Hot-swap this repo's built dist into the global @hivelore (or legacy @hiveai) install so the global binary runs your local code.\")\n .option(\"-d, --dir <dir>\", \"repo root (default: discovered from cwd)\")\n .option(\"--json\", \"emit a machine-readable summary\", false)\n .action(async (opts: DevLinkOptions) => {\n const root = findProjectRoot(opts.dir);\n if (!existsSync(path.join(root, \"packages\", \"cli\", \"dist\", \"index.js\"))) {\n ui.error(`Not the Hivelore monorepo (no packages/cli/dist) at ${root}. Run \\`pnpm -r build\\` first, or pass --dir.`);\n process.exitCode = 1;\n return;\n }\n\n let globalModules: string;\n try {\n globalModules = (await exec(\"npm\", [\"root\", \"-g\"])).stdout.trim();\n } catch {\n // Fallback: derive from the running node binary (…/bin/node → …/lib/node_modules).\n globalModules = path.join(path.dirname(path.dirname(process.execPath)), \"lib\", \"node_modules\");\n }\n // Transition: prefer the new @hivelore scope, fall back to a legacy @hiveai global install.\n const scopeDirs = [\"@hivelore\", \"@hiveai\"]\n .map((scope) => path.join(globalModules, scope))\n .filter((dir) => existsSync(dir));\n if (scopeDirs.length === 0) {\n ui.error(`No global @hivelore (or legacy @hiveai) install under ${globalModules}. Install once with \\`npm i -g @hivelore/cli\\`, then re-run.`);\n process.exitCode = 1;\n return;\n }\n\n const linked: string[] = [];\n const copyDist = async (fromPkg: string, toDistDir: string): Promise<void> => {\n const from = path.join(root, \"packages\", fromPkg, \"dist\");\n if (!existsSync(from) || !existsSync(path.dirname(toDistDir))) return;\n await cp(from, toDistDir, { recursive: true });\n linked.push(path.relative(globalModules, toDistDir));\n };\n\n // The globally-installed packages are cli and mcp; core/embeddings live nested inside them.\n for (const globalHive of scopeDirs) {\n const nestedScope = path.basename(globalHive);\n for (const pkg of [\"cli\", \"mcp\"] as const) {\n await copyDist(pkg, path.join(globalHive, pkg, \"dist\"));\n // Nested workspace deps that pnpm placed under each package.\n for (const nested of [\"core\", \"embeddings\"] as const) {\n await copyDist(nested, path.join(globalHive, pkg, \"node_modules\", nestedScope, nested, \"dist\"));\n }\n }\n // A top-level core (npm-flat installs) if present.\n await copyDist(\"core\", path.join(globalHive, \"core\", \"dist\"));\n }\n\n let version = \"unknown\";\n try {\n version = JSON.parse(await readFile(path.join(root, \"package.json\"), \"utf8\")).version ?? \"unknown\";\n } catch { /* ignore */ }\n\n if (opts.json) {\n console.log(JSON.stringify({ ok: linked.length > 0, version, global_roots: scopeDirs, linked }, null, 2));\n return;\n }\n if (linked.length === 0) {\n ui.warn(\"Nothing linked — no matching dist targets were found in the global install.\");\n return;\n }\n ui.success(`Linked local dist (v${version}) into the global install(s): ${scopeDirs.map((d) => path.basename(d)).join(\", \")}`);\n for (const t of linked) console.log(` ${ui.dim(\"→\")} ${t}`);\n console.log(ui.dim(\"The global binary now runs your local build (git hooks + MCP included).\"));\n });\n}\n","/**\n * `hivelore coverage` — harness coverage-gap report.\n *\n * Crosses the repo's hottest files (git churn) with the memory corpus to surface the\n * frequently-edited files that carry NO covering decision/convention/gotcha/architecture memory.\n * Those blind spots are where a confident agent is most likely to break an unwritten rule. The\n * inverse of `hivelore eval` (which checks the memories that exist surface correctly).\n */\nimport { readFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n findCoverageGaps,\n findProjectRoot,\n mergeHotFiles,\n resolveHaivePaths,\n tallyHotFiles,\n type HotFile,\n} from \"@hivelore/core\";\nimport { loadMemoriesFromDir } from \"../utils/fs.js\";\nimport { buildRadar } from \"../utils/briefing-radar.js\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface CoverageOptions {\n json?: boolean;\n minChanges?: string;\n limit?: string;\n days?: string;\n source?: string;\n dir?: string;\n}\n\n/**\n * Agent-edit heat: files touched by Edit/Write/Bash, captured by the `hivelore observe` PostToolUse hook\n * into `.ai/.cache/observations.jsonl`. Complements committed git churn — surfaces files agents work\n * on heavily that may not yet show up in git history (new work, uncommitted churn).\n */\nasync function readAgentHotFiles(root: string, cacheFile: string, sinceMs: number): Promise<HotFile[]> {\n if (!existsSync(cacheFile)) return [];\n const raw = await readFile(cacheFile, \"utf8\").catch(() => \"\");\n const files: string[] = [];\n for (const line of raw.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n try {\n const obs = JSON.parse(trimmed) as { ts?: string; files?: string[] };\n if (sinceMs > 0 && obs.ts) {\n const t = Date.parse(obs.ts);\n if (Number.isFinite(t) && t < sinceMs) continue;\n }\n for (const f of obs.files ?? []) {\n if (typeof f !== \"string\" || !f) continue;\n const rel = path.isAbsolute(f) ? path.relative(root, f) : f;\n // Drop paths that escape the repo (relative starts with ..) — they're not our blind spots.\n if (rel.startsWith(\"..\")) continue;\n files.push(rel);\n }\n } catch {\n // skip a corrupt observation line\n }\n }\n return tallyHotFiles(files, \"agent\");\n}\n\n/** Generated / non-source files that should never count as a coverage blind spot. */\nfunction isNoisePath(p: string): boolean {\n if (/(^|\\/)(node_modules|dist|build|coverage|\\.next)\\//.test(p)) return true;\n if (p.startsWith(\".ai/\")) return true;\n if (/\\.(jsonl|lock|map|snap|min\\.js)$/.test(p)) return true;\n if (/(^|\\/)(pnpm-lock\\.yaml|package-lock\\.json|yarn\\.lock)$/.test(p)) return true;\n if (/(^|\\/)(CHANGELOG|LICENSE)(\\.md)?$/.test(p)) return true;\n return false;\n}\n\nexport function registerCoverage(program: Command): void {\n program\n .command(\"coverage\")\n .description(\n \"Coverage-gap report: frequently-edited files with no covering team memory (blind spots).\",\n )\n .option(\"--json\", \"emit JSON\", false)\n .option(\"--min-changes <n>\", \"minimum churn count to flag a file\", \"3\")\n .option(\"--limit <n>\", \"max gaps to report\", \"20\")\n .option(\"--days <n>\", \"lookback window in days (git history + agent edits)\", \"90\")\n .option(\"--source <which>\", \"heat source: git | agent | both\", \"both\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: CoverageOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n const minChanges = Math.max(1, parseInt(opts.minChanges ?? \"3\", 10) || 3);\n const limit = Math.max(1, parseInt(opts.limit ?? \"20\", 10) || 20);\n const days = Math.max(1, parseInt(opts.days ?? \"90\", 10) || 90);\n const source = (opts.source ?? \"both\").toLowerCase();\n if (![\"git\", \"agent\", \"both\"].includes(source)) {\n ui.error(\"--source must be one of: git | agent | both\");\n process.exitCode = 1;\n return;\n }\n const useGit = source === \"git\" || source === \"both\";\n const useAgent = source === \"agent\" || source === \"both\";\n\n const radar = useGit\n ? await buildRadar({\n root,\n taskTokens: null,\n filePaths: [],\n daysBack: Math.ceil(days / 6), // getHotFiles multiplies daysBack by 6\n maxHotFiles: 500,\n })\n : null;\n const gitHotFiles: HotFile[] = (radar?.hotFiles ?? [])\n .filter((h) => !isNoisePath(h.path))\n .map((h) => ({ path: h.path, changes: h.changes, source: \"git\" as const }));\n\n const sinceMs = Date.now() - days * 86_400_000;\n const agentHotFiles: HotFile[] = useAgent\n ? (await readAgentHotFiles(root, path.join(paths.haiveDir, \".cache\", \"observations.jsonl\"), sinceMs))\n .filter((h) => !isNoisePath(h.path))\n : [];\n\n const hotFiles = mergeHotFiles(gitHotFiles, agentHotFiles);\n const memories = await loadMemoriesFromDir(paths.memoriesDir);\n const gaps = findCoverageGaps(hotFiles, memories, { minChanges, limit });\n\n if (opts.json) {\n console.log(JSON.stringify({\n root,\n source,\n scanned_hot_files: hotFiles.length,\n git_hot_files: gitHotFiles.length,\n agent_hot_files: agentHotFiles.length,\n gaps,\n }, null, 2));\n return;\n }\n\n if (useGit && radar && !radar.insideGitRepo && agentHotFiles.length === 0) {\n ui.warn(\"Not a git repository and no agent-edit history — nothing to cross-check.\");\n return;\n }\n if (gaps.length === 0) {\n ui.success(`No coverage gaps: every file changed ≥${minChanges}× is covered by a team memory.`);\n return;\n }\n console.log(ui.bold(`Hivelore coverage — ${gaps.length} blind spot(s) (hot files with no covering memory)`));\n for (const gap of gaps) {\n const src = gap.source ? ui.dim(` [${gap.source}]`) : \"\";\n console.log(` ${ui.yellow(\"○\")} ${gap.path} ${ui.dim(`(${gap.changes} change${gap.changes === 1 ? \"\" : \"s\"})`)}${src}`);\n }\n console.log(\n ui.dim(\n \"\\nAdd a decision/convention/gotcha anchored to the top files, or a sensor, to close the gap.\",\n ),\n );\n });\n}\n","/**\n * `hivelore merge-driver` — deterministic git merge driver for Hivelore memory files.\n *\n * Several agents + the human edit `.ai/` in parallel with manual pull/push, so memory files\n * (especially the topic-upsert session recap) regularly collide and leave `<<<<<<<` markers. A\n * memory has a total order in its frontmatter (revision_count → created_at), so the conflict is\n * mechanically resolvable. This registers as a git merge driver via `.gitattributes`.\n *\n * hivelore merge-driver install # one-time: git config + .gitattributes block\n * hivelore merge-driver run %O %A %B # invoked by git (writes the winner into %A, exits 0)\n */\nimport { execFileSync } from \"node:child_process\";\nimport { readFileSync, writeFileSync, existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport { findProjectRoot, mergeMemoryVersions } from \"@hivelore/core\";\nimport { ui } from \"../utils/ui.js\";\n\nconst GITATTRIBUTES_MARK = \"# Hivelore merge driver\";\nconst GITATTRIBUTES_BLOCK = [\n GITATTRIBUTES_MARK,\n \".ai/memories/**/*.md merge=haive\",\n \"# Hivelore merge driver end\",\n].join(\"\\n\");\n\nexport function registerMergeDriver(program: Command): void {\n const cmd = program\n .command(\"merge-driver\")\n .description(\"Deterministic git merge driver for Hivelore memory files (kills .ai/ conflict markers)\");\n\n cmd\n .command(\"run <base> <ours> <theirs>\")\n .description(\"Git merge-driver entrypoint: resolve ours/theirs by frontmatter order, write into <ours>\")\n .action((base: string, ours: string, theirs: string) => {\n // A merge driver MUST be robust: any throw should fall back to a real conflict (exit 1),\n // never crash git. Read ours/theirs, pick the winner, write it back into <ours>.\n try {\n const oursContent = readFileSync(ours, \"utf8\");\n const theirsContent = readFileSync(theirs, \"utf8\");\n const result = mergeMemoryVersions(oursContent, theirsContent);\n if (result.content !== oursContent) writeFileSync(ours, result.content, \"utf8\");\n // exit 0 = resolved\n process.exit(0);\n } catch {\n // Could not resolve — let git record a normal conflict.\n process.exit(1);\n }\n });\n\n cmd\n .command(\"install\")\n .description(\"Configure git + .gitattributes so memory-file conflicts auto-resolve\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action((opts: { dir?: string }) => {\n const root = findProjectRoot(opts.dir);\n try {\n execFileSync(\"git\", [\"config\", \"merge.haive.name\", \"Hivelore memory merge driver\"], { cwd: root });\n execFileSync(\"git\", [\"config\", \"merge.haive.driver\", \"hivelore merge-driver run %O %A %B\"], { cwd: root });\n } catch {\n ui.error(\"Could not set git config — is this a git repository?\");\n process.exitCode = 1;\n return;\n }\n\n const gaPath = path.join(root, \".gitattributes\");\n let content = existsSync(gaPath) ? readFileSync(gaPath, \"utf8\") : \"\";\n if (!content.includes(GITATTRIBUTES_MARK)) {\n if (content.length > 0 && !content.endsWith(\"\\n\")) content += \"\\n\";\n content += GITATTRIBUTES_BLOCK + \"\\n\";\n writeFileSync(gaPath, content, \"utf8\");\n ui.success(\"Installed Hivelore merge driver (git config + .gitattributes).\");\n } else {\n ui.info(\"Hivelore merge driver already present in .gitattributes — refreshed git config.\");\n }\n ui.info(\"Memory-file conflicts under .ai/memories/ now resolve by revision_count → created_at.\");\n });\n}\n","/**\n * `hivelore memory resolve-conflict <id_a> <id_b>` — turn a detected contradiction into a resolution.\n *\n * `hivelore memory conflict-candidates` finds pairs that contradict each other; this APPLIES the fix:\n * it deprecates the losing memory (by the deterministic order in `planConflictResolution`) and\n * stamps it with a stale_reason pointing at the winner. Keeps the corpus coherent as it grows —\n * Fowler's \"incoherence at scale\" challenge.\n */\nimport { writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { Command } from \"commander\";\nimport {\n applyConflictResolution,\n findProjectRoot,\n planConflictResolution,\n resolveHaivePaths,\n serializeMemory,\n} from \"@hivelore/core\";\nimport { loadMemoriesFromDir } from \"../utils/fs.js\";\nimport { ui } from \"../utils/ui.js\";\n\ninterface ResolveConflictOptions {\n yes?: boolean;\n json?: boolean;\n dir?: string;\n}\n\nexport function registerMemoryResolveConflict(memory: Command): void {\n memory\n .command(\"resolve-conflict <id_a> <id_b>\")\n .description(\"Resolve a contradiction: keep the stronger memory, deprecate (supersede) the other\")\n .option(\"--yes\", \"apply the resolution (without this, only previews it)\", false)\n .option(\"--json\", \"emit JSON\", false)\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (idA: string, idB: string, opts: ResolveConflictOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.memoriesDir)) {\n ui.error(`No .ai/memories at ${root}.`);\n process.exitCode = 1;\n return;\n }\n\n const memories = await loadMemoriesFromDir(paths.memoriesDir);\n const a = memories.find((m) => m.memory.frontmatter.id === idA);\n const b = memories.find((m) => m.memory.frontmatter.id === idB);\n if (!a || !b) {\n ui.error(`Memory not found: ${!a ? idA : \"\"} ${!b ? idB : \"\"}`.trim());\n process.exitCode = 1;\n return;\n }\n\n const plan = planConflictResolution(a, b);\n const winner = plan.keep_id === idA ? a : b;\n const loser = plan.supersede_id === idA ? a : b;\n const applied = applyConflictResolution(winner, loser, plan);\n\n if (opts.json) {\n console.log(JSON.stringify({\n ...plan,\n winner_revision_count: applied.winner.revision_count,\n topic: applied.topic,\n topic_adopted: applied.topic_adopted,\n applied: Boolean(opts.yes),\n }, null, 2));\n } else {\n console.log(ui.bold(\"Conflict resolution\"));\n console.log(` keep: ${ui.green(plan.keep_id)} ${ui.dim(`(rev ${winner.memory.frontmatter.revision_count}→${applied.winner.revision_count})`)}`);\n console.log(` supersede: ${ui.red(plan.supersede_id)} ${ui.dim(`→ deprecated`)}`);\n console.log(` reason: ${plan.reason}`);\n if (applied.topic) {\n console.log(` topic: ${applied.topic}${applied.topic_adopted ? ui.dim(\" (adopted from superseded — future captures upsert into the winner)\") : \"\"}`);\n }\n }\n\n if (!opts.yes) {\n if (!opts.json) ui.info(\"Preview only — re-run with --yes to apply.\");\n return;\n }\n\n // Persist BOTH: promote the winner (revision/topic) and deprecate the loser, so the corpus\n // converges on a single authoritative memory per subject instead of leaving a silent contradiction.\n await writeFile(\n winner.filePath,\n serializeMemory({ frontmatter: applied.winner, body: winner.memory.body }),\n \"utf8\",\n );\n await writeFile(\n loser.filePath,\n serializeMemory({ frontmatter: applied.loser, body: loser.memory.body }),\n \"utf8\",\n );\n if (!opts.json) {\n ui.success(`Deprecated ${plan.supersede_id}; promoted ${plan.keep_id} (rev ${applied.winner.revision_count}${applied.topic ? `, topic=${applied.topic}` : \"\"}).`);\n }\n });\n}\n","/**\n * `hivelore memory seed-git` — cold-start the corpus from git history.\n *\n * A fresh repo has no memories, so the harness has no feedforward value until the team invests.\n * Reverts and urgent fixups are the cheapest signal of a real, repo-specific mistake already paid\n * for. This scans `git log`, proposes DRAFT `attempt` seeds (never validated — human reviews), and\n * (with --apply) writes them so future briefings carry the lesson. Closes Fowler's \"legacy is hard\"\n * harnessability gap with zero manual authoring.\n */\nimport { execFile } from \"node:child_process\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { Command } from \"commander\";\nimport {\n buildFrontmatter,\n findProjectRoot,\n memoryFilePath,\n proposeSeedsFromCommits,\n resolveHaivePaths,\n serializeMemory,\n type GitCommit,\n type MemoryScope,\n} from \"@hivelore/core\";\nimport { ui } from \"../utils/ui.js\";\n\nconst exec = promisify(execFile);\n\ninterface SeedGitOptions {\n apply?: boolean;\n limit?: string;\n days?: string;\n scope?: MemoryScope;\n json?: boolean;\n dir?: string;\n}\n\nexport function registerMemorySeedGit(memory: Command): void {\n memory\n .command(\"seed-git\")\n .description(\"Propose draft `attempt` seeds from revert/hotfix commits in git history (cold-start)\")\n .option(\"--apply\", \"write the proposed seeds as draft memories (default: preview only)\", false)\n .option(\"--limit <n>\", \"max seeds to propose\", \"20\")\n .option(\"--days <n>\", \"git-history lookback window in days\", \"365\")\n .option(\"--scope <scope>\", \"personal | team\", \"team\")\n .option(\"--json\", \"emit JSON\", false)\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: SeedGitOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n if (!existsSync(paths.haiveDir)) {\n ui.error(`No .ai/ found at ${root}. Run \\`hivelore init\\` first.`);\n process.exitCode = 1;\n return;\n }\n\n const limit = Math.max(1, parseInt(opts.limit ?? \"20\", 10) || 20);\n const days = Math.max(1, parseInt(opts.days ?? \"365\", 10) || 365);\n const commits = await readCommits(root, days);\n const proposals = proposeSeedsFromCommits(commits, limit);\n\n if (opts.json) {\n console.log(JSON.stringify({ scanned_commits: commits.length, proposals, applied: Boolean(opts.apply) }, null, 2));\n } else if (proposals.length === 0) {\n ui.info(\"No revert/hotfix signals found in git history — nothing to seed.\");\n return;\n } else {\n console.log(ui.bold(`Hivelore seed-git — ${proposals.length} proposal(s) from ${commits.length} commit(s)`));\n for (const p of proposals) {\n console.log(` ${ui.yellow(\"◆\")} ${ui.dim(`[${p.kind}]`)} ${p.what}`);\n if (p.paths.length > 0) console.log(` ${ui.dim(\"paths:\")} ${p.paths.join(\", \")}`);\n }\n }\n\n if (!opts.apply) {\n if (!opts.json) ui.info(\"Preview only — re-run with --apply to write these as draft memories.\");\n return;\n }\n\n let written = 0;\n for (const p of proposals) {\n const fm = {\n ...buildFrontmatter({\n type: \"attempt\",\n slug: p.slug,\n scope: opts.scope ?? \"team\",\n tags: [\"seed\", \"git-history\", p.kind],\n paths: p.paths,\n }),\n status: \"draft\" as const, // human reviews before it becomes validated\n };\n const body = `# ${p.what}\\n\\n**Why it failed / do NOT use:** ${p.why_failed}\\n\\n_Seeded from git ${p.kind} commit ${p.source_sha}. Review and validate (or delete) — not yet authoritative._\\n`;\n const file = memoryFilePath(paths, fm.scope, fm.id, fm.module);\n if (existsSync(file)) continue;\n await mkdir(path.dirname(file), { recursive: true });\n await writeFile(file, serializeMemory({ frontmatter: fm, body }), \"utf8\");\n written += 1;\n }\n if (!opts.json) {\n ui.success(`Wrote ${written} draft seed(s). Review them: \\`hivelore memory pending\\` → validate or delete.`);\n }\n });\n}\n\n/** Read recent commits with their touched files for seeding. Best-effort; returns [] off-git. */\nasync function readCommits(root: string, days: number): Promise<GitCommit[]> {\n try {\n const { stdout } = await exec(\n \"git\",\n [\"log\", `--since=${days}.days.ago`, \"--name-only\", \"--pretty=format:%x1f%h%x1f%s\", \"-n\", \"500\"],\n { cwd: root, maxBuffer: 8 * 1024 * 1024 },\n );\n const blocks = stdout.split(\"\\x1f\").filter((b) => b.length > 0);\n const commits: GitCommit[] = [];\n for (let i = 0; i + 1 < blocks.length; i += 2) {\n const sha = blocks[i]!.trim();\n const tail = blocks[i + 1]!;\n const lines = tail.split(\"\\n\").map((l) => l.trim()).filter(Boolean);\n const subject = lines.shift() ?? \"\";\n commits.push({ sha, subject, files: lines });\n }\n return commits;\n } catch {\n return [];\n }\n}\n","import { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport {\n findProjectRoot,\n resolveHaivePaths,\n BRIDGE_TARGET_PATH,\n BRIDGE_TARGETS,\n type BridgeTarget,\n} from \"@hivelore/core\";\nimport { ui } from \"../utils/ui.js\";\nimport { getBridgeFileStatuses, writeBridgeFiles } from \"../utils/bridge-files.js\";\n\ninterface BridgesSyncOptions {\n all?: boolean;\n only?: string;\n maxMemories?: string;\n dryRun?: boolean;\n dir?: string;\n}\n\ninterface BridgesStatusOptions {\n dir?: string;\n maxMemories?: string;\n}\n\nexport function registerBridges(program: Command): void {\n const bridges = program\n .command(\"bridges\")\n .description(\n \"Generate native agent bridge files from the Hivelore corpus.\\n\" +\n \" Bridges inject top validated memories and block sensors into agent-harness-specific\\n\" +\n \" config files (.cursor/rules/haive-memories.mdc, .clinerules, .windsurfrules,\\n\" +\n \" .continuerules, .sourcegraph/cody-rules.md, .rules, AGENTS.md,\\n\" +\n \" .github/copilot-instructions.md).\\n\" +\n \" This is the reach differentiator vs memories.sh: our bridges carry enforcement, not just injection.\\n\\n\" +\n \" Example:\\n\" +\n \" hivelore bridges sync --all\\n\" +\n \" hivelore bridges sync --only cline,windsurf\\n\",\n );\n\n bridges\n .command(\"sync\")\n .description(\n \"Regenerate bridge files idempotently (marker-based, preserves manual content outside markers).\\n\" +\n \" Supported targets: \" + BRIDGE_TARGETS.join(\", \") + \"\\n\",\n )\n .option(\"--all\", \"generate all supported bridge targets\")\n .option(\n \"--only <targets>\",\n \"comma-separated list of targets to generate (e.g. cline,windsurf,agents)\",\n )\n .option(\"--max-memories <n>\", \"max memories to inject per bridge\", \"8\")\n .option(\"--dry-run\", \"show what would change without writing\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .action(async (opts: BridgesSyncOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n const dryRun = opts.dryRun === true;\n\n if (!existsSync(paths.memoriesDir)) {\n ui.warn(`No .ai/memories at ${root}. Run \\`hivelore init\\` first.`);\n process.exitCode = 1;\n return;\n }\n\n // ── Determine targets ─────────────────────────────────────────────\n let targets: BridgeTarget[];\n if (opts.only) {\n const requested = opts.only\n .split(\",\")\n .map((t) => t.trim().toLowerCase())\n .filter(Boolean);\n const invalid = requested.filter((t) => !BRIDGE_TARGETS.includes(t as BridgeTarget));\n if (invalid.length > 0) {\n ui.error(`Unknown bridge target(s): ${invalid.join(\", \")}. Valid: ${BRIDGE_TARGETS.join(\", \")}`);\n process.exitCode = 1;\n return;\n }\n targets = requested as BridgeTarget[];\n } else if (opts.all) {\n targets = BRIDGE_TARGETS;\n } else {\n // Default: generate only for files that already exist in the project.\n targets = BRIDGE_TARGETS.filter((t) =>\n existsSync(path.join(root, BRIDGE_TARGET_PATH[t])),\n );\n if (targets.length === 0) {\n ui.info(\n \"No existing bridge files detected. Pass --all to generate all targets, or \" +\n \"--only <target> to generate a specific one.\",\n );\n return;\n }\n }\n\n // ── Generate + write (delegated to the shared writer) ─────────────\n const maxMemories = Math.max(1, Number(opts.maxMemories ?? 8));\n const res = await writeBridgeFiles(root, paths, { targets, maxMemories, dryRun });\n\n if (dryRun) {\n for (const p of res.created) console.log(ui.dim(`[dry-run] would create ${p}`));\n for (const p of res.updated) console.log(ui.dim(`[dry-run] would update ${p}`));\n for (const p of res.unchanged) console.log(ui.dim(`[dry-run] unchanged ${p}`));\n for (const warning of res.warnings) ui.warn(warning);\n return;\n }\n for (const p of res.created) console.log(ui.dim(`bridges: created ${p}`));\n for (const p of res.updated) console.log(ui.dim(`bridges: updated ${p}`));\n for (const warning of res.warnings) ui.warn(warning);\n\n const parts: string[] = [];\n if (res.created.length > 0) parts.push(`${res.created.length} created`);\n if (res.updated.length > 0) parts.push(`${res.updated.length} updated`);\n if (res.unchanged.length > 0) parts.push(`${res.unchanged.length} unchanged`);\n if (res.skipped.length > 0) parts.push(`${res.skipped.length} skipped`);\n console.log(ui.dim(`bridges: ${parts.join(\" · \") || \"nothing to do\"}`));\n });\n\n // ── List subcommand ───────────────────────────────────────────────────\n bridges\n .command(\"status\")\n .alias(\"list\")\n .description(\"List bridge targets and whether their Hivelore-managed blocks are current\")\n .option(\"-d, --dir <dir>\", \"project root\")\n .option(\"--max-memories <n>\", \"max memories expected in generated bridge blocks\", \"8\")\n .action(async (opts: BridgesStatusOptions) => {\n const root = findProjectRoot(opts.dir);\n const paths = resolveHaivePaths(root);\n const statuses = await getBridgeFileStatuses(root, paths, {\n targets: BRIDGE_TARGETS,\n maxMemories: Math.max(1, Number(opts.maxMemories ?? 8)),\n });\n console.log(ui.bold(\"Hivelore bridge targets:\"));\n for (const status of statuses) {\n const marker =\n status.state === \"invalid\" ? ui.yellow(\"!\") :\n status.wouldChange ? ui.dim(\"~\") :\n status.exists ? ui.dim(\"✓\") :\n ui.dim(\"·\");\n const note =\n status.state === \"missing\" ? \"not present\" :\n status.state === \"invalid\" ? `invalid: ${status.issues.join(\"; \")}` :\n status.wouldChange ? `${status.state}, stale` :\n status.state;\n console.log(` ${marker} ${status.target.padEnd(10)} ${status.path} (${note})`);\n }\n console.log(\"\");\n console.log(ui.dim(\"Run `hivelore bridges sync --all` to create missing targets and refresh stale managed blocks.\"));\n });\n}\n"],"mappings":";;;AAAA,SAAS,WAAAA,iBAAe;;;ACAxB,SAAS,cAAAC,mBAAkB;AAC3B,SAAS,OAAO,YA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KAAK,MAAM,GAAG,EAAE,CAAC;AACnD,aAAO,WAAW,MAAM,SAAS,OAAO,OAAO,CAAC;IAClD;EACF;AAEA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAA8B;AACnC,cAAQ,OAAO,kBAAkB,MAAM,SAAS;AAChD,aAAO,WAAW,MAAM,cAAc,OAAO,OAAO,CAAC;IACvD;EACF;AAEA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAA+B;AACpC,cAAQ,OAAO,mBAAmB,GAAG,MAAM,MAAM,IAAI,MAAM,eAAe,QAAQ,EAAE;AACpF,aAAO,WAAW,MAAM,eAAe,OAAO,OAAO,CAAC;IACxD;EACF;AAEA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAA2B;AAChC,cAAQ,OAAO,eAAe,MAAM,KAAK;AACzC,aAAO,WAAW,MAAM,WAAW,OAAO,OAAO,CAAC;IACpD;EACF;AAEA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAA8B;AACnC,cAAQ,OAAO,mBAAmB,MAAM,KAAK,MAAM,GAAG,EAAE,CAAC;AACzD,aAAO,WAAW,MAAM,cAAc,OAAO,OAAO,CAAC;IACvD;EACF;AAIA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAA4B;AACjC,cAAQ,OAAO,gBAAgB,MAAM,QAAQ,EAAE;AAC/C,aAAO,WAAW,MAAM,YAAY,OAAO,OAAO,CAAC;IACrD;EACF;AAEA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAA0B;AAC/B,cAAQ,OAAO,cAAc,MAAM,MAAM,MAAM,GAAG,EAAE,CAAC;AACrD,aAAO,WAAW,MAAM,UAAU,OAAO,OAAO,CAAC;IACnD;EACF;AAEA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAA4B,WAAW,MAAM,YAAY,OAAO,OAAO,CAAC;EACjF;AAEA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAA4B,WAAW,MAAM,YAAY,OAAO,OAAO,CAAC;EACjF;AAEA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAAuB,WAAW,MAAM,OAAO,OAAO,OAAO,CAAC;EACvE;AAEA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAAwB,WAAW,MAAM,QAAQ,OAAO,OAAO,CAAC;EACzE;AAIA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UACL,WAAW,MAAM,kBAAkB,OAAO,OAAO,CAAC;EACtD;AAEA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UACL,WAAW,MAAM,qBAAqB,OAAO,OAAO,CAAC;EACzD;AAEA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAAwB,WAAW,MAAM,YAAY,OAAO,OAAO,CAAC;EAC7E;AAEA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UACL,WAAW,MAAM,kBAAkB,OAAO,OAAO,CAAC;EACtD;AAIA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAA0B,WAAW,MAAM,UAAU,OAAO,OAAO,CAAC;EAC7E;AAEA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAA0B,WAAW,MAAM,UAAU,OAAO,OAAO,CAAC;EAC7E;AAEA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAA2B,WAAW,MAAM,WAAW,OAAO,OAAO,CAAC;EAC/E;AAEA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAA0B,WAAW,MAAM,UAAU,OAAO,OAAO,CAAC;EAC7E;AAEA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAA4B,WAAW,MAAM,YAAY,OAAO,OAAO,CAAC;EACjF;AAEA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAA2B,WAAW,MAAM,WAAW,OAAO,OAAO,CAAC;EAC/E;AAEA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAA0B,WAAW,MAAM,UAAU,OAAO,OAAO,CAAC;EAC7E;AAKA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAAyB;AAC9B,cAAQ,OAAO,aAAa,MAAM,KAAK;AACvC,aAAO,WAAW,MAAM,SAAS,OAAO,OAAO,CAAC;IAClD;EACF;AAEA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAA8B;AACnC,cAAQ,OAAO,mBAAmB,MAAM,KAAK,MAAM,GAAG,EAAE,CAAC;AACzD,aAAO,WAAW,MAAM,cAAc,OAAO,OAAO,CAAC;IACvD;EACF;AAIA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAA2B;AAChC,cAAQ,OAAO,eAAe,MAAM,MAAM,MAAM,GAAG,EAAE,CAAC;AACtD,aAAO,WAAW,MAAM,WAAW,OAAO,OAAO,CAAC;IACpD;EACF;AAIA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAA4B;AACjC,cAAQ,OAAO,iBAAiB,MAAM,IAAI;AAC1C,aAAO,WAAW,MAAM,YAAY,OAAO,OAAO,CAAC;IACrD;EACF;AAIA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAAkC;AACvC,cAAQ,OAAO,uBAAuB,MAAM,MAAM,KAAK,GAAG,EAAE,MAAM,GAAG,EAAE,CAAC;AACxE,aAAO,WAAW,MAAM,kBAAkB,OAAO,OAAO,CAAC;IAC3D;EACF;AAIA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAA2B;AAChC,cAAQ,OAAO,eAAe,GAAG,MAAM,WAAW,UAAU,MAAM,UAAU,GAAG;AAC/E,aAAO,WAAW,MAAM,WAAW,OAAO,OAAO,CAAC;IACpD;EACF;AAEA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAAgC;AACrC,cAAQ,OAAO,qBAAqB,MAAM,EAAE;AAC5C,aAAO,WAAW,MAAM,gBAAgB,OAAO,OAAO,CAAC;IACzD;EACF;AAEA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAA6B;AAClC,cAAQ,OAAO,sBAAsB,MAAM,EAAE;AAC7C,aAAO,WAAW,MAAM,aAAa,OAAO,OAAO,CAAC;IACtD;EACF;AAEA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAAsC;AAC3C,cAAQ,OAAO,2BAA2B,GAAG,MAAM,UAAU,GAAG;AAChE,aAAO,WAAW,MAAM,sBAAsB,OAAO,OAAO,CAAC;IAC/D;EACF;AAEA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UACL,WAAW,MAAM,qBAAqB,OAAO,OAAO,CAAC;EACzD;AAEA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UACL,WAAW,MAAM,mBAAmB,OAAO,OAAO,CAAC;EACvD;AAEA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAA+B;AACpC,cAAQ,OAAO,oBAAoB,GAAG,MAAM,MAAM,MAAM,GAAG;AAC3D,aAAO,WAAW,MAAM,eAAe,OAAO,OAAO,CAAC;IACxD;EACF;AAEA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAA8B;AACnC,cAAQ,OAAO,kBAAkB,SAAS,MAAM,UAAU,aAAa,MAAM,OAAO,EAAE;AACtF,aAAO,WAAW,MAAM,cAAc,OAAO,OAAO,CAAC;IACvD;EACF;AAEA;IACE;IACA;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;IACF,EAAE,KAAK,IAAI;IACX;IACA,OAAO,UAAwB,WAAW,MAAM,QAAQ,OAAO,OAAO,CAAC;EACzE;AAEA,MAAI,qBAAqB,mBAAmB,GAAG;AAC7C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A,GAAG;AAAA,MACH;AAAA,MACA;AAAA,IACF,EAAE,KAAK,IAAI;AAAA,EACb;AACA,QAAM,gBAAgB,KAAK,SAAS,KAAK,CAAC,QAAQ,IAAI,KAAK,MAAM,QAAQ;AACzE,iBAAe;AAAA,IACb;AAAA,IACA;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,IACF,EAAE,KAAK,IAAI;AAAA,EACb;AACF;AAEA,SAAS,oBAAoB,SAAwB;AACnD,aAAW,SAAS,QAAQ,UAAU;AACpC,QAAI,CAAC,cAAc,SAAS,KAAK,GAAG;AAClC,MAAC,MAA0C,UAAU;AAAA,IACvD;AACA,wBAAoB,KAAK;AAAA,EAC3B;AACF;AAEA,SAAS,cAAc,QAAiB,OAAyB;AAC/D,QAAM,aAAa,OAAO,KAAK;AAC/B,QAAM,YAAY,MAAM,KAAK;AAC7B,MAAI,eAAe,WAAY,QAAO,mBAAmB,IAAI,SAAS;AACtE,MAAI,eAAe,SAAU,QAAO,qBAAqB,IAAI,SAAS;AACtE,MAAI,eAAe,UAAW,QAAO,sBAAsB,IAAI,SAAS;AACxE,SAAO;AACT;AAEA,SAAS,WACP,KACgE;AAChE,SACE,QAAQ,QACR,OAAO,QAAQ,YACf,YAAY,OACZ,MAAM,QAAS,IAAgC,MAAM;AAEzD;","names":["Command","existsSync","readFile","path","findProjectRoot","loadCodeMap","loadConfig","loadMemoriesFromDir","loadUsageIndex","resolveHaivePaths","path","existsSync","writeFile","path","loadCodeMap","loadMemoriesFromDir","path","memory","path","writeFile","existsSync","path","loadCodeMap","loadMemoriesFromDir","program","findProjectRoot","resolveHaivePaths","existsSync","readFile","loadMemoriesFromDir","path","loadConfig","loadUsageIndex","loadCodeMap","findProjectRoot","program","existsSync","path","findProjectRoot","resolveHaivePaths","program","findProjectRoot","resolveHaivePaths","existsSync","path","stat","existsSync","path","buildCodeMap","findProjectRoot","loadCodeMap","resolveHaivePaths","saveCodeMap","program","findProjectRoot","resolveHaivePaths","buildCodeMap","saveCodeMap","path","existsSync","loadCodeMap","execFile","mkdir","readFile","readdir","writeFile","existsSync","path","spawnSync","promisify","AUTOPILOT_DEFAULTS","buildCodeMap","buildFrontmatter","memoryFilePath","resolveHaivePaths","saveCodeMap","saveConfig","serializeMemory","mkdir","readFile","writeFile","existsSync","path","loadMemoriesFromDir","existing","merged","spawnSync","existsSync","mkdir","writeFile","os","path","findProjectRoot","resolveHaivePaths","readFile","writeFile","mkdir","existsSync","path","program","findProjectRoot","resolveHaivePaths","path","existsSync","mkdir","writeFile","spawnSync","os","readFile","existsSync","path","mkdir","writeFile","existsSync","path","loadMemoriesFromDir","serializeMemory","memory","promisify","execFile","program","path","resolveHaivePaths","existsSync","mkdir","writeFile","saveConfig","AUTOPILOT_DEFAULTS","spawnSync","buildCodeMap","saveCodeMap","readdir","readFile","buildFrontmatter","memoryFilePath","serializeMemory","mkdir","writeFile","readFile","existsSync","path","findProjectRoot","existsSync","mkdir","readFile","writeFile","path","findProjectRoot","path","existsSync","mkdir","readFile","writeFile","program","mkdir","existsSync","path","findProjectRoot","resolveHaivePaths","program","findProjectRoot","findProjectRoot","resolveHaivePaths","mkdir","writeFile","existsSync","path","readFile","readdir","z","loadMemoriesFromDir","buildFrontmatter","loadConfig","memoryFilePath","serializeMemory","getUsage","literalMatchesAllTokens","literalMatchesAnyToken","loadUsageIndex","tokenizeQuery","trackReads","recordRejection","saveUsageIndex","deriveConfidence","memoryMatchesAnchorPaths","suggestSensorSeed","execSync","computeImpact","compactAutoRecapBody","extractActionsBriefBody","inferModulesFromPaths","isRetiredMemory","loadCodeMap","memoryHasExcludedTag","rankMemoriesLexical","queryCodeMap","resolveBriefingBudget","specificityScore","writeBriefingMarker","estimateTokens","BRIDGE_TARGET_PATH","spawn","pathsOverlap","appendRuntimeJournalEntry","assessBootstrapState","renderBootstrapChecklist","memory","top","classifyMemoryPriority","loadModuleContexts","rm","jaccard","runGitLog","runCommand","cp","program","findProjectRoot","spawnSync","readFile","writeFile","mkdir","existsSync","path","DEFAULT_AUTO_PROMOTE_RULE","buildFrontmatter","findProjectRoot","getUsage","isAutoPromoteEligible","isDecaying","loadCodeMap","loadConfig","loadMemoriesFromDir","loadUsageIndex","resolveHaivePaths","serializeMemory","verifyAnchor","BRIDGE_TARGETS","program","findProjectRoot","resolveHaivePaths","existsSync","loadConfig","DEFAULT_AUTO_PROMOTE_RULE","loadMemoriesFromDir","memory","writeFile","serializeMemory","verifyAnchor","loadUsageIndex","isAutoPromoteEligible","getUsage","path","BRIDGE_TARGETS","isDecaying","buildFrontmatter","mkdir","loadCodeMap","buildCodeMap","saveCodeMap","spawnSync","oneLine","readFile","createHash","mkdir","readFile","writeFile","existsSync","path","buildFrontmatter","suggestSensorSeed","findProjectRoot","inferModulesFromPaths","loadConfig","loadMemoriesFromDir","memoryFilePath","resolveHaivePaths","serializeMemory","memory","findProjectRoot","resolveHaivePaths","existsSync","loadConfig","parseCsv","inferModulesFromPaths","path","readFile","createHash","loadMemoriesFromDir","writeFile","serializeMemory","buildFrontmatter","memoryFilePath","mkdir","suggestSensorSeed","existsSync","path","findProjectRoot","resolveHaivePaths","loadMemoriesFromDir","memory","findProjectRoot","resolveHaivePaths","existsSync","loadMemoriesFromDir","path","mkdir","unlink","writeFile","existsSync","path","findProjectRoot","memoryFilePath","resolveHaivePaths","serializeMemory","memory","findProjectRoot","resolveHaivePaths","existsSync","loadMemoriesFromDir","memoryFilePath","mkdir","path","writeFile","serializeMemory","unlink","existsSync","writeFile","path","findProjectRoot","resolveHaivePaths","serializeMemory","memory","findProjectRoot","resolveHaivePaths","existsSync","loadMemoriesFromDir","found","next","writeFile","serializeMemory","path","readFile","writeFile","existsSync","path","findProjectRoot","resolveHaivePaths","serializeMemory","memory","findProjectRoot","resolveHaivePaths","existsSync","loadMemoriesFromDir","parseCsv","readFile","writeFile","serializeMemory","path","writeFile","existsSync","path","DEFAULT_AUTO_PROMOTE_RULE","findProjectRoot","getUsage","isAutoPromoteEligible","loadUsageIndex","resolveHaivePaths","serializeMemory","memory","DEFAULT_AUTO_PROMOTE_RULE","findProjectRoot","resolveHaivePaths","existsSync","loadMemoriesFromDir","loadUsageIndex","isAutoPromoteEligible","getUsage","path","writeFile","serializeMemory","spawn","existsSync","readFile","path","findProjectRoot","resolveHaivePaths","memory","findProjectRoot","resolveHaivePaths","existsSync","loadMemoriesFromDir","path","readFile","spawn","existsSync","path","deriveConfidence","findProjectRoot","getUsage","inferModulesFromPaths","loadUsageIndex","memoryMatchesAnchorPaths","resolveHaivePaths","memory","findProjectRoot","resolveHaivePaths","existsSync","loadMemoriesFromDir","loadUsageIndex","inferModulesFromPaths","memoryMatchesAnchorPaths","extractPathSegments","getUsage","deriveConfidence","path","existsSync","path","findProjectRoot","getUsage","loadUsageIndex","resolveHaivePaths","memory","findProjectRoot","resolveHaivePaths","existsSync","loadMemoriesFromDir","loadUsageIndex","getUsage","path","mkdir","writeFile","existsSync","path","buildFrontmatter","findProjectRoot","memoryFilePath","resolveHaivePaths","serializeMemory","suggestSensorSeed","memory","findProjectRoot","resolveHaivePaths","existsSync","buildFrontmatter","parseCsv","memoryFilePath","mkdir","path","writeFile","serializeMemory","suggestSensorSeed","readFile","existsSync","path","findProjectRoot","loadConfig","resolveHaivePaths","readFile","path","memory","findProjectRoot","resolveHaivePaths","existsSync","loadConfig","existsSync","path","findProjectRoot","getUsage","loadUsageIndex","resolveHaivePaths","memory","findProjectRoot","resolveHaivePaths","existsSync","loadMemoriesFromDir","loadUsageIndex","getUsage","path","existsSync","path","extractSnippet","findProjectRoot","literalMatchesAllTokens","literalMatchesAnyToken","pickSnippetNeedle","resolveHaivePaths","tokenizeQuery","trackReads","memory","findProjectRoot","resolveHaivePaths","existsSync","tokenizeQuery","loadMemoriesFromDir","passesFilters","literalMatchesAllTokens","literalMatchesAnyToken","pickSnippetNeedle","path","extractSnippet","trackReads","writeFile","existsSync","findProjectRoot","loadUsageIndex","recordRejection","resolveHaivePaths","saveUsageIndex","serializeMemory","memory","findProjectRoot","resolveHaivePaths","existsSync","loadMemoriesFromDir","writeFile","serializeMemory","loadUsageIndex","recordRejection","saveUsageIndex","existsSync","unlink","path","createInterface","findProjectRoot","loadUsageIndex","resolveHaivePaths","saveUsageIndex","memory","findProjectRoot","resolveHaivePaths","existsSync","loadMemoriesFromDir","path","createInterface","unlink","loadUsageIndex","saveUsageIndex","existsSync","readFile","path","deriveConfidence","findProjectRoot","getUsage","loadUsageIndex","resolveHaivePaths","memory","findProjectRoot","resolveHaivePaths","existsSync","loadMemoriesFromDir","readFile","loadUsageIndex","getUsage","deriveConfidence","path","existsSync","path","deriveConfidence","findProjectRoot","getUsage","loadUsageIndex","resolveHaivePaths","memory","findProjectRoot","resolveHaivePaths","existsSync","loadMemoriesFromDir","loadUsageIndex","getUsage","deriveConfidence","path","existsSync","computeImpact","findProjectRoot","getUsage","loadUsageIndex","resolveHaivePaths","memory","findProjectRoot","resolveHaivePaths","existsSync","loadMemoriesFromDir","loadUsageIndex","computeImpact","getUsage","existsSync","writeFile","applyFeedbackAdjustment","computeImpact","findProjectRoot","getUsage","loadUsageIndex","recordApplied","recordRejection","recommendFeedbackAdjustment","resolveHaivePaths","saveUsageIndex","serializeMemory","memory","findProjectRoot","resolveHaivePaths","existsSync","loadMemoriesFromDir","loadUsageIndex","recordApplied","recordRejection","saveUsageIndex","getUsage","recommendFeedbackAdjustment","applyFeedbackAdjustment","writeFile","serializeMemory","computeImpact","writeFile","existsSync","path","findProjectRoot","resolveHaivePaths","serializeMemory","verifyAnchor","memory","findProjectRoot","resolveHaivePaths","existsSync","loadMemoriesFromDir","verifyAnchor","path","applyVerification","writeFile","serializeMemory","readFile","existsSync","findProjectRoot","resolveHaivePaths","memory","findProjectRoot","resolveHaivePaths","existsSync","readFile","existsSync","readFile","mkdir","writeFile","path","buildFrontmatter","findProjectRoot","resolveHaivePaths","serializeMemory","section","memory","findProjectRoot","resolveHaivePaths","path","existsSync","readFile","mkdir","buildFrontmatter","writeFile","serializeMemory","existsSync","writeFile","path","deriveConfidence","findProjectRoot","getUsage","loadMemoriesFromDir","loadUsageIndex","resolveHaivePaths","program","findProjectRoot","resolveHaivePaths","existsSync","loadMemoriesFromDir","loadUsageIndex","getUsage","deriveConfidence","path","writeFile","writeFile","mkdir","readFile","rm","existsSync","spawn","path","Option","buildFrontmatter","findProjectRoot","loadConfig","loadMemoriesFromDir","loadPreventionEvents","loadUsageIndex","memoryFilePath","resolveHaivePaths","serializeMemory","writeSessionHandoff","path","existsSync","readFile","parseCsv","spawn","loadMemoriesFromDir","loadUsageIndex","loadPreventionEvents","recapTopic","session","Option","findProjectRoot","resolveHaivePaths","rm","loadConfig","writeSessionHandoff","memory","writeFile","serializeMemory","buildFrontmatter","memoryFilePath","mkdir","existsSync","readdir","path","findProjectRoot","loadConfig","resolveHaivePaths","program","findProjectRoot","resolveHaivePaths","existsSync","path","readdir","name","config","loadConfig","contract","existsSync","mkdir","readFile","writeFile","path","spawnSync","findProjectRoot","loadConfig","loadMemoriesFromDir","resolveHaivePaths","saveConfig","serializeMemory","program","path","mkdir","spawnSync","writeFile","findProjectRoot","resolveHaivePaths","loadConfig","existsSync","loadMemoriesFromDir","memory","serializeMemory","readdir","readFile","saveConfig","existsSync","mkdir","writeFile","path","findProjectRoot","loadMemoriesFromDir","loadUsageIndex","readUsageEvents","resolveHaivePaths","program","findProjectRoot","resolveHaivePaths","readUsageEvents","pct","path","existsSync","loadMemoriesFromDir","memory","loadUsageIndex","mkdir","writeFile","estimateTokens","findProjectRoot","resolveHaivePaths","program","findProjectRoot","resolveHaivePaths","estimateTokens","existsSync","readdir","readFile","writeFile","path","estimateTokens","findProjectRoot","program","path","writeFile","findProjectRoot","existsSync","readdir","readFile","estimateTokens","mkdir","readFile","writeFile","existsSync","path","findProjectRoot","loadConfig","loadPreventionEvents","loadUsageIndex","resolveHaivePaths","program","findProjectRoot","resolveHaivePaths","existsSync","loadUsageIndex","loadPreventionEvents","loadConfig","path","mkdir","writeFile","readFile","renderMarkdown","memories","loadMemoriesFromDir","synthesized","mkdir","writeFile","existsSync","path","aggregateUsage","buildFrontmatter","findProjectRoot","loadConfig","loadMemoriesFromDir","memoryFilePath","parseSince","readUsageEvents","resolveHaivePaths","serializeMemory","memory","findProjectRoot","resolveHaivePaths","readUsageEvents","parseSince","loadConfig","existsSync","loadMemoriesFromDir","slugify","buildFrontmatter","memoryFilePath","mkdir","path","writeFile","serializeMemory","truncate","aggregateUsage","existsSync","writeFile","path","findProjectRoot","getUsage","retirementSignal","loadConfig","loadMemoriesFromDir","loadUsageIndex","resolveHaivePaths","serializeMemory","MS_PER_DAY","memory","findProjectRoot","resolveHaivePaths","existsSync","loadConfig","loadMemoriesFromDir","loadUsageIndex","retirementSignal","path","getUsage","writeFile","serializeMemory","existsSync","statSync","readFile","writeFile","path","execSync","codeMapPath","findProjectRoot","getUsage","isStackPackSeed","loadCodeMap","loadConfig","loadMemoriesFromDir","loadUsageIndex","readUsageEvents","resolveHaivePaths","MS_PER_DAY","program","findProjectRoot","resolveHaivePaths","loadConfig","existsSync","readFile","path","loadMemoriesFromDir","loadUsageIndex","isStackPackSeed","getUsage","loadCodeMap","codeMapPath","readUsageEvents","execSync","writeFile","section","pct","stat","commandExists","statSync","existsSync","findProjectRoot","loadMemoriesFromDir","parseSince","readUsageEvents","resolveHaivePaths","program","findProjectRoot","resolveHaivePaths","readUsageEvents","parseSince","existsSync","loadMemoriesFromDir","memory","truncate","spawn","findProjectRoot","loadConfig","resolveHaivePaths","program","findProjectRoot","resolveHaivePaths","loadConfig","runCommand","spawn","existsSync","findProjectRoot","loadMemoriesFromDir","resolveHaivePaths","program","findProjectRoot","resolveHaivePaths","existsSync","loadMemoriesFromDir","memory","MemoryTypeSchema","suggestTopicKey","memory","MemoryTypeSchema","suggestTopicKey","path","resolveProjectInfo","program","existsSync","path","appendRuntimeJournalEntry","findProjectRoot","readRuntimeJournalTail","resolveHaivePaths","program","path","resolveHaivePaths","findProjectRoot","appendRuntimeJournalEntry","existsSync","readRuntimeJournalTail","existsSync","path","collectTimelineEntries","findProjectRoot","resolveHaivePaths","memory","path","resolveHaivePaths","findProjectRoot","existsSync","loadMemoriesFromDir","collectTimelineEntries","existsSync","path","findLexicalConflictPairs","findTopicStatusConflictPairs","findProjectRoot","resolveHaivePaths","memory","path","resolveHaivePaths","findProjectRoot","existsSync","loadMemoriesFromDir","findLexicalConflictPairs","findTopicStatusConflictPairs","execFile","execFileSync","spawn","existsSync","statSync","chmod","mkdir","readFile","readdir","rm","writeFile","path","promisify","antiPatternGateParams","assessBootstrapState","findProjectRoot","loadCodeMap","renderBootstrapChecklist","hasRecentBriefingMarker","isRetiredMemory","loadConfig","loadMemoriesFromDir","memoryMatchesAnchorPaths","recordPreventionHits","resolveBriefingBudget","resolveHaivePaths","runSensors","saveConfig","sensorTargetsFromDiff","verifyAnchor","writeBriefingMarker","execFileAsync","promisify","execFile","MAX_STDIN_BYTES","program","findProjectRoot","resolveHaivePaths","mkdir","loadConfig","saveConfig","path","existsSync","resolveBriefingBudget","writeBriefingMarker","memory","hasRecentBriefingMarker","readFile","loadMemoriesFromDir","spawn","writeFile","loadCodeMap","readdir","assessBootstrapState","renderBootstrapChecklist","verifyAnchor","memoryMatchesAnchorPaths","antiPatternGateParams","isRetiredMemory","sensorTargetsFromDiff","runSensors","recordPreventionHits","runCommand","rm","extractAbsoluteHaiveBins","versionForBinary","statSync","execFileSync","chmod","readStdin","program","execFile","existsSync","chmod","mkdir","readFile","writeFile","path","promisify","extractSensorExamples","findProjectRoot","isRetiredMemory","judgeProposedSensor","loadConfig","loadMemoriesFromDir","recordPreventionHits","resolveHaivePaths","runSensors","selectCommandSensors","sensorPatternBrittleness","sensorSelfCheck","serializeMemory","exec","promisify","execFile","program","findProjectRoot","resolveHaivePaths","readFile","path","runSensors","loadConfig","selectCommandSensors","recordPreventionHits","existsSync","loadMemoriesFromDir","memory","sensorPatternBrittleness","sensorSelfCheck","extractSensorExamples","writeFile","serializeMemory","judgeProposedSensor","mkdir","chmod","isRetiredMemory","existsSync","mkdir","readFile","writeFile","path","draftsFromFindings","filterNewDrafts","findProjectRoot","loadMemoriesFromDir","memoryFilePath","parseFindings","resolveHaivePaths","serializeMemory","program","findProjectRoot","resolveHaivePaths","existsSync","path","readFile","parseFindings","draftsFromFindings","loadMemoriesFromDir","memory","filterNewDrafts","created","writeDraft","memoryFilePath","mkdir","writeFile","serializeMemory","existsSync","findProjectRoot","loadConfig","loadMemoriesFromDir","loadPreventionEvents","loadUsageIndex","resolveHaivePaths","program","findProjectRoot","resolveHaivePaths","existsSync","loadMemoriesFromDir","loadUsageIndex","loadPreventionEvents","loadConfig","r","execFile","readFile","existsSync","path","promisify","findProjectRoot","exec","promisify","execFile","program","findProjectRoot","existsSync","path","readFile","readFile","existsSync","path","findProjectRoot","resolveHaivePaths","existsSync","readFile","path","program","findProjectRoot","resolveHaivePaths","loadMemoriesFromDir","execFileSync","existsSync","path","findProjectRoot","program","findProjectRoot","execFileSync","path","existsSync","writeFile","existsSync","findProjectRoot","planConflictResolution","resolveHaivePaths","serializeMemory","memory","findProjectRoot","resolveHaivePaths","existsSync","loadMemoriesFromDir","planConflictResolution","writeFile","serializeMemory","execFile","mkdir","writeFile","existsSync","path","promisify","buildFrontmatter","findProjectRoot","memoryFilePath","proposeSeedsFromCommits","resolveHaivePaths","serializeMemory","exec","promisify","execFile","memory","findProjectRoot","resolveHaivePaths","existsSync","proposeSeedsFromCommits","buildFrontmatter","memoryFilePath","mkdir","path","writeFile","serializeMemory","existsSync","path","findProjectRoot","resolveHaivePaths","BRIDGE_TARGET_PATH","BRIDGE_TARGETS","program","BRIDGE_TARGETS","findProjectRoot","resolveHaivePaths","existsSync","path","BRIDGE_TARGET_PATH","Command"]}
|