toon-memory 4.3.4 → 4.4.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/README.de.md +2 -2
- package/README.es.md +2 -2
- package/README.fr.md +2 -2
- package/README.ja.md +2 -2
- package/README.ko.md +2 -2
- package/README.md +59 -13
- package/README.pt-br.md +2 -2
- package/README.zh.md +2 -2
- package/bin/toon-memory.js +4 -0
- package/dist/cli/capture.js +658 -26
- package/dist/cli/setup.js +1813 -143
- package/mcp/server.js +1391 -380
- package/package.json +6 -3
- package/src/bin/toon-memory.ts +4 -0
- package/src/cli/ambient.ts +117 -0
- package/src/cli/capture.ts +5 -2
- package/src/cli/commands.ts +3 -1
- package/src/cli/constants.ts +19 -11
- package/src/cli/dense.ts +50 -0
- package/src/cli/instructions.ts +2 -2
- package/src/cli/opencode-plugin.ts +100 -95
- package/src/cli/setup.ts +51 -4
- package/src/cli/sleep.ts +45 -0
- package/src/lib/activation.ts +32 -0
- package/src/lib/compiler.ts +178 -0
- package/src/lib/dense.ts +123 -0
- package/src/lib/graph.ts +123 -36
- package/src/lib/handoff.ts +144 -0
- package/src/lib/ngrams.ts +68 -0
- package/src/lib/promoter.ts +140 -0
- package/src/lib/quality.ts +25 -10
- package/src/lib/utils.ts +17 -7
- package/src/mcp/args.ts +46 -0
- package/src/mcp/config.ts +20 -0
- package/src/mcp/edges.ts +99 -0
- package/src/mcp/entries.ts +34 -9
- package/src/mcp/feedback.ts +130 -0
- package/src/mcp/resources.ts +12 -9
- package/src/mcp/server.ts +13 -1
- package/src/mcp/tools.ts +271 -102
- package/src/viewer/html.ts +23 -25
- package/src/viewer/index.ts +8 -8
package/src/cli/setup.ts
CHANGED
|
@@ -2,9 +2,45 @@ import { captureToggle } from "./capture-toggle"
|
|
|
2
2
|
import { init, uninstall, status, upgrade, stats, exportMemory, importMemory, dumpMemory, interactiveInstall } from "./commands"
|
|
3
3
|
import { watch } from "./watch"
|
|
4
4
|
import { viewer, viewerExport } from "../viewer"
|
|
5
|
+
import { printBrief, printDoctor, recordSignal, runPromotion } from "./ambient"
|
|
6
|
+
import { runSleep } from "./sleep"
|
|
7
|
+
import { runDense } from "./dense"
|
|
5
8
|
|
|
6
9
|
const args = process.argv.slice(2)
|
|
7
10
|
|
|
11
|
+
if (args[0] === "brief") {
|
|
12
|
+
printBrief(args.slice(1).join(" ") || process.env.TOON_MEMORY_TASK || "")
|
|
13
|
+
process.exit(0)
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
if (args[0] === "doctor") {
|
|
17
|
+
printDoctor()
|
|
18
|
+
process.exit(0)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
if (args[0] === "signal") {
|
|
22
|
+
recordSignal(args.slice(1))
|
|
23
|
+
process.exit(0)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
if (args[0] === "promote") {
|
|
27
|
+
runPromotion(args.slice(1))
|
|
28
|
+
process.exit(0)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
if (args[0] === "sleep") {
|
|
32
|
+
const result = runSleep()
|
|
33
|
+
console.log(result.ran
|
|
34
|
+
? `Sleep complete: ${result.promoted} promoted, ${result.edges} edges, ${result.pruned} pruned, ${result.duplicates} duplicates.`
|
|
35
|
+
: "Sleep is disabled (config.sleep.enabled or TOON_MEMORY_SLEEP=1).")
|
|
36
|
+
process.exit(0)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
if (args[0] === "dense") {
|
|
40
|
+
await runDense(args.slice(1))
|
|
41
|
+
process.exit(0)
|
|
42
|
+
}
|
|
43
|
+
|
|
8
44
|
if (args[0] === "capture") {
|
|
9
45
|
captureToggle(args[1] === "on")
|
|
10
46
|
process.exit(0)
|
|
@@ -22,17 +58,22 @@ if (args[0] === "init") {
|
|
|
22
58
|
}
|
|
23
59
|
const rest = args.slice(1)
|
|
24
60
|
const agentNames: string[] = []
|
|
61
|
+
const scopes = new Set(["local", "global"])
|
|
62
|
+
const addAgents = (value: string) =>
|
|
63
|
+
value.split(",").map((a) => a.trim().toLowerCase()).filter(Boolean).forEach((a) => agentNames.push(a))
|
|
25
64
|
let scope: string | undefined
|
|
26
65
|
let i = 0
|
|
27
66
|
while (i < rest.length) {
|
|
28
67
|
if (rest[i] === "--agent" && rest[i + 1]) {
|
|
29
|
-
|
|
68
|
+
addAgents(rest[i + 1])
|
|
30
69
|
i += 2
|
|
31
70
|
} else if (rest[i] === "--scope" && rest[i + 1]) {
|
|
32
71
|
scope = rest[i + 1]
|
|
33
72
|
i += 2
|
|
34
73
|
} else if (rest[i] !== "--agent" && rest[i] !== "--scope") {
|
|
35
|
-
|
|
74
|
+
const token = rest[i].toLowerCase()
|
|
75
|
+
if (scopes.has(token) && !scope) scope = token
|
|
76
|
+
else addAgents(token)
|
|
36
77
|
i++
|
|
37
78
|
} else {
|
|
38
79
|
i++
|
|
@@ -118,9 +159,15 @@ Press 'r' in the terminal while serving to reload the graph.`)
|
|
|
118
159
|
/** Minimal usage string for unknown commands. */
|
|
119
160
|
function printUsage(): void {
|
|
120
161
|
console.log(`Usage: toon-memory <command> [options]
|
|
121
|
-
Commands: init, status, stats, export, import, watch, viewer, uninstall, capture, upgrade, mcp
|
|
162
|
+
Commands: init, status, stats, export, import, watch, viewer, uninstall, capture, upgrade, brief, doctor, signal, promote, sleep, dense, mcp
|
|
163
|
+
brief [task] — Print the compact handoff brief injected at session start
|
|
164
|
+
doctor — Check memory path, signals and injection channel
|
|
165
|
+
signal --type <t> --summary <s> [--file <f>] — Append one deterministic signal
|
|
166
|
+
promote [--threshold <0-1>] — Promote high-confidence signals into memory
|
|
167
|
+
sleep — Deterministic consolidation (opt-in: config.sleep.enabled)
|
|
168
|
+
dense <status|enable|disable|build|install> — Optional local embeddings with BM25 fallback
|
|
122
169
|
viewer [--export] [--port <n>] — Start an HTTP server with the graph viewer (press 'r' to reload). --export saves static HTML.
|
|
123
|
-
Init: toon-memory init [
|
|
170
|
+
Init: toon-memory init [local|global] [agent...] | --agent <name>[,<name>...] [--scope local|global]
|
|
124
171
|
Without --agent: interactive agent and scope selector.
|
|
125
172
|
With --agent: non-interactive installation (default: scope local).
|
|
126
173
|
Options: -v/--version, -h/--help
|
package/src/cli/sleep.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { loadConfig } from "../mcp/config"
|
|
2
|
+
import { readMemory, writeMemory } from "../mcp/memory-io"
|
|
3
|
+
import { readObservations, pruneObservations } from "../mcp/observations"
|
|
4
|
+
import { promoteSignals, type Signal } from "../lib/promoter"
|
|
5
|
+
import { readFeedback } from "../mcp/feedback"
|
|
6
|
+
import { rebuildEdges } from "../mcp/edges"
|
|
7
|
+
import { pruneExpiredEntries } from "../mcp/archive"
|
|
8
|
+
import { consolidateEntries } from "../mcp/consolidation"
|
|
9
|
+
|
|
10
|
+
export interface SleepResult {
|
|
11
|
+
ran: boolean
|
|
12
|
+
promoted: number
|
|
13
|
+
edges: number
|
|
14
|
+
pruned: number
|
|
15
|
+
duplicates: number
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function runSleep(): SleepResult {
|
|
19
|
+
const config = loadConfig()
|
|
20
|
+
if (!config.sleep?.enabled && process.env.TOON_MEMORY_SLEEP !== "1") {
|
|
21
|
+
return { ran: false, promoted: 0, edges: 0, pruned: 0, duplicates: 0 }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const signals: Signal[] = readObservations().map((o) => ({
|
|
25
|
+
type: o.tool,
|
|
26
|
+
summary: o.summary,
|
|
27
|
+
file: o.file,
|
|
28
|
+
session: o.session,
|
|
29
|
+
ts: o.ts,
|
|
30
|
+
}))
|
|
31
|
+
const promotedResult = promoteSignals(readMemory(), signals, {})
|
|
32
|
+
if (promotedResult.promoted.length > 0) writeMemory(promotedResult.data)
|
|
33
|
+
|
|
34
|
+
const edges = rebuildEdges(readMemory(), readFeedback())
|
|
35
|
+
const pruned = pruneExpiredEntries() + pruneObservations()
|
|
36
|
+
const duplicates = consolidateEntries().removed
|
|
37
|
+
|
|
38
|
+
return {
|
|
39
|
+
ran: true,
|
|
40
|
+
promoted: promotedResult.promoted.length,
|
|
41
|
+
edges,
|
|
42
|
+
pruned,
|
|
43
|
+
duplicates,
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export interface ActivationEdge {
|
|
2
|
+
from: string
|
|
3
|
+
to: string
|
|
4
|
+
type: string
|
|
5
|
+
weight: number
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function activationScores(
|
|
9
|
+
edges: ActivationEdge[],
|
|
10
|
+
seeds: string[],
|
|
11
|
+
depth = 1
|
|
12
|
+
): Map<string, number> {
|
|
13
|
+
const out = new Map<string, number>()
|
|
14
|
+
let frontier = [...new Set(seeds)]
|
|
15
|
+
for (let d = 0; d < Math.max(0, depth); d++) {
|
|
16
|
+
const next: string[] = []
|
|
17
|
+
for (const node of frontier) {
|
|
18
|
+
for (const edge of edges) {
|
|
19
|
+
let other = ""
|
|
20
|
+
if (edge.from === node) other = edge.to
|
|
21
|
+
else if (edge.to === node) other = edge.from
|
|
22
|
+
if (!other || other === node || seeds.includes(other)) continue
|
|
23
|
+
const kind = edge.type === "supports" || edge.type === "used_in" ? 1 : edge.type === "contradicts" ? 0.6 : 0.8
|
|
24
|
+
const gain = edge.weight * kind * Math.pow(0.5, d)
|
|
25
|
+
out.set(other, (out.get(other) || 0) + gain)
|
|
26
|
+
next.push(other)
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
frontier = [...new Set(next)]
|
|
30
|
+
}
|
|
31
|
+
return out
|
|
32
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { basename } from "path"
|
|
2
|
+
import { graphRecallDetailed, parseEntries, type GraphEntry } from "./graph"
|
|
3
|
+
import { estimateTokens, isExpiredLocal, isPrivate, tokenize } from "./utils"
|
|
4
|
+
import { entryAgeDays, projectSlug } from "./handoff"
|
|
5
|
+
import type { ActivationEdge } from "./activation"
|
|
6
|
+
|
|
7
|
+
export interface ContextSection {
|
|
8
|
+
title: string
|
|
9
|
+
lines: string[]
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface ContextPackage {
|
|
13
|
+
task: string
|
|
14
|
+
asOf: string
|
|
15
|
+
freshness: string
|
|
16
|
+
project: string
|
|
17
|
+
slug: string
|
|
18
|
+
root: string
|
|
19
|
+
sections: ContextSection[]
|
|
20
|
+
queries: string[]
|
|
21
|
+
hydrate: string[]
|
|
22
|
+
usedTokens: number
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface CompileOpts {
|
|
26
|
+
root?: string
|
|
27
|
+
today?: string
|
|
28
|
+
maxTokens?: number
|
|
29
|
+
utility?: Map<string, number>
|
|
30
|
+
edges?: ActivationEdge[]
|
|
31
|
+
activation?: boolean
|
|
32
|
+
dense?: Map<string, number>
|
|
33
|
+
sessions?: string[]
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function claim(e: GraphEntry, maxChars = 120): string {
|
|
37
|
+
const text = e.content.replace(/\s+/g, " ").trim()
|
|
38
|
+
if (!text) return e.key
|
|
39
|
+
const sentence = text.match(/^[^.!?]+[.!?]?/)?.[0] || text
|
|
40
|
+
if (sentence.length <= maxChars) return sentence.trim()
|
|
41
|
+
return `${sentence.slice(0, maxChars).replace(/\s+\S*$/, "")} · ${e.key}`
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function line(e: GraphEntry, today: string): string {
|
|
45
|
+
const age = entryAgeDays(e.date, today)
|
|
46
|
+
const stale = age > 30 ? ` [stale ${age}d]` : ""
|
|
47
|
+
const file = e.file ? ` @ ${e.file}` : ""
|
|
48
|
+
return `- [${e.category}] ${e.key}: ${claim(e)}${file}${stale}`
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function compileContext(data: string, task: string, opts: CompileOpts = {}): ContextPackage {
|
|
52
|
+
const today = opts.today || new Date().toISOString().split("T")[0]
|
|
53
|
+
const root = opts.root || process.cwd()
|
|
54
|
+
const maxTokens = opts.maxTokens ?? 900
|
|
55
|
+
const usable = parseEntries(data).filter(
|
|
56
|
+
(e) =>
|
|
57
|
+
e.status !== "obsolete" &&
|
|
58
|
+
e.status !== "draft" &&
|
|
59
|
+
!isPrivate(e) &&
|
|
60
|
+
!(e.ttl && isExpiredLocal(e.ttl, today))
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
const newest = usable.reduce((acc, e) => (e.date > acc ? e.date : acc), "")
|
|
64
|
+
const age = entryAgeDays(newest, today)
|
|
65
|
+
const freshness = !newest ? "empty" : age > 30 ? `stale-${age}d` : "fresh"
|
|
66
|
+
|
|
67
|
+
const graphRanked = graphRecallDetailed(data, task, {
|
|
68
|
+
limit: 12,
|
|
69
|
+
utility: opts.utility,
|
|
70
|
+
edges: opts.edges,
|
|
71
|
+
activation: opts.activation,
|
|
72
|
+
dense: opts.dense,
|
|
73
|
+
}).entries
|
|
74
|
+
const utilitySeeds = [...(opts.utility?.entries() || [])]
|
|
75
|
+
.filter(([, value]) => value > 0)
|
|
76
|
+
.sort((a, b) => b[1] - a[1])
|
|
77
|
+
.map(([key]) => key)
|
|
78
|
+
const utilityEntries = utilitySeeds
|
|
79
|
+
.map((key) => usable.find((e) => e.key === key))
|
|
80
|
+
.filter((e): e is GraphEntry => Boolean(e))
|
|
81
|
+
const ranked = [...utilityEntries, ...graphRanked.filter((e) => !utilitySeeds.includes(e.key))]
|
|
82
|
+
const seen = new Set<string>()
|
|
83
|
+
const take = (list: GraphEntry[]): GraphEntry[] => {
|
|
84
|
+
const out: GraphEntry[] = []
|
|
85
|
+
for (const e of list) {
|
|
86
|
+
if (seen.has(e.key)) continue
|
|
87
|
+
seen.add(e.key)
|
|
88
|
+
out.push(e)
|
|
89
|
+
}
|
|
90
|
+
return out
|
|
91
|
+
}
|
|
92
|
+
const byDate = (a: GraphEntry, b: GraphEntry) => b.date.localeCompare(a.date)
|
|
93
|
+
|
|
94
|
+
const directives = take(
|
|
95
|
+
usable
|
|
96
|
+
.filter(
|
|
97
|
+
(e) =>
|
|
98
|
+
(e.origin === "human" || e.importance === "critical" || e.priority > 0) &&
|
|
99
|
+
e.category !== "warning" &&
|
|
100
|
+
e.evidence !== "conflict"
|
|
101
|
+
)
|
|
102
|
+
.sort((a, b) => b.priority - a.priority || byDate(a, b))
|
|
103
|
+
.slice(0, 3)
|
|
104
|
+
)
|
|
105
|
+
const constraints = take(
|
|
106
|
+
usable
|
|
107
|
+
.filter(
|
|
108
|
+
(e) =>
|
|
109
|
+
e.category === "warning" ||
|
|
110
|
+
e.evidence === "conflict" ||
|
|
111
|
+
e.tags.some((t) => ["trap", "gotcha", "risk", "warning", "outdated"].includes(t.toLowerCase()))
|
|
112
|
+
)
|
|
113
|
+
.sort(byDate)
|
|
114
|
+
.slice(0, 2)
|
|
115
|
+
)
|
|
116
|
+
const memory = take(ranked.slice(0, 5))
|
|
117
|
+
const decisions = take(ranked.filter((e) => e.category === "decision").slice(0, 2))
|
|
118
|
+
|
|
119
|
+
const tokens = tokenize(task).slice(0, 4)
|
|
120
|
+
const queries: string[] = []
|
|
121
|
+
if (task.trim()) queries.push(task.trim().slice(0, 140))
|
|
122
|
+
if (tokens.length >= 2) queries.push(`${tokens[0]} ${tokens[1]}`)
|
|
123
|
+
if (memory.length > 0 && tokens.length > 0) queries.push(`${memory[0].key} ${tokens[0]}`)
|
|
124
|
+
const queriesOut = [...new Set(queries)].slice(0, 3)
|
|
125
|
+
|
|
126
|
+
const hydrate = [...new Set([...directives, ...constraints, ...memory, ...decisions].map((e) => e.key))].slice(0, 8)
|
|
127
|
+
const files = [...new Set([...directives, ...constraints, ...memory, ...decisions].map((e) => e.file).filter(Boolean))].slice(0, 4)
|
|
128
|
+
const sessionLines = (opts.sessions || []).slice(0, 2).map((s) => `- ${s}`)
|
|
129
|
+
|
|
130
|
+
const sections: ContextSection[] = [
|
|
131
|
+
{ title: "Directives", lines: directives.map((e) => line(e, today)) },
|
|
132
|
+
{ title: "Constraints", lines: constraints.map((e) => line(e, today)) },
|
|
133
|
+
{ title: "Memory", lines: memory.map((e) => line(e, today)) },
|
|
134
|
+
{ title: "Decisions", lines: decisions.map((e) => line(e, today)) },
|
|
135
|
+
{ title: "Retrieval", lines: queriesOut.map((q) => `- query: ${q}`) },
|
|
136
|
+
{ title: "Hydrate", lines: hydrate.length ? hydrate.map((k) => `- ${k}`) : ["- (none)"] },
|
|
137
|
+
{ title: "Files", lines: files.map((f) => `- ${f}`) },
|
|
138
|
+
{ title: "Sessions", lines: sessionLines.length ? sessionLines : ["- (none)"] },
|
|
139
|
+
].filter((s) => s.lines.length > 0)
|
|
140
|
+
|
|
141
|
+
const pkg: ContextPackage = {
|
|
142
|
+
task,
|
|
143
|
+
asOf: today,
|
|
144
|
+
freshness,
|
|
145
|
+
project: basename(root) || root,
|
|
146
|
+
slug: projectSlug(root),
|
|
147
|
+
root,
|
|
148
|
+
sections: [],
|
|
149
|
+
queries: queriesOut,
|
|
150
|
+
hydrate,
|
|
151
|
+
usedTokens: 0,
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
let used = estimateTokens(
|
|
155
|
+
`<memory project="${pkg.project}" as_of="${today}" freshness="${freshness}">\nidentity: mcp_project=${pkg.slug} | root=${root}\n</memory>`
|
|
156
|
+
)
|
|
157
|
+
for (const section of sections) {
|
|
158
|
+
const block = `${section.title}\n${section.lines.join("\n")}`
|
|
159
|
+
const cost = estimateTokens(`\n${block}`)
|
|
160
|
+
if (used + cost > maxTokens) continue
|
|
161
|
+
used += cost
|
|
162
|
+
pkg.sections.push(section)
|
|
163
|
+
}
|
|
164
|
+
pkg.usedTokens = used
|
|
165
|
+
return pkg
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export function renderContextPackage(pkg: ContextPackage): string {
|
|
169
|
+
const task = pkg.task.replace(/"/g, """).slice(0, 140)
|
|
170
|
+
const out = [
|
|
171
|
+
`<memory project="${pkg.project}" as_of="${pkg.asOf}" freshness="${pkg.freshness}" task="${task}">`,
|
|
172
|
+
`identity: mcp_project=${pkg.slug} | root=${pkg.root}`,
|
|
173
|
+
]
|
|
174
|
+
for (const section of pkg.sections) out.push(`${section.title}\n${section.lines.join("\n")}`)
|
|
175
|
+
if (pkg.sections.length === 0) out.push("(no stable memories yet)")
|
|
176
|
+
out.push("</memory>")
|
|
177
|
+
return out.join("\n")
|
|
178
|
+
}
|
package/src/lib/dense.ts
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"
|
|
2
|
+
import { dirname } from "path"
|
|
3
|
+
import { parseEntries } from "../lib/graph"
|
|
4
|
+
import { loadConfig, VECTORS_FILE } from "../mcp/config"
|
|
5
|
+
import { withLockSync } from "../lib/lock"
|
|
6
|
+
|
|
7
|
+
export interface DenseModule {
|
|
8
|
+
embed(texts: string[], model?: string): Promise<number[][]>
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface StoredVectors {
|
|
12
|
+
dim: number
|
|
13
|
+
vectors: Map<string, number[]>
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export async function loadDenseModule(): Promise<DenseModule | null> {
|
|
17
|
+
const spec = process.env.TOON_MEMORY_DENSE_MODULE || "toon-memory-dense"
|
|
18
|
+
try {
|
|
19
|
+
const mod: any = await import(spec)
|
|
20
|
+
const embed = mod?.embed || mod?.default?.embed || mod?.default
|
|
21
|
+
return typeof embed === "function" ? { embed } : null
|
|
22
|
+
} catch {
|
|
23
|
+
return null
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function cosine(a: number[], b: number[]): number {
|
|
28
|
+
const n = Math.min(a.length, b.length)
|
|
29
|
+
if (n === 0) return 0
|
|
30
|
+
let dot = 0
|
|
31
|
+
let na = 0
|
|
32
|
+
let nb = 0
|
|
33
|
+
for (let i = 0; i < n; i++) {
|
|
34
|
+
dot += a[i] * b[i]
|
|
35
|
+
na += a[i] * a[i]
|
|
36
|
+
nb += b[i] * b[i]
|
|
37
|
+
}
|
|
38
|
+
if (na === 0 || nb === 0) return 0
|
|
39
|
+
const value = dot / (Math.sqrt(na) * Math.sqrt(nb))
|
|
40
|
+
return Number.isFinite(value) ? value : 0
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function readVectors(): StoredVectors {
|
|
44
|
+
const empty = { dim: 0, vectors: new Map<string, number[]>() }
|
|
45
|
+
if (!existsSync(VECTORS_FILE)) return empty
|
|
46
|
+
try {
|
|
47
|
+
const buf = readFileSync(VECTORS_FILE)
|
|
48
|
+
const newline = buf.indexOf(0x0a)
|
|
49
|
+
if (newline === -1) return empty
|
|
50
|
+
const match = buf.subarray(0, newline).toString("utf-8").match(/^TMVEC1 (\d+)$/)
|
|
51
|
+
if (!match) return empty
|
|
52
|
+
const dim = Number(match[1])
|
|
53
|
+
if (!Number.isFinite(dim) || dim <= 0) return empty
|
|
54
|
+
let offset = newline + 1
|
|
55
|
+
const vectors = new Map<string, number[]>()
|
|
56
|
+
while (offset + 2 <= buf.length) {
|
|
57
|
+
const len = buf.readUInt16BE(offset)
|
|
58
|
+
offset += 2
|
|
59
|
+
if (offset + len + dim * 4 > buf.length) break
|
|
60
|
+
const key = buf.subarray(offset, offset + len).toString("utf-8")
|
|
61
|
+
offset += len
|
|
62
|
+
const vec: number[] = []
|
|
63
|
+
for (let i = 0; i < dim; i++) vec.push(buf.readFloatLE(offset + i * 4))
|
|
64
|
+
offset += dim * 4
|
|
65
|
+
vectors.set(key, vec)
|
|
66
|
+
}
|
|
67
|
+
return { dim, vectors }
|
|
68
|
+
} catch {
|
|
69
|
+
return empty
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function writeVectors(vectors: Map<string, number[]>, dim: number): number {
|
|
74
|
+
const dir = dirname(VECTORS_FILE)
|
|
75
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
|
|
76
|
+
const chunks: Buffer[] = [Buffer.from(`TMVEC1 ${dim}\n`, "utf-8")]
|
|
77
|
+
let written = 0
|
|
78
|
+
for (const [key, vec] of vectors) {
|
|
79
|
+
if (vec.length !== dim) continue
|
|
80
|
+
const keyBuf = Buffer.from(key, "utf-8")
|
|
81
|
+
const lenBuf = Buffer.alloc(2)
|
|
82
|
+
lenBuf.writeUInt16BE(keyBuf.length)
|
|
83
|
+
const vecBuf = Buffer.alloc(dim * 4)
|
|
84
|
+
for (let i = 0; i < dim; i++) vecBuf.writeFloatLE(vec[i], i * 4)
|
|
85
|
+
chunks.push(lenBuf, keyBuf, vecBuf)
|
|
86
|
+
written++
|
|
87
|
+
}
|
|
88
|
+
const out = Buffer.concat(chunks)
|
|
89
|
+
withLockSync(VECTORS_FILE, () => writeFileSync(VECTORS_FILE, out))
|
|
90
|
+
return written
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export async function buildVectors(data: string, module: DenseModule, model?: string): Promise<number> {
|
|
94
|
+
const entries = parseEntries(data).filter((e) => e.status !== "obsolete" && e.status !== "draft")
|
|
95
|
+
if (entries.length === 0) return 0
|
|
96
|
+
const embedded = await module.embed(entries.map((e) => `${e.key} ${e.content}`), model)
|
|
97
|
+
const dim = embedded[0]?.length || loadConfig().dense?.dim || 0
|
|
98
|
+
if (!dim) return 0
|
|
99
|
+
const vectors = new Map<string, number[]>()
|
|
100
|
+
entries.forEach((e, i) => {
|
|
101
|
+
if (embedded[i]?.length === dim) vectors.set(e.key, embedded[i])
|
|
102
|
+
})
|
|
103
|
+
return writeVectors(vectors, dim)
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export async function denseScores(query: string, data: string): Promise<Map<string, number>> {
|
|
107
|
+
const config = loadConfig()
|
|
108
|
+
if (!config.dense?.enabled || !query.trim()) return new Map()
|
|
109
|
+
try {
|
|
110
|
+
const module = await loadDenseModule()
|
|
111
|
+
if (!module) return new Map()
|
|
112
|
+
if (readVectors().vectors.size === 0) await buildVectors(data, module, config.dense.model)
|
|
113
|
+
const stored = readVectors()
|
|
114
|
+
if (stored.vectors.size === 0) return new Map()
|
|
115
|
+
const [queryVec] = await module.embed([query], config.dense.model)
|
|
116
|
+
if (!queryVec) return new Map()
|
|
117
|
+
const out = new Map<string, number>()
|
|
118
|
+
for (const [key, vec] of stored.vectors) out.set(key, cosine(queryVec, vec))
|
|
119
|
+
return out
|
|
120
|
+
} catch {
|
|
121
|
+
return new Map()
|
|
122
|
+
}
|
|
123
|
+
}
|