toon-memory 4.3.5 → 4.4.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.
@@ -86,25 +86,50 @@ export function inferTags(content: string, key: string, vocab?: Record<string, s
86
86
 
87
87
  /**
88
88
  * Parse a relative date string into an absolute YYYY-MM-DD date.
89
- * Supports: "24h", "7d", "30d", or an exact date "2026-07-10".
89
+ * Supports compact ("24h", "7d"), exact dates, and natural language in
90
+ * Spanish/English ("ayer", "la semana pasada", "hace 3 dias", "last 7 days").
90
91
  */
91
92
  export function parseRelativeDate(since: string): string {
92
93
  const trimmed = since.trim()
94
+ const iso = (d: Date) => d.toISOString().split("T")[0]
95
+ const shiftDays = (days: number) => {
96
+ const d = new Date()
97
+ d.setDate(d.getDate() - days)
98
+ return iso(d)
99
+ }
100
+
93
101
  const hourMatch = trimmed.match(/^(\d+)h$/)
94
102
  if (hourMatch) {
95
103
  const d = new Date()
96
104
  d.setHours(d.getHours() - parseInt(hourMatch[1]))
97
- return d.toISOString().split("T")[0]
105
+ return iso(d)
98
106
  }
99
107
  const dayMatch = trimmed.match(/^(\d+)d$/)
100
- if (dayMatch) {
101
- const d = new Date()
102
- d.setDate(d.getDate() - parseInt(dayMatch[1]))
103
- return d.toISOString().split("T")[0]
104
- }
108
+ if (dayMatch) return shiftDays(parseInt(dayMatch[1]))
105
109
  if (/^\d{4}-\d{2}-\d{2}$/.test(trimmed)) return trimmed
106
- const today = new Date().toISOString().split("T")[0]
107
- return today
110
+
111
+ const key = trimmed
112
+ .toLowerCase()
113
+ .normalize("NFD")
114
+ .replace(/[\u0300-\u036f]/g, "")
115
+ .replace(/\s+/g, " ")
116
+ .trim()
117
+
118
+ if (key === "hoy" || key === "today") return iso(new Date())
119
+ if (key === "ayer" || key === "yesterday") return shiftDays(1)
120
+ if (/^(la |el )?semana pasada$/.test(key) || key === "last week") return shiftDays(7)
121
+ if (/^(la |el )?mes pasada?$/.test(key) || key === "last month") return shiftDays(30)
122
+
123
+ const natural = key.match(/^(?:hace|last|ultimos?|past)\s+(\d+)\s*(dia|dias|day|days|semana|semanas|week|weeks|mes|meses|month|months)\b/)
124
+ if (natural) {
125
+ const n = parseInt(natural[1])
126
+ const unit = natural[2]
127
+ if (/^(dia|dias|day|days)$/.test(unit)) return shiftDays(n)
128
+ if (/^(semana|semanas|week|weeks)$/.test(unit)) return shiftDays(n * 7)
129
+ return shiftDays(n * 30)
130
+ }
131
+
132
+ return iso(new Date())
108
133
  }
109
134
 
110
135
  export { normalize } from "../lib/utils"
@@ -0,0 +1,130 @@
1
+ import { existsSync, mkdirSync, readFileSync } from "fs"
2
+ import { dirname } from "path"
3
+ import { randomBytes } from "crypto"
4
+ import { withLockSync, atomicWrite } from "../lib/lock"
5
+ import { parseToonLine, toToonLine } from "../lib/utils"
6
+ import { FEEDBACK_FILE } from "./config"
7
+ import { readMemory, writeMemory } from "./memory-io"
8
+
9
+ export type FeedbackSignal = "useful" | "irrelevant" | "outdated" | "wrong"
10
+ export type FeedbackSource = "explicit" | "implicit"
11
+
12
+ export interface FeedbackEvent {
13
+ id: string
14
+ key: string
15
+ signal: FeedbackSignal
16
+ source: FeedbackSource
17
+ ts: string
18
+ session: string
19
+ task: string
20
+ }
21
+
22
+ const HEADER = "version: 1\nfeedback[0|]{id|key|signal|source|ts|session|task}:"
23
+ const MAX_EVENTS = 1000
24
+ const SIGNAL_WEIGHT: Record<FeedbackSignal, number> = {
25
+ useful: 1,
26
+ irrelevant: -1,
27
+ outdated: -1.5,
28
+ wrong: -2,
29
+ }
30
+
31
+ export function readFeedback(): FeedbackEvent[] {
32
+ if (!existsSync(FEEDBACK_FILE)) return []
33
+ let data = ""
34
+ try {
35
+ data = readFileSync(FEEDBACK_FILE, "utf-8")
36
+ } catch {
37
+ return []
38
+ }
39
+ const lines = data.split("\n")
40
+ const headerIdx = lines.findIndex((l) => l.startsWith("feedback[") || /^\[\d+\|]/.test(l))
41
+ if (headerIdx === -1) return []
42
+ const out: FeedbackEvent[] = []
43
+ for (const line of lines.slice(headerIdx + 1)) {
44
+ if (!line.startsWith(" ") || !line.includes("|")) continue
45
+ const p = parseToonLine(line.trim())
46
+ if (p.length < 5) continue
47
+ const signal = p[2] as FeedbackSignal
48
+ if (!(signal in SIGNAL_WEIGHT)) continue
49
+ out.push({
50
+ id: p[0],
51
+ key: p[1],
52
+ signal,
53
+ source: p[3] === "implicit" ? "implicit" : "explicit",
54
+ ts: p[4],
55
+ session: p[5] || "",
56
+ task: p[6] || "",
57
+ })
58
+ }
59
+ return out
60
+ }
61
+
62
+ export function appendFeedback(
63
+ event: Omit<FeedbackEvent, "id" | "ts" | "session"> & { session?: string; id?: string; ts?: string }
64
+ ): FeedbackEvent {
65
+ const full: FeedbackEvent = {
66
+ id: event.id || `fb-${randomBytes(4).toString("hex")}`,
67
+ key: event.key,
68
+ signal: event.signal,
69
+ source: event.source,
70
+ ts: event.ts || new Date().toISOString(),
71
+ session: event.session || "",
72
+ task: event.task || "",
73
+ }
74
+ const dir = dirname(FEEDBACK_FILE)
75
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
76
+ withLockSync(FEEDBACK_FILE, () => {
77
+ const data = existsSync(FEEDBACK_FILE) ? readFileSync(FEEDBACK_FILE, "utf-8") : HEADER
78
+ const lines = data.split("\n")
79
+ let headerIdx = lines.findIndex((l) => l.startsWith("feedback[") || /^\[\d+\|]/.test(l))
80
+ if (headerIdx === -1) {
81
+ lines.unshift(HEADER.split("\n")[1])
82
+ headerIdx = 0
83
+ }
84
+ const rows = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && l.startsWith(" "))
85
+ const row = toToonLine([
86
+ full.id, full.key, full.signal, full.source, full.ts,
87
+ full.session, full.task.slice(0, 2000),
88
+ ])
89
+ const kept = [row, ...rows].slice(0, MAX_EVENTS)
90
+ const countMatch = lines[headerIdx].match(/\[(\d+)\|/)
91
+ const count = countMatch ? parseInt(countMatch[1], 10) : 0
92
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`)
93
+ lines.splice(headerIdx + 1, lines.length - headerIdx - 1, ...kept)
94
+ atomicWrite(FEEDBACK_FILE, lines.join("\n"))
95
+ })
96
+ return full
97
+ }
98
+
99
+ export function utilityMap(today?: string): Map<string, number> {
100
+ const ref = today || new Date().toISOString().split("T")[0]
101
+ const refTime = Date.parse(`${ref}T00:00:00Z`)
102
+ const out = new Map<string, number>()
103
+ for (const e of readFeedback()) {
104
+ const days = Number.isNaN(refTime) ? 0 : Math.max(0, (refTime - Date.parse(e.ts)) / 86400000)
105
+ const decay = Math.pow(0.9, days)
106
+ const delta = SIGNAL_WEIGHT[e.signal] * decay
107
+ out.set(e.key, Math.max(-3, Math.min(3, Number(((out.get(e.key) || 0) + delta).toFixed(3)))))
108
+ }
109
+ return out
110
+ }
111
+
112
+ export function markWrong(key: string): boolean {
113
+ const data = readMemory()
114
+ const lines = data.split("\n")
115
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
116
+ if (headerIdx === -1) return false
117
+ for (let i = headerIdx + 1; i < lines.length; i++) {
118
+ const line = lines[i]
119
+ if (!line.startsWith(" ") || !line.includes("|")) continue
120
+ if (line.startsWith(" summaries:")) break
121
+ const parts = parseToonLine(line)
122
+ if (parts[0] !== key && parts[2] !== key) continue
123
+ while (parts.length < 20) parts.push("")
124
+ parts[19] = "conflict"
125
+ lines[i] = toToonLine(parts)
126
+ writeMemory(lines.join("\n"))
127
+ return true
128
+ }
129
+ return false
130
+ }
@@ -60,18 +60,21 @@ export function registerResources(server: McpServer): void {
60
60
  }
61
61
  )
62
62
 
63
- // MCP Apps: interactive graph viewer rendered inline in MCP hosts
64
- const viewerResource = createUIResource({
65
- uri: "ui://viewer",
66
- content: { type: "rawHtml", htmlString: generateHtml(buildViewerData()) },
67
- encoding: "text",
68
- adapters: { mcpApps: { enabled: true } },
69
- })
63
+ // MCP Apps: interactive graph viewer rendered inline in MCP hosts.
64
+ // Built lazily: a bad viewer build must never kill MCP startup.
70
65
  registerAppResource(
71
66
  server as unknown as Parameters<typeof registerAppResource>[0],
72
67
  "Memory Graph Viewer",
73
- viewerResource.resource.uri,
68
+ "ui://viewer",
74
69
  { description: "Interactive memory graph viewer (D3.js force-directed graph with stats, timeline, detail panel)" },
75
- async () => ({ contents: [viewerResource.resource] }),
70
+ async (uri) => {
71
+ const viewerResource = createUIResource({
72
+ uri: "ui://viewer",
73
+ content: { type: "rawHtml", htmlString: generateHtml(buildViewerData()) },
74
+ encoding: "text",
75
+ adapters: { mcpApps: { enabled: true } },
76
+ })
77
+ return { contents: [{ ...viewerResource.resource, uri: uri.href }] }
78
+ },
76
79
  )
77
80
  }
package/src/mcp/server.ts CHANGED
@@ -3,13 +3,24 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
3
3
  import { InitializeRequestSchema, SUPPORTED_PROTOCOL_VERSIONS, LATEST_PROTOCOL_VERSION } from "@modelcontextprotocol/sdk/types.js"
4
4
  import { registerTools } from "./tools"
5
5
  import { registerResources } from "./resources"
6
+ import { registerPrompts } from "./prompts"
6
7
  import { pruneExpiredEntries } from "./archive"
7
8
 
8
9
  declare const TOON_VERSION: string
9
10
 
11
+ const INSTRUCTIONS = [
12
+ "toon-memory: at task start call context_compile(task=...) and hydrate only the keys you need.",
13
+ "Before reading files, call memory_recall(query=<path or concept>).",
14
+ "When recalled memory was useful or wrong, call memory_feedback(key=..., signal=...).",
15
+ "Save decisions, directives and resolved bugs with memory_remember.",
16
+ ].join(" ")
17
+
10
18
  const server = new McpServer(
11
19
  { name: "toon-memory", version: TOON_VERSION },
12
- { capabilities: { tools: { listChanged: true }, resources: { listChanged: true }, experimental: { "io.modelcontextprotocol/ui": {} } } }
20
+ {
21
+ instructions: INSTRUCTIONS,
22
+ capabilities: { tools: { listChanged: true }, resources: { listChanged: true }, experimental: { "io.modelcontextprotocol/ui": {} } },
23
+ }
13
24
  )
14
25
 
15
26
  // MCP Apps support is advertised via capabilities.experimental.
@@ -32,6 +43,7 @@ s.setRequestHandler(InitializeRequestSchema, async (request: any) => {
32
43
 
33
44
  registerResources(server)
34
45
  registerTools(server)
46
+ registerPrompts(server)
35
47
 
36
48
  // Startup TTL prune: drop entries whose TTL has elapsed. Best-effort — never
37
49
  // block server startup on a prune failure.