toon-memory 4.3.0 → 4.3.2

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/lib/graph.ts CHANGED
@@ -612,6 +612,42 @@ export function graphRecall(
612
612
  return graphRecallDetailed(data, query, opts).entries
613
613
  }
614
614
 
615
+ export interface FetchByIdsOpts {
616
+ /** Temporal view: include superseded entries still valid on that date. */
617
+ asOf?: string
618
+ /** Reference date for TTL expiry checks. Defaults to the wall clock. */
619
+ today?: string
620
+ }
621
+
622
+ /**
623
+ * Resolve ids or keys (comma/space/`;`-separated tokens) to entries, preserving
624
+ * input order. Skips unknown tokens and entries that are obsolete/draft (unless
625
+ * they were still valid under `asOf`). Used by `memory_recall`'s batch fetch —
626
+ * the "second layer" of progressive disclosure after browsing the index.
627
+ */
628
+ export function fetchEntriesByIds(data: string, tokens: string[], opts: FetchByIdsOpts = {}): GraphEntry[] {
629
+ const byId = new Map<string, GraphEntry>()
630
+ const byKey = new Map<string, GraphEntry>()
631
+ const asOf = opts.asOf || ""
632
+ for (const e of parseEntries(data)) {
633
+ const visible =
634
+ e.status === "active" ||
635
+ e.status === "resolved" ||
636
+ (asOf && e.status === "obsolete" && e.supersededOn && e.supersededOn > asOf)
637
+ if (!visible) continue
638
+ if (asOf && e.date && e.date > asOf) continue
639
+ if (e.ttl && isExpiredLocal(e.ttl, opts.today)) continue
640
+ if (!byId.has(e.id)) byId.set(e.id, e)
641
+ if (!byKey.has(e.key)) byKey.set(e.key, e)
642
+ }
643
+ const out: GraphEntry[] = []
644
+ for (const t of tokens) {
645
+ const e = byKey.get(t) || byId.get(t)
646
+ if (e && !out.includes(e)) out.push(e)
647
+ }
648
+ return out
649
+ }
650
+
615
651
  export interface RenderCompactOpts {
616
652
  /** Restricted adjacency for numeric edge rendering (graph mode). */
617
653
  adjacency?: Map<string, string[]>
@@ -729,3 +765,33 @@ export function renderCompact(entries: GraphEntry[], opts: RenderCompactOpts = {
729
765
 
730
766
  return rendered.join("\n\n")
731
767
  }
768
+
769
+ export interface RenderIndexOpts {
770
+ /** Final combined score per key. Normalized to the best result and shown as %. */
771
+ scores?: Map<string, number>
772
+ }
773
+
774
+ /**
775
+ * Token-cheapest listing of recall results — the "first layer" of progressive
776
+ * disclosure. One line per entry: index, key, id, category, date, optional
777
+ * relative relevance %. No content. The agent picks ids from here, then does a
778
+ * full fetch with `memory_recall`'s `ids` parameter. Deterministic, no LLM.
779
+ */
780
+ export function renderIndex(entries: GraphEntry[], opts: RenderIndexOpts = {}): string {
781
+ let max = 0
782
+ if (opts.scores) {
783
+ for (const v of opts.scores.values()) if (v > max) max = v
784
+ }
785
+ const lines: string[] = []
786
+ for (let i = 0; i < entries.length; i++) {
787
+ const e = entries[i]
788
+ const pin = e.priority > 0 ? (e.priority > 1 ? ` 📌${e.priority}` : " 📌") : ""
789
+ let score = ""
790
+ if (opts.scores && max > 0) {
791
+ const s = opts.scores.get(e.key)
792
+ if (s !== undefined) score = ` · ${Math.round((s / max) * 100)}%`
793
+ }
794
+ lines.push(`[${i + 1}] ${e.key} (${e.id})${pin} · ${e.category} · ${e.date}${score}`)
795
+ }
796
+ return lines.join("\n")
797
+ }
@@ -6,6 +6,16 @@ import { isExpired } from "./entries"
6
6
  import { entryScoreForLine } from "./scoring"
7
7
  import { parseToonLine } from "../lib/utils"
8
8
 
9
+ /** Match both header conventions: `entries[N|]` (MCP writers) and `[N|]` (CLI init). */
10
+ function findHeaderIdx(lines: string[]): number {
11
+ return lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
12
+ }
13
+
14
+ /** Bump the entry count in a header line, preserving its `entries`/`archived` prefix if present. */
15
+ function bumpHeaderCount(line: string, count: number): string {
16
+ return line.replace(/^([a-z]+)?\[(\d+)\|/, (_m, pre: string) => `${pre || ""}[${count}|`)
17
+ }
18
+
9
19
  /**
10
20
  * Archive entries older than ARCHIVE_DAYS or with expired TTL.
11
21
  * When `trimToMax` is set, also archive the lowest-importance entries
@@ -14,7 +24,7 @@ import { parseToonLine } from "../lib/utils"
14
24
  export function archiveOldEntries(opts: { trimToMax?: boolean } = {}): { archived: number; kept: number } {
15
25
  const data = readMemory()
16
26
  const lines = data.split("\n")
17
- const headerIdx = lines.findIndex((l) => l.startsWith("entries["))
27
+ const headerIdx = findHeaderIdx(lines)
18
28
 
19
29
  if (headerIdx === -1) return { archived: 0, kept: 0 }
20
30
 
@@ -67,18 +77,18 @@ export function archiveOldEntries(opts: { trimToMax?: boolean } = {}): { archive
67
77
  archiveHeaderIdx = archiveLines.length - 1
68
78
  }
69
79
 
70
- const archiveMatch = archiveLines[archiveHeaderIdx].match(/archived\[(\d+)\|/)
80
+ const archiveMatch = archiveLines[archiveHeaderIdx].match(/\[(\d+)\|/)
71
81
  const archiveCount = archiveMatch ? parseInt(archiveMatch[1]) : 0
72
82
 
73
83
  for (const entry of toArchiveLines) {
74
84
  archiveLines.splice(archiveHeaderIdx + 1, 0, ` ${entry}`)
75
85
  }
76
- archiveLines[archiveHeaderIdx] = archiveLines[archiveHeaderIdx].replace(/archived\[\d+\|/, `[${archiveCount + toArchiveLines.length}|`)
86
+ archiveLines[archiveHeaderIdx] = bumpHeaderCount(archiveLines[archiveHeaderIdx], archiveCount + toArchiveLines.length)
77
87
 
78
88
  safeWrite(ARCHIVE_FILE, archiveLines.join("\n"))
79
89
 
80
90
  // Update main file
81
- lines[headerIdx] = lines[headerIdx].replace(/entries\[\d+\|/, `[${toKeepLines.length}|`)
91
+ lines[headerIdx] = bumpHeaderCount(lines[headerIdx], toKeepLines.length)
82
92
  const keepSet = new Set(toKeepLines)
83
93
  const allEntryLines = lines.slice(headerIdx + 1)
84
94
  const newEntryLines = allEntryLines.filter((l) => {
@@ -104,7 +114,7 @@ export function pruneExpiredEntries(): number {
104
114
  withLockSync(MEMORY_FILE, () => {
105
115
  const data = readMemory()
106
116
  const lines = data.split("\n")
107
- const headerIdx = lines.findIndex((l) => l.startsWith("entries["))
117
+ const headerIdx = findHeaderIdx(lines)
108
118
  if (headerIdx === -1) return
109
119
 
110
120
  const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"))
@@ -120,7 +130,7 @@ export function pruneExpiredEntries(): number {
120
130
  })
121
131
  if (pruned === 0) return
122
132
 
123
- lines[headerIdx] = lines[headerIdx].replace(/entries\[\d+\|/, `[${kept.length}|`)
133
+ lines[headerIdx] = bumpHeaderCount(lines[headerIdx], kept.length)
124
134
  const keepSet = new Set(kept.map((l) => l.trim()))
125
135
  const allEntryLines = lines.slice(headerIdx + 1)
126
136
  const newLines = allEntryLines.filter((l) => l.trim().length === 0 || keepSet.has(l.trim()))
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"
@@ -563,12 +563,14 @@ server.registerTool(
563
563
  title: "Search Memory",
564
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.",
565
565
  inputSchema: {
566
- 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)"),
567
567
  category: z.string().optional().default("").describe("Filter by category (empty = all)"),
568
568
  from_date: z.string().optional().default("").describe("Start date filter (YYYY-MM-DD)"),
569
569
  to_date: z.string().optional().default("").describe("End date filter (YYYY-MM-DD)"),
570
- 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."),
571
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."),
572
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."),
573
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'."),
574
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."),
@@ -580,14 +582,61 @@ server.registerTool(
580
582
  },
581
583
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
582
584
  },
583
- 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 }) => {
584
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
+ }
585
619
 
586
- // Delegate to graphRecallDetailed for both flat and graph modes
620
+ // Delegate to graphRecallDetailed for flat / graph / index modes
587
621
  // This avoids duplicating BM25 + ranking logic
588
622
  const sessionFiles = bias === "session" ? getCurrentSessionFiles() : undefined
589
- const resolvedBudget = budgetParam || (compact ? "normal" : "deep")
590
- 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
+
591
640
  if (detail.entries.length === 0) {
592
641
  return { content: [{ type: "text" as const, text: `No results found for "${query}"` }] }
593
642
  }