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/README.de.md +245 -22
- package/README.es.md +185 -14
- package/README.fr.md +237 -15
- package/README.ja.md +239 -18
- package/README.ko.md +244 -21
- package/README.md +53 -9
- package/README.pt-br.md +243 -22
- package/README.zh.md +238 -16
- package/bin/toon-memory.js +18 -7
- package/dist/cli/setup.js +106 -50
- package/dist/cli/toon-memory.js +12 -3
- package/install.ps1 +25 -15
- package/mcp/server.js +136 -18
- package/package.json +3 -3
- package/src/bin/toon-memory.ts +3 -2
- package/src/cli/config-writer.ts +34 -23
- package/src/cli/entry.ts +11 -0
- package/src/cli/hooks.ts +33 -11
- package/src/cli/opencode-plugin.ts +57 -18
- package/src/cli/toon-memory.ts +4 -3
- package/src/lib/graph.ts +79 -3
- package/src/lib/quality.ts +14 -4
- package/src/lib/utils.ts +24 -0
- package/src/mcp/tools.ts +60 -10
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "toon-memory",
|
|
3
3
|
"mcpName": "io.github.LuiggiVal08/toon-memory",
|
|
4
|
-
"version": "4.
|
|
5
|
-
"description": "
|
|
4
|
+
"version": "4.3.1",
|
|
5
|
+
"description": "The Continuity Layer for AI Agents — an MCP memory server that preserves project knowledge, decisions, and conventions across sessions so every session starts where the last one ended. Offline, token-efficient, no LLM, no server; works with 15+ agents.",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"bin": {
|
|
8
8
|
"toon-memory": "./bin/toon-memory.js"
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
],
|
|
20
20
|
"scripts": {
|
|
21
21
|
"build": "npm run build:bin && npm run build:mcp && npm run build:cli",
|
|
22
|
-
"build:bin": "esbuild src/bin/toon-memory.ts --platform=node --format=esm --outfile=bin/toon-memory.js",
|
|
22
|
+
"build:bin": "esbuild src/bin/toon-memory.ts --bundle --platform=node --format=esm --outfile=bin/toon-memory.js",
|
|
23
23
|
"build:mcp": "node -e \"const{version}=require('./package.json');const esbuild=require('esbuild');esbuild.build({entryPoints:['src/mcp/server.ts'],bundle:true,platform:'node',format:'esm',outfile:'mcp/server.js',define:{TOON_VERSION:JSON.stringify(version)}})\"",
|
|
24
24
|
"build:cli": "esbuild src/cli/setup.ts --bundle --platform=node --format=esm --packages=external --outfile=dist/cli/setup.js && esbuild src/cli/toon-memory.ts --bundle --platform=node --format=esm --outfile=dist/cli/toon-memory.js && esbuild src/cli/capture.ts --bundle --platform=node --format=esm --outfile=dist/cli/capture.js && esbuild src/cli/session-start.ts --bundle --platform=node --format=esm --outfile=dist/cli/session-start.js",
|
|
25
25
|
"test": "vitest run",
|
package/src/bin/toon-memory.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import { dirname, join } from "path"
|
|
3
3
|
import { readFileSync } from "fs"
|
|
4
4
|
import { fileURLToPath } from "url"
|
|
5
|
+
import { fileImportURL } from "../cli/entry"
|
|
5
6
|
|
|
6
7
|
const __dirname = dirname(fileURLToPath(import.meta.url))
|
|
7
8
|
const args = process.argv.slice(2)
|
|
@@ -55,8 +56,8 @@ if (args[0] === "-h" || args[0] === "--help") {
|
|
|
55
56
|
}
|
|
56
57
|
|
|
57
58
|
if (args[0] === "mcp") {
|
|
58
|
-
await import(
|
|
59
|
+
await import(fileImportURL(__dirname, "..", "mcp", "server.js"))
|
|
59
60
|
} else {
|
|
60
61
|
process.argv = ["node", "toon-memory", ...args]
|
|
61
|
-
await import(
|
|
62
|
+
await import(fileImportURL(__dirname, "..", "dist", "cli", "setup.js"))
|
|
62
63
|
}
|
package/src/cli/config-writer.ts
CHANGED
|
@@ -3,6 +3,21 @@ import { dirname } from "path"
|
|
|
3
3
|
import type { Agent } from "./types"
|
|
4
4
|
import { MEMORY_DIR, CAPTURE_CONFIG } from "./constants"
|
|
5
5
|
|
|
6
|
+
/**
|
|
7
|
+
* Read an existing JSON config file.
|
|
8
|
+
* Returns {} when the file is missing, or null when it exists but cannot be
|
|
9
|
+
* parsed — callers MUST skip (never overwrite) on null to avoid wiping the
|
|
10
|
+
* user's other settings.
|
|
11
|
+
*/
|
|
12
|
+
function loadJSON(file: string): Record<string, any> | null {
|
|
13
|
+
if (!existsSync(file)) return {}
|
|
14
|
+
try {
|
|
15
|
+
return JSON.parse(readFileSync(file, "utf-8"))
|
|
16
|
+
} catch {
|
|
17
|
+
return null
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
6
21
|
/**
|
|
7
22
|
* Install MCP server configuration for a JSON-format agent.
|
|
8
23
|
*/
|
|
@@ -17,13 +32,10 @@ export function installJSONConfig(agent: Agent, scope: string): void {
|
|
|
17
32
|
const configDir = dirname(configPath)
|
|
18
33
|
if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
|
|
19
34
|
|
|
20
|
-
|
|
21
|
-
if (
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
} catch {
|
|
25
|
-
config = {}
|
|
26
|
-
}
|
|
35
|
+
const config = loadJSON(configPath)
|
|
36
|
+
if (config === null) {
|
|
37
|
+
console.log(` ⚠️ Skipping ${configPath}: existing file is not valid JSON — fix it manually, then re-run.`)
|
|
38
|
+
return
|
|
27
39
|
}
|
|
28
40
|
|
|
29
41
|
const mcpKey = agent.mcpKey || "mcpServers"
|
|
@@ -80,17 +92,22 @@ export function installZedConfig(agent: Agent): void {
|
|
|
80
92
|
const configDir = dirname(configPath)
|
|
81
93
|
if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
|
|
82
94
|
|
|
83
|
-
let config: Record<string, any> = {}
|
|
95
|
+
let config: Record<string, any> | null = {}
|
|
84
96
|
if (existsSync(configPath)) {
|
|
85
97
|
try {
|
|
86
98
|
const raw = readFileSync(configPath, "utf-8")
|
|
87
99
|
const stripped = raw.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "")
|
|
88
100
|
config = JSON.parse(stripped)
|
|
89
101
|
} catch {
|
|
90
|
-
config =
|
|
102
|
+
config = null
|
|
91
103
|
}
|
|
92
104
|
}
|
|
93
105
|
|
|
106
|
+
if (config === null) {
|
|
107
|
+
console.log(` ⚠️ Skipping ${configPath}: existing file is not valid JSON — fix it manually, then re-run.`)
|
|
108
|
+
return
|
|
109
|
+
}
|
|
110
|
+
|
|
94
111
|
if (!config.context_servers) config.context_servers = {}
|
|
95
112
|
|
|
96
113
|
config.context_servers["toon-memory"] = {
|
|
@@ -114,13 +131,10 @@ export function installContinueConfig(agent: Agent): void {
|
|
|
114
131
|
const configDir = dirname(configPath)
|
|
115
132
|
if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
|
|
116
133
|
|
|
117
|
-
|
|
118
|
-
if (
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
} catch {
|
|
122
|
-
config = {}
|
|
123
|
-
}
|
|
134
|
+
const config = loadJSON(configPath)
|
|
135
|
+
if (config === null) {
|
|
136
|
+
console.log(` ⚠️ Skipping ${configPath}: existing file is not valid JSON — fix it manually, then re-run.`)
|
|
137
|
+
return
|
|
124
138
|
}
|
|
125
139
|
|
|
126
140
|
if (!config.experimental) config.experimental = {}
|
|
@@ -158,13 +172,10 @@ export function installOpenClawConfig(agent: Agent): void {
|
|
|
158
172
|
const configDir = dirname(configPath)
|
|
159
173
|
if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
|
|
160
174
|
|
|
161
|
-
|
|
162
|
-
if (
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
} catch {
|
|
166
|
-
config = {}
|
|
167
|
-
}
|
|
175
|
+
const config = loadJSON(configPath)
|
|
176
|
+
if (config === null) {
|
|
177
|
+
console.log(` ⚠️ Skipping ${configPath}: existing file is not valid JSON — fix it manually, then re-run.`)
|
|
178
|
+
return
|
|
168
179
|
}
|
|
169
180
|
|
|
170
181
|
if (!config.mcp) config.mcp = {}
|
package/src/cli/entry.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { join } from "path"
|
|
2
|
+
import { pathToFileURL } from "url"
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Build a file:// URL for a dynamic import relative to the running module.
|
|
6
|
+
* pathToFileURL is required on Windows: `import("C:\\...")` is parsed as a
|
|
7
|
+
* URL with scheme "c:" and throws ERR_UNSUPPORTED_ESM_URL_SCHEME.
|
|
8
|
+
*/
|
|
9
|
+
export function fileImportURL(dirname: string, ...parts: string[]): string {
|
|
10
|
+
return pathToFileURL(join(dirname, ...parts)).href
|
|
11
|
+
}
|
package/src/cli/hooks.ts
CHANGED
|
@@ -3,6 +3,21 @@ import { dirname, join } from "path"
|
|
|
3
3
|
import type { Agent } from "./types"
|
|
4
4
|
import { projectRoot, CAPTURE_JS, SESSION_START_JS, CAPTURE_CONFIG, ANTIGRAVITY_HOOK_NAME } from "./constants"
|
|
5
5
|
|
|
6
|
+
/**
|
|
7
|
+
* Read an existing JSON config file.
|
|
8
|
+
* Returns {} when the file is missing, or null when it exists but cannot be
|
|
9
|
+
* parsed — callers MUST skip (never overwrite) on null to avoid wiping the
|
|
10
|
+
* user's other settings.
|
|
11
|
+
*/
|
|
12
|
+
function readJSON(file: string): Record<string, any> | null {
|
|
13
|
+
if (!existsSync(file)) return {}
|
|
14
|
+
try {
|
|
15
|
+
return JSON.parse(readFileSync(file, "utf-8"))
|
|
16
|
+
} catch {
|
|
17
|
+
return null
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
6
21
|
/** Hook script content for SessionStart reminder */
|
|
7
22
|
export function sessionStartHookContent(agentName: string): string {
|
|
8
23
|
return `#!/bin/bash
|
|
@@ -76,13 +91,10 @@ export function registerCaptureHookJSON(agent: Agent, scriptPath: string): void
|
|
|
76
91
|
const configDir = dirname(configPath)
|
|
77
92
|
if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
|
|
78
93
|
|
|
79
|
-
|
|
80
|
-
if (
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
} catch {
|
|
84
|
-
config = {}
|
|
85
|
-
}
|
|
94
|
+
const config = readJSON(configPath)
|
|
95
|
+
if (config === null) {
|
|
96
|
+
console.log(` ⚠️ Skipping ${configPath}: existing file is not valid JSON — fix it manually, then re-run.`)
|
|
97
|
+
return
|
|
86
98
|
}
|
|
87
99
|
|
|
88
100
|
if (!config.hooks) config.hooks = {}
|
|
@@ -136,7 +148,7 @@ export function registerHookJSON(agent: Agent, hookPath: string): void {
|
|
|
136
148
|
const configDir = dirname(configPath)
|
|
137
149
|
if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
|
|
138
150
|
|
|
139
|
-
let config: Record<string, any> = {}
|
|
151
|
+
let config: Record<string, any> | null = {}
|
|
140
152
|
if (existsSync(configPath)) {
|
|
141
153
|
try {
|
|
142
154
|
if (agent.format === "jsonc") {
|
|
@@ -147,10 +159,15 @@ export function registerHookJSON(agent: Agent, hookPath: string): void {
|
|
|
147
159
|
config = JSON.parse(readFileSync(configPath, "utf-8"))
|
|
148
160
|
}
|
|
149
161
|
} catch {
|
|
150
|
-
config =
|
|
162
|
+
config = null
|
|
151
163
|
}
|
|
152
164
|
}
|
|
153
165
|
|
|
166
|
+
if (config === null) {
|
|
167
|
+
console.log(` ⚠️ Skipping ${configPath}: existing file is not valid JSON — fix it manually, then re-run.`)
|
|
168
|
+
return
|
|
169
|
+
}
|
|
170
|
+
|
|
154
171
|
if (agent.name === "claude" || agent.name === "gemini") {
|
|
155
172
|
if (!config.hooks) config.hooks = {}
|
|
156
173
|
if (!config.hooks.SessionStart) config.hooks.SessionStart = []
|
|
@@ -186,15 +203,20 @@ export function registerAntigravityHooks(agent: Agent): void {
|
|
|
186
203
|
const hooksFile = join(base, "hooks.json")
|
|
187
204
|
mkdirSync(base, { recursive: true })
|
|
188
205
|
|
|
189
|
-
let cfg: Record<string, any> = {}
|
|
206
|
+
let cfg: Record<string, any> | null = {}
|
|
190
207
|
if (existsSync(hooksFile)) {
|
|
191
208
|
try {
|
|
192
209
|
cfg = JSON.parse(readFileSync(hooksFile, "utf-8"))
|
|
193
210
|
} catch {
|
|
194
|
-
cfg =
|
|
211
|
+
cfg = null
|
|
195
212
|
}
|
|
196
213
|
}
|
|
197
214
|
|
|
215
|
+
if (cfg === null) {
|
|
216
|
+
console.log(` ⚠️ Skipping ${hooksFile}: existing file is not valid JSON — fix it manually, then re-run.`)
|
|
217
|
+
return
|
|
218
|
+
}
|
|
219
|
+
|
|
198
220
|
cfg[ANTIGRAVITY_HOOK_NAME] = {
|
|
199
221
|
PreInvocation: [{ type: "command", command: sessionPath }],
|
|
200
222
|
PostToolUse: [{ matcher: "*", hooks: [{ type: "command", command: capPath }] }],
|
|
@@ -29,6 +29,7 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
|
29
29
|
const recall = async (query, opts = {}) => {
|
|
30
30
|
try {
|
|
31
31
|
const args = { query, mode: "flat", budget: opts.budget || "tiny", path_scope: opts.path_scope || "" }
|
|
32
|
+
if (opts.category) args.category = opts.category
|
|
32
33
|
const result = await $\`npx -y toon-memory mcp\`.cwd(root)
|
|
33
34
|
.stdin(JSON.stringify({
|
|
34
35
|
jsonrpc: "2.0",
|
|
@@ -42,11 +43,44 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
|
42
43
|
} catch { return "" }
|
|
43
44
|
}
|
|
44
45
|
|
|
46
|
+
// Pre-edit risk surfacing: warning-category entries scoped to a file path.
|
|
47
|
+
// Injected as a distinct block so the agent sees known risks before it edits.
|
|
48
|
+
const risks = async (filePath) => {
|
|
49
|
+
return await recall(filePath, { budget: "tiny", path_scope: filePath, category: "warning" })
|
|
50
|
+
}
|
|
51
|
+
|
|
45
52
|
const write = (text) => {
|
|
46
53
|
fs.mkdirSync(INS, { recursive: true })
|
|
47
54
|
fs.writeFileSync(OUT, text)
|
|
48
55
|
}
|
|
49
56
|
|
|
57
|
+
const pickPath = (args) => {
|
|
58
|
+
if (!args) return ""
|
|
59
|
+
if (args.file) return args.file
|
|
60
|
+
if (args.path) return args.path
|
|
61
|
+
if (args.filePath) return args.filePath
|
|
62
|
+
if (args.target) return args.target
|
|
63
|
+
return ""
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const buildQuery = (filePath) => {
|
|
67
|
+
const basename = path.basename(filePath, path.extname(filePath))
|
|
68
|
+
const dirParts = path.dirname(filePath).split(path.sep).filter(Boolean)
|
|
69
|
+
return [basename, ...dirParts.slice(-2)].join(" ")
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const inject = (ctx, key, text) => {
|
|
73
|
+
if (!text || text.includes("(empty)") || text.includes("No results")) return
|
|
74
|
+
if (typeof ctx?.setContext === "function") ctx.setContext(key, text)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Edit/write-ish tools are where known risks matter most.
|
|
78
|
+
const isEditTool = (name) => {
|
|
79
|
+
if (!name) return false
|
|
80
|
+
return name === "edit" || name === "write" || name === "apply-patch" ||
|
|
81
|
+
name.includes("edit") || name.includes("write") || name.includes("patch")
|
|
82
|
+
}
|
|
83
|
+
|
|
50
84
|
return {
|
|
51
85
|
"session.created": async () => {
|
|
52
86
|
try {
|
|
@@ -60,6 +94,19 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
|
60
94
|
if (Array.isArray(output?.context)) output.context.push(out)
|
|
61
95
|
} catch {}
|
|
62
96
|
},
|
|
97
|
+
"tool.execute.before": async (input, output) => {
|
|
98
|
+
// Pre-edit risk surfacing: for edit/write tools, surface known
|
|
99
|
+
// warning entries for the target file BEFORE the tool runs.
|
|
100
|
+
try {
|
|
101
|
+
const toolName = input?.tool || ""
|
|
102
|
+
if (!isEditTool(toolName)) return
|
|
103
|
+
const args = output?.args || input?.args || {}
|
|
104
|
+
const filePath = pickPath(args)
|
|
105
|
+
if (!filePath) return
|
|
106
|
+
const text = await risks(filePath)
|
|
107
|
+
inject(input, "toon-memory:risks:" + filePath, "⚠ KNOWN RISKS for " + filePath + ":\\n" + text)
|
|
108
|
+
} catch {}
|
|
109
|
+
},
|
|
63
110
|
"tool.execute.after": async (input) => {
|
|
64
111
|
// Intelligent auto-loading: extract file path from tool result,
|
|
65
112
|
// recall only memory relevant to that file, inject as context.
|
|
@@ -69,11 +116,7 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
|
69
116
|
const args = input?.args || {}
|
|
70
117
|
|
|
71
118
|
// Extract file path from tool arguments or output
|
|
72
|
-
let filePath =
|
|
73
|
-
if (args.file) filePath = args.file
|
|
74
|
-
else if (args.path) filePath = args.path
|
|
75
|
-
else if (args.filePath) filePath = args.filePath
|
|
76
|
-
else if (args.target) filePath = args.target
|
|
119
|
+
let filePath = pickPath(args)
|
|
77
120
|
|
|
78
121
|
// Also try to extract from tool output text
|
|
79
122
|
if (!filePath && input?.output) {
|
|
@@ -84,15 +127,15 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
|
84
127
|
|
|
85
128
|
if (filePath) {
|
|
86
129
|
// Build recall query from file path components
|
|
87
|
-
const
|
|
88
|
-
const dirParts = path.dirname(filePath).split(path.sep).filter(Boolean)
|
|
89
|
-
const query = [basename, ...dirParts.slice(-2)].join(" ")
|
|
90
|
-
|
|
130
|
+
const query = buildQuery(filePath)
|
|
91
131
|
const text = await recall(query, { budget: "tiny", path_scope: filePath })
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
132
|
+
inject(input, "toon-memory:" + filePath, text)
|
|
133
|
+
|
|
134
|
+
// Pre-edit risk block for edit/write tools (same key as the before
|
|
135
|
+
// hook — setContext overwrites, so no duplication when both fire).
|
|
136
|
+
if (isEditTool(toolName)) {
|
|
137
|
+
const riskText = await risks(filePath)
|
|
138
|
+
inject(input, "toon-memory:risks:" + filePath, "⚠ KNOWN RISKS for " + filePath + ":\\n" + riskText)
|
|
96
139
|
}
|
|
97
140
|
}
|
|
98
141
|
|
|
@@ -110,11 +153,7 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
|
110
153
|
|
|
111
154
|
if (toolKeywords.length > 3) {
|
|
112
155
|
const text = await recall(toolKeywords, { budget: "tiny" })
|
|
113
|
-
|
|
114
|
-
if (typeof input?.setContext === "function") {
|
|
115
|
-
input.setContext("toon-memory:" + toolName, text)
|
|
116
|
-
}
|
|
117
|
-
}
|
|
156
|
+
inject(input, "toon-memory:" + toolName, text)
|
|
118
157
|
}
|
|
119
158
|
}
|
|
120
159
|
} catch {}
|
package/src/cli/toon-memory.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
import { dirname
|
|
1
|
+
import { dirname } from "path"
|
|
2
2
|
import { fileURLToPath } from "url"
|
|
3
|
+
import { fileImportURL } from "./entry"
|
|
3
4
|
|
|
4
5
|
const __dirname = dirname(fileURLToPath(import.meta.url))
|
|
5
6
|
const args = process.argv.slice(2)
|
|
6
7
|
|
|
7
8
|
if (args[0] === "mcp") {
|
|
8
|
-
await import(
|
|
9
|
+
await import(fileImportURL(__dirname, "..", "mcp", "server.js"))
|
|
9
10
|
} else {
|
|
10
11
|
process.argv = ["node", "toon-memory", ...args]
|
|
11
|
-
await import(
|
|
12
|
+
await import(fileImportURL(__dirname, "..", "dist", "cli", "setup.js"))
|
|
12
13
|
}
|
package/src/lib/graph.ts
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* without mutating the stored `.toon` file.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
import { normalize, isExpiredLocal, tokenize, importance, estimateTokens, parseToonLine } from "./utils"
|
|
17
|
+
import { normalize, isExpiredLocal, tokenize, importance, importanceBoost, importanceRank, estimateTokens, parseToonLine } from "./utils"
|
|
18
18
|
import { expandSynonyms } from "./synonyms"
|
|
19
19
|
import { fuzzyMatch } from "./fuzzy"
|
|
20
20
|
|
|
@@ -42,6 +42,8 @@ export interface GraphEntry {
|
|
|
42
42
|
status: "active" | "obsolete" | "resolved" | "draft"
|
|
43
43
|
/** ISO date when this entry was superseded (set by memory_forget action=supersede). Empty if never superseded. */
|
|
44
44
|
supersededOn: string
|
|
45
|
+
/** Explicit importance level: "critical" | "high" | "medium" | "low". Empty = auto (recency+frequency). */
|
|
46
|
+
importance: string
|
|
45
47
|
}
|
|
46
48
|
|
|
47
49
|
/** Edge type labels used in typed links (`type:key`). */
|
|
@@ -128,6 +130,7 @@ export function parseEntries(data: string): GraphEntry[] {
|
|
|
128
130
|
origin: parts.length > 15 && parts[15] ? parts[15] as "human" | "agent" | "inferred" : "agent",
|
|
129
131
|
status: parts.length > 16 && parts[16] ? parts[16] as "active" | "obsolete" | "resolved" | "draft" : "active",
|
|
130
132
|
supersededOn: parts.length > 17 ? parts[17] || "" : "",
|
|
133
|
+
importance: parts.length > 18 ? parts[18] || "" : "",
|
|
131
134
|
})
|
|
132
135
|
}
|
|
133
136
|
return out
|
|
@@ -419,6 +422,7 @@ export function buildReason(
|
|
|
419
422
|
parts.push("never used")
|
|
420
423
|
}
|
|
421
424
|
parts.push(impScore >= 0.7 ? "importance HIGH" : impScore >= 0.4 ? "importance MED" : "importance LOW")
|
|
425
|
+
if (e.importance) parts.push(`explicit ${e.importance}`)
|
|
422
426
|
return parts.join(" · ")
|
|
423
427
|
}
|
|
424
428
|
|
|
@@ -490,10 +494,13 @@ export function graphRecallDetailed(
|
|
|
490
494
|
...visibleEntries
|
|
491
495
|
.sort((a, b) => {
|
|
492
496
|
if (a.priority !== b.priority) return b.priority - a.priority
|
|
497
|
+
const ia = importanceRank(a.importance)
|
|
498
|
+
const ib = importanceRank(b.importance)
|
|
499
|
+
if (ia !== ib) return ib - ia
|
|
493
500
|
return importance(b, opts.today) - importance(a, opts.today)
|
|
494
501
|
})
|
|
495
502
|
.slice(0, opts.limit ?? 6)
|
|
496
|
-
.map((e) => ({ e, s: importance(e, opts.today) }))
|
|
503
|
+
.map((e) => ({ e, s: importance(e, opts.today) + importanceBoost(e.importance) }))
|
|
497
504
|
)
|
|
498
505
|
} else {
|
|
499
506
|
// BFS from all seeds, recording the shortest hop distance to each node.
|
|
@@ -541,6 +548,8 @@ export function graphRecallDetailed(
|
|
|
541
548
|
}
|
|
542
549
|
// Negative-memory boost: warnings surface first.
|
|
543
550
|
if (e.category === "warning") s += 0.2
|
|
551
|
+
// Explicit importance boost: critical/high entries surface first, low last.
|
|
552
|
+
s += importanceBoost(e.importance)
|
|
544
553
|
s *= decay
|
|
545
554
|
return { e, s, priority: e.priority }
|
|
546
555
|
})
|
|
@@ -603,6 +612,42 @@ export function graphRecall(
|
|
|
603
612
|
return graphRecallDetailed(data, query, opts).entries
|
|
604
613
|
}
|
|
605
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
|
+
|
|
606
651
|
export interface RenderCompactOpts {
|
|
607
652
|
/** Restricted adjacency for numeric edge rendering (graph mode). */
|
|
608
653
|
adjacency?: Map<string, string[]>
|
|
@@ -685,7 +730,8 @@ export function renderCompact(entries: GraphEntry[], opts: RenderCompactOpts = {
|
|
|
685
730
|
const scopeInfo = e.path_scope ? ` · scope: ${e.path_scope}` : ""
|
|
686
731
|
const statusInfo = e.status !== "active" ? ` · status: ${e.status}` : ""
|
|
687
732
|
const supersededInfo = e.supersededOn ? ` · superseded: ${e.supersededOn}` : ""
|
|
688
|
-
|
|
733
|
+
const impInfo = e.importance ? ` · importance: ${e.importance}` : ""
|
|
734
|
+
block = `[${n}] ${e.category}/${e.key}${pin} (${e.id})\n ${e.content}\n File: ${e.file} | Tags: ${e.tags.join(";")} | Date: ${e.date}${ttlInfo}${accessInfo}${lastAccess}${originInfo}${scopeInfo}${statusInfo}${supersededInfo}${impInfo}${links}`
|
|
689
735
|
} else {
|
|
690
736
|
// "normal" budget (default)
|
|
691
737
|
let body = e.content
|
|
@@ -719,3 +765,33 @@ export function renderCompact(entries: GraphEntry[], opts: RenderCompactOpts = {
|
|
|
719
765
|
|
|
720
766
|
return rendered.join("\n\n")
|
|
721
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
|
+
}
|
package/src/lib/quality.ts
CHANGED
|
@@ -20,7 +20,7 @@ import {
|
|
|
20
20
|
buildReason,
|
|
21
21
|
type GraphEntry,
|
|
22
22
|
} from "./graph"
|
|
23
|
-
import { normalize, isExpiredLocal, tokenize, importance, isPrivate, estimateTokens, languageFamily, parseToonLine, toToonLine } from "./utils"
|
|
23
|
+
import { normalize, isExpiredLocal, tokenize, importance, importanceBoost, importanceRank, isPrivate, estimateTokens, languageFamily, parseToonLine, toToonLine } from "./utils"
|
|
24
24
|
import { expandSynonyms } from "./synonyms"
|
|
25
25
|
import { fuzzyMatch } from "./fuzzy"
|
|
26
26
|
|
|
@@ -180,7 +180,12 @@ export function mergeEntries(existingLine: string, newLine: string): string {
|
|
|
180
180
|
// Preserve superseded_on (field 17) from the existing entry.
|
|
181
181
|
const existingSupersededOn = ep.length > 17 ? ep[17] || "" : ""
|
|
182
182
|
|
|
183
|
-
|
|
183
|
+
// Take the more important explicit level (field 18). Empty (auto) counts as medium.
|
|
184
|
+
const existingImportance = ep.length > 18 ? ep[18] || "" : ""
|
|
185
|
+
const newImportance = np.length > 18 ? np[18] || "" : ""
|
|
186
|
+
const importance = importanceRank(newImportance) >= importanceRank(existingImportance) ? newImportance : existingImportance
|
|
187
|
+
|
|
188
|
+
return toToonLine([id, category, key, content, file, mergedTags, date, ttl, String(accessed), mergedLinks, quality.toFixed(2), String(confidence), lastAccessed, String(priority), path_scope, origin, status, existingSupersededOn, importance])
|
|
184
189
|
}
|
|
185
190
|
|
|
186
191
|
/**
|
|
@@ -272,12 +277,14 @@ export function generateSmartRecall(
|
|
|
272
277
|
if (e.path_scope && globMatch(e.path_scope, ".")) folderBoost = 0.05
|
|
273
278
|
// Negative-memory boost: warnings are cheap to ignore and expensive to repeat.
|
|
274
279
|
const warningBoost = e.category === "warning" ? 0.2 : 0
|
|
280
|
+
// Explicit importance boost: critical/high entries surface first, low last.
|
|
281
|
+
const impBoost = importanceBoost(e.importance)
|
|
275
282
|
let combined: number
|
|
276
283
|
if (opts.rrf) {
|
|
277
|
-
combined = (fused?.get(e.key) ?? 0) - drift + sessionBias + langBoost + folderBoost + warningBoost
|
|
284
|
+
combined = (fused?.get(e.key) ?? 0) - drift + sessionBias + langBoost + folderBoost + warningBoost + impBoost
|
|
278
285
|
} else {
|
|
279
286
|
combined =
|
|
280
|
-
bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift + sessionBias + langBoost + folderBoost + warningBoost
|
|
287
|
+
bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift + sessionBias + langBoost + folderBoost + warningBoost + impBoost
|
|
281
288
|
}
|
|
282
289
|
return { entry: e, score: combined, matchesQuery, priority: e.priority, bm25Score }
|
|
283
290
|
})
|
|
@@ -304,6 +311,9 @@ export function generateSmartRecall(
|
|
|
304
311
|
const top = eligible
|
|
305
312
|
.sort((a, b) => {
|
|
306
313
|
if (a.priority !== b.priority) return b.priority - a.priority
|
|
314
|
+
const ia = importanceRank(a.importance)
|
|
315
|
+
const ib = importanceRank(b.importance)
|
|
316
|
+
if (ia !== ib) return ib - ia
|
|
307
317
|
return importance(b, opts.today) - importance(a, opts.today)
|
|
308
318
|
})
|
|
309
319
|
.slice(0, limit)
|
package/src/lib/utils.ts
CHANGED
|
@@ -23,6 +23,30 @@ export function importance(
|
|
|
23
23
|
return recency * 0.6 + freq * 0.4
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
+
/** Explicit importance levels, highest to lowest. Empty string = auto (no boost). */
|
|
27
|
+
export const IMPORTANCE_LEVELS = ["critical", "high", "medium", "low"] as const
|
|
28
|
+
export type ImportanceLevel = (typeof IMPORTANCE_LEVELS)[number]
|
|
29
|
+
|
|
30
|
+
/** Ranking boost for an explicit importance level. Auto (empty) = 0. */
|
|
31
|
+
export const IMPORTANCE_BOOST: Record<ImportanceLevel, number> = {
|
|
32
|
+
critical: 0.3,
|
|
33
|
+
high: 0.15,
|
|
34
|
+
medium: 0,
|
|
35
|
+
low: -0.1,
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Map an explicit importance level to its ranking boost (empty/unknown = 0). */
|
|
39
|
+
export const importanceBoost = (level: string): number =>
|
|
40
|
+
IMPORTANCE_BOOST[level as ImportanceLevel] ?? 0
|
|
41
|
+
|
|
42
|
+
/** Rank order for merging: higher value wins. Empty (auto) counts as medium. */
|
|
43
|
+
export const importanceRank = (level: string): number => {
|
|
44
|
+
if (level === "critical") return 4
|
|
45
|
+
if (level === "high") return 3
|
|
46
|
+
if (level === "low") return 1
|
|
47
|
+
return 2 // medium or auto
|
|
48
|
+
}
|
|
49
|
+
|
|
26
50
|
export const tokenize = (s: string): string[] =>
|
|
27
51
|
s
|
|
28
52
|
.replace(/([a-z])([A-Z])/g, "$1 $2")
|