@hiveai/mcp 0.2.7 → 0.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/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/get-briefing.ts","../src/tools/code-map.ts","../src/prompts/bootstrap-project.ts","../src/prompts/post-task.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 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 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\";\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 } {\n const context = createContext(options);\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) => jsonResult(await memSave(input, context)),\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) => jsonResult(await getBriefing(input, context)),\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) => jsonResult(await memTried(input, context)),\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 return { server, context };\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 { mkdir, writeFile } 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 MemSaveInputSchema = {\n type: z\n .enum([\"convention\", \"decision\", \"gotcha\", \"architecture\", \"glossary\", \"attempt\"])\n .describe(\"Kind of memory being saved. Use 'attempt' for failed approaches (auto-validated).\"),\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};\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 warning?: string;\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 frontmatter = buildFrontmatter({\n type: input.type,\n slug: input.slug,\n scope: input.scope,\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 });\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 // Dedup check: warn if a memory with a similar slug already exists\n let warning: string | undefined;\n if (existsSync(ctx.paths.memoriesDir)) {\n const existing = await loadMemoriesFromDir(ctx.paths.memoriesDir);\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 slugTokens.length >= 2 && slugTokens.filter((t) => id.includes(t)).length >= Math.ceil(slugTokens.length * 0.6);\n });\n if (similar.length > 0) {\n warning = `Possible duplicate detected. Similar memories: ${similar.map((m) => m.memory.frontmatter.id).join(\", \")}. Consider updating one of these instead.`;\n }\n }\n\n await writeFile(file, serializeMemory({ frontmatter, body: input.body }), \"utf8\");\n\n return {\n id: frontmatter.id,\n scope: frontmatter.scope,\n file_path: file,\n ...(warning ? { warning } : {}),\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\"])\n .optional()\n .describe(\"Restrict results to a memory type\"),\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\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 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 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 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 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 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 for (const loaded of all) {\n if (seen.has(loaded.memory.frontmatter.id)) 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 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 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\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 { 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 literalMatchesAllTokens,\n loadMemoriesFromDir,\n loadUsageIndex,\n memoryMatchesAnchorPaths,\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};\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 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 BriefingOutput {\n task?: string;\n search_mode: \"semantic\" | \"literal_fallback\" | \"literal\";\n match_quality_note?: string;\n inferred_modules: string[];\n project_context: { content: string; truncated: boolean } | null;\n module_contexts: Array<{ name: string; content: string; truncated: boolean }>;\n memories: BriefingMemory[];\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\n if (existsSync(ctx.paths.memoriesDir)) {\n const allLoaded = await loadMemoriesFromDir(ctx.paths.memoriesDir);\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 return true;\n });\n const 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 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 for (const loaded of allMemories) {\n if (literalMatchesAllTokens(loaded.memory, tokens)) {\n addOrUpdate(loaded, \"semantic\", undefined, \"exact\");\n }\n }\n if (semanticHits) {\n const byId = new Map(allMemories.map((m) => [m.memory.frontmatter.id, m]));\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 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 projectContext =\n input.include_project_context && existsSync(ctx.paths.projectContext)\n ? await readFile(ctx.paths.projectContext, \"utf8\")\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 const trimmedMemoriesText = memoriesSlice.text;\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 return {\n ...(input.task ? { task: input.task } : {}),\n search_mode: searchMode,\n inferred_modules: inferred,\n project_context: projectContext\n ? { content: projectSlice.text, truncated: projectSlice.truncated }\n : null,\n module_contexts: trimmedModules,\n memories: trimmedMemories,\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\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 { 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### 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?\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\nWhen done, respond with a brief summary: \"Saved N memories: [list of IDs]\" or \"Nothing new to save.\"\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"],"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,WAAW;AAC9B,UAAM,IAAI;AAAA,MACR,GAAG,MAAM;AAAA,IACX;AAAA,EACF;AAEA,QAAM,MAAM,KAAK,QAAQ,MAAM,GAAG,E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,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","readFile","readdir","existsSync","path","deriveConfidence","getUsage","inferModulesFromPaths","literalMatchesAllTokens","loadMemoriesFromDir","loadUsageIndex","memoryMatchesAnchorPaths","tokenizeQuery","trackReads","z","loadModuleContexts","z","z","z"]}
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/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"],"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 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\";\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 } {\n const context = createContext(options);\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) => jsonResult(await memSave(input, context)),\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) => jsonResult(await getBriefing(input, context)),\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) => jsonResult(await memTried(input, context)),\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.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 };\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 { mkdir, writeFile } 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 MemSaveInputSchema = {\n type: z\n .enum([\"convention\", \"decision\", \"gotcha\", \"architecture\", \"glossary\", \"attempt\"])\n .describe(\"Kind of memory being saved. Use 'attempt' for failed approaches (auto-validated).\"),\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};\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 warning?: string;\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 frontmatter = buildFrontmatter({\n type: input.type,\n slug: input.slug,\n scope: input.scope,\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 });\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 // Dedup check: warn if a memory with a similar slug already exists\n let warning: string | undefined;\n if (existsSync(ctx.paths.memoriesDir)) {\n const existing = await loadMemoriesFromDir(ctx.paths.memoriesDir);\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 slugTokens.length >= 2 && slugTokens.filter((t) => id.includes(t)).length >= Math.ceil(slugTokens.length * 0.6);\n });\n if (similar.length > 0) {\n warning = `Possible duplicate detected. Similar memories: ${similar.map((m) => m.memory.frontmatter.id).join(\", \")}. Consider updating one of these instead.`;\n }\n }\n\n await writeFile(file, serializeMemory({ frontmatter, body: input.body }), \"utf8\");\n\n return {\n id: frontmatter.id,\n scope: frontmatter.scope,\n file_path: file,\n ...(warning ? { warning } : {}),\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\"])\n .optional()\n .describe(\"Restrict results to a memory type\"),\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\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 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 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 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 for (const loaded of all) {\n if (seen.has(loaded.memory.frontmatter.id)) 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 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 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\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 { 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 loadMemoriesFromDir,\n loadUsageIndex,\n memoryMatchesAnchorPaths,\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};\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 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 BriefingOutput {\n task?: string;\n search_mode: \"semantic\" | \"literal_fallback\" | \"literal\";\n match_quality_note?: string;\n inferred_modules: string[];\n project_context: { content: string; truncated: boolean } | null;\n module_contexts: Array<{ name: string; content: string; truncated: boolean }>;\n memories: BriefingMemory[];\n decay_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 if (existsSync(ctx.paths.memoriesDir)) {\n const allLoaded = await loadMemoriesFromDir(ctx.paths.memoriesDir);\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 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 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 for (const loaded of allMemories) {\n if (literalMatchesAllTokens(loaded.memory, tokens)) {\n addOrUpdate(loaded, \"semantic\", undefined, \"exact\");\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 projectContext =\n input.include_project_context && existsSync(ctx.paths.projectContext)\n ? await readFile(ctx.paths.projectContext, \"utf8\")\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 return {\n ...(input.task ? { task: input.task } : {}),\n search_mode: searchMode,\n inferred_modules: inferred,\n project_context: projectContext\n ? { content: projectSlice.text, truncated: projectSlice.truncated }\n : null,\n module_contexts: trimmedModules,\n memories: outputMemories,\n decay_warnings: decayWarnings,\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### 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?\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\nWhen done, respond with a brief summary: \"Saved N memories: [list of IDs]\" or \"Nothing new to save.\"\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"],"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,qBACp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,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","readFile","readdir","existsSync","path","deriveConfidence","getUsage","inferModulesFromPaths","literalMatchesAllTokens","loadMemoriesFromDir","loadUsageIndex","memoryMatchesAnchorPaths","tokenizeQuery","trackReads","z","loadModuleContexts","z","existsSync","loadMemoriesFromDir","z","z","z","z"]}