toon-memory 4.2.0 → 4.3.1

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/src/mcp/tools.ts CHANGED
@@ -12,7 +12,7 @@ import { archiveOldEntries } from "./archive"
12
12
  import { consolidateEntries, consolidateVersions } from "./consolidation"
13
13
  import { readUnderLock } from "../lib/lock"
14
14
  import { encrypt, decrypt } from "./crypto"
15
- import { graphRecallDetailed, renderCompact, parseEntries, buildGraph, parseLinkToken, formatLink, typedLinks } from "../lib/graph"
15
+ import { graphRecallDetailed, renderCompact, renderIndex, fetchEntriesByIds, parseEntries, buildGraph, parseLinkToken, formatLink, typedLinks } from "../lib/graph"
16
16
  import { qualityScore, mergeEntries, generateSmartRecall } from "../lib/quality"
17
17
  import { generateContextBrief, generateContextGenerate, generateContextDiff, generateContextFocus, generateContextHealth, generateContextExport } from "../lib/context"
18
18
  import { coordinationView, resolveSessionId, currentBranch, SESSION_TTL_MS, getCurrentSessionFiles } from "../lib/sessions"
@@ -466,10 +466,11 @@ server.registerTool(
466
466
  links: z.string().optional().default("").describe("Related entry keys, separated by space or ';' (e.g. risk-spec engine-arch). Builds graph edges."),
467
467
  path_scope: z.string().optional().default("").describe("Glob pattern to scope this entry (e.g. src/**.ts). Empty = global."),
468
468
  origin: z.enum(["human", "agent", "inferred"]).optional().default("agent").describe("Who created this entry."),
469
+ importance: z.enum(["critical", "high", "medium", "low"]).optional().describe("Explicit importance level — critical/high entries surface first in recall, low last. Omit for auto (recency + frequency)."),
469
470
  },
470
471
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
471
472
  },
