@hiveai/mcp 0.4.5 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1200,6 +1200,9 @@ var GetBriefingInputSchema = {
1200
1200
  ),
1201
1201
  symbols: z17.array(z17.string()).default([]).describe(
1202
1202
  "Symbol names to look up in the code-map (e.g. ['PaymentService', 'TenantFilter']). Returns the file(s) exporting each symbol so agents don't need to grep. Requires `haive index code` to have been run."
1203
+ ),
1204
+ min_semantic_score: z17.number().min(0).max(1).default(0).describe(
1205
+ "Drop semantic-only memory hits whose cosine score is below this threshold. Useful to avoid weakly-related noise when the task is short or the corpus is broad. Has no effect on memories matched via anchor/module/literal \u2014 those are always kept. Try 0.25\u20130.4 for stricter matching."
1203
1206
  )
1204
1207
  };
1205
1208
  async function getBriefing(input, ctx) {
@@ -1232,6 +1235,7 @@ async function getBriefing(input, ctx) {
1232
1235
  return true;
1233
1236
  });
1234
1237
  usage = await loadUsageIndex7(ctx.paths);
1238
+ byId = new Map(allMemories.map((m) => [m.memory.frontmatter.id, m]));
1235
1239
  const semanticHits = input.task && input.semantic ? await trySemanticHits(ctx, input.task, allMemories.length * 2) : null;
1236
1240
  if (input.task && input.semantic) {
1237
1241
  searchMode = semanticHits ? "semantic" : "literal_fallback";
@@ -1296,6 +1300,10 @@ async function getBriefing(input, ctx) {
1296
1300
  }
1297
1301
  if (semanticHits) {
1298
1302
  for (const hit of semanticHits) {
1303
+ if (hit.score < input.min_semantic_score) {
1304
+ const existing = seen.get(hit.id);
1305
+ if (!existing) continue;
1306
+ }
1299
1307
  const loaded = byId.get(hit.id);
1300
1308
  if (loaded) addOrUpdate(loaded, "semantic", hit.score, "semantic");
1301
1309
  }
@@ -1309,7 +1317,6 @@ async function getBriefing(input, ctx) {
1309
1317
  const sb = reasonScore(b) + confidenceScore(b) + (b.semantic_score ?? 0);
1310
1318
  return sb - sa;
1311
1319
  });
1312
- byId = new Map(allMemories.map((m) => [m.memory.frontmatter.id, m]));
1313
1320
  for (const mem of ranked.slice(0, input.max_memories)) {
1314
1321
  if (seen.size >= input.max_memories * 2) break;
1315
1322
  const loaded = byId.get(mem.id);
@@ -1501,6 +1508,36 @@ ${m.content}`).join("\n\n---\n\n"),
1501
1508
  });
1502
1509
  }
1503
1510
  }
1511
+ const memoriesEmpty = outputMemories.length === 0;
1512
+ const hasMemoriesDir = existsSync17(ctx.paths.memoriesDir);
1513
+ const isColdStart = isTemplateContext && memoriesEmpty && !lastSession && !autoContextGenerated;
1514
+ const hints = [];
1515
+ if (isColdStart) {
1516
+ hints.push(
1517
+ "haive is uninitialized for this project (project-context.md is template, 0 memories, no past session). Skip future get_briefing calls until memories exist \u2014 use Read/Grep directly. Run `haive init` and the bootstrap_project prompt to fix."
1518
+ );
1519
+ } else {
1520
+ if (outputMemories.some((m) => m.type === "attempt")) {
1521
+ hints.push(
1522
+ "\u26A0\uFE0F One or more 'attempt' memories matched \u2014 these document failed approaches. Read them BEFORE writing code to avoid repeating the mistake."
1523
+ );
1524
+ }
1525
+ if (outputMemories.some((m) => m.type === "gotcha")) {
1526
+ hints.push(
1527
+ "Gotcha memories matched \u2014 non-obvious traps. Verify the 'how to apply' line still holds before assuming behavior."
1528
+ );
1529
+ }
1530
+ if (memoriesEmpty && hasMemoriesDir && input.task) {
1531
+ hints.push(
1532
+ "No memories matched this task. Try mem_search with broader/different terms, or call mem_for_files with the files you intend to edit."
1533
+ );
1534
+ }
1535
+ if (input.task && outputMemories.length > 0 && actionRequired.length === 0) {
1536
+ hints.push(
1537
+ "After completing the task: capture new gotchas with mem_observe, failed approaches with mem_tried, validated patterns with mem_save."
1538
+ );
1539
+ }
1540
+ }
1504
1541
  return {
1505
1542
  ...input.task ? { task: input.task } : {},
1506
1543
  search_mode: searchMode,
@@ -1518,6 +1555,8 @@ ${m.content}`).join("\n\n---\n\n"),
1518
1555
  action_required: actionRequired,
1519
1556
  decay_warnings: decayWarnings,
1520
1557
  setup_warnings: setupWarnings,
1558
+ ...isColdStart ? { low_value: true } : {},
1559
+ ...hints.length > 0 ? { hints } : {},
1521
1560
  estimated_tokens: totalTokens,
1522
1561
  budget: {
1523
1562
  max_tokens: input.max_tokens,
@@ -1565,12 +1604,18 @@ async function loadModuleContexts2(ctx, modules) {
1565
1604
  }
1566
1605
 
1567
1606
  // src/tools/code-map.ts
1568
- import { loadCodeMap as loadCodeMap2, queryCodeMap as queryCodeMap2 } from "@hiveai/core";
1607
+ import { estimateTokens as estimateTokens2, loadCodeMap as loadCodeMap2, queryCodeMap as queryCodeMap2 } from "@hiveai/core";
1569
1608
  import { z as z18 } from "zod";
1570
1609
  var CodeMapInputSchema = {
1571
1610
  file: z18.string().optional().describe("Filter to files whose path contains this substring"),
1572
1611
  symbol: z18.string().optional().describe("Filter to files exporting a symbol whose name contains this substring"),
1573
- max_files: z18.number().int().positive().default(40).describe("Cap on returned files")
1612
+ paths: z18.array(z18.string()).default([]).describe(
1613
+ "Filter to files under any of these path prefixes (e.g. ['packages/mcp/src/tools/', 'src/auth/']). OR-joined with `file` substring; useful to get a focused view of one module."
1614
+ ),
1615
+ max_files: z18.number().int().positive().default(40).describe("Cap on returned files (hard limit, applied after token budget)"),
1616
+ max_tokens: z18.number().int().positive().optional().describe(
1617
+ "Approximate token budget for the response. When the matching set exceeds it, files are ranked by export density (exports per LOC) and the highest-signal ones are kept first. Omit to disable budgeting (legacy behavior)."
1618
+ )
1574
1619
  };
1575
1620
  async function codeMapTool(input, ctx) {
1576
1621
  const map = await loadCodeMap2(ctx.paths);
@@ -1581,19 +1626,63 @@ async function codeMapTool(input, ctx) {
1581
1626
  notice: "No code map found. Run `haive index code` to generate `.ai/code-map.json`."
1582
1627
  };
1583
1628
  }
1584
- const { files } = queryCodeMap2(map, { file: input.file, symbol: input.symbol });
1629
+ const { files: matched } = queryCodeMap2(map, { file: input.file, symbol: input.symbol });
1630
+ const pathsFiltered = input.paths.length === 0 ? matched : matched.filter((f) => input.paths.some((p) => f.path.startsWith(stripLeadingSlash(p))));
1631
+ const alphabetical = [...pathsFiltered].sort((a, b) => a.path.localeCompare(b.path));
1632
+ let kept = alphabetical;
1633
+ let budgetClipped = false;
1634
+ if (input.max_tokens !== void 0) {
1635
+ const byDensity = [...alphabetical].sort((a, b) => {
1636
+ const da = density(a.entry.exports.length, a.entry.loc);
1637
+ const db = density(b.entry.exports.length, b.entry.loc);
1638
+ if (da !== db) return db - da;
1639
+ return a.path.localeCompare(b.path);
1640
+ });
1641
+ const keepSet = /* @__PURE__ */ new Set();
1642
+ let spent = 0;
1643
+ for (const f of byDensity) {
1644
+ const cost = estimateFileEntryTokens(f);
1645
+ if (spent + cost > input.max_tokens && keepSet.size > 0) {
1646
+ budgetClipped = true;
1647
+ break;
1648
+ }
1649
+ keepSet.add(f.path);
1650
+ spent += cost;
1651
+ }
1652
+ if (budgetClipped) {
1653
+ kept = alphabetical.filter((f) => keepSet.has(f.path));
1654
+ }
1655
+ }
1656
+ const finalFiles = kept.slice(0, input.max_files);
1657
+ const totalDropped = pathsFiltered.length - finalFiles.length;
1585
1658
  return {
1586
1659
  available: true,
1587
1660
  generated_at: map.generated_at,
1588
1661
  total_files: Object.keys(map.files).length,
1589
- files: files.slice(0, input.max_files).map((f) => ({
1662
+ files: finalFiles.map((f) => ({
1590
1663
  path: f.path,
1591
1664
  ...f.entry.summary ? { summary: f.entry.summary } : {},
1592
1665
  loc: f.entry.loc,
1593
1666
  exports: f.entry.exports
1594
- }))
1667
+ })),
1668
+ ...totalDropped > 0 ? { truncated: totalDropped } : {},
1669
+ ...budgetClipped ? { budget_clipped: true } : {}
1595
1670
  };
1596
1671
  }
1672
+ function density(exports, loc) {
1673
+ if (loc <= 0) return 0;
1674
+ return exports / Math.max(loc, 1);
1675
+ }
1676
+ function stripLeadingSlash(p) {
1677
+ return p.startsWith("/") ? p.slice(1) : p;
1678
+ }
1679
+ function estimateFileEntryTokens(f) {
1680
+ const exportsCost = f.entry.exports.reduce(
1681
+ (acc, e) => acc + 6 + estimateTokens2(e.description ?? ""),
1682
+ 0
1683
+ );
1684
+ return estimateTokens2(f.path) + estimateTokens2(f.entry.summary ?? "") + exportsCost + 4;
1685
+ }
1597
1686
 
1598
1687
  // src/tools/mem-diff.ts
1599
1688
  import { existsSync as existsSync18 } from "fs";
@@ -1640,13 +1729,856 @@ async function memDiff(input, ctx) {
1640
1729
  };
1641
1730
  }
1642
1731
 
1643
- // src/prompts/bootstrap-project.ts
1732
+ // src/tools/get-recap.ts
1733
+ import { existsSync as existsSync19 } from "fs";
1734
+ import { loadMemoriesFromDir as loadMemoriesFromDir15 } from "@hiveai/core";
1644
1735
  import { z as z20 } from "zod";
1736
+ var GetRecapInputSchema = {
1737
+ scope: z20.enum(["personal", "team", "any"]).default("any").describe(
1738
+ "Limit to a specific scope's recap. Default 'any' returns the most recent recap across both personal and team scopes."
1739
+ )
1740
+ };
1741
+ async function getRecap(input, ctx) {
1742
+ if (!existsSync19(ctx.paths.memoriesDir)) {
1743
+ return { recap: null, notice: "No .ai/memories directory \u2014 haive not initialized here." };
1744
+ }
1745
+ const all = await loadMemoriesFromDir15(ctx.paths.memoriesDir);
1746
+ const recaps = all.filter(({ memory }) => memory.frontmatter.type === "session_recap").filter(({ memory }) => input.scope === "any" || memory.frontmatter.scope === input.scope).sort(
1747
+ (a, b) => new Date(b.memory.frontmatter.created_at).getTime() - new Date(a.memory.frontmatter.created_at).getTime()
1748
+ );
1749
+ if (recaps.length === 0) {
1750
+ return {
1751
+ recap: null,
1752
+ notice: input.scope === "any" ? "No session recap saved yet. Run mem_session_end (or post_task prompt) to capture one." : `No session recap found in scope '${input.scope}'.`
1753
+ };
1754
+ }
1755
+ const r = recaps[0];
1756
+ const fm = r.memory.frontmatter;
1757
+ return {
1758
+ recap: {
1759
+ id: fm.id,
1760
+ scope: fm.scope,
1761
+ revision_count: fm.revision_count ?? 0,
1762
+ created_at: fm.created_at,
1763
+ body: r.memory.body
1764
+ }
1765
+ };
1766
+ }
1767
+
1768
+ // src/tools/mem-relevant-to.ts
1769
+ import { z as z21 } from "zod";
1770
+ var MemRelevantToInputSchema = {
1771
+ task: z21.string().min(1).describe("What you are about to do, in 1\u20132 sentences. Used to rank relevant memories."),
1772
+ files: z21.array(z21.string()).default([]).describe("Optional: files you are about to edit \u2014 surfaces anchored memories."),
1773
+ limit: z21.number().int().positive().max(30).default(8).describe("Cap on returned memories."),
1774
+ min_semantic_score: z21.number().min(0).max(1).default(0.25).describe("Drop weakly-related semantic hits below this cosine threshold."),
1775
+ format: z21.enum(["full", "compact"]).default("full").describe("'compact' = id + 1-line summary; 'full' = complete bodies.")
1776
+ };
1777
+ async function memRelevantTo(input, ctx) {
1778
+ const briefingInput = {
1779
+ task: input.task,
1780
+ files: input.files,
1781
+ max_tokens: 16e3,
1782
+ max_memories: input.limit,
1783
+ include_project_context: false,
1784
+ include_module_contexts: false,
1785
+ semantic: true,
1786
+ include_stale: false,
1787
+ track: true,
1788
+ format: input.format,
1789
+ symbols: [],
1790
+ min_semantic_score: input.min_semantic_score
1791
+ };
1792
+ const briefing = await getBriefing(briefingInput, ctx);
1793
+ const out = {
1794
+ task: input.task,
1795
+ search_mode: briefing.search_mode,
1796
+ memories: briefing.memories
1797
+ };
1798
+ if (briefing.hints && briefing.hints.length > 0) out.hints = briefing.hints;
1799
+ if (briefing.memories.length === 0) out.empty = true;
1800
+ return out;
1801
+ }
1802
+
1803
+ // src/tools/code-search.ts
1804
+ import { z as z22 } from "zod";
1805
+ var CodeSearchInputSchema = {
1806
+ query: z22.string().min(1).describe(
1807
+ "Natural-language description of what you are looking for in the codebase (e.g. 'function that hashes passwords', 'JWT signing logic', 'route registration')."
1808
+ ),
1809
+ k: z22.number().int().positive().max(50).default(5).describe("Number of top hits to return."),
1810
+ min_score: z22.number().min(0).max(1).default(0.2).describe(
1811
+ "Minimum cosine similarity. Hits below this threshold are dropped to avoid noise. Try 0.3+ for stricter matching."
1812
+ )
1813
+ };
1814
+ async function codeSearch(input, ctx) {
1815
+ let mod;
1816
+ try {
1817
+ mod = await import("@hiveai/embeddings");
1818
+ } catch {
1819
+ return {
1820
+ available: false,
1821
+ hits: [],
1822
+ notice: "@hiveai/embeddings is not installed. Install it (`pnpm add @hiveai/embeddings`) and run `haive index code-search` to enable semantic code search."
1823
+ };
1824
+ }
1825
+ const result = await mod.codeSemanticSearch(ctx.paths, input.query, {
1826
+ limit: input.k,
1827
+ minScore: input.min_score
1828
+ });
1829
+ if (!result) {
1830
+ return {
1831
+ available: false,
1832
+ hits: [],
1833
+ notice: "Code semantic-search index not built. Run `haive index code-search` to generate it (builds embeddings for every exported symbol in the code-map)."
1834
+ };
1835
+ }
1836
+ return { available: true, hits: result.hits };
1837
+ }
1838
+
1839
+ // src/tools/why-this-file.ts
1840
+ import { existsSync as existsSync20 } from "fs";
1841
+ import { spawn } from "child_process";
1842
+ import path9 from "path";
1843
+ import {
1844
+ deriveConfidence as deriveConfidence5,
1845
+ getUsage as getUsage6,
1846
+ loadCodeMap as loadCodeMap3,
1847
+ loadMemoriesFromDir as loadMemoriesFromDir16,
1848
+ loadUsageIndex as loadUsageIndex8,
1849
+ memoryMatchesAnchorPaths as memoryMatchesAnchorPaths3
1850
+ } from "@hiveai/core";
1851
+ import { z as z23 } from "zod";
1852
+ var WhyThisFileInputSchema = {
1853
+ path: z23.string().min(1).describe(
1854
+ "Project-relative path to the file you want context on (e.g. 'packages/mcp/src/tools/mem-save.ts')."
1855
+ ),
1856
+ git_log_limit: z23.number().int().positive().max(20).default(5).describe("How many recent commits touching this file to include."),
1857
+ memory_limit: z23.number().int().positive().max(20).default(5).describe("Cap on memories anchored to this path.")
1858
+ };
1859
+ async function whyThisFile(input, ctx) {
1860
+ const fileExists = existsSync20(path9.join(ctx.paths.root, input.path));
1861
+ const [commits, memories, codeMap] = await Promise.all([
1862
+ runGitLog(ctx.paths.root, input.path, input.git_log_limit).catch(() => []),
1863
+ collectAnchoredMemories(ctx, input.path, input.memory_limit),
1864
+ loadCodeMap3(ctx.paths)
1865
+ ]);
1866
+ const codeMapEntry = codeMap?.files[input.path];
1867
+ const hints = [];
1868
+ if (!fileExists) {
1869
+ hints.push(`File '${input.path}' does not exist on disk \u2014 path may be wrong or file removed.`);
1870
+ }
1871
+ if (commits.length === 0 && fileExists) {
1872
+ hints.push("No git history found \u2014 file may be untracked or git not initialized.");
1873
+ }
1874
+ if (memories.length === 0 && fileExists) {
1875
+ hints.push(
1876
+ "No memories anchored here. If you discover something non-obvious while editing, use mem_observe (with where=" + input.path + ") to capture it."
1877
+ );
1878
+ }
1879
+ if (memories.some((m) => m.type === "attempt" || m.type === "gotcha")) {
1880
+ hints.push("\u26A0\uFE0F attempt/gotcha memories anchored to this file \u2014 read them BEFORE editing.");
1881
+ }
1882
+ return {
1883
+ file: input.path,
1884
+ exists: fileExists,
1885
+ recent_commits: commits,
1886
+ memories,
1887
+ code_map_entry: codeMapEntry ? {
1888
+ ...codeMapEntry.summary ? { summary: codeMapEntry.summary } : {},
1889
+ loc: codeMapEntry.loc,
1890
+ exports: codeMapEntry.exports.map((e) => ({
1891
+ name: e.name,
1892
+ kind: e.kind,
1893
+ line: e.line,
1894
+ ...e.description ? { description: e.description } : {}
1895
+ }))
1896
+ } : null,
1897
+ ...hints.length > 0 ? { hints } : {}
1898
+ };
1899
+ }
1900
+ async function collectAnchoredMemories(ctx, filePath, limit) {
1901
+ if (!existsSync20(ctx.paths.memoriesDir)) return [];
1902
+ const all = await loadMemoriesFromDir16(ctx.paths.memoriesDir);
1903
+ const usage = await loadUsageIndex8(ctx.paths);
1904
+ const out = [];
1905
+ for (const { memory } of all) {
1906
+ const fm = memory.frontmatter;
1907
+ if (fm.status === "rejected" || fm.status === "deprecated") continue;
1908
+ if (fm.type === "session_recap") continue;
1909
+ if (!memoryMatchesAnchorPaths3(memory, [filePath])) continue;
1910
+ const u = getUsage6(usage, fm.id);
1911
+ out.push({
1912
+ id: fm.id,
1913
+ type: fm.type,
1914
+ scope: fm.scope,
1915
+ confidence: deriveConfidence5(fm, u),
1916
+ body_preview: memory.body.split("\n").slice(0, 6).join("\n")
1917
+ });
1918
+ if (out.length >= limit) break;
1919
+ }
1920
+ return out;
1921
+ }
1922
+ async function runGitLog(cwd, filePath, limit) {
1923
+ const sep = "<<HV>>";
1924
+ const fmt = `%h${sep}%an${sep}%ar${sep}%s`;
1925
+ const output = await runCommand(
1926
+ "git",
1927
+ ["log", `-n`, String(limit), `--pretty=format:${fmt}`, "--", filePath],
1928
+ cwd
1929
+ );
1930
+ if (!output.trim()) return [];
1931
+ return output.split("\n").map((line) => {
1932
+ const [sha = "", author = "", relative_date = "", subject = ""] = line.split(sep);
1933
+ return { sha, author, relative_date, subject };
1934
+ }).filter((c) => c.sha);
1935
+ }
1936
+ function runCommand(cmd, args, cwd) {
1937
+ return new Promise((resolve, reject) => {
1938
+ const proc = spawn(cmd, args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
1939
+ let stdout = "";
1940
+ let stderr = "";
1941
+ proc.stdout.on("data", (chunk) => {
1942
+ stdout += chunk.toString();
1943
+ });
1944
+ proc.stderr.on("data", (chunk) => {
1945
+ stderr += chunk.toString();
1946
+ });
1947
+ proc.on("error", reject);
1948
+ proc.on("close", (code) => {
1949
+ if (code === 0) resolve(stdout);
1950
+ else reject(new Error(stderr || `${cmd} exited with code ${code}`));
1951
+ });
1952
+ });
1953
+ }
1954
+
1955
+ // src/tools/anti-patterns-check.ts
1956
+ import { existsSync as existsSync21 } from "fs";
1957
+ import {
1958
+ deriveConfidence as deriveConfidence6,
1959
+ getUsage as getUsage7,
1960
+ loadMemoriesFromDir as loadMemoriesFromDir17,
1961
+ loadUsageIndex as loadUsageIndex9,
1962
+ literalMatchesAnyToken as literalMatchesAnyToken3,
1963
+ memoryMatchesAnchorPaths as memoryMatchesAnchorPaths4,
1964
+ tokenizeQuery as tokenizeQuery3
1965
+ } from "@hiveai/core";
1966
+ import { z as z24 } from "zod";
1967
+ var AntiPatternsCheckInputSchema = {
1968
+ diff: z24.string().optional().describe(
1969
+ "Raw unified diff text (or any code/text snippet) to scan for previously documented anti-patterns. Tokens from the diff are used to match memory bodies and the embeddings index."
1970
+ ),
1971
+ paths: z24.array(z24.string()).default([]).describe(
1972
+ "File paths affected by the change. Memories anchored to any of these paths are surfaced regardless of the diff content."
1973
+ ),
1974
+ limit: z24.number().int().positive().max(20).default(8).describe("Cap on returned warnings."),
1975
+ semantic: z24.boolean().default(true).describe(
1976
+ "When true, also use semantic search (requires @hiveai/embeddings + memory index) to find related anti-patterns."
1977
+ )
1978
+ };
1979
+ async function antiPatternsCheck(input, ctx) {
1980
+ if (!input.diff && input.paths.length === 0) {
1981
+ return {
1982
+ scanned: 0,
1983
+ warnings: [],
1984
+ notice: "Nothing to check \u2014 provide either `diff` text or `paths`."
1985
+ };
1986
+ }
1987
+ if (!existsSync21(ctx.paths.memoriesDir)) {
1988
+ return { scanned: 0, warnings: [], notice: "No .ai/memories directory \u2014 nothing to check against." };
1989
+ }
1990
+ const all = await loadMemoriesFromDir17(ctx.paths.memoriesDir);
1991
+ const negative = all.filter(({ memory }) => {
1992
+ const t = memory.frontmatter.type;
1993
+ if (t !== "attempt" && t !== "gotcha") return false;
1994
+ const s = memory.frontmatter.status;
1995
+ return s !== "rejected" && s !== "deprecated" && s !== "stale";
1996
+ });
1997
+ if (negative.length === 0) {
1998
+ return { scanned: 0, warnings: [], notice: "No attempt/gotcha memories found yet." };
1999
+ }
2000
+ const usage = await loadUsageIndex9(ctx.paths);
2001
+ const seen = /* @__PURE__ */ new Map();
2002
+ const upsert = (fm, body, reason, score) => {
2003
+ const existing = seen.get(fm.id);
2004
+ if (existing) {
2005
+ if (!existing.reasons.includes(reason)) existing.reasons.push(reason);
2006
+ if (score !== void 0 && (existing.semantic_score ?? 0) < score) {
2007
+ existing.semantic_score = score;
2008
+ }
2009
+ return;
2010
+ }
2011
+ const u = getUsage7(usage, fm.id);
2012
+ seen.set(fm.id, {
2013
+ id: fm.id,
2014
+ type: fm.type,
2015
+ scope: fm.scope,
2016
+ confidence: deriveConfidence6(fm, u),
2017
+ body_preview: body.split("\n").slice(0, 5).join("\n").slice(0, 400),
2018
+ reasons: [reason],
2019
+ ...score !== void 0 ? { semantic_score: score } : {}
2020
+ });
2021
+ };
2022
+ if (input.paths.length > 0) {
2023
+ for (const { memory } of negative) {
2024
+ if (memoryMatchesAnchorPaths4(memory, input.paths)) {
2025
+ upsert(memory.frontmatter, memory.body, "anchor");
2026
+ }
2027
+ }
2028
+ }
2029
+ if (input.diff) {
2030
+ const tokens = tokenizeQuery3(input.diff);
2031
+ if (tokens.length > 0) {
2032
+ for (const { memory } of negative) {
2033
+ if (literalMatchesAnyToken3(memory, tokens)) {
2034
+ upsert(memory.frontmatter, memory.body, "literal");
2035
+ }
2036
+ }
2037
+ }
2038
+ }
2039
+ if (input.semantic && input.diff) {
2040
+ try {
2041
+ const mod = await import("@hiveai/embeddings");
2042
+ const result = await mod.semanticSearch(ctx.paths, input.diff, { limit: input.limit * 2 });
2043
+ if (result) {
2044
+ const negativeIds = new Set(negative.map(({ memory }) => memory.frontmatter.id));
2045
+ for (const hit of result.hits) {
2046
+ if (!negativeIds.has(hit.id)) continue;
2047
+ const found = negative.find(({ memory }) => memory.frontmatter.id === hit.id);
2048
+ if (found) upsert(found.memory.frontmatter, found.memory.body, "semantic", hit.score);
2049
+ }
2050
+ }
2051
+ } catch {
2052
+ }
2053
+ }
2054
+ const warnings = [...seen.values()].sort((a, b) => {
2055
+ const score = (w) => {
2056
+ const reasonW = (w.reasons.includes("anchor") ? 4 : 0) + (w.reasons.includes("literal") ? 2 : 0) + (w.reasons.includes("semantic") ? 1 : 0);
2057
+ const confW = w.confidence === "authoritative" ? 3 : w.confidence === "trusted" ? 2 : w.confidence === "low" ? 1 : 0;
2058
+ return reasonW + confW + (w.semantic_score ?? 0);
2059
+ };
2060
+ return score(b) - score(a);
2061
+ }).slice(0, input.limit);
2062
+ return {
2063
+ scanned: negative.length,
2064
+ warnings
2065
+ };
2066
+ }
2067
+
2068
+ // src/tools/mem-distill.ts
2069
+ import { existsSync as existsSync22 } from "fs";
2070
+ import {
2071
+ loadMemoriesFromDir as loadMemoriesFromDir18,
2072
+ tokenizeQuery as tokenizeQuery4
2073
+ } from "@hiveai/core";
2074
+ import { z as z25 } from "zod";
2075
+ var MemDistillInputSchema = {
2076
+ since_days: z25.number().int().positive().default(30).describe("Only consider memories created in the last N days."),
2077
+ min_cluster: z25.number().int().min(2).default(3).describe("Minimum cluster size to surface."),
2078
+ type_filter: z25.enum(["gotcha", "attempt", "all"]).default("gotcha").describe(
2079
+ "Memory type to scan. 'gotcha' targets observe-style discoveries that recur, 'attempt' surfaces failed approaches that repeat, 'all' considers both."
2080
+ ),
2081
+ scope: z25.enum(["personal", "team", "module", "any"]).default("any").describe("Restrict to a specific scope.")
2082
+ };
2083
+ var MS_PER_DAY = 24 * 60 * 60 * 1e3;
2084
+ var STOP_WORDS = /* @__PURE__ */ new Set([
2085
+ "the",
2086
+ "and",
2087
+ "for",
2088
+ "with",
2089
+ "that",
2090
+ "this",
2091
+ "from",
2092
+ "into",
2093
+ "when",
2094
+ "then",
2095
+ "also",
2096
+ "must",
2097
+ "have",
2098
+ "does",
2099
+ "not",
2100
+ "but",
2101
+ "you",
2102
+ "your",
2103
+ "its",
2104
+ "because",
2105
+ "why",
2106
+ "how",
2107
+ "what",
2108
+ "use",
2109
+ "using",
2110
+ "used",
2111
+ "add",
2112
+ "added",
2113
+ "make",
2114
+ "made",
2115
+ "fix",
2116
+ "fixed",
2117
+ "bug",
2118
+ "error"
2119
+ ]);
2120
+ async function memDistill(input, ctx) {
2121
+ if (!existsSync22(ctx.paths.memoriesDir)) {
2122
+ return { scanned: 0, singletons: 0, clusters: [], notice: "No .ai/memories directory." };
2123
+ }
2124
+ const cutoff = Date.now() - input.since_days * MS_PER_DAY;
2125
+ const all = await loadMemoriesFromDir18(ctx.paths.memoriesDir);
2126
+ const candidates = all.filter(({ memory }) => {
2127
+ const fm = memory.frontmatter;
2128
+ if (fm.status === "rejected" || fm.status === "deprecated" || fm.status === "stale") return false;
2129
+ if (input.scope !== "any" && fm.scope !== input.scope) return false;
2130
+ if (input.type_filter === "gotcha" && fm.type !== "gotcha") return false;
2131
+ if (input.type_filter === "attempt" && fm.type !== "attempt") return false;
2132
+ if (input.type_filter === "all" && fm.type !== "gotcha" && fm.type !== "attempt") return false;
2133
+ if (Date.parse(fm.created_at) < cutoff) return false;
2134
+ return true;
2135
+ });
2136
+ if (candidates.length < input.min_cluster) {
2137
+ return {
2138
+ scanned: candidates.length,
2139
+ singletons: candidates.length,
2140
+ clusters: [],
2141
+ notice: candidates.length === 0 ? `No matching memories in the last ${input.since_days} days.` : `Only ${candidates.length} candidate${candidates.length === 1 ? "" : "s"} \u2014 below min_cluster=${input.min_cluster}.`
2142
+ };
2143
+ }
2144
+ const features = candidates.map((loaded) => ({
2145
+ loaded,
2146
+ keywords: keywordSet(loaded),
2147
+ paths: new Set(loaded.memory.frontmatter.anchor.paths)
2148
+ }));
2149
+ const parent = features.map((_, i) => i);
2150
+ const find = (i) => parent[i] === i ? i : parent[i] = find(parent[i] ?? 0);
2151
+ const union = (a, b) => {
2152
+ const ra = find(a), rb = find(b);
2153
+ if (ra !== rb) parent[ra] = rb;
2154
+ };
2155
+ for (let i = 0; i < features.length; i++) {
2156
+ for (let j = i + 1; j < features.length; j++) {
2157
+ const fi = features[i], fj = features[j];
2158
+ const pathSim = jaccard(fi.paths, fj.paths);
2159
+ const kwSim = jaccard(fi.keywords, fj.keywords);
2160
+ if (pathSim >= 0.5 || kwSim >= 0.4) union(i, j);
2161
+ }
2162
+ }
2163
+ const groups = /* @__PURE__ */ new Map();
2164
+ for (let i = 0; i < features.length; i++) {
2165
+ const root = find(i);
2166
+ const arr = groups.get(root) ?? [];
2167
+ arr.push(i);
2168
+ groups.set(root, arr);
2169
+ }
2170
+ const clusters = [];
2171
+ let singletons = 0;
2172
+ for (const indices of groups.values()) {
2173
+ if (indices.length < input.min_cluster) {
2174
+ singletons += indices.length;
2175
+ continue;
2176
+ }
2177
+ const members = indices.map((i) => features[i]);
2178
+ const allPaths = /* @__PURE__ */ new Set();
2179
+ const allKeywords = /* @__PURE__ */ new Map();
2180
+ let latest = 0;
2181
+ for (const m of members) {
2182
+ for (const p of m.paths) allPaths.add(p);
2183
+ for (const k of m.keywords) allKeywords.set(k, (allKeywords.get(k) ?? 0) + 1);
2184
+ const t = Date.parse(m.loaded.memory.frontmatter.created_at);
2185
+ if (t > latest) latest = t;
2186
+ }
2187
+ const commonKeywords = [...allKeywords.entries()].filter(([, n]) => n >= Math.max(2, Math.floor(members.length / 2))).sort((a, b) => b[1] - a[1]).slice(0, 5).map(([k]) => k);
2188
+ const titles = members.map((m) => firstHeading(m.loaded.memory.body) ?? m.loaded.memory.frontmatter.id).slice(0, 5);
2189
+ const suggestedType = members.every((m) => m.loaded.memory.frontmatter.type === "attempt") ? "gotcha" : "convention";
2190
+ clusters.push({
2191
+ suggested_topic: commonKeywords.slice(0, 3).join("-") || "merged-observations",
2192
+ suggested_type: suggestedType,
2193
+ member_ids: members.map((m) => m.loaded.memory.frontmatter.id),
2194
+ overlapping_paths: [...allPaths].slice(0, 10),
2195
+ common_keywords: commonKeywords,
2196
+ sample_titles: titles,
2197
+ latest_at: new Date(latest).toISOString()
2198
+ });
2199
+ }
2200
+ clusters.sort((a, b) => b.member_ids.length - a.member_ids.length);
2201
+ return {
2202
+ scanned: candidates.length,
2203
+ singletons,
2204
+ clusters
2205
+ };
2206
+ }
2207
+ function keywordSet(loaded) {
2208
+ const text = (loaded.memory.body + " " + loaded.memory.frontmatter.tags.join(" ")).slice(0, 800);
2209
+ const tokens = tokenizeQuery4(text).filter((t) => t.length >= 4 && !STOP_WORDS.has(t));
2210
+ return new Set(tokens);
2211
+ }
2212
+ function jaccard(a, b) {
2213
+ if (a.size === 0 && b.size === 0) return 0;
2214
+ let intersect = 0;
2215
+ for (const x of a) if (b.has(x)) intersect++;
2216
+ const union = a.size + b.size - intersect;
2217
+ return union === 0 ? 0 : intersect / union;
2218
+ }
2219
+ function firstHeading(body) {
2220
+ for (const line of body.split("\n")) {
2221
+ const t = line.trim();
2222
+ if (t.startsWith("#")) return t.replace(/^#+\s*/, "").slice(0, 80);
2223
+ if (t.length > 0) return t.slice(0, 80);
2224
+ }
2225
+ return void 0;
2226
+ }
2227
+
2228
+ // src/tools/why-this-decision.ts
2229
+ import { existsSync as existsSync23 } from "fs";
2230
+ import { spawn as spawn2 } from "child_process";
2231
+ import {
2232
+ deriveConfidence as deriveConfidence7,
2233
+ getUsage as getUsage8,
2234
+ loadMemoriesFromDir as loadMemoriesFromDir19,
2235
+ loadUsageIndex as loadUsageIndex10,
2236
+ pathsOverlap as singlePathsOverlap
2237
+ } from "@hiveai/core";
2238
+ import { z as z26 } from "zod";
2239
+ var WhyThisDecisionInputSchema = {
2240
+ id: z26.string().min(1).describe("Memory id to inspect (e.g. '2026-04-25-decision-esm-only')."),
2241
+ git_log_limit: z26.number().int().positive().max(20).default(5).describe("How many recent commits per anchor path to surface.")
2242
+ };
2243
+ async function whyThisDecision(input, ctx) {
2244
+ if (!existsSync23(ctx.paths.memoriesDir)) {
2245
+ return {
2246
+ found: false,
2247
+ related: [],
2248
+ path_neighbors: [],
2249
+ recent_commits: [],
2250
+ notice: "No .ai/memories directory."
2251
+ };
2252
+ }
2253
+ const all = await loadMemoriesFromDir19(ctx.paths.memoriesDir);
2254
+ const usage = await loadUsageIndex10(ctx.paths);
2255
+ const target = all.find(({ memory }) => memory.frontmatter.id === input.id);
2256
+ if (!target) {
2257
+ return {
2258
+ found: false,
2259
+ related: [],
2260
+ path_neighbors: [],
2261
+ recent_commits: [],
2262
+ notice: `Memory '${input.id}' not found.`
2263
+ };
2264
+ }
2265
+ const fm = target.memory.frontmatter;
2266
+ const targetUsage = getUsage8(usage, fm.id);
2267
+ const decision = {
2268
+ id: fm.id,
2269
+ type: fm.type,
2270
+ scope: fm.scope,
2271
+ status: fm.status,
2272
+ confidence: deriveConfidence7(fm, targetUsage),
2273
+ body: target.memory.body,
2274
+ created_at: fm.created_at
2275
+ };
2276
+ const relatedSet = new Set(fm.related_ids ?? []);
2277
+ const related = [];
2278
+ for (const { memory } of all) {
2279
+ if (memory.frontmatter.id === fm.id) continue;
2280
+ const isExplicit = relatedSet.has(memory.frontmatter.id);
2281
+ const isBackLink = (memory.frontmatter.related_ids ?? []).includes(fm.id);
2282
+ if (!isExplicit && !isBackLink) continue;
2283
+ const u = getUsage8(usage, memory.frontmatter.id);
2284
+ related.push({
2285
+ id: memory.frontmatter.id,
2286
+ type: memory.frontmatter.type,
2287
+ scope: memory.frontmatter.scope,
2288
+ confidence: deriveConfidence7(memory.frontmatter, u),
2289
+ body_preview: memory.body.split("\n").slice(0, 4).join("\n").slice(0, 300),
2290
+ relation: isExplicit ? "explicit" : "back-link"
2291
+ });
2292
+ }
2293
+ const targetPaths = fm.anchor.paths;
2294
+ const path_neighbors = [];
2295
+ if (targetPaths.length > 0) {
2296
+ for (const { memory } of all) {
2297
+ if (memory.frontmatter.id === fm.id) continue;
2298
+ if (relatedSet.has(memory.frontmatter.id)) continue;
2299
+ const overlappingPaths = memory.frontmatter.anchor.paths.filter(
2300
+ (p) => targetPaths.some((tp) => singlePathsOverlap(p, tp))
2301
+ );
2302
+ if (overlappingPaths.length === 0) continue;
2303
+ const u = getUsage8(usage, memory.frontmatter.id);
2304
+ path_neighbors.push({
2305
+ id: memory.frontmatter.id,
2306
+ type: memory.frontmatter.type,
2307
+ scope: memory.frontmatter.scope,
2308
+ confidence: deriveConfidence7(memory.frontmatter, u),
2309
+ overlap: overlappingPaths,
2310
+ body_preview: memory.body.split("\n").slice(0, 3).join("\n").slice(0, 200)
2311
+ });
2312
+ if (path_neighbors.length >= 10) break;
2313
+ }
2314
+ }
2315
+ const recent_commits = [];
2316
+ for (const p of targetPaths.slice(0, 5)) {
2317
+ try {
2318
+ const commits = await runGitLog2(ctx.paths.root, p, input.git_log_limit);
2319
+ for (const c of commits) recent_commits.push({ path: p, ...c });
2320
+ } catch {
2321
+ }
2322
+ }
2323
+ const hints = [];
2324
+ if (decision.confidence === "low" || decision.confidence === "stale") {
2325
+ hints.push(`\u26A0\uFE0F Confidence is ${decision.confidence}. Verify this decision still applies before quoting it.`);
2326
+ }
2327
+ if (related.length === 0 && path_neighbors.length === 0 && targetPaths.length === 0) {
2328
+ hints.push("No related memories and no anchored paths \u2014 this decision is isolated; consider adding related_ids or paths.");
2329
+ }
2330
+ if (fm.type !== "decision" && fm.type !== "architecture") {
2331
+ hints.push(`Memory type is '${fm.type}', not 'decision'/'architecture' \u2014 output may be less informative.`);
2332
+ }
2333
+ return {
2334
+ found: true,
2335
+ decision,
2336
+ related,
2337
+ path_neighbors,
2338
+ recent_commits,
2339
+ ...hints.length > 0 ? { hints } : {}
2340
+ };
2341
+ }
2342
+ async function runGitLog2(cwd, filePath, limit) {
2343
+ const sep = "<<HV>>";
2344
+ const fmt = `%h${sep}%an${sep}%ar${sep}%s`;
2345
+ const output = await runCommand2(
2346
+ "git",
2347
+ ["log", "-n", String(limit), `--pretty=format:${fmt}`, "--", filePath],
2348
+ cwd
2349
+ );
2350
+ if (!output.trim()) return [];
2351
+ return output.split("\n").map((line) => {
2352
+ const [sha = "", author = "", relative_date = "", subject = ""] = line.split(sep);
2353
+ return { sha, author, relative_date, subject };
2354
+ }).filter((c) => c.sha);
2355
+ }
2356
+ function runCommand2(cmd, args, cwd) {
2357
+ return new Promise((resolve, reject) => {
2358
+ const proc = spawn2(cmd, args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
2359
+ let stdout = "";
2360
+ let stderr = "";
2361
+ proc.stdout.on("data", (chunk) => {
2362
+ stdout += chunk.toString();
2363
+ });
2364
+ proc.stderr.on("data", (chunk) => {
2365
+ stderr += chunk.toString();
2366
+ });
2367
+ proc.on("error", reject);
2368
+ proc.on("close", (code) => {
2369
+ if (code === 0) resolve(stdout);
2370
+ else reject(new Error(stderr || `${cmd} exited with code ${code}`));
2371
+ });
2372
+ });
2373
+ }
2374
+
2375
+ // src/tools/mem-conflicts.ts
2376
+ import { existsSync as existsSync24 } from "fs";
2377
+ import {
2378
+ deriveConfidence as deriveConfidence8,
2379
+ getUsage as getUsage9,
2380
+ loadMemoriesFromDir as loadMemoriesFromDir20,
2381
+ loadUsageIndex as loadUsageIndex11,
2382
+ pathsOverlap,
2383
+ tokenizeQuery as tokenizeQuery5
2384
+ } from "@hiveai/core";
2385
+ import { z as z27 } from "zod";
2386
+ var MemConflictsInputSchema = {
2387
+ id: z27.string().min(1).describe("Memory id to check for conflicts."),
2388
+ min_score: z27.number().min(0).max(1).default(0.5).describe("Minimum cosine similarity to consider a memory as a potential conflict (semantic mode)."),
2389
+ semantic: z27.boolean().default(true).describe("Use embeddings for similarity. Falls back to keyword overlap when embeddings are not installed.")
2390
+ };
2391
+ var POSITIVE_PATTERNS = /\b(use|prefer|always|should use|do this|recommended|ok to)\b/i;
2392
+ var NEGATIVE_PATTERNS = /\b(do not use|don'?t use|never|avoid|forbidden|deprecated|stop using|do NOT|❌)\b/i;
2393
+ async function memConflicts(input, ctx) {
2394
+ if (!existsSync24(ctx.paths.memoriesDir)) {
2395
+ return { found: false, scanned: 0, conflicts: [], notice: "No .ai/memories directory." };
2396
+ }
2397
+ const all = await loadMemoriesFromDir20(ctx.paths.memoriesDir);
2398
+ const target = all.find(({ memory }) => memory.frontmatter.id === input.id);
2399
+ if (!target) {
2400
+ return { found: false, scanned: 0, conflicts: [], notice: `Memory '${input.id}' not found.` };
2401
+ }
2402
+ const usage = await loadUsageIndex11(ctx.paths);
2403
+ const others = all.filter(
2404
+ ({ memory }) => memory.frontmatter.id !== input.id && memory.frontmatter.type !== "session_recap"
2405
+ );
2406
+ const simScores = input.semantic ? await trySemanticSimilarities(ctx, target, others) : null;
2407
+ const targetText = (target.memory.body + " " + target.memory.frontmatter.tags.join(" ")).toLowerCase();
2408
+ const targetTokens = new Set(tokenizeQuery5(targetText));
2409
+ const targetPolarity = polarity(targetText);
2410
+ const targetPaths = target.memory.frontmatter.anchor.paths;
2411
+ const explicitContradicts = extractContradictsTags(target.memory.body);
2412
+ const conflicts = [];
2413
+ for (const other of others) {
2414
+ const fm = other.memory.frontmatter;
2415
+ const otherText = (other.memory.body + " " + fm.tags.join(" ")).toLowerCase();
2416
+ const reasons = [];
2417
+ const sim = simScores?.get(fm.id) ?? null;
2418
+ const hasPathOverlap = fm.anchor.paths.some((p) => targetPaths.some((tp) => pathsOverlap(p, tp)));
2419
+ const otherTokens = new Set(tokenizeQuery5(otherText));
2420
+ const tokenOverlap = countIntersection(targetTokens, otherTokens);
2421
+ const isSemanticNeighbor = sim !== null && sim >= input.min_score;
2422
+ if (!hasPathOverlap && tokenOverlap < 4 && !isSemanticNeighbor) continue;
2423
+ const otherContradicts = extractContradictsTags(other.memory.body);
2424
+ if (explicitContradicts.has(fm.id) || otherContradicts.has(input.id)) {
2425
+ reasons.push("explicit-contradiction-tag");
2426
+ }
2427
+ if (target.memory.frontmatter.status === "validated" && fm.status === "rejected" || target.memory.frontmatter.status === "rejected" && fm.status === "validated") {
2428
+ if (tokenOverlap >= 4 || isSemanticNeighbor) reasons.push("opposite-status");
2429
+ }
2430
+ if (hasPathOverlap) {
2431
+ const tType = target.memory.frontmatter.type;
2432
+ const oType = fm.type;
2433
+ const isAttemptVsRule = tType === "attempt" && (oType === "convention" || oType === "decision") || oType === "attempt" && (tType === "convention" || tType === "decision");
2434
+ if (isAttemptVsRule) reasons.push("attempt-vs-convention-same-paths");
2435
+ }
2436
+ if (isSemanticNeighbor) {
2437
+ const otherPolarity = polarity(otherText);
2438
+ if (targetPolarity === "positive" && otherPolarity === "negative" || targetPolarity === "negative" && otherPolarity === "positive") {
2439
+ reasons.push("polarity-keywords");
2440
+ }
2441
+ }
2442
+ if (reasons.length === 0) continue;
2443
+ const u = getUsage9(usage, fm.id);
2444
+ conflicts.push({
2445
+ id: fm.id,
2446
+ type: fm.type,
2447
+ scope: fm.scope,
2448
+ status: fm.status,
2449
+ confidence: deriveConfidence8(fm, u),
2450
+ body_preview: other.memory.body.split("\n").slice(0, 4).join("\n").slice(0, 300),
2451
+ similarity: sim,
2452
+ reasons,
2453
+ shared_paths: fm.anchor.paths.filter((p) => targetPaths.some((tp) => pathsOverlap(p, tp)))
2454
+ });
2455
+ }
2456
+ conflicts.sort((a, b) => {
2457
+ const score = (c) => (c.reasons.includes("explicit-contradiction-tag") ? 100 : 0) + (c.reasons.includes("opposite-status") ? 50 : 0) + (c.reasons.includes("attempt-vs-convention-same-paths") ? 25 : 0) + (c.reasons.includes("polarity-keywords") ? 10 : 0) + (c.similarity ?? 0) * 5;
2458
+ return score(b) - score(a);
2459
+ });
2460
+ return {
2461
+ found: true,
2462
+ target: {
2463
+ id: target.memory.frontmatter.id,
2464
+ type: target.memory.frontmatter.type,
2465
+ status: target.memory.frontmatter.status
2466
+ },
2467
+ scanned: others.length,
2468
+ conflicts: conflicts.slice(0, 10)
2469
+ };
2470
+ }
2471
+ function polarity(text) {
2472
+ const neg = NEGATIVE_PATTERNS.test(text);
2473
+ const pos = POSITIVE_PATTERNS.test(text);
2474
+ if (neg && !pos) return "negative";
2475
+ if (pos && !neg) return "positive";
2476
+ return "neutral";
2477
+ }
2478
+ function extractContradictsTags(body) {
2479
+ const out = /* @__PURE__ */ new Set();
2480
+ for (const m of body.matchAll(/#contradicts:([\w-]+)/g)) {
2481
+ if (m[1]) out.add(m[1]);
2482
+ }
2483
+ return out;
2484
+ }
2485
+ function countIntersection(a, b) {
2486
+ let n = 0;
2487
+ for (const x of a) if (b.has(x)) n++;
2488
+ return n;
2489
+ }
2490
+ async function trySemanticSimilarities(ctx, target, others) {
2491
+ let mod;
2492
+ try {
2493
+ mod = await import("@hiveai/embeddings");
2494
+ } catch {
2495
+ return null;
2496
+ }
2497
+ const result = await mod.semanticSearch(
2498
+ ctx.paths,
2499
+ target.memory.body,
2500
+ { limit: others.length }
2501
+ );
2502
+ if (!result) return null;
2503
+ const map = /* @__PURE__ */ new Map();
2504
+ for (const hit of result.hits) map.set(hit.id, hit.score);
2505
+ return map;
2506
+ }
2507
+
2508
+ // src/tools/precommit-check.ts
2509
+ import { z as z28 } from "zod";
2510
+ var PreCommitCheckInputSchema = {
2511
+ diff: z28.string().optional().describe(
2512
+ "Raw unified diff text to scan. If omitted, only `paths` is used. When called from a pre-commit hook, pipe the output of `git diff --cached`."
2513
+ ),
2514
+ paths: z28.array(z28.string()).default([]).describe("Project-relative paths affected by the change. At least one of `diff` or `paths` should be provided."),
2515
+ block_on: z28.enum(["any", "high-confidence", "never"]).default("high-confidence").describe(
2516
+ "When to set should_block=true: 'any' = any warning blocks; 'high-confidence' = only warnings from authoritative/trusted memories block; 'never' = report only, never block."
2517
+ ),
2518
+ semantic: z28.boolean().default(true).describe("Enable semantic search in anti_patterns_check (requires embeddings index).")
2519
+ };
2520
+ async function preCommitCheck(input, ctx) {
2521
+ if (!input.diff && input.paths.length === 0) {
2522
+ return {
2523
+ should_block: false,
2524
+ summary: { anti_patterns: 0, relevant_memories: 0, stale_anchors: 0 },
2525
+ warnings: [],
2526
+ relevant_memories: [],
2527
+ stale_anchors: [],
2528
+ notice: "Nothing to check \u2014 provide either `diff` or `paths`."
2529
+ };
2530
+ }
2531
+ const apResult = await antiPatternsCheck({
2532
+ diff: input.diff,
2533
+ paths: input.paths,
2534
+ limit: 20,
2535
+ semantic: input.semantic
2536
+ }, ctx);
2537
+ const relevant = input.paths.length > 0 ? await memForFiles({ files: input.paths, include_module_contexts: false, track: false }, ctx) : { by_anchor: [], by_module: [], by_domain: [], module_contexts: [], inferred_modules: [] };
2538
+ const relevantMatches = [...relevant.by_anchor, ...relevant.by_module];
2539
+ const verifyResult = input.paths.length > 0 ? await memVerify({ update: false, id: void 0 }, ctx) : { results: [], summary: { checked: 0, fresh: 0, stale: 0, anchorless_skipped: 0, updated: 0 } };
2540
+ const filesTouching = new Set(relevantMatches.map((m) => m.id));
2541
+ const staleHits = verifyResult.results.filter((r) => r.stale && filesTouching.has(r.id));
2542
+ const blockOn = input.block_on;
2543
+ let should_block = false;
2544
+ if (blockOn !== "never") {
2545
+ const high = apResult.warnings.filter(
2546
+ (w) => w.confidence === "authoritative" || w.confidence === "trusted"
2547
+ );
2548
+ if (blockOn === "any" && (apResult.warnings.length > 0 || staleHits.length > 0)) should_block = true;
2549
+ if (blockOn === "high-confidence" && (high.length > 0 || staleHits.length > 0)) should_block = true;
2550
+ }
2551
+ const relevant_memories = relevantMatches.slice(0, 8).map((m) => ({
2552
+ id: m.id,
2553
+ type: m.type,
2554
+ confidence: String(m.confidence),
2555
+ body_preview: (m.body ?? "").split("\n").slice(0, 4).join("\n").slice(0, 250)
2556
+ }));
2557
+ return {
2558
+ should_block,
2559
+ summary: {
2560
+ anti_patterns: apResult.warnings.length,
2561
+ relevant_memories: relevant_memories.length,
2562
+ stale_anchors: staleHits.length
2563
+ },
2564
+ warnings: apResult.warnings,
2565
+ relevant_memories,
2566
+ stale_anchors: staleHits.map((r) => ({
2567
+ id: r.id,
2568
+ // The matching `relevantMatches` entry tells us which paths overlap.
2569
+ paths: relevantMatches.find((m) => m.id === r.id) ? input.paths.filter((p) => relevantMatches.some((m) => m.id === r.id)) : [],
2570
+ body_preview: r.reason ?? "anchored code drifted; verify before relying on this memory"
2571
+ }))
2572
+ };
2573
+ }
2574
+
2575
+ // src/prompts/bootstrap-project.ts
2576
+ import { z as z29 } from "zod";
1645
2577
  var BootstrapProjectArgsSchema = {
1646
- module: z20.string().optional().describe(
2578
+ module: z29.string().optional().describe(
1647
2579
  "Optional module name to scope the analysis to (writes to .ai/modules/<module>/context.md)"
1648
2580
  ),
1649
- focus: z20.string().optional().describe("Optional area to emphasize (e.g. 'data layer', 'API surface')")
2581
+ focus: z29.string().optional().describe("Optional area to emphasize (e.g. 'data layer', 'API surface')")
1650
2582
  };
1651
2583
  var ROOT_TEMPLATE = `# Project context
1652
2584
 
@@ -1728,10 +2660,10 @@ ${template}\`\`\`
1728
2660
  }
1729
2661
 
1730
2662
  // src/prompts/post-task.ts
1731
- import { z as z21 } from "zod";
2663
+ import { z as z30 } from "zod";
1732
2664
  var PostTaskArgsSchema = {
1733
- task_summary: z21.string().optional().describe("One sentence describing what you just did"),
1734
- files_touched: z21.array(z21.string()).optional().describe("Files you created or modified during the task")
2665
+ task_summary: z30.string().optional().describe("One sentence describing what you just did"),
2666
+ files_touched: z30.array(z30.string()).optional().describe("Files you created or modified during the task")
1735
2667
  };
1736
2668
  function postTaskPrompt(args, ctx) {
1737
2669
  const taskLine = args.task_summary ? `
@@ -1813,12 +2745,12 @@ When done, respond with a brief summary: "Saved N memories: [list of IDs]. Sessi
1813
2745
  }
1814
2746
 
1815
2747
  // src/prompts/import-docs.ts
1816
- import { z as z22 } from "zod";
2748
+ import { z as z31 } from "zod";
1817
2749
  var ImportDocsArgsSchema = {
1818
- content: z22.string().describe("The documentation content to analyze and import as memories (Markdown, README, ADR, etc.)"),
1819
- source: z22.string().optional().describe("Origin of the content (file path, URL, or document title) \u2014 used to anchor memories"),
1820
- scope: z22.enum(["personal", "team"]).default("team").describe("Scope to assign to created memories"),
1821
- dry_run: z22.boolean().default(false).describe("If true, describe what would be saved without actually calling mem_save")
2750
+ content: z31.string().describe("The documentation content to analyze and import as memories (Markdown, README, ADR, etc.)"),
2751
+ source: z31.string().optional().describe("Origin of the content (file path, URL, or document title) \u2014 used to anchor memories"),
2752
+ scope: z31.enum(["personal", "team"]).default("team").describe("Scope to assign to created memories"),
2753
+ dry_run: z31.boolean().default(false).describe("If true, describe what would be saved without actually calling mem_save")
1822
2754
  };
1823
2755
  function importDocsPrompt(args, ctx) {
1824
2756
  const sourceLine = args.source ? `
@@ -1882,7 +2814,7 @@ When done, respond with: "Imported N memories: [list of IDs]" or "Nothing action
1882
2814
  }
1883
2815
 
1884
2816
  // src/session-tracker.ts
1885
- import { loadConfig as loadConfig3 } from "@hiveai/core";
2817
+ import { appendUsageEvent, loadConfig as loadConfig3 } from "@hiveai/core";
1886
2818
  var SessionTracker = class {
1887
2819
  events = [];
1888
2820
  startedAt = (/* @__PURE__ */ new Date()).toISOString();
@@ -1899,7 +2831,9 @@ var SessionTracker = class {
1899
2831
  }
1900
2832
  }
1901
2833
  record(tool, summary) {
1902
- this.events.push({ tool, at: (/* @__PURE__ */ new Date()).toISOString(), summary });
2834
+ const event = { tool, at: (/* @__PURE__ */ new Date()).toISOString(), summary };
2835
+ this.events.push(event);
2836
+ void appendUsageEvent(this.ctx.paths, event);
1903
2837
  }
1904
2838
  registerShutdownHandler() {
1905
2839
  if (this.shutdownRegistered) return;
@@ -1952,7 +2886,7 @@ function summarizeTools(events) {
1952
2886
 
1953
2887
  // src/server.ts
1954
2888
  var SERVER_NAME = "haive";
1955
- var SERVER_VERSION = "0.4.5";
2889
+ var SERVER_VERSION = "0.6.0";
1956
2890
  function jsonResult(data) {
1957
2891
  return {
1958
2892
  content: [
@@ -2161,7 +3095,10 @@ function createHaiveServer(options = {}) {
2161
3095
  "RETURNS: array of { id, type, scope, status, confidence, body, match_quality }"
2162
3096
  ].join("\n"),
2163
3097
  MemSearchInputSchema,
2164
- async (input) => jsonResult(await memSearch(input, context))
3098
+ async (input) => {
3099
+ tracker.record("mem_search", input.query.slice(0, 80));
3100
+ return jsonResult(await memSearch(input, context));
3101
+ }
2165
3102
  );
2166
3103
  server.tool(
2167
3104
  "mem_for_files",
@@ -2389,6 +3326,211 @@ function createHaiveServer(options = {}) {
2389
3326
  MemDeleteInputSchema,
2390
3327
  async (input) => jsonResult(await memDelete(input, context))
2391
3328
  );
3329
+ server.tool(
3330
+ "get_recap",
3331
+ [
3332
+ "Return ONLY the most recent session_recap. Cheaper than get_briefing when",
3333
+ "you just want to know 'what was I doing last time?' and don't need project",
3334
+ "context, modules, or memory ranking.",
3335
+ "",
3336
+ "PARAMETERS:",
3337
+ " scope \u2014 'personal' | 'team' | 'any' (default 'any', returns the most recent across both)",
3338
+ "",
3339
+ "RETURNS: { recap: { id, scope, revision_count, created_at, body } | null, notice? }"
3340
+ ].join("\n"),
3341
+ GetRecapInputSchema,
3342
+ async (input) => {
3343
+ tracker.record("get_recap", input.scope);
3344
+ return jsonResult(await getRecap(input, context));
3345
+ }
3346
+ );
3347
+ server.tool(
3348
+ "mem_relevant_to",
3349
+ [
3350
+ "One-shot ranked memories for a task \u2014 use instead of get_briefing when",
3351
+ "project context is already loaded and you only want the relevant memory layer.",
3352
+ "",
3353
+ "Reuses the same ranking pipeline (anchor / module / literal / semantic) but",
3354
+ "skips project_context, modules, action_required, etc.",
3355
+ "",
3356
+ "PARAMETERS:",
3357
+ " task \u2014 1\u20132 sentences describing what you are about to do (required)",
3358
+ " files \u2014 files you'll edit (surfaces anchored memories)",
3359
+ " limit \u2014 cap on returned memories (default 8)",
3360
+ " min_semantic_score \u2014 drop weak semantic hits below this cosine (default 0.25)",
3361
+ "",
3362
+ "RETURNS: { task, search_mode, memories: [...], hints?: [...], empty?: true }"
3363
+ ].join("\n"),
3364
+ MemRelevantToInputSchema,
3365
+ async (input) => {
3366
+ tracker.record("mem_relevant_to", input.task.slice(0, 80));
3367
+ return jsonResult(await memRelevantTo(input, context));
3368
+ }
3369
+ );
3370
+ server.tool(
3371
+ "code_search",
3372
+ [
3373
+ "Semantic search over the codebase \u2014 finds exported symbols (functions, classes,",
3374
+ "interfaces) related to a natural-language query. Replaces blind grep when you",
3375
+ "don't know the exact symbol name.",
3376
+ "",
3377
+ "Requires `haive index code-search` to have been run (builds embeddings for every",
3378
+ "exported symbol from the code-map). Falls back to a notice when index is missing.",
3379
+ "",
3380
+ "PARAMETERS:",
3381
+ " query \u2014 natural language (e.g. 'function that hashes passwords', 'JWT signing')",
3382
+ " k \u2014 number of top hits (default 5)",
3383
+ " min_score \u2014 minimum cosine similarity (default 0.2; try 0.3+ for stricter)",
3384
+ "",
3385
+ "RETURNS: { available: bool, hits: [{ file, name, kind, line, description?, score }] }"
3386
+ ].join("\n"),
3387
+ CodeSearchInputSchema,
3388
+ async (input) => {
3389
+ tracker.record("code_search", input.query.slice(0, 80));
3390
+ return jsonResult(await codeSearch(input, context));
3391
+ }
3392
+ );
3393
+ server.tool(
3394
+ "why_this_file",
3395
+ [
3396
+ "One-shot file-context lookup: combines recent git history, memories anchored",
3397
+ "to the path, and the code-map entry. Answers 'why is this file the way it is?'",
3398
+ "in a single call instead of 3-4 manual ones.",
3399
+ "",
3400
+ "PARAMETERS:",
3401
+ " path \u2014 project-relative path (required)",
3402
+ " git_log_limit \u2014 recent commits to include (default 5)",
3403
+ " memory_limit \u2014 anchored memories cap (default 5)",
3404
+ "",
3405
+ "RETURNS: { file, exists, recent_commits: [...], memories: [...], code_map_entry, hints? }"
3406
+ ].join("\n"),
3407
+ WhyThisFileInputSchema,
3408
+ async (input) => {
3409
+ tracker.record("why_this_file", input.path);
3410
+ return jsonResult(await whyThisFile(input, context));
3411
+ }
3412
+ );
3413
+ server.tool(
3414
+ "anti_patterns_check",
3415
+ [
3416
+ "Scan a diff (or set of paths) against documented attempt/gotcha memories.",
3417
+ "Surfaces 'you are about to repeat a known mistake' warnings BEFORE you commit.",
3418
+ "",
3419
+ "USE BEFORE finalizing a non-trivial change. Cheap and high-signal: the only",
3420
+ "memories scanned are 'attempt' and 'gotcha' types.",
3421
+ "",
3422
+ "PARAMETERS:",
3423
+ " diff \u2014 raw unified diff text (or any code snippet) \u2014 optional if `paths` provided",
3424
+ " paths \u2014 affected file paths (optional if `diff` provided)",
3425
+ " limit \u2014 cap on returned warnings (default 8)",
3426
+ " semantic \u2014 also use semantic search (default true; requires embeddings index)",
3427
+ "",
3428
+ "RETURNS: { scanned, warnings: [{ id, type, scope, confidence, body_preview, reasons, semantic_score? }] }"
3429
+ ].join("\n"),
3430
+ AntiPatternsCheckInputSchema,
3431
+ async (input) => {
3432
+ tracker.record("anti_patterns_check", input.paths.join(",").slice(0, 80));
3433
+ return jsonResult(await antiPatternsCheck(input, context));
3434
+ }
3435
+ );
3436
+ server.tool(
3437
+ "mem_distill",
3438
+ [
3439
+ "Cluster recurring observations / failed attempts so a human can collapse",
3440
+ "N similar memories into one richer convention/gotcha. Cheap heuristic",
3441
+ "(anchor path overlap + body keyword overlap) \u2014 no embeddings required.",
3442
+ "",
3443
+ "USE periodically (e.g. monthly) to prevent memory pollution from agents",
3444
+ "saving the same observation many times.",
3445
+ "",
3446
+ "PARAMETERS:",
3447
+ " since_days \u2014 only consider memories from the last N days (default 30)",
3448
+ " min_cluster \u2014 minimum cluster size to surface (default 3)",
3449
+ " type_filter \u2014 'gotcha' | 'attempt' | 'all' (default 'gotcha')",
3450
+ " scope \u2014 'personal' | 'team' | 'module' | 'any' (default 'any')",
3451
+ "",
3452
+ "RETURNS: { scanned, singletons, clusters: [{ suggested_topic, member_ids, ... }] }",
3453
+ "Output is advisory \u2014 nothing is written to disk."
3454
+ ].join("\n"),
3455
+ MemDistillInputSchema,
3456
+ async (input) => {
3457
+ tracker.record("mem_distill", `${input.type_filter}/since=${input.since_days}d`);
3458
+ return jsonResult(await memDistill(input, context));
3459
+ }
3460
+ );
3461
+ server.tool(
3462
+ "why_this_decision",
3463
+ [
3464
+ "Trace the genealogy of a memory (especially decision/architecture):",
3465
+ "the memory itself + memories explicitly linked via related_ids + memories",
3466
+ "anchored to overlapping paths + recent commits touching those paths.",
3467
+ "",
3468
+ "USE WHEN you find a memory and need to understand WHY it was made and",
3469
+ "what surrounds it. One call instead of 4-5 manual lookups.",
3470
+ "",
3471
+ "PARAMETERS:",
3472
+ " id \u2014 memory id (required)",
3473
+ " git_log_limit \u2014 how many recent commits per anchor path (default 5)",
3474
+ "",
3475
+ "RETURNS: { decision, related: [...], path_neighbors: [...], recent_commits: [...] }"
3476
+ ].join("\n"),
3477
+ WhyThisDecisionInputSchema,
3478
+ async (input) => {
3479
+ tracker.record("why_this_decision", input.id);
3480
+ return jsonResult(await whyThisDecision(input, context));
3481
+ }
3482
+ );
3483
+ server.tool(
3484
+ "mem_conflicts_with",
3485
+ [
3486
+ "Detect memories that potentially CONTRADICT a given memory.",
3487
+ "",
3488
+ "USE BEFORE relying on a memory's advice \u2014 surfaces 'another memory says",
3489
+ "the opposite'. Detection uses several heuristics layered together:",
3490
+ "",
3491
+ " 1. Opposite status \u2014 validated vs rejected on overlapping topic",
3492
+ " 2. attempt-vs-convention on overlapping anchor paths",
3493
+ " 3. Polarity keywords \u2014 'use X' vs 'do not use X' among semantic neighbors",
3494
+ " 4. Explicit #contradicts:<id> tags in either body",
3495
+ "",
3496
+ "PARAMETERS:",
3497
+ " id \u2014 memory id to check (required)",
3498
+ " min_score \u2014 minimum cosine similarity for semantic neighbors (default 0.5)",
3499
+ " semantic \u2014 use embeddings (default true)",
3500
+ "",
3501
+ "RETURNS: { found, target, scanned, conflicts: [{ id, reasons, similarity, ... }] }"
3502
+ ].join("\n"),
3503
+ MemConflictsInputSchema,
3504
+ async (input) => {
3505
+ tracker.record("mem_conflicts_with", input.id);
3506
+ return jsonResult(await memConflicts(input, context));
3507
+ }
3508
+ );
3509
+ server.tool(
3510
+ "pre_commit_check",
3511
+ [
3512
+ "One-shot 'should I block this commit?' check. Combines three signals:",
3513
+ "",
3514
+ " 1. anti_patterns_check \u2014 known gotchas/attempts that match the diff",
3515
+ " 2. mem_for_files \u2014 conventions/decisions anchored to touched files",
3516
+ " 3. mem_verify \u2014 memories whose anchors are stale (knowledge may be wrong)",
3517
+ "",
3518
+ "USE FROM A GIT HOOK or before finalizing a non-trivial change.",
3519
+ "",
3520
+ "PARAMETERS:",
3521
+ " diff \u2014 raw unified diff text (e.g. `git diff --cached`)",
3522
+ " paths \u2014 affected file paths (project-relative)",
3523
+ " block_on \u2014 'any' | 'high-confidence' (default) | 'never'",
3524
+ " semantic \u2014 use embeddings in anti_patterns_check (default true)",
3525
+ "",
3526
+ "RETURNS: { should_block, summary, warnings, relevant_memories, stale_anchors }"
3527
+ ].join("\n"),
3528
+ PreCommitCheckInputSchema,
3529
+ async (input) => {
3530
+ tracker.record("pre_commit_check", `${input.paths.length}p`);
3531
+ return jsonResult(await preCommitCheck(input, context));
3532
+ }
3533
+ );
2392
3534
  server.tool(
2393
3535
  "mem_diff",
2394
3536
  [