@hiveai/mcp 0.3.0 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -130,6 +130,7 @@ import { existsSync as existsSync4 } from "fs";
130
130
  import path3 from "path";
131
131
  import {
132
132
  buildFrontmatter,
133
+ loadConfig,
133
134
  loadMemoriesFromDir as loadMemoriesFromDir2,
134
135
  memoryFilePath,
135
136
  serializeMemory
@@ -207,10 +208,12 @@ async function memSave(input, ctx) {
207
208
  };
208
209
  }
209
210
  }
211
+ const haiveConfig = await loadConfig(ctx.paths);
212
+ const resolvedScope = input.scope !== "personal" ? input.scope : haiveConfig.defaultScope ?? "personal";
210
213
  const frontmatter = buildFrontmatter({
211
214
  type: input.type,
212
215
  slug: input.slug,
213
- scope: input.scope,
216
+ scope: resolvedScope,
214
217
  module: input.module,
215
218
  tags: input.tags,
216
219
  domain: input.domain,
@@ -218,7 +221,8 @@ async function memSave(input, ctx) {
218
221
  paths: input.paths,
219
222
  symbols: input.symbols,
220
223
  commit: input.commit,
221
- topic: input.topic
224
+ topic: input.topic,
225
+ status: haiveConfig.defaultStatus === "validated" ? "validated" : void 0
222
226
  });
223
227
  const file = memoryFilePath(
224
228
  ctx.paths,
@@ -1165,6 +1169,7 @@ import {
1165
1169
  literalMatchesAllTokens as literalMatchesAllTokens2,
1166
1170
  literalMatchesAnyToken as literalMatchesAnyToken2,
1167
1171
  loadCodeMap,
1172
+ loadConfig as loadConfig2,
1168
1173
  loadMemoriesFromDir as loadMemoriesFromDir13,
1169
1174
  loadUsageIndex as loadUsageIndex7,
1170
1175
  memoryMatchesAnchorPaths as memoryMatchesAnchorPaths2,
@@ -1322,17 +1327,55 @@ async function getBriefing(input, ctx) {
1322
1327
  }
1323
1328
  const projectContextRaw = input.include_project_context && existsSync17(ctx.paths.projectContext) ? await readFile3(ctx.paths.projectContext, "utf8") : "";
1324
1329
  const isTemplateContext = projectContextRaw.includes("TODO \u2014 high-level overview") || projectContextRaw.includes("Generated by `haive init`");
1325
- const projectContext = isTemplateContext ? "" : projectContextRaw;
1326
1330
  const setupWarnings = [];
1327
- if (isTemplateContext) {
1328
- setupWarnings.push(
1329
- "project-context.md still contains the default template. Invoke the bootstrap_project MCP prompt to auto-fill it from your codebase. Until then, get_briefing returns no project context."
1330
- );
1331
- }
1332
- if (!existsSync17(ctx.paths.projectContext)) {
1333
- setupWarnings.push(
1334
- "No project-context.md found. Run `haive init` then invoke the bootstrap_project MCP prompt."
1335
- );
1331
+ let autoContextGenerated = false;
1332
+ let projectContext = isTemplateContext ? "" : projectContextRaw;
1333
+ if ((isTemplateContext || !existsSync17(ctx.paths.projectContext)) && input.include_project_context) {
1334
+ const haiveConfig = await loadConfig2(ctx.paths);
1335
+ if (haiveConfig.autoContext) {
1336
+ const codeMap = await loadCodeMap(ctx.paths);
1337
+ if (codeMap) {
1338
+ const totalFiles = Object.keys(codeMap.files).length;
1339
+ const extensions = /* @__PURE__ */ new Map();
1340
+ for (const filePath of Object.keys(codeMap.files)) {
1341
+ const ext = filePath.slice(filePath.lastIndexOf(".") + 1).toLowerCase();
1342
+ extensions.set(ext, (extensions.get(ext) ?? 0) + 1);
1343
+ }
1344
+ const topExts = [...extensions.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5).map(([e, n]) => `${e} (${n})`).join(", ");
1345
+ const topSymbols = Object.entries(codeMap.files).flatMap(
1346
+ ([fp, entry]) => entry.exports.slice(0, 3).map((e) => `${e.name} (${fp.split("/").slice(-2).join("/")})`)
1347
+ ).slice(0, 15).join(", ");
1348
+ projectContext = `# Project context (auto-generated by hAIve)
1349
+
1350
+ > \u26A0 This is a minimal auto-generated context based on the code-map. Invoke the \`bootstrap_project\` MCP prompt to replace it with a full analysis.
1351
+
1352
+ ## Codebase overview
1353
+ - **${totalFiles} files** indexed in code-map
1354
+ - **Main file types:** ${topExts}
1355
+ - **Generated at:** ${codeMap.generated_at}
1356
+
1357
+ ## Key exports (sample)
1358
+ ` + topSymbols + "\n";
1359
+ autoContextGenerated = true;
1360
+ setupWarnings.push(
1361
+ "project-context.md is still the default template. A minimal auto-generated context has been injected from the code-map. Invoke bootstrap_project to replace it with a full AI-analyzed context."
1362
+ );
1363
+ } else {
1364
+ setupWarnings.push(
1365
+ "project-context.md is still the default template and no code-map found. Run `haive index code` then invoke bootstrap_project for a full context."
1366
+ );
1367
+ }
1368
+ } else {
1369
+ if (isTemplateContext) {
1370
+ setupWarnings.push(
1371
+ "project-context.md still contains the default template. Invoke the bootstrap_project MCP prompt to auto-fill it from your codebase. Until then, get_briefing returns no project context."
1372
+ );
1373
+ } else {
1374
+ setupWarnings.push(
1375
+ "No project-context.md found. Run `haive init` then invoke the bootstrap_project MCP prompt."
1376
+ );
1377
+ }
1378
+ }
1336
1379
  }
1337
1380
  const moduleContents = input.include_module_contexts ? await loadModuleContexts2(ctx, inferred) : [];
1338
1381
  const memoriesText = memories.map((m) => {
@@ -1431,10 +1474,11 @@ ${m.content}`).join("\n\n---\n\n"),
1431
1474
  search_mode: searchMode,
1432
1475
  inferred_modules: inferred,
1433
1476
  ...lastSession ? { last_session: lastSession } : {},
1434
- project_context: projectContextRaw ? {
1477
+ project_context: projectContextRaw || autoContextGenerated ? {
1435
1478
  content: projectSlice.text,
1436
1479
  truncated: projectSlice.truncated,
1437
- ...isTemplateContext ? { is_template: true } : {}
1480
+ ...isTemplateContext && !autoContextGenerated ? { is_template: true } : {},
1481
+ ...autoContextGenerated ? { auto_generated: true } : {}
1438
1482
  } : null,
1439
1483
  module_contexts: trimmedModules,
1440
1484
  memories: outputMemories,
@@ -1804,9 +1848,78 @@ When done, respond with: "Imported N memories: [list of IDs]" or "Nothing action
1804
1848
  };
1805
1849
  }
1806
1850
 
1851
+ // src/session-tracker.ts
1852
+ import { loadConfig as loadConfig3 } from "@hiveai/core";
1853
+ var SessionTracker = class {
1854
+ events = [];
1855
+ startedAt = (/* @__PURE__ */ new Date()).toISOString();
1856
+ config = null;
1857
+ ctx;
1858
+ shutdownRegistered = false;
1859
+ constructor(ctx) {
1860
+ this.ctx = ctx;
1861
+ }
1862
+ async init() {
1863
+ this.config = await loadConfig3(this.ctx.paths);
1864
+ if (this.config.autoSessionEnd) {
1865
+ this.registerShutdownHandler();
1866
+ }
1867
+ }
1868
+ record(tool, summary) {
1869
+ this.events.push({ tool, at: (/* @__PURE__ */ new Date()).toISOString(), summary });
1870
+ }
1871
+ registerShutdownHandler() {
1872
+ if (this.shutdownRegistered) return;
1873
+ this.shutdownRegistered = true;
1874
+ const save = async () => {
1875
+ const writingTools = this.events.filter(
1876
+ (e) => ["mem_save", "mem_tried", "mem_observe", "mem_update", "bootstrap_project_save"].includes(e.tool)
1877
+ );
1878
+ const totalCalls = this.events.length;
1879
+ if (totalCalls === 0) return;
1880
+ const toolSummary = summarizeTools(this.events);
1881
+ const filesSet = /* @__PURE__ */ new Set();
1882
+ for (const e of this.events) {
1883
+ if (e.summary) {
1884
+ const matches = e.summary.match(/[^\s"',]+\.[a-zA-Z]{1,6}/g) ?? [];
1885
+ for (const m of matches) filesSet.add(m);
1886
+ }
1887
+ }
1888
+ try {
1889
+ await memSessionEnd(
1890
+ {
1891
+ goal: `Auto-captured session (${totalCalls} tool call${totalCalls === 1 ? "" : "s"})`,
1892
+ accomplished: toolSummary,
1893
+ discoveries: writingTools.length > 0 ? `${writingTools.length} memor${writingTools.length === 1 ? "y" : "ies"} saved during this session.` : "No new memories saved this session.",
1894
+ files_touched: [...filesSet].slice(0, 10),
1895
+ next_steps: "",
1896
+ scope: this.config?.defaultScope ?? "personal",
1897
+ module: void 0
1898
+ },
1899
+ this.ctx
1900
+ );
1901
+ } catch {
1902
+ }
1903
+ };
1904
+ process.once("SIGTERM", () => {
1905
+ void save().finally(() => process.exit(0));
1906
+ });
1907
+ process.once("SIGINT", () => {
1908
+ void save().finally(() => process.exit(0));
1909
+ });
1910
+ }
1911
+ };
1912
+ function summarizeTools(events) {
1913
+ const counts = /* @__PURE__ */ new Map();
1914
+ for (const e of events) {
1915
+ counts.set(e.tool, (counts.get(e.tool) ?? 0) + 1);
1916
+ }
1917
+ return [...counts.entries()].sort((a, b) => b[1] - a[1]).map(([t, n]) => `${t} \xD7${n}`).join(", ");
1918
+ }
1919
+
1807
1920
  // src/server.ts
1808
1921
  var SERVER_NAME = "haive";
1809
- var SERVER_VERSION = "0.3.0";
1922
+ var SERVER_VERSION = "0.3.3";
1810
1923
  function jsonResult(data) {
1811
1924
  return {
1812
1925
  content: [
@@ -1819,143 +1932,474 @@ function jsonResult(data) {
1819
1932
  }
1820
1933
  function createHaiveServer(options = {}) {
1821
1934
  const context = createContext(options);
1935
+ const tracker = new SessionTracker(context);
1936
+ void tracker.init();
1822
1937
  const server = new McpServer(
1823
1938
  { name: SERVER_NAME, version: SERVER_VERSION },
1824
1939
  { capabilities: { tools: {}, prompts: {} } }
1825
1940
  );
1826
1941
  server.tool(
1827
1942
  "mem_save",
1828
- "Save a new memory (convention, decision, gotcha, architecture, glossary). For failed approaches use mem_tried instead \u2014 it enforces a structured format that is more useful to future agents. Use scope=team to share with the whole team.",
1943
+ [
1944
+ "Save a piece of knowledge as a persistent memory that survives across AI sessions.",
1945
+ "",
1946
+ "USE THIS WHEN you discover something worth remembering for future sessions:",
1947
+ " - A project convention (how things are done here)",
1948
+ " - An architectural decision and its rationale",
1949
+ " - A gotcha or non-obvious behavior that surprised you",
1950
+ " - A domain term and what it means in this codebase",
1951
+ "",
1952
+ "DO NOT USE for failed approaches \u2192 use mem_tried instead (better structure).",
1953
+ "DO NOT USE for code discoveries during exploration \u2192 use mem_observe instead.",
1954
+ "",
1955
+ "PARAMETERS:",
1956
+ " type \u2014 convention | decision | gotcha | architecture | glossary | attempt",
1957
+ " slug \u2014 short kebab-case id (e.g. 'flyway-no-modify-existing')",
1958
+ " body \u2014 Markdown content with the full knowledge",
1959
+ " scope \u2014 team (shared with all devs) | personal (private) | module (component-scoped)",
1960
+ " paths \u2014 anchor to source files for staleness detection (STRONGLY recommended)",
1961
+ " topic \u2014 stable key for upsert: if a memory with same topic+scope exists, update it in-place",
1962
+ "",
1963
+ "RETURNS: { id, scope, file_path, action: 'created'|'updated', warning?, invalid_paths? }",
1964
+ "WARNING: if paths point to non-existent files, they will be immediately stale after haive sync.",
1965
+ "DEDUP: identical body content within the same scope is rejected \u2014 use mem_update to modify."
1966
+ ].join("\n"),
1829
1967
  MemSaveInputSchema,
1830
- async (input) => jsonResult(await memSave(input, context))
1968
+ async (input) => {
1969
+ tracker.record("mem_save", input.slug);
1970
+ return jsonResult(await memSave(input, context));
1971
+ }
1972
+ );
1973
+ server.tool(
1974
+ "mem_tried",
1975
+ [
1976
+ "Record a FAILED approach so future agents don't repeat the same mistake.",
1977
+ "",
1978
+ "USE THIS IMMEDIATELY when you try something and it doesn't work. This is the",
1979
+ "most valuable type of negative knowledge \u2014 it saves hours of debugging for",
1980
+ "future agents working on the same codebase.",
1981
+ "",
1982
+ "Auto-validated (no approval cycle). Surfaced FIRST in future get_briefing calls",
1983
+ "so it's impossible to miss.",
1984
+ "",
1985
+ "PARAMETERS:",
1986
+ " what \u2014 short title of what you tried (e.g. 'importing X with ESM dynamic import')",
1987
+ " why_failed \u2014 the exact error or reason it failed",
1988
+ " instead \u2014 what to do instead (the correct approach)",
1989
+ " scope \u2014 team (default) | personal",
1990
+ " paths \u2014 source files where the issue lives",
1991
+ "",
1992
+ "RETURNS: { id, file_path, action: 'created' }"
1993
+ ].join("\n"),
1994
+ MemTriedInputSchema,
1995
+ async (input) => {
1996
+ tracker.record("mem_tried", input.what.slice(0, 80));
1997
+ return jsonResult(await memTried(input, context));
1998
+ }
1999
+ );
2000
+ server.tool(
2001
+ "mem_observe",
2002
+ [
2003
+ "Capture a code-level discovery made WHILE READING existing code.",
2004
+ "",
2005
+ "USE THIS when you read a file and spot something the team may not know about:",
2006
+ " - A bug or race condition hiding in the code",
2007
+ " - A security gap or missing validation",
2008
+ " - An inconsistency between two files",
2009
+ " - A missing configuration or environment variable",
2010
+ " - Anything that could silently break in production",
2011
+ "",
2012
+ "DIFFERENCE from mem_save: mem_observe is for REACTIVE discoveries during code",
2013
+ "reading. mem_save is for deliberate knowledge capture (conventions, decisions).",
2014
+ "",
2015
+ "Auto-validated, anchored to file paths for staleness detection.",
2016
+ "",
2017
+ "PARAMETERS:",
2018
+ " what \u2014 one-line title (e.g. 'MobilePaymentController: duplicate @RequestBody')",
2019
+ " where \u2014 file path(s) where the issue lives",
2020
+ " impact \u2014 what breaks or could break because of this",
2021
+ " fix \u2014 suggested fix (optional)",
2022
+ " scope \u2014 team (default, since discoveries benefit everyone)",
2023
+ "",
2024
+ "RETURNS: { id, file_path }"
2025
+ ].join("\n"),
2026
+ MemObserveInputSchema,
2027
+ async (input) => {
2028
+ tracker.record("mem_observe", input.where);
2029
+ return jsonResult(await memObserve(input, context));
2030
+ }
2031
+ );
2032
+ server.tool(
2033
+ "mem_session_end",
2034
+ [
2035
+ "Save an end-of-session recap so the NEXT session starts with fresh context.",
2036
+ "",
2037
+ "CALL THIS before closing any significant working session. In autopilot mode,",
2038
+ "the MCP server saves a minimal recap automatically on exit \u2014 but calling this",
2039
+ "manually produces a richer, more useful recap.",
2040
+ "",
2041
+ "HOW IT WORKS: uses topic-upsert \u2014 one recap per scope is kept and updated",
2042
+ "in-place (revision_count increments). get_briefing surfaces the latest recap",
2043
+ "at the very top of the next session's briefing, before project context.",
2044
+ "",
2045
+ "PARAMETERS:",
2046
+ " goal \u2014 what you were trying to accomplish (1\u20132 sentences)",
2047
+ " accomplished \u2014 what was actually done (bullet list recommended)",
2048
+ " discoveries \u2014 bugs, surprises, missing knowledge found during this session",
2049
+ " files_touched \u2014 key files read or modified (used as anchor for staleness)",
2050
+ " next_steps \u2014 what should happen in the next session or for a teammate",
2051
+ " scope \u2014 personal (default) | team",
2052
+ "",
2053
+ "RETURNS: { id, scope, action: 'created'|'updated', revision_count }"
2054
+ ].join("\n"),
2055
+ MemSessionEndInputSchema,
2056
+ async (input) => {
2057
+ tracker.record("mem_session_end", input.goal.slice(0, 80));
2058
+ return jsonResult(await memSessionEnd(input, context));
2059
+ }
2060
+ );
2061
+ server.tool(
2062
+ "get_briefing",
2063
+ [
2064
+ "\u2B50 CALL THIS FIRST at the start of every task. One-shot onboarding that returns",
2065
+ "everything relevant in a single call under a token budget.",
2066
+ "",
2067
+ "RETURNS (in order of priority):",
2068
+ " 1. last_session \u2014 recap of the previous session (goal, what was done, next steps)",
2069
+ " 2. project_context \u2014 .ai/project-context.md (auto-generated from code-map if template)",
2070
+ " 3. module_contexts \u2014 relevant .ai/modules/<name>/context.md based on files being edited",
2071
+ " 4. memories \u2014 ranked team memories relevant to your task",
2072
+ " 5. symbol_locations \u2014 file:line:kind for any requested symbols (no grep needed)",
2073
+ " 6. setup_warnings \u2014 actionable warnings if setup is incomplete",
2074
+ " 7. decay_warnings \u2014 memories not read in >90 days (consider reviewing)",
2075
+ "",
2076
+ "KEY PARAMETERS:",
2077
+ " task \u2014 what you are about to do (1\u20132 sentences) \u2014 ALWAYS provide this",
2078
+ " files \u2014 files you are about to edit \u2014 surfaces anchored memories",
2079
+ " symbols \u2014 symbol names to look up in the code-map (e.g. ['PaymentService'])",
2080
+ " format \u2014 'full' (default) | 'compact' (1-line summaries, use when token budget is tight)",
2081
+ "",
2082
+ "EXAMPLE USAGE:",
2083
+ " get_briefing({ task: 'add a Stripe payment integration', files: ['src/payments/'], symbols: ['PaymentService'] })",
2084
+ "",
2085
+ "CONFIDENCE LEVELS in memories:",
2086
+ " authoritative \u2014 validated + read 10+ times (highest trust)",
2087
+ " trusted \u2014 validated or proposed + read 3+ times",
2088
+ " low \u2014 proposed, few reads (take with caution)",
2089
+ " unverified \u2014 draft (unverified: true flag set)",
2090
+ "",
2091
+ "Replaces 4\u20135 separate tool calls. Always call this before any other tool."
2092
+ ].join("\n"),
2093
+ GetBriefingInputSchema,
2094
+ async (input) => {
2095
+ tracker.record("get_briefing", input.task ?? "");
2096
+ return jsonResult(await getBriefing(input, context));
2097
+ }
1831
2098
  );
1832
2099
  server.tool(
1833
2100
  "mem_search",
1834
- "Search memories by substring across id, tags, and body. Optional filters by scope/type/module.",
2101
+ [
2102
+ "Search memories by keyword or semantic similarity.",
2103
+ "",
2104
+ "USE WHEN you need to find a specific memory and don't know its id.",
2105
+ "For session onboarding, use get_briefing instead (richer, ranked, budgeted).",
2106
+ "",
2107
+ "SEARCH MODES:",
2108
+ " Literal (default): AND search across id, tags, and body \u2014 all tokens must match.",
2109
+ " Falls back to OR automatically if no AND results (partial match).",
2110
+ " Semantic (semantic: true): embedding-based similarity \u2014 finds related memories",
2111
+ " even with different wording. Requires haive embeddings index to be built.",
2112
+ "",
2113
+ "PARAMETERS:",
2114
+ " query \u2014 search terms or natural language question",
2115
+ " scope \u2014 filter by personal | team | module",
2116
+ " type \u2014 filter by convention | decision | gotcha | architecture | glossary",
2117
+ " semantic \u2014 true for embedding-based search (requires @hiveai/embeddings)",
2118
+ " limit \u2014 max results (default 10)",
2119
+ "",
2120
+ "RETURNS: array of { id, type, scope, status, confidence, body, match_quality }"
2121
+ ].join("\n"),
1835
2122
  MemSearchInputSchema,
1836
2123
  async (input) => jsonResult(await memSearch(input, context))
1837
2124
  );
2125
+ server.tool(
2126
+ "mem_for_files",
2127
+ [
2128
+ "Surface memories relevant to the files you are currently editing.",
2129
+ "",
2130
+ "USE WHEN starting work on specific files and you want to know:",
2131
+ " - What conventions apply to these files",
2132
+ " - What gotchas are anchored to these paths",
2133
+ " - What decisions were made about this module",
2134
+ "",
2135
+ "Matching strategy (in priority order):",
2136
+ " 1. Anchor overlap \u2014 memories whose paths overlap with your files",
2137
+ " 2. Module context \u2014 .ai/modules/<name>/context.md if module is inferred",
2138
+ " 3. Domain/tag match \u2014 memories whose tags include path segments",
2139
+ "",
2140
+ "PARAMETERS:",
2141
+ " files \u2014 list of project-relative file paths you are editing",
2142
+ " scope \u2014 filter by scope (default: all)",
2143
+ "",
2144
+ "RETURNS: { memories: [...], module_contexts: [...] }"
2145
+ ].join("\n"),
2146
+ MemForFilesInputSchema,
2147
+ async (input) => jsonResult(await memForFiles(input, context))
2148
+ );
2149
+ server.tool(
2150
+ "mem_get",
2151
+ [
2152
+ "Fetch a single memory by its full id with all details.",
2153
+ "",
2154
+ "USE WHEN get_briefing returned a memory in 'compact' format and you need",
2155
+ "the full body, or when you know the exact id of a memory.",
2156
+ "",
2157
+ "PARAMETERS:",
2158
+ " id \u2014 full memory id (e.g. '2026-04-28-gotcha-flyway-strict-no-ddl')",
2159
+ "",
2160
+ "RETURNS: { id, type, scope, status, confidence, body, anchor, tags, usage }"
2161
+ ].join("\n"),
2162
+ MemGetInputSchema,
2163
+ async (input) => jsonResult(await memGet(input, context))
2164
+ );
1838
2165
  server.tool(
1839
2166
  "mem_list",
1840
- "List memories with optional filters by scope/type/module/tag.",
2167
+ [
2168
+ "List memories with optional filters. Use for browsing, not for task onboarding.",
2169
+ "",
2170
+ "For task onboarding use get_briefing (ranked + budgeted).",
2171
+ "For keyword search use mem_search.",
2172
+ "",
2173
+ "PARAMETERS:",
2174
+ " scope \u2014 personal | team | module",
2175
+ " type \u2014 convention | decision | gotcha | architecture | glossary",
2176
+ " status \u2014 draft | proposed | validated | stale | rejected",
2177
+ " tags \u2014 filter by tags (AND match)",
2178
+ " module \u2014 filter by module name",
2179
+ "",
2180
+ "RETURNS: array of { id, type, scope, status, confidence, tags, created_at }"
2181
+ ].join("\n"),
1841
2182
  MemListInputSchema,
1842
2183
  async (input) => jsonResult(await memList(input, context))
1843
2184
  );
1844
2185
  server.tool(
1845
2186
  "get_project_context",
1846
- "Read the shared .ai/project-context.md (and optionally a module context).",
2187
+ [
2188
+ "Read .ai/project-context.md (and optionally a module context) directly.",
2189
+ "",
2190
+ "USE WHEN you need the full project context without the memory ranking and",
2191
+ "token budgeting of get_briefing \u2014 e.g. for a reference architecture review.",
2192
+ "",
2193
+ "For normal task onboarding, use get_briefing instead (more efficient).",
2194
+ "",
2195
+ "PARAMETERS:",
2196
+ " module \u2014 also load .ai/modules/<module>/context.md if provided",
2197
+ "",
2198
+ "RETURNS: { content: string, module_context?: string }"
2199
+ ].join("\n"),
1847
2200
  GetProjectContextInputSchema,
1848
2201
  async (input) => jsonResult(await getProjectContext(input, context))
1849
2202
  );
1850
2203
  server.tool(
1851
- "get_briefing",
1852
- "One-shot onboarding: returns project context + module contexts + ranked relevant memories under a token budget. Replaces 4\u20135 separate calls when an agent starts a task.",
1853
- GetBriefingInputSchema,
1854
- async (input) => jsonResult(await getBriefing(input, context))
2204
+ "bootstrap_project_save",
2205
+ [
2206
+ "Persist the project context document (.ai/project-context.md) or a module",
2207
+ "context (.ai/modules/<name>/context.md) analyzed by the AI.",
2208
+ "",
2209
+ "USE AFTER the bootstrap_project MCP prompt: the prompt tells you how to",
2210
+ "analyze the codebase; this tool saves the result.",
2211
+ "",
2212
+ "PARAMETERS:",
2213
+ " content \u2014 full Markdown content of the context document",
2214
+ " module \u2014 if provided, saves as a module context (not root project context)",
2215
+ "",
2216
+ "RETURNS: { file_path, module? }"
2217
+ ].join("\n"),
2218
+ BootstrapProjectSaveInputSchema,
2219
+ async (input) => jsonResult(await bootstrapProjectSave(input, context))
1855
2220
  );
1856
2221
  server.tool(
1857
2222
  "code_map",
1858
- "Browse the project's pre-computed code map (file \u2192 exports + 1-line description) instead of grepping. Requires `haive index code`.",
2223
+ [
2224
+ "Look up where symbols (classes, functions, interfaces) are defined in the codebase.",
2225
+ "",
2226
+ "USE INSTEAD OF grepping when you need to find where something lives.",
2227
+ "Requires haive index code to have been run (done automatically in autopilot mode).",
2228
+ "",
2229
+ "TIP: include symbols in get_briefing directly for auto-lookup at session start.",
2230
+ "",
2231
+ "PARAMETERS:",
2232
+ " symbol \u2014 name or partial name to search (e.g. 'PaymentService')",
2233
+ " file \u2014 filter by file path substring",
2234
+ " max_files \u2014 cap on results (default 40)",
2235
+ "",
2236
+ "RETURNS: { available: bool, files: [{ path, exports: [{ name, kind, line, description }] }] }",
2237
+ "If available: false \u2192 run haive index code first."
2238
+ ].join("\n"),
1859
2239
  CodeMapInputSchema,
1860
2240
  async (input) => jsonResult(await codeMapTool(input, context))
1861
2241
  );
1862
2242
  server.tool(
1863
- "bootstrap_project_save",
1864
- "Persist a project (or module) context document analyzed by the AI client.",
1865
- BootstrapProjectSaveInputSchema,
1866
- async (input) => jsonResult(await bootstrapProjectSave(input, context))
2243
+ "mem_update",
2244
+ [
2245
+ "Update the body, tags, or anchor of an existing memory in-place.",
2246
+ "",
2247
+ "USE WHEN a memory exists but its content has become outdated or incomplete.",
2248
+ "This preserves the memory's id, usage history, and read_count.",
2249
+ "",
2250
+ "For evolving memories that you will update repeatedly, use mem_save with a",
2251
+ "topic key instead (topic-upsert pattern).",
2252
+ "",
2253
+ "PARAMETERS:",
2254
+ " id \u2014 full memory id to update",
2255
+ " body \u2014 new Markdown content (replaces existing body)",
2256
+ " tags \u2014 new tag list (replaces existing tags)",
2257
+ " paths \u2014 new anchor paths (replaces existing paths)",
2258
+ " symbols \u2014 new anchor symbols (replaces existing symbols)",
2259
+ "",
2260
+ "RETURNS: { id, file_path, updated_fields: string[] }"
2261
+ ].join("\n"),
2262
+ MemUpdateInputSchema,
2263
+ async (input) => jsonResult(await memUpdate(input, context))
1867
2264
  );
1868
2265
  server.tool(
1869
2266
  "mem_verify",
1870
- "Check anchor freshness for one or every memory; optionally write status updates back to disk.",
2267
+ [
2268
+ "Check whether memory anchor paths and symbols still exist in the current code.",
2269
+ "",
2270
+ "USE WHEN you want to know if a specific memory is still valid after a refactor,",
2271
+ "or to check all memories for staleness (haive sync does this automatically).",
2272
+ "",
2273
+ "PARAMETERS:",
2274
+ " id \u2014 check a single memory (omit to check all)",
2275
+ " update \u2014 write 'stale' or 'validated' status back to disk",
2276
+ "",
2277
+ "RETURNS: { results: [{ id, status: 'fresh'|'stale'|'anchorless', reason? }] }",
2278
+ "Stale means the anchored file/symbol no longer exists at that path.",
2279
+ "Anchorless means the memory has no paths/symbols \u2014 staleness is undetectable."
2280
+ ].join("\n"),
1871
2281
  MemVerifyInputSchema,
1872
2282
  async (input) => jsonResult(await memVerify(input, context))
1873
2283
  );
2284
+ server.tool(
2285
+ "mem_approve",
2286
+ [
2287
+ "Mark a memory as validated (trusted, approved by a human or the team).",
2288
+ "",
2289
+ "In autopilot mode, memories are validated automatically \u2014 you rarely need this.",
2290
+ "In manual mode, call this after reviewing a proposed memory to activate it.",
2291
+ "",
2292
+ "PARAMETERS:",
2293
+ " id \u2014 full memory id to approve",
2294
+ "",
2295
+ "RETURNS: { id, previous_status, new_status: 'validated' }"
2296
+ ].join("\n"),
2297
+ MemApproveInputSchema,
2298
+ async (input) => jsonResult(await memApprove(input, context))
2299
+ );
1874
2300
  server.tool(
1875
2301
  "mem_reject",
1876
- "Record a rejection for a memory (blocks auto-promotion and lowers its trust signal).",
2302
+ [
2303
+ "Mark a memory as rejected and record a reason.",
2304
+ "",
2305
+ "USE WHEN a memory is factually wrong, outdated, or not useful.",
2306
+ "Rejection blocks auto-promotion and lowers the memory's trust signal.",
2307
+ "Rejected memories are excluded from get_briefing by default.",
2308
+ "",
2309
+ "PARAMETERS:",
2310
+ " id \u2014 full memory id to reject",
2311
+ " reason \u2014 why this memory is being rejected (stored in frontmatter)",
2312
+ "",
2313
+ "RETURNS: { id, previous_status, new_status: 'rejected' }"
2314
+ ].join("\n"),
1877
2315
  MemRejectInputSchema,
1878
2316
  async (input) => jsonResult(await memReject(input, context))
1879
2317
  );
1880
- server.tool(
1881
- "mem_for_files",
1882
- "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.",
1883
- MemForFilesInputSchema,
1884
- async (input) => jsonResult(await memForFiles(input, context))
1885
- );
1886
- server.tool(
1887
- "mem_get",
1888
- "Fetch a single memory by id, including its body, anchor, usage, and confidence.",
1889
- MemGetInputSchema,
1890
- async (input) => jsonResult(await memGet(input, context))
1891
- );
1892
- server.tool(
1893
- "mem_delete",
1894
- "Delete a memory by id (and its usage entry by default).",
1895
- MemDeleteInputSchema,
1896
- async (input) => jsonResult(await memDelete(input, context))
1897
- );
1898
- server.tool(
1899
- "mem_update",
1900
- "Update the body, tags, or anchor of an existing memory without changing its id or losing usage history.",
1901
- MemUpdateInputSchema,
1902
- async (input) => jsonResult(await memUpdate(input, context))
1903
- );
1904
2318
  server.tool(
1905
2319
  "mem_pending",
1906
- "List 'proposed' memories awaiting review, sorted by reads (most-read first).",
2320
+ [
2321
+ "List memories in 'proposed' status awaiting review, sorted by read count.",
2322
+ "",
2323
+ "USE IN MANUAL MODE to see what memories are waiting for human review.",
2324
+ "In autopilot mode, proposed memories auto-approve after 72h.",
2325
+ "",
2326
+ "High read_count on a proposed memory = many agents found it useful without",
2327
+ "rejecting it = strong signal to approve.",
2328
+ "",
2329
+ "RETURNS: array of { id, type, scope, read_count, created_at, body_preview }"
2330
+ ].join("\n"),
1907
2331
  MemPendingInputSchema,
1908
2332
  async (input) => jsonResult(await memPending(input, context))
1909
2333
  );
1910
2334
  server.tool(
1911
- "mem_approve",
1912
- "Mark a memory as validated immediately (explicit team review).",
1913
- MemApproveInputSchema,
1914
- async (input) => jsonResult(await memApprove(input, context))
1915
- );
1916
- server.tool(
1917
- "mem_tried",
1918
- "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 \u2014 prevents the same mistake from happening in the next session.",
1919
- MemTriedInputSchema,
1920
- async (input) => jsonResult(await memTried(input, context))
2335
+ "mem_delete",
2336
+ [
2337
+ "Permanently delete a memory by id.",
2338
+ "",
2339
+ "USE WITH CAUTION \u2014 prefer mem_reject for outdated memories (preserves history).",
2340
+ "Use delete only for accidentally created memories or duplicates.",
2341
+ "",
2342
+ "PARAMETERS:",
2343
+ " id \u2014 full memory id to delete",
2344
+ " delete_usage \u2014 also delete usage stats (default: true)",
2345
+ "",
2346
+ "RETURNS: { deleted: true, id }"
2347
+ ].join("\n"),
2348
+ MemDeleteInputSchema,
2349
+ async (input) => jsonResult(await memDelete(input, context))
1921
2350
  );
1922
2351
  server.tool(
1923
2352
  "mem_diff",
1924
- "Compare two memories side-by-side: shows frontmatter fields that differ and lines unique to each body. Useful before merging or deduplicating memories.",
2353
+ [
2354
+ "Compare two memories side-by-side to decide if they should be merged.",
2355
+ "",
2356
+ "USE BEFORE merging or deduplicating similar memories.",
2357
+ "Shows: frontmatter fields that differ + lines unique to each body.",
2358
+ "",
2359
+ "PARAMETERS:",
2360
+ " id_a \u2014 first memory id",
2361
+ " id_b \u2014 second memory id",
2362
+ "",
2363
+ "RETURNS: { frontmatter_diff: {...}, body_only_in_a: [...], body_only_in_b: [...] }"
2364
+ ].join("\n"),
1925
2365
  MemDiffInputSchema,
1926
2366
  async (input) => jsonResult(await memDiff(input, context))
1927
2367
  );
1928
- server.tool(
1929
- "mem_observe",
1930
- "Capture a code-level discovery made during exploration: a bug, inconsistency, missing config, or security gap found by reading existing code that was NOT in the briefing. Use this whenever you read code and spot something that could silently break in production. Auto-validated, anchored to file paths for staleness detection. Prefer this over mem_save for reactive discoveries during code reading.",
1931
- MemObserveInputSchema,
1932
- async (input) => jsonResult(await memObserve(input, context))
1933
- );
1934
- server.tool(
1935
- "mem_session_end",
1936
- "Save a structured end-of-session recap (goal / accomplished / discoveries / next steps). Uses topic-upsert: one recap per scope is kept and updated in-place so the next session always has fresh context. Call this before closing every significant session. get_briefing automatically surfaces the latest recap at the top of the next session's briefing.",
1937
- MemSessionEndInputSchema,
1938
- async (input) => jsonResult(await memSessionEnd(input, context))
1939
- );
1940
2368
  server.prompt(
1941
2369
  "bootstrap_project",
1942
- "Instructions for the AI client to analyze the project and save the context.",
2370
+ [
2371
+ "Analyze the project codebase and write .ai/project-context.md \u2014 run once after haive init.",
2372
+ "The AI explores the directory structure, reads key files (package.json, README, config),",
2373
+ "identifies the tech stack, architectural patterns, key modules, and conventions,",
2374
+ "then persists everything via bootstrap_project_save.",
2375
+ "For multi-component projects, run with module param to create .ai/modules/<name>/context.md."
2376
+ ].join(" "),
1943
2377
  BootstrapProjectArgsSchema,
1944
2378
  (args) => bootstrapProjectPrompt(args, context)
1945
2379
  );
1946
2380
  server.prompt(
1947
2381
  "post_task",
1948
- "Post-task checklist: run this after completing a task to capture failed approaches, new conventions, decisions, and gotchas before closing the session.",
2382
+ [
2383
+ "\u2B50 Post-task reflection \u2014 run at the end of every session to capture what you learned:",
2384
+ "failed approaches (mem_tried), new conventions/decisions/gotchas (mem_save),",
2385
+ "code discoveries (mem_observe), and an end-of-session recap (mem_session_end).",
2386
+ "In autopilot mode a minimal recap saves automatically; calling this produces a richer one."
2387
+ ].join(" "),
1949
2388
  PostTaskArgsSchema,
1950
2389
  (args) => postTaskPrompt(args, context)
1951
2390
  );
1952
2391
  server.prompt(
1953
2392
  "import_docs",
1954
- "Analyze documentation (README, ADR, wiki page, etc.) and save the actionable knowledge as hAIve memories. Pass the content and an optional source/scope.",
2393
+ [
2394
+ "Import knowledge from a document (README, ADR, wiki, API spec) as hAIve memories.",
2395
+ "Pass the full document content; the AI extracts up to 10 actionable memories",
2396
+ "(conventions, decisions, gotchas, architecture) and saves them via mem_save.",
2397
+ "Good candidates: ADRs, onboarding docs, runbooks, team wikis."
2398
+ ].join(" "),
1955
2399
  ImportDocsArgsSchema,
1956
2400
  (args) => importDocsPrompt(args, context)
1957
2401
  );
1958
- return { server, context };
2402
+ return { server, context, tracker };
1959
2403
  }
1960
2404
 
1961
2405
  // src/index.ts