472
- async ({ category, key, content, file, tags, ttl, links, path_scope, origin }) => {
473
+ async ({ category, key, content, file, tags, ttl, links, path_scope, origin, importance = "" }) => {
473
474
  const data = readMemory()
474
475
  const newId = generateId()
475
476
  const date = new Date().toISOString().split("T")[0]
@@ -504,7 +505,7 @@ server.registerTool(
504
505
  const resolvedLinks = links
505
506
  ? links.split(/[\s;]+/).filter(Boolean).join(" ")
506
507
  : existingParts[9] || ""
507
- let newEntry = toToonLine([entryId, category, key, content, file || "", resolvedTags, date, resolvedTtl, "0", resolvedLinks, "", "", "", path_scope || "", origin])
508
+ let newEntry = toToonLine([entryId, category, key, content, file || "", resolvedTags, date, resolvedTtl, "0", resolvedLinks, "", "", "", "0", path_scope || "", origin, "", "", importance])
508
509
  let action = "Saved"
509
510
  let mergeInfo = ""
510
511
  const tagsInferred = !tags && resolvedTags ? true : false
@@ -519,7 +520,7 @@ server.registerTool(
519
520
  const lastAccessed = ""
520
521
  const quality = verbatim ? 0.5 : qualityScore(resolvedTags, resolvedLinks, content, date, accessed, lastAccessed, origin)
521
522
  const confidence = 1.0
522
- newEntry = toToonLine([entryId, category, key, content, file || "", resolvedTags, date, resolvedTtl, String(accessed), resolvedLinks, quality.toFixed(2), String(confidence), lastAccessed, "0", path_scope || "", origin, "active"])
523
+ newEntry = toToonLine([entryId, category, key, content, file || "", resolvedTags, date, resolvedTtl, String(accessed), resolvedLinks, quality.toFixed(2), String(confidence), lastAccessed, "0", path_scope || "", origin, "active", "", importance])
523
524
  const match = lines[headerIdx].match(/\[(\d+)\|/)
524
525
  const count = match ? parseInt(match[1]) : 0
525
526
  lines.splice(headerIdx + 1, 0, newEntry)
@@ -562,12 +563,14 @@ server.registerTool(
562
563
  title: "Search Memory",
563
564
  description: "Search the project's persistent memory. Returns relevant entries. Use BEFORE reading files. Pattern: recall → context_diff for recent changes → capture to save observations.",
564
565
  inputSchema: {
565
- query: z.string().describe("Text to search for"),
566
+ query: z.string().optional().default("").describe("Text to search for (optional when mode:'index' or ids is given)"),
566
567
  category: z.string().optional().default("").describe("Filter by category (empty = all)"),
567
568
  from_date: z.string().optional().default("").describe("Start date filter (YYYY-MM-DD)"),
568
569
  to_date: z.string().optional().default("").describe("End date filter (YYYY-MM-DD)"),
569
- mode: z.enum(["flat", "graph"]).optional().default("flat").describe("'flat' = keyword search (default). 'graph' = graph-based recall: expands the related-entry subgraph from matches (more precise, fewer tokens)."),
570
+ mode: z.enum(["flat", "graph", "index"]).optional().default("flat").describe("'flat' = keyword search (default). 'graph' = graph-based recall: expands the related-entry subgraph from matches (more precise, fewer tokens). 'index' = one line per entry (key, id, category, date, relevance %) with no content — browse then fetch full entries with `ids`."),
571
+ ids: z.string().optional().default("").describe("Batch fetch: comma/space/;-separated entry ids or keys, rendered in the given order (unknown entries skipped). Complements mode:'index' — layer 2 of progressive disclosure. Overrides mode."),
570
572
  hops: z.number().optional().default(1).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
573
+ limit: z.number().optional().describe("Maximum entries returned. Default 6 (15 in 'index' mode). Keeps token cost low."),
571
574
  compact: z.boolean().optional().default(false).describe("Token-efficient output: numeric indices (1, 2), omits id/date/file (keeps tags), edges as '->2', truncates graph neighbors to a snippet. Does not mutate .toon file."),
572
575
  budget: z.enum(["tiny", "normal", "deep"]).optional().default("deep").describe("'tiny': key+1 line (~50 tokens). 'normal': compact with tags/edges. 'deep': all fields (default). Overrides 'compact'."),
573
576
  budget_tokens: z.number().optional().default(0).describe("Deterministic token budget: include entries until the estimated output reaches ~N tokens (overrides limit). 0 = no budget."),
@@ -579,14 +582,61 @@ server.registerTool(
579
582
  },
580
583
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
581
584
  },
582
- async ({ query, category, from_date, to_date, mode, hops, compact, budget: budgetParam, budget_tokens, explain, bias, path_scope, rrf, as_of }) => {
585
+ async ({ query, category, from_date, to_date, mode, ids, hops, limit: limitParam, compact, budget: budgetParam, budget_tokens, explain, bias, path_scope, rrf, as_of }) => {
583
586
  const data = readMemory()
587
+ const resolvedBudget = budgetParam || (compact ? "normal" : "deep")
588
+ const resolvedAsOf = as_of || undefined
589
+
590
+ // ── Batch fetch by ids/keys (layer 2 of progressive disclosure) ──────
591
+ if (ids && ids.trim()) {
592
+ const tokens = ids.split(/[\s,;]+/).map((t) => t.trim()).filter(Boolean)
593
+ const entries = fetchEntriesByIds(data, tokens, { asOf: resolvedAsOf })
594
+ if (entries.length === 0) {
595
+ return { content: [{ type: "text" as const, text: `No entries found for ids: ${ids}` }] }
596
+ }
597
+ bumpAccessed(entries.map((e) => e.id))
598
+ const label = entries.length === 1 ? "entry" : "entries"
599
+ if (resolvedBudget === "tiny" || resolvedBudget === "normal") {
600
+ const formatted = renderCompact(entries, {
601
+ budget: resolvedBudget,
602
+ budgetTokens: budget_tokens || undefined,
603
+ })
604
+ return { content: [{ type: "text" as const, text: `Fetched ${entries.length} ${label}:\n\n${formatted}` }] }
605
+ }
606
+ const formatted = entries
607
+ .map((r) => {
608
+ const links = r.links.length ? `\n links: ${r.links.join(", ")}` : ""
609
+ const pin = r.priority > 0 ? (r.priority > 1 ? ` 📌${r.priority}` : " 📌") : ""
610
+ const originInfo = r.origin !== "agent" ? ` | origin: ${r.origin}` : ""
611
+ const scopeInfo = r.path_scope ? ` | scope: ${r.path_scope}` : ""
612
+ const statusInfo = r.status !== "active" ? ` | status: ${r.status}` : ""
613
+ const supersededInfo = r.supersededOn ? ` | superseded: ${r.supersededOn}` : ""
614
+ return `[${r.category}] ${r.key}${pin} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags.join(";")} | Date: ${r.date}${links}${originInfo}${scopeInfo}${statusInfo}${supersededInfo}`
615
+ })
616
+ .join("\n\n")
617
+ return { content: [{ type: "text" as const, text: `Fetched ${entries.length} ${label}:\n\n${formatted}` }] }
618
+ }
584
619
 
585
- // Delegate to graphRecallDetailed for both flat and graph modes
620
+ // Delegate to graphRecallDetailed for flat / graph / index modes
586
621
  // This avoids duplicating BM25 + ranking logic
587
622
  const sessionFiles = bias === "session" ? getCurrentSessionFiles() : undefined
588
- const resolvedBudget = budgetParam || (compact ? "normal" : "deep")
589
- const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops, sessionFiles, path_scope: path_scope || undefined, rrf, asOf: as_of || undefined })
623
+ const limit = limitParam ?? (mode === "index" ? 15 : 6)
624
+ const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops, limit, sessionFiles, path_scope: path_scope || undefined, rrf, asOf: resolvedAsOf })
625
+
626
+ // ── Index mode: one line per entry, no content ───────────────────────
627
+ if (mode === "index") {
628
+ if (detail.entries.length === 0) {
629
+ return { content: [{ type: "text" as const, text: `No results found for "${query}"` }] }
630
+ }
631
+ const formatted = renderIndex(detail.entries, { scores: detail.scores })
632
+ return {
633
+ content: [{
634
+ type: "text" as const,
635
+ text: `📇 Memory index (${detail.entries.length} entries):\n\n${formatted}\n\nFetch full entries with memory_recall ids="<id1>,<id2>" or search with mode:"flat".`,
636
+ }],
637
+ }
638
+ }
639
+
590
640
  if (detail.entries.length === 0) {
591
641
  return { content: [{ type: "text" as const, text: `No results found for "${query}"` }] }
592
642
  }