@hiveai/mcp 0.3.2 → 0.3.3
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/README.md +26 -13
- package/dist/index.js +391 -77
- package/dist/index.js.map +1 -1
- package/dist/server.js +391 -77
- package/dist/server.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/server.ts","../src/context.ts","../src/tools/bootstrap-project-save.ts","../src/tools/get-project-context.ts","../src/tools/mem-list.ts","../src/tools/mem-save.ts","../src/tools/mem-search.ts","../src/tools/mem-verify.ts","../src/tools/mem-reject.ts","../src/tools/mem-for-files.ts","../src/tools/mem-get.ts","../src/tools/mem-delete.ts","../src/tools/mem-update.ts","../src/tools/mem-pending.ts","../src/tools/mem-approve.ts","../src/tools/mem-tried.ts","../src/tools/mem-observe.ts","../src/tools/mem-session-end.ts","../src/tools/get-briefing.ts","../src/tools/code-map.ts","../src/tools/mem-diff.ts","../src/prompts/bootstrap-project.ts","../src/prompts/post-task.ts","../src/prompts/import-docs.ts","../src/session-tracker.ts"],"sourcesContent":["import { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { createHaiveServer, SERVER_VERSION } from \"./server.js\";\n\nfunction parseArgs(argv: string[]): { root?: string } {\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 out;\n}\n\nasync function main(): Promise<void> {\n const { root } = parseArgs(process.argv);\n const { server, context } = createHaiveServer({ root });\n // stderr is safe — stdio transport uses stdin/stdout exclusively for MCP frames.\n console.error(\n `[haive-mcp] starting server v${SERVER_VERSION} (project root: ${context.paths.root})`,\n );\n const transport = new StdioServerTransport();\n await server.connect(transport);\n}\n\nmain().catch((err: unknown) => {\n console.error(\"[haive-mcp] fatal:\", err instanceof Error ? err.message : err);\n process.exit(1);\n});\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.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 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 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 BootstrapProjectArgsSchema,\n bootstrapProjectPrompt,\n type BootstrapProjectArgs,\n} from \"./prompts/bootstrap-project.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\";\n\ndeclare const __HAIVE_VERSION__: string;\n\nexport const SERVER_NAME = \"haive\";\nexport const SERVER_VERSION = __HAIVE_VERSION__;\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 function createHaiveServer(\n options: CreateContextOptions = {},\n): { server: McpServer; context: HaiveContext; tracker: SessionTracker } {\n const context = createContext(options);\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 server.tool(\n \"mem_save\",\n \"Save a new memory (convention, decision, gotcha, architecture, glossary). For failed approaches use mem_tried instead — it enforces a structured format that is more useful to future agents. Use scope=team to share with the whole team.\",\n MemSaveInputSchema,\n async (input: MemSaveInput) => {\n tracker.record(\"mem_save\", input.slug);\n return jsonResult(await memSave(input, context));\n },\n );\n\n server.tool(\n \"mem_search\",\n \"Search memories by substring across id, tags, and body. Optional filters by scope/type/module.\",\n MemSearchInputSchema,\n async (input: MemSearchInput) => jsonResult(await memSearch(input, context)),\n );\n\n server.tool(\n \"mem_list\",\n \"List memories with optional filters by scope/type/module/tag.\",\n MemListInputSchema,\n async (input: MemListInput) => jsonResult(await memList(input, context)),\n );\n\n server.tool(\n \"get_project_context\",\n \"Read the shared .ai/project-context.md (and optionally a module context).\",\n GetProjectContextInputSchema,\n async (input: GetProjectContextInput) =>\n jsonResult(await getProjectContext(input, context)),\n );\n\n server.tool(\n \"get_briefing\",\n \"One-shot onboarding: returns project context + module contexts + ranked relevant memories under a token budget. Replaces 4–5 separate calls when an agent starts a task.\",\n GetBriefingInputSchema,\n async (input: GetBriefingInput) => {\n tracker.record(\"get_briefing\", input.task ?? \"\");\n return jsonResult(await getBriefing(input, context));\n },\n );\n\n server.tool(\n \"code_map\",\n \"Browse the project's pre-computed code map (file → exports + 1-line description) instead of grepping. Requires `haive index code`.\",\n CodeMapInputSchema,\n async (input: CodeMapInput) => jsonResult(await codeMapTool(input, context)),\n );\n\n server.tool(\n \"bootstrap_project_save\",\n \"Persist a project (or module) context document analyzed by the AI client.\",\n BootstrapProjectSaveInputSchema,\n async (input: BootstrapProjectSaveInput) =>\n jsonResult(await bootstrapProjectSave(input, context)),\n );\n\n server.tool(\n \"mem_verify\",\n \"Check anchor freshness for one or every memory; optionally write status updates back to disk.\",\n MemVerifyInputSchema,\n async (input: MemVerifyInput) => jsonResult(await memVerify(input, context)),\n );\n\n server.tool(\n \"mem_reject\",\n \"Record a rejection for a memory (blocks auto-promotion and lowers its trust signal).\",\n MemRejectInputSchema,\n async (input: MemRejectInput) => jsonResult(await memReject(input, context)),\n );\n\n server.tool(\n \"mem_for_files\",\n \"Given the file paths the agent is currently working on, return relevant memories grouped by reason (anchor overlap, module, domain) plus any matching .ai/modules/<name>/context.md contents.\",\n MemForFilesInputSchema,\n async (input: MemForFilesInput) => jsonResult(await memForFiles(input, context)),\n );\n\n server.tool(\n \"mem_get\",\n \"Fetch a single memory by id, including its body, anchor, usage, and confidence.\",\n MemGetInputSchema,\n async (input: MemGetInput) => jsonResult(await memGet(input, context)),\n );\n\n server.tool(\n \"mem_delete\",\n \"Delete a memory by id (and its usage entry by default).\",\n MemDeleteInputSchema,\n async (input: MemDeleteInput) => jsonResult(await memDelete(input, context)),\n );\n\n server.tool(\n \"mem_update\",\n \"Update the body, tags, or anchor of an existing memory without changing its id or losing usage history.\",\n MemUpdateInputSchema,\n async (input: MemUpdateInput) => jsonResult(await memUpdate(input, context)),\n );\n\n server.tool(\n \"mem_pending\",\n \"List 'proposed' memories awaiting review, sorted by reads (most-read first).\",\n MemPendingInputSchema,\n async (input: MemPendingInput) => jsonResult(await memPending(input, context)),\n );\n\n server.tool(\n \"mem_approve\",\n \"Mark a memory as validated immediately (explicit team review).\",\n MemApproveInputSchema,\n async (input: MemApproveInput) => jsonResult(await memApprove(input, context)),\n );\n\n server.tool(\n \"mem_tried\",\n \"Preferred way to record a failed approach. Enforces a structured what/why_failed/instead format that is immediately actionable for future agents. Auto-validated (no approval cycle). Use whenever you tried an approach and it failed — prevents the same mistake from happening in the next session.\",\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 server.tool(\n \"mem_diff\",\n \"Compare two memories side-by-side: shows frontmatter fields that differ and lines unique to each body. Useful before merging or deduplicating memories.\",\n MemDiffInputSchema,\n async (input: MemDiffInput) => jsonResult(await memDiff(input, context)),\n );\n\n server.tool(\n \"mem_observe\",\n \"Capture a code-level discovery made during exploration: a bug, inconsistency, missing config, or security gap found by reading existing code that was NOT in the briefing. Use this whenever you read code and spot something that could silently break in production. Auto-validated, anchored to file paths for staleness detection. Prefer this over mem_save for reactive discoveries during code reading.\",\n MemObserveInputSchema,\n async (input: MemObserveInput) => {\n tracker.record(\"mem_observe\", input.where);\n return jsonResult(await memObserve(input, context));\n },\n );\n\n server.tool(\n \"mem_session_end\",\n \"Save a structured end-of-session recap (goal / accomplished / discoveries / next steps). \" +\n \"Uses topic-upsert: one recap per scope is kept and updated in-place so the next session always has \" +\n \"fresh context. Call this before closing every significant session. \" +\n \"get_briefing automatically surfaces the latest recap at the top of the next session's briefing.\",\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 server.prompt(\n \"bootstrap_project\",\n \"Instructions for the AI client to analyze the project and save the context.\",\n BootstrapProjectArgsSchema,\n (args: BootstrapProjectArgs) => bootstrapProjectPrompt(args, context),\n );\n\n server.prompt(\n \"post_task\",\n \"Post-task checklist: run this after completing a task to capture failed approaches, new conventions, decisions, and gotchas before closing the session.\",\n PostTaskArgsSchema,\n (args: PostTaskArgs) => postTaskPrompt(args, context),\n );\n\n server.prompt(\n \"import_docs\",\n \"Analyze documentation (README, ADR, wiki page, etc.) and save the actionable knowledge as hAIve memories. Pass the content and an optional source/scope.\",\n ImportDocsArgsSchema,\n (args: ImportDocsArgs) => importDocsPrompt(args, context),\n );\n\n return { server, context, tracker };\n}\n","import { findProjectRoot, resolveHaivePaths, type HaivePaths } from \"@hiveai/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 \"@hiveai/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} from \"@hiveai/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\", \"attempt\", \"session_recap\"])\n .describe(\n \"Kind of memory being saved. 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 .default(\"personal\")\n .describe(\"Visibility scope: personal | team | module\"),\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};\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 invalid_paths?: string[];\n}\n\nfunction bodyHash(body: string): string {\n return createHash(\"sha256\").update(body.trim()).digest(\"hex\").slice(0, 12);\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 'haive init' first.`,\n );\n }\n\n const existing = existsSync(ctx.paths.memoriesDir)\n ? await loadMemoriesFromDir(ctx.paths.memoriesDir)\n : [];\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 === input.scope,\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 // ── Topic upsert ───────────────────────────────────────────────────────\n if (input.topic) {\n const topicMatch = existing.find(({ memory }) =>\n memory.frontmatter.topic === input.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 newFrontmatter = {\n ...fm,\n body: input.body,\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 return {\n id: fm.id,\n scope: fm.scope,\n file_path: topicMatch.filePath,\n action: \"updated\",\n revision_count: newFrontmatter.revision_count,\n ...(invalidPaths.length > 0 ? { invalid_paths: invalidPaths, warning: `Anchor path(s) not found in project: ${invalidPaths.join(\", \")}. They will be marked stale by haive sync.` } : {}),\n };\n }\n }\n\n // ── Create new memory ──────────────────────────────────────────────────\n const haiveConfig = await loadConfig(ctx.paths);\n\n // In autopilot mode: memories go directly to validated (skip approval cycle)\n // Also apply config defaults for scope\n const resolvedScope = input.scope !== \"personal\"\n ? input.scope\n : (haiveConfig.defaultScope ?? \"personal\");\n\n const frontmatter = buildFrontmatter({\n type: input.type,\n slug: input.slug,\n scope: resolvedScope as \"personal\" | \"team\" | \"module\",\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 });\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 // Merge invalid_paths warning with slug similarity warning\n const finalWarning = [\n invalidPaths.length > 0\n ? `Anchor path(s) not found in project: ${invalidPaths.join(\", \")}. They will be marked stale by \\`haive sync\\`.`\n : null,\n warning ?? 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 ...(invalidPaths.length > 0 ? { invalid_paths: invalidPaths } : {}),\n };\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 tokenizeQuery,\n trackReads,\n type ConfidenceLevel,\n type LoadedMemory,\n type UsageIndex,\n} from \"@hiveai/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 `haive embeddings index`).\",\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\";\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 @hiveai/embeddings not installed). Falling back to literal search.\",\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(\"@hiveai/embeddings\");\n try {\n mod = await import(\"@hiveai/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","import { writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport {\n loadMemoriesFromDir,\n serializeMemory,\n verifyAnchor,\n type Memory,\n} from \"@hiveai/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 \"@hiveai/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 { 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 \"@hiveai/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 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 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 \"@hiveai/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 \"@hiveai/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 \"@hiveai/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 \"@hiveai/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 \"@hiveai/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 frontmatter: { ...found.memory.frontmatter, status: \"validated\" 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} from \"@hiveai/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\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 'haive 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 return { id: frontmatter.id, scope: frontmatter.scope, file_path: file };\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} from \"@hiveai/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};\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}\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 'haive 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, 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 \"@hiveai/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.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 'haive init' first.`);\n }\n\n const body = buildBody(input);\n const topic = recapTopic(input.scope, input.module);\n\n // Validate anchor paths exist before saving\n const invalidPaths = input.files_touched.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 revision_count: revisionCount,\n anchor: {\n ...fm.anchor,\n paths: input.files_touched.length ? input.files_touched : fm.anchor.paths,\n },\n };\n await writeFile(\n topicMatch.filePath,\n serializeMemory({ frontmatter: newFrontmatter, body }),\n \"utf8\",\n );\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: input.files_touched,\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 return {\n id: frontmatter.id,\n scope: frontmatter.scope,\n file_path: file,\n action: \"created\",\n revision_count: 0,\n };\n}\n","import { readFile, readdir } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n allocateBudget,\n deriveConfidence,\n estimateTokens,\n getUsage,\n inferModulesFromPaths,\n isDecaying,\n literalMatchesAllTokens,\n literalMatchesAnyToken,\n loadCodeMap,\n loadConfig,\n loadMemoriesFromDir,\n loadUsageIndex,\n memoryMatchesAnchorPaths,\n queryCodeMap,\n tokenizeQuery,\n trackReads,\n truncateToTokens,\n type ConfidenceLevel,\n type LoadedMemory,\n type UsageIndex,\n} from \"@hiveai/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.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 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 `haive 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\"])\n .default(\"full\")\n .describe(\n \"Output format: 'full' returns complete memory bodies; 'compact' returns id + 1-line summary only (call mem_get for details).\",\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 `haive index code` to have been run.\",\n ),\n};\n\nexport type GetBriefingInput = {\n [K in keyof typeof GetBriefingInputSchema]: z.infer<(typeof GetBriefingInputSchema)[K]>;\n};\n\nexport interface BriefingMemory {\n id: string;\n scope: string;\n type: string;\n module?: string;\n tags: string[];\n status: string;\n confidence: ConfidenceLevel;\n /** Present when confidence is 'low' or 'unverified' — AI should weight this memory cautiously. */\n unverified?: true;\n read_count: number;\n reasons: Array<\"anchor\" | \"module\" | \"domain\" | \"semantic\">;\n match_quality: \"exact\" | \"partial\" | \"semantic\";\n semantic_score?: number;\n body: string;\n file_path: string;\n}\n\nexport interface CodeMapSymbolHit {\n symbol: string;\n /** files that export this symbol */\n locations: Array<{\n file: string;\n kind: string;\n line: number;\n description?: string;\n }>;\n}\n\nexport interface BriefingOutput {\n task?: string;\n search_mode: \"semantic\" | \"literal_fallback\" | \"literal\";\n match_quality_note?: string;\n inferred_modules: string[];\n last_session?: { id: string; scope: string; revision_count: number; body: string };\n project_context: { content: string; truncated: boolean; is_template?: boolean; auto_generated?: boolean } | null;\n module_contexts: Array<{ name: string; content: string; truncated: boolean }>;\n memories: BriefingMemory[];\n symbol_locations?: CodeMapSymbolHit[];\n decay_warnings: string[];\n setup_warnings: string[];\n estimated_tokens: number;\n budget: { max_tokens: number; spent: { project: number; modules: number; memories: number } };\n}\n\nexport async function getBriefing(\n input: GetBriefingInput,\n ctx: HaiveContext,\n): Promise<BriefingOutput> {\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 // Find the most recent session_recap (by created_at) — exclude from main ranking\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 body: r.memory.body,\n };\n }\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 // session_recap surfaces separately in last_session, not in the ranked memories list\n if (memory.frontmatter.type === \"session_recap\") return false;\n return true;\n });\n usage = await loadUsageIndex(ctx.paths);\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 // upgrade match_quality if better evidence found\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 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 reasons: [reason],\n match_quality: matchQuality ?? \"partial\",\n ...(score !== undefined ? { semantic_score: score } : {}),\n body: loaded.memory.body,\n file_path: loaded.filePath,\n });\n };\n\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.task) {\n const tokens = tokenizeQuery(input.task);\n // AND first — exact match\n const andHits = allMemories.filter((m) => literalMatchesAllTokens(m.memory, tokens));\n for (const loaded of andHits) {\n addOrUpdate(loaded, \"semantic\", undefined, \"exact\");\n }\n // OR fallback — if AND produced nothing, partial match is better than nothing\n if (andHits.length === 0 && tokens.length > 1) {\n for (const loaded of allMemories) {\n if (literalMatchesAnyToken(loaded.memory, tokens)) {\n addOrUpdate(loaded, \"semantic\", undefined, \"partial\");\n }\n }\n }\n if (semanticHits) {\n for (const hit of semanticHits) {\n const loaded = byId.get(hit.id);\n if (loaded) addOrUpdate(loaded, \"semantic\", hit.score, \"semantic\");\n }\n }\n }\n\n const ranked = [...seen.values()].sort((a, b) => {\n const reasonScore = (m: BriefingMemory): number =>\n (m.type === \"attempt\" ? 3 : 0) + // attempt = negative knowledge, surface first to prevent repeating mistakes\n (m.reasons.includes(\"anchor\") ? 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 const sa = reasonScore(a) + confidenceScore(a) + (a.semantic_score ?? 0);\n const sb = reasonScore(b) + confidenceScore(b) + (b.semantic_score ?? 0);\n return sb - sa;\n });\n\n // Expand related_ids: pull in memories linked from the top results\n byId = new Map(allMemories.map((m) => [m.memory.frontmatter.id, m]));\n for (const mem of ranked.slice(0, input.max_memories)) {\n if (seen.size >= input.max_memories * 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, input.max_memories));\n\n if (input.track && memories.length > 0) {\n await trackReads(ctx.paths, memories.map((m) => m.id));\n }\n }\n\n // Build raw section payloads\n const projectContextRaw =\n input.include_project_context && existsSync(ctx.paths.projectContext)\n ? await readFile(ctx.paths.projectContext, \"utf8\")\n : \"\";\n const isTemplateContext =\n projectContextRaw.includes(\"TODO — high-level overview\") ||\n projectContextRaw.includes(\"Generated by `haive init`\");\n\n const setupWarnings: string[] = [];\n let autoContextGenerated = false;\n\n // In autopilot mode: if project-context.md is still the template, auto-generate\n // a minimal context from the code-map so get_briefing is useful immediately.\n let projectContext = isTemplateContext ? \"\" : projectContextRaw;\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\n // Pick top exported symbols as a starting overview\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 projectContext =\n `# Project context (auto-generated by hAIve)\\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 `## 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 `haive index code` then invoke bootstrap_project for a full context.\",\n );\n }\n } else {\n if (isTemplateContext) {\n setupWarnings.push(\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 );\n } else {\n setupWarnings.push(\n \"No project-context.md found. Run `haive init` then invoke the bootstrap_project MCP prompt.\",\n );\n }\n }\n }\n\n const moduleContents = input.include_module_contexts\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 // Allocate budget across the three large pieces\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 input.max_tokens,\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 // Distribute the modules slice across module entries proportionally\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 // Recompute memory bodies to fit using a cascade approach:\n // top-ranked memories get full budget first; lower-ranked ones are dropped if budget runs out.\n // This is better than uniform truncation which gives all memories a 37%-fragment.\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 // Enough budget for a meaningful fragment — truncate and include\n const t = truncateToTokens(m.body, { maxTokens: remaining, mode: \"head\" });\n trimmedMemories.push({ ...m, body: t.text });\n remaining = 0;\n }\n // Otherwise skip — too small a fragment to be useful\n }\n }\n\n const totalTokens =\n projectSlice.estimatedTokens + modulesSlice.estimatedTokens + memoriesSlice.estimatedTokens;\n\n // Decay warnings: memories not read in >90 days\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 // Compact format: replace body with 1-line summary\n const outputMemories =\n input.format === \"compact\"\n ? trimmedMemories.map((m) => ({ ...m, body: compactSummary(m.body) }))\n : trimmedMemories;\n\n // ── Code-map symbol lookup ──────────────────────────────────────────────\n // Also auto-look up symbols found in anchor paths of returned memories +\n // any explicit symbols[] the caller requested.\n let symbolLocations: CodeMapSymbolHit[] | undefined;\n const symbolsToLookup = new Set<string>(input.symbols);\n // Auto-collect symbols from memory anchors so agents get locations for free\n for (const m of outputMemories) {\n const loaded = byId.get(m.id);\n for (const sym of loaded?.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 return {\n ...(input.task ? { task: input.task } : {}),\n search_mode: searchMode,\n inferred_modules: inferred,\n ...(lastSession ? { last_session: lastSession } : {}),\n project_context: (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 ...(symbolLocations ? { symbol_locations: symbolLocations } : {}),\n decay_warnings: decayWarnings,\n setup_warnings: setupWarnings,\n estimated_tokens: totalTokens,\n budget: {\n max_tokens: input.max_tokens,\n spent: {\n project: projectSlice.estimatedTokens,\n modules: modulesSlice.estimatedTokens,\n memories: memoriesSlice.estimatedTokens,\n },\n },\n };\n}\n\nfunction 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\nasync function trySemanticHits(\n ctx: HaiveContext,\n task: string,\n limit: number,\n): Promise<Array<{ id: string; score: number }> | null> {\n let mod: typeof import(\"@hiveai/embeddings\");\n try {\n mod = await import(\"@hiveai/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\nasync 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\n// Re-export estimateTokens at the module level for tests.\nexport { estimateTokens };\n","import { loadCodeMap, queryCodeMap } from \"@hiveai/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 max_files: z\n .number()\n .int()\n .positive()\n .default(40)\n .describe(\"Cap on returned files\"),\n};\n\nexport type CodeMapInput = {\n [K in keyof typeof CodeMapInputSchema]: z.infer<(typeof CodeMapInputSchema)[K]>;\n};\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 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 `haive index code` to generate `.ai/code-map.json`.\",\n };\n }\n const { files } = queryCodeMap(map, { file: input.file, symbol: input.symbol });\n return {\n available: true,\n generated_at: map.generated_at,\n total_files: Object.keys(map.files).length,\n files: files.slice(0, input.max_files).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 };\n}\n","import { existsSync } from \"node:fs\";\nimport { loadMemoriesFromDir } from \"@hiveai/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 { 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 hAIve 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 { 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\nWhen done, respond with a brief summary: \"Saved N memories: [list of IDs]. Session recap saved.\"\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 hAIve 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 hAIve memories\",\n messages: [\n {\n role: \"user\",\n content: { type: \"text\", text },\n },\n ],\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 * saves a session recap via mem_session_end — no human action needed.\n */\nimport { loadConfig, type HaiveConfig } from \"@hiveai/core\";\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\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 this.events.push({ tool, at: new Date().toISOString(), summary });\n }\n\n private registerShutdownHandler(): void {\n if (this.shutdownRegistered) return;\n this.shutdownRegistered = true;\n\n const save = async (): Promise<void> => {\n // Only save if something actually happened this session\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 // Extract any file paths mentioned in summaries\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 try {\n 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 } catch {\n // Non-fatal — never block process exit\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\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"],"mappings":";;;AAAA,SAAS,4BAA4B;;;ACArC,SAAS,iBAAiB;;;ACA1B,SA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pC,UAAI,OAAO,KAAK,EAAE,CAAC;AAAA,IACrB,WAAW,KAAK,WAAW,SAAS,GAAG;AACrC,UAAI,OAAO,IAAI,MAAM,UAAU,MAAM;AAAA,IACvC;AAAA,EACF;AACA,SAAO;AACT;AAEA,eAAe,OAAsB;AACnC,QAAM,EAAE,KAAK,IAAI,UAAU,QAAQ,IAAI;AACvC,QAAM,EAAE,QAAQ,QAAQ,IAAI,kBAAkB,EAAE,KAAK,CAAC;AAEtD,UAAQ;AAAA,IACN,gCAAgC,cAAc,mBAAmB,QAAQ,MAAM,IAAI;AAAA,EACrF;AACA,QAAM,YAAY,IAAI,qBAAqB;AAC3C,QAAM,OAAO,QAAQ,SAAS;AAChC;AAEA,KAAK,EAAE,MAAM,CAAC,QAAiB;AAC7B,UAAQ,MAAM,sBAAsB,eAAe,QAAQ,IAAI,UAAU,GAAG;AAC5E,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["existsSync","path","z","existsSync","z","mkdir","writeFile","existsSync","path","loadMemoriesFromDir","z","existsSync","loadMemoriesFromDir","z","top","writeFile","existsSync","loadMemoriesFromDir","serializeMemory","z","writeFile","existsSync","loadMemoriesFromDir","loadUsageIndex","serializeMemory","z","readFile","readdir","existsSync","path","deriveConfidence","getUsage","loadMemoriesFromDir","loadUsageIndex","trackReads","z","existsSync","deriveConfidence","getUsage","loadMemoriesFromDir","loadUsageIndex","z","existsSync","loadMemoriesFromDir","loadUsageIndex","saveUsageIndex","z","writeFile","existsSync","loadMemoriesFromDir","serializeMemory","z","existsSync","getUsage","loadMemoriesFromDir","loadUsageIndex","z","writeFile","existsSync","loadMemoriesFromDir","serializeMemory","z","mkdir","writeFile","existsSync","path","buildFrontmatter","memoryFilePath","serializeMemory","z","mkdir","writeFile","existsSync","path","buildFrontmatter","memoryFilePath","serializeMemory","z","writeFile","mkdir","existsSync","path","buildFrontmatter","loadMemoriesFromDir","memoryFilePath","serializeMemory","z","readFile","readdir","existsSync","path","deriveConfidence","getUsage","inferModulesFromPaths","literalMatchesAllTokens","literalMatchesAnyToken","loadConfig","loadMemoriesFromDir","loadUsageIndex","memoryMatchesAnchorPaths","tokenizeQuery","trackReads","z","loadModuleContexts","loadCodeMap","queryCodeMap","z","existsSync","loadMemoriesFromDir","z","z","z","z","loadConfig","loadConfig"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/server.ts","../src/context.ts","../src/tools/bootstrap-project-save.ts","../src/tools/get-project-context.ts","../src/tools/mem-list.ts","../src/tools/mem-save.ts","../src/tools/mem-search.ts","../src/tools/mem-verify.ts","../src/tools/mem-reject.ts","../src/tools/mem-for-files.ts","../src/tools/mem-get.ts","../src/tools/mem-delete.ts","../src/tools/mem-update.ts","../src/tools/mem-pending.ts","../src/tools/mem-approve.ts","../src/tools/mem-tried.ts","../src/tools/mem-observe.ts","../src/tools/mem-session-end.ts","../src/tools/get-briefing.ts","../src/tools/code-map.ts","../src/tools/mem-diff.ts","../src/prompts/bootstrap-project.ts","../src/prompts/post-task.ts","../src/prompts/import-docs.ts","../src/session-tracker.ts"],"sourcesContent":["import { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { createHaiveServer, SERVER_VERSION } from \"./server.js\";\n\nfunction parseArgs(argv: string[]): { root?: string } {\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 out;\n}\n\nasync function main(): Promise<void> {\n const { root } = parseArgs(process.argv);\n const { server, context } = createHaiveServer({ root });\n // stderr is safe — stdio transport uses stdin/stdout exclusively for MCP frames.\n console.error(\n `[haive-mcp] starting server v${SERVER_VERSION} (project root: ${context.paths.root})`,\n );\n const transport = new StdioServerTransport();\n await server.connect(transport);\n}\n\nmain().catch((err: unknown) => {\n console.error(\"[haive-mcp] fatal:\", err instanceof Error ? err.message : err);\n process.exit(1);\n});\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.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 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 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 BootstrapProjectArgsSchema,\n bootstrapProjectPrompt,\n type BootstrapProjectArgs,\n} from \"./prompts/bootstrap-project.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\";\n\ndeclare const __HAIVE_VERSION__: string;\n\nexport const SERVER_NAME = \"haive\";\nexport const SERVER_VERSION = __HAIVE_VERSION__;\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 function createHaiveServer(\n options: CreateContextOptions = {},\n): { server: McpServer; context: HaiveContext; tracker: SessionTracker } {\n const context = createContext(options);\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 // ── Memory creation ────────────────────────────────────────────────────\n\n server.tool(\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 haive 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 server.tool(\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 server.tool(\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 server.tool(\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 server.tool(\n \"get_briefing\",\n [\n \"⭐ CALL THIS FIRST at the start of every task. One-shot onboarding that returns\",\n \"everything relevant in a single call under a token budget.\",\n \"\",\n \"RETURNS (in order of priority):\",\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 \"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 summaries, use when token budget is tight)\",\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. Always call this before any other tool.\",\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 server.tool(\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 \" Semantic (semantic: true): embedding-based similarity — finds related memories\",\n \" even with different wording. Requires haive 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 @hiveai/embeddings)\",\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) => jsonResult(await memSearch(input, context)),\n );\n\n server.tool(\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 server.tool(\n \"mem_get\",\n [\n \"Fetch a single memory by its full id with all details.\",\n \"\",\n \"USE WHEN get_briefing returned a memory in 'compact' format 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 server.tool(\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 server.tool(\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 server.tool(\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 server.tool(\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 haive 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 haive index code first.\",\n ].join(\"\\n\"),\n CodeMapInputSchema,\n async (input: CodeMapInput) => jsonResult(await codeMapTool(input, context)),\n );\n\n // ── Memory lifecycle ───────────────────────────────────────────────────\n\n server.tool(\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 server.tool(\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 (haive 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 server.tool(\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 server.tool(\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 server.tool(\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 server.tool(\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 server.tool(\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 server.prompt(\n \"bootstrap_project\",\n [\n \"Analyze the project codebase and write .ai/project-context.md — run once after haive 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 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 server.prompt(\n \"import_docs\",\n [\n \"Import knowledge from a document (README, ADR, wiki, API spec) as hAIve 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 return { server, context, tracker };\n}\n","import { findProjectRoot, resolveHaivePaths, type HaivePaths } from \"@hiveai/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 \"@hiveai/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} from \"@hiveai/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\", \"attempt\", \"session_recap\"])\n .describe(\n \"Kind of memory being saved. 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 .default(\"personal\")\n .describe(\"Visibility scope: personal | team | module\"),\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};\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 invalid_paths?: string[];\n}\n\nfunction bodyHash(body: string): string {\n return createHash(\"sha256\").update(body.trim()).digest(\"hex\").slice(0, 12);\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 'haive init' first.`,\n );\n }\n\n const existing = existsSync(ctx.paths.memoriesDir)\n ? await loadMemoriesFromDir(ctx.paths.memoriesDir)\n : [];\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 === input.scope,\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 // ── Topic upsert ───────────────────────────────────────────────────────\n if (input.topic) {\n const topicMatch = existing.find(({ memory }) =>\n memory.frontmatter.topic === input.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 newFrontmatter = {\n ...fm,\n body: input.body,\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 return {\n id: fm.id,\n scope: fm.scope,\n file_path: topicMatch.filePath,\n action: \"updated\",\n revision_count: newFrontmatter.revision_count,\n ...(invalidPaths.length > 0 ? { invalid_paths: invalidPaths, warning: `Anchor path(s) not found in project: ${invalidPaths.join(\", \")}. They will be marked stale by haive sync.` } : {}),\n };\n }\n }\n\n // ── Create new memory ──────────────────────────────────────────────────\n const haiveConfig = await loadConfig(ctx.paths);\n\n // In autopilot mode: memories go directly to validated (skip approval cycle)\n // Also apply config defaults for scope\n const resolvedScope = input.scope !== \"personal\"\n ? input.scope\n : (haiveConfig.defaultScope ?? \"personal\");\n\n const frontmatter = buildFrontmatter({\n type: input.type,\n slug: input.slug,\n scope: resolvedScope as \"personal\" | \"team\" | \"module\",\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 });\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 // Merge invalid_paths warning with slug similarity warning\n const finalWarning = [\n invalidPaths.length > 0\n ? `Anchor path(s) not found in project: ${invalidPaths.join(\", \")}. They will be marked stale by \\`haive sync\\`.`\n : null,\n warning ?? 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 ...(invalidPaths.length > 0 ? { invalid_paths: invalidPaths } : {}),\n };\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 tokenizeQuery,\n trackReads,\n type ConfidenceLevel,\n type LoadedMemory,\n type UsageIndex,\n} from \"@hiveai/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 `haive embeddings index`).\",\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\";\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 @hiveai/embeddings not installed). Falling back to literal search.\",\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(\"@hiveai/embeddings\");\n try {\n mod = await import(\"@hiveai/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","import { writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport {\n loadMemoriesFromDir,\n serializeMemory,\n verifyAnchor,\n type Memory,\n} from \"@hiveai/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 \"@hiveai/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 { 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 \"@hiveai/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 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 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 \"@hiveai/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 \"@hiveai/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 \"@hiveai/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 \"@hiveai/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 \"@hiveai/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 frontmatter: { ...found.memory.frontmatter, status: \"validated\" 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} from \"@hiveai/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\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 'haive 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 return { id: frontmatter.id, scope: frontmatter.scope, file_path: file };\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} from \"@hiveai/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};\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}\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 'haive 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, 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 \"@hiveai/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.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 'haive init' first.`);\n }\n\n const body = buildBody(input);\n const topic = recapTopic(input.scope, input.module);\n\n // Validate anchor paths exist before saving\n const invalidPaths = input.files_touched.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 revision_count: revisionCount,\n anchor: {\n ...fm.anchor,\n paths: input.files_touched.length ? input.files_touched : fm.anchor.paths,\n },\n };\n await writeFile(\n topicMatch.filePath,\n serializeMemory({ frontmatter: newFrontmatter, body }),\n \"utf8\",\n );\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: input.files_touched,\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 return {\n id: frontmatter.id,\n scope: frontmatter.scope,\n file_path: file,\n action: \"created\",\n revision_count: 0,\n };\n}\n","import { readFile, readdir } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n allocateBudget,\n deriveConfidence,\n estimateTokens,\n getUsage,\n inferModulesFromPaths,\n isDecaying,\n literalMatchesAllTokens,\n literalMatchesAnyToken,\n loadCodeMap,\n loadConfig,\n loadMemoriesFromDir,\n loadUsageIndex,\n memoryMatchesAnchorPaths,\n queryCodeMap,\n tokenizeQuery,\n trackReads,\n truncateToTokens,\n type ConfidenceLevel,\n type LoadedMemory,\n type UsageIndex,\n} from \"@hiveai/core\";\nimport { z } from \"zod\";\nimport type { HaiveContext } from \"../context.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 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 `haive 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\"])\n .default(\"full\")\n .describe(\n \"Output format: 'full' returns complete memory bodies; 'compact' returns id + 1-line summary only (call mem_get for details).\",\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 `haive index code` to have been run.\",\n ),\n};\n\nexport type GetBriefingInput = {\n [K in keyof typeof GetBriefingInputSchema]: z.infer<(typeof GetBriefingInputSchema)[K]>;\n};\n\nexport interface BriefingMemory {\n id: string;\n scope: string;\n type: string;\n module?: string;\n tags: string[];\n status: string;\n confidence: ConfidenceLevel;\n /** Present when confidence is 'low' or 'unverified' — AI should weight this memory cautiously. */\n unverified?: true;\n read_count: number;\n reasons: Array<\"anchor\" | \"module\" | \"domain\" | \"semantic\">;\n match_quality: \"exact\" | \"partial\" | \"semantic\";\n semantic_score?: number;\n body: string;\n file_path: string;\n}\n\nexport interface CodeMapSymbolHit {\n symbol: string;\n /** files that export this symbol */\n locations: Array<{\n file: string;\n kind: string;\n line: number;\n description?: string;\n }>;\n}\n\nexport interface BriefingOutput {\n task?: string;\n search_mode: \"semantic\" | \"literal_fallback\" | \"literal\";\n match_quality_note?: string;\n inferred_modules: string[];\n last_session?: { id: string; scope: string; revision_count: number; body: string };\n project_context: { content: string; truncated: boolean; is_template?: boolean; auto_generated?: boolean } | null;\n module_contexts: Array<{ name: string; content: string; truncated: boolean }>;\n memories: BriefingMemory[];\n symbol_locations?: CodeMapSymbolHit[];\n decay_warnings: string[];\n setup_warnings: string[];\n estimated_tokens: number;\n budget: { max_tokens: number; spent: { project: number; modules: number; memories: number } };\n}\n\nexport async function getBriefing(\n input: GetBriefingInput,\n ctx: HaiveContext,\n): Promise<BriefingOutput> {\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 // Find the most recent session_recap (by created_at) — exclude from main ranking\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 body: r.memory.body,\n };\n }\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 // session_recap surfaces separately in last_session, not in the ranked memories list\n if (memory.frontmatter.type === \"session_recap\") return false;\n return true;\n });\n usage = await loadUsageIndex(ctx.paths);\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 // upgrade match_quality if better evidence found\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 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 reasons: [reason],\n match_quality: matchQuality ?? \"partial\",\n ...(score !== undefined ? { semantic_score: score } : {}),\n body: loaded.memory.body,\n file_path: loaded.filePath,\n });\n };\n\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.task) {\n const tokens = tokenizeQuery(input.task);\n // AND first — exact match\n const andHits = allMemories.filter((m) => literalMatchesAllTokens(m.memory, tokens));\n for (const loaded of andHits) {\n addOrUpdate(loaded, \"semantic\", undefined, \"exact\");\n }\n // OR fallback — if AND produced nothing, partial match is better than nothing\n if (andHits.length === 0 && tokens.length > 1) {\n for (const loaded of allMemories) {\n if (literalMatchesAnyToken(loaded.memory, tokens)) {\n addOrUpdate(loaded, \"semantic\", undefined, \"partial\");\n }\n }\n }\n if (semanticHits) {\n for (const hit of semanticHits) {\n const loaded = byId.get(hit.id);\n if (loaded) addOrUpdate(loaded, \"semantic\", hit.score, \"semantic\");\n }\n }\n }\n\n const ranked = [...seen.values()].sort((a, b) => {\n const reasonScore = (m: BriefingMemory): number =>\n (m.type === \"attempt\" ? 3 : 0) + // attempt = negative knowledge, surface first to prevent repeating mistakes\n (m.reasons.includes(\"anchor\") ? 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 const sa = reasonScore(a) + confidenceScore(a) + (a.semantic_score ?? 0);\n const sb = reasonScore(b) + confidenceScore(b) + (b.semantic_score ?? 0);\n return sb - sa;\n });\n\n // Expand related_ids: pull in memories linked from the top results\n byId = new Map(allMemories.map((m) => [m.memory.frontmatter.id, m]));\n for (const mem of ranked.slice(0, input.max_memories)) {\n if (seen.size >= input.max_memories * 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, input.max_memories));\n\n if (input.track && memories.length > 0) {\n await trackReads(ctx.paths, memories.map((m) => m.id));\n }\n }\n\n // Build raw section payloads\n const projectContextRaw =\n input.include_project_context && existsSync(ctx.paths.projectContext)\n ? await readFile(ctx.paths.projectContext, \"utf8\")\n : \"\";\n const isTemplateContext =\n projectContextRaw.includes(\"TODO — high-level overview\") ||\n projectContextRaw.includes(\"Generated by `haive init`\");\n\n const setupWarnings: string[] = [];\n let autoContextGenerated = false;\n\n // In autopilot mode: if project-context.md is still the template, auto-generate\n // a minimal context from the code-map so get_briefing is useful immediately.\n let projectContext = isTemplateContext ? \"\" : projectContextRaw;\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\n // Pick top exported symbols as a starting overview\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 projectContext =\n `# Project context (auto-generated by hAIve)\\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 `## 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 `haive index code` then invoke bootstrap_project for a full context.\",\n );\n }\n } else {\n if (isTemplateContext) {\n setupWarnings.push(\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 );\n } else {\n setupWarnings.push(\n \"No project-context.md found. Run `haive init` then invoke the bootstrap_project MCP prompt.\",\n );\n }\n }\n }\n\n const moduleContents = input.include_module_contexts\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 // Allocate budget across the three large pieces\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 input.max_tokens,\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 // Distribute the modules slice across module entries proportionally\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 // Recompute memory bodies to fit using a cascade approach:\n // top-ranked memories get full budget first; lower-ranked ones are dropped if budget runs out.\n // This is better than uniform truncation which gives all memories a 37%-fragment.\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 // Enough budget for a meaningful fragment — truncate and include\n const t = truncateToTokens(m.body, { maxTokens: remaining, mode: \"head\" });\n trimmedMemories.push({ ...m, body: t.text });\n remaining = 0;\n }\n // Otherwise skip — too small a fragment to be useful\n }\n }\n\n const totalTokens =\n projectSlice.estimatedTokens + modulesSlice.estimatedTokens + memoriesSlice.estimatedTokens;\n\n // Decay warnings: memories not read in >90 days\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 // Compact format: replace body with 1-line summary\n const outputMemories =\n input.format === \"compact\"\n ? trimmedMemories.map((m) => ({ ...m, body: compactSummary(m.body) }))\n : trimmedMemories;\n\n // ── Code-map symbol lookup ──────────────────────────────────────────────\n // Also auto-look up symbols found in anchor paths of returned memories +\n // any explicit symbols[] the caller requested.\n let symbolLocations: CodeMapSymbolHit[] | undefined;\n const symbolsToLookup = new Set<string>(input.symbols);\n // Auto-collect symbols from memory anchors so agents get locations for free\n for (const m of outputMemories) {\n const loaded = byId.get(m.id);\n for (const sym of loaded?.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 return {\n ...(input.task ? { task: input.task } : {}),\n search_mode: searchMode,\n inferred_modules: inferred,\n ...(lastSession ? { last_session: lastSession } : {}),\n project_context: (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 ...(symbolLocations ? { symbol_locations: symbolLocations } : {}),\n decay_warnings: decayWarnings,\n setup_warnings: setupWarnings,\n estimated_tokens: totalTokens,\n budget: {\n max_tokens: input.max_tokens,\n spent: {\n project: projectSlice.estimatedTokens,\n modules: modulesSlice.estimatedTokens,\n memories: memoriesSlice.estimatedTokens,\n },\n },\n };\n}\n\nfunction 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\nasync function trySemanticHits(\n ctx: HaiveContext,\n task: string,\n limit: number,\n): Promise<Array<{ id: string; score: number }> | null> {\n let mod: typeof import(\"@hiveai/embeddings\");\n try {\n mod = await import(\"@hiveai/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\nasync 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\n// Re-export estimateTokens at the module level for tests.\nexport { estimateTokens };\n","import { loadCodeMap, queryCodeMap } from \"@hiveai/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 max_files: z\n .number()\n .int()\n .positive()\n .default(40)\n .describe(\"Cap on returned files\"),\n};\n\nexport type CodeMapInput = {\n [K in keyof typeof CodeMapInputSchema]: z.infer<(typeof CodeMapInputSchema)[K]>;\n};\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 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 `haive index code` to generate `.ai/code-map.json`.\",\n };\n }\n const { files } = queryCodeMap(map, { file: input.file, symbol: input.symbol });\n return {\n available: true,\n generated_at: map.generated_at,\n total_files: Object.keys(map.files).length,\n files: files.slice(0, input.max_files).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 };\n}\n","import { existsSync } from \"node:fs\";\nimport { loadMemoriesFromDir } from \"@hiveai/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 { 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 hAIve 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 { 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\nWhen done, respond with a brief summary: \"Saved N memories: [list of IDs]. Session recap saved.\"\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 hAIve 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 hAIve memories\",\n messages: [\n {\n role: \"user\",\n content: { type: \"text\", text },\n },\n ],\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 * saves a session recap via mem_session_end — no human action needed.\n */\nimport { loadConfig, type HaiveConfig } from \"@hiveai/core\";\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\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 this.events.push({ tool, at: new Date().toISOString(), summary });\n }\n\n private registerShutdownHandler(): void {\n if (this.shutdownRegistered) return;\n this.shutdownRegistered = true;\n\n const save = async (): Promise<void> => {\n // Only save if something actually happened this session\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 // Extract any file paths mentioned in summaries\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 try {\n 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 } catch {\n // Non-fatal — never block process exit\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\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"],"mappings":";;;AAAA,SAAS,4BAA4B;;;ACArC,SAAS,iBAAiB;;;ACA1B,SAAS,iBAAiB,yBAA0C;AAY7D,SAAS,cAAc,UAAgC,CAAC,GAAiB;AAC9E,QAAM,MAAM,QAAQ,OAAO,QAAQ;AACnC,QAAM,MAAM,QAAQ,OAAO,QAAQ,IAAI;AACvC,QAAM,OACJ,QAAQ,QACR,IAAI,sBACJ,gBAAgB,GAAG;AACrB,SAAO,EAAE,OAAO,kBAAkB,IAAI,EAAE;AAC1C;;;ACpBA,SAAS,OAAO,iBAAiB;AACjC,SAAS,kBAAkB;AAC3B,OAAO,UAAU;AACjB,SAAS,SAAS;AAGX,IAAM,kCAAkC;AAAA,EAC7C,SAAS,EACN,OAAO,EACP,IAAI,CAAC,EACL,SAAS,gEAAgE;AAAA,EAC5E,QAAQ,EACL,OAAO,EACP,SAAS,EACT;AAAA,IACC;AAAA,EACF;AAAA,EACF,WAAW,EACR,QAAQ,EACR,QAAQ,KAAK,EACb,SAAS,+CAA+C;AAC7D;AAaA,eAAsB,qBACpB,OACA,KACqC;AACrC,QAAM,SAAS,MAAM,SACjB,KAAK,KAAK,IAAI,MAAM,mBAAmB,MAAM,QAAQ,YAAY,IACjE,IAAI,MAAM;AAEd,QAAM,SAAS,WAAW,MAAM;AAChC,MAAI,UAAU,CAAC,MAAM,W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ACtE;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,EAAE,KAAK,GAAG;AAAA,IACV;AAAA,IACA,CAAC,SAAuB,eAAe,MAAM,OAAO;AAAA,EACtD;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,EAAE,KAAK,GAAG;AAAA,IACV;AAAA,IACA,CAAC,SAAyB,iBAAiB,MAAM,OAAO;AAAA,EAC1D;AAEA,SAAO,EAAE,QAAQ,SAAS,QAAQ;AACpC;;;AD9mBA,SAAS,UAAU,MAAmC;AACpD,QAAM,MAAyB,CAAC;AAChC,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,UAAM,MAAM,KAAK,CAAC;AAClB,QAAI,QAAQ,YAAY,QAAQ,MAAM;AACpC,UAAI,OAAO,KAAK,EAAE,CAAC;AAAA,IACrB,WAAW,KAAK,WAAW,SAAS,GAAG;AACrC,UAAI,OAAO,IAAI,MAAM,UAAU,MAAM;AAAA,IACvC;AAAA,EACF;AACA,SAAO;AACT;AAEA,eAAe,OAAsB;AACnC,QAAM,EAAE,KAAK,IAAI,UAAU,QAAQ,IAAI;AACvC,QAAM,EAAE,QAAQ,QAAQ,IAAI,kBAAkB,EAAE,KAAK,CAAC;AAEtD,UAAQ;AAAA,IACN,gCAAgC,cAAc,mBAAmB,QAAQ,MAAM,IAAI;AAAA,EACrF;AACA,QAAM,YAAY,IAAI,qBAAqB;AAC3C,QAAM,OAAO,QAAQ,SAAS;AAChC;AAEA,KAAK,EAAE,MAAM,CAAC,QAAiB;AAC7B,UAAQ,MAAM,sBAAsB,eAAe,QAAQ,IAAI,UAAU,GAAG;AAC5E,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["existsSync","path","z","existsSync","z","mkdir","writeFile","existsSync","path","loadMemoriesFromDir","z","existsSync","loadMemoriesFromDir","z","top","writeFile","existsSync","loadMemoriesFromDir","serializeMemory","z","writeFile","existsSync","loadMemoriesFromDir","loadUsageIndex","serializeMemory","z","readFile","readdir","existsSync","path","deriveConfidence","getUsage","loadMemoriesFromDir","loadUsageIndex","trackReads","z","existsSync","deriveConfidence","getUsage","loadMemoriesFromDir","loadUsageIndex","z","existsSync","loadMemoriesFromDir","loadUsageIndex","saveUsageIndex","z","writeFile","existsSync","loadMemoriesFromDir","serializeMemory","z","existsSync","getUsage","loadMemoriesFromDir","loadUsageIndex","z","writeFile","existsSync","loadMemoriesFromDir","serializeMemory","z","mkdir","writeFile","existsSync","path","buildFrontmatter","memoryFilePath","serializeMemory","z","mkdir","writeFile","existsSync","path","buildFrontmatter","memoryFilePath","serializeMemory","z","writeFile","mkdir","existsSync","path","buildFrontmatter","loadMemoriesFromDir","memoryFilePath","serializeMemory","z","readFile","readdir","existsSync","path","deriveConfidence","getUsage","inferModulesFromPaths","literalMatchesAllTokens","literalMatchesAnyToken","loadConfig","loadMemoriesFromDir","loadUsageIndex","memoryMatchesAnchorPaths","tokenizeQuery","trackReads","z","loadModuleContexts","loadCodeMap","queryCodeMap","z","existsSync","loadMemoriesFromDir","z","z","z","z","loadConfig","loadConfig"]}
|