@tangjs/dsh-memory 0.0.0-stage → 1.0.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.
@@ -0,0 +1,144 @@
1
+ // Pure handlers behind the two model-facing tools. index.js wraps them with
2
+ // defineTool; keeping the logic here lets CI test it without the harness.
3
+
4
+ import { GLOBAL_SPACE, MEMORY_TYPES, StoreError } from './store.mjs'
5
+ import { rankNotes } from './score.mjs'
6
+
7
+ const EXCERPT_CHARS = 600
8
+
9
+ /**
10
+ * @param {object} options
11
+ * @param {ReturnType<import('./store.mjs').createStore>} options.store
12
+ * @param {(spaceKey: string, query: string, limit?: number) => Promise<Array<{file: string, score: number}>>} [options.rank]
13
+ */
14
+ export function createHandlers({ store, rank } = {}) {
15
+ if (store === undefined) throw new Error('createHandlers requires a store')
16
+
17
+ /**
18
+ * Search one or more spaces. `spaceKey` is the legacy single-space form;
19
+ * `spaces` is `[{key, scope}]` and merges a workspace with the global space.
20
+ */
21
+ async function search({ spaceKey, spaces, query = '', type, limit = 8 }) {
22
+ const max = Math.max(1, Math.min(Number(limit) || 8, 20))
23
+ const targets = normalizeSpaces(spaces, spaceKey)
24
+ const needle = String(query).toLowerCase().trim()
25
+ /** @type {Map<string, object>} */
26
+ const candidates = new Map()
27
+ for (const target of targets) {
28
+ const notes = await store.listNotes(target.key).catch(() => [])
29
+ for (const note of notes) {
30
+ if (type !== undefined && note.type !== type) continue
31
+ const id = `${target.key}/${note.file}`
32
+ candidates.set(id, { ...note, space: target.key, scope: target.scope, id })
33
+ }
34
+ }
35
+ let picked = [...candidates.values()]
36
+ if (needle !== '') {
37
+ // A legacy single-space ranker keeps its previous contract.
38
+ let ordered = null
39
+ if (typeof rank === 'function' && targets.length === 1) {
40
+ const ranked = await rank(targets[0].key, query, candidates.size || 1).catch(() => null)
41
+ if (Array.isArray(ranked) && ranked.length > 0) {
42
+ const byFile = new Map(picked.map(note => [note.file, note]))
43
+ ordered = ranked.map(item => byFile.get(item.file)).filter(item => item !== undefined)
44
+ }
45
+ }
46
+ if (ordered === null) {
47
+ // Rank the merged set by a stable id so same-named files in different
48
+ // spaces never collapse into one candidate.
49
+ const rankable = picked.map(note => ({ file: note.id, name: note.name, description: note.description }))
50
+ const scored = rankNotes(query, rankable)
51
+ ordered = scored.map(hit => candidates.get(hit.file)).filter(note => note !== undefined)
52
+ if (ordered.length === 0) {
53
+ ordered = picked.filter(note => `${note.name}\n${note.description}`.toLowerCase().includes(needle))
54
+ }
55
+ }
56
+ picked = ordered
57
+ }
58
+ picked = picked.slice(0, max)
59
+ const results = []
60
+ for (const note of picked) {
61
+ let body = ''
62
+ try {
63
+ body = (await store.readNote(note.space, note.file)).body
64
+ } catch {
65
+ body = ''
66
+ }
67
+ results.push({
68
+ file: note.file,
69
+ space: note.space,
70
+ scope: note.scope,
71
+ name: note.name,
72
+ description: note.description,
73
+ type: note.type,
74
+ updated: note.updated,
75
+ excerpt: body.length > EXCERPT_CHARS ? `${body.slice(0, EXCERPT_CHARS)}…` : body,
76
+ })
77
+ }
78
+ return { count: results.length, notes: results }
79
+ }
80
+
81
+ /** Write or update one note. Same-name writes update in place. */
82
+ async function write({ spaceKey, name, description, type, body, origin = 'agent', sessionId, seq }) {
83
+ if (!MEMORY_TYPES.includes(type)) {
84
+ throw new StoreError('INVALID_TYPE', `type must be one of ${MEMORY_TYPES.join(', ')}`)
85
+ }
86
+ const before = await store.listNotes(spaceKey).catch(() => [])
87
+ const duplicate = before.find(
88
+ note => note.name !== name && closeEnough(note.name, name),
89
+ )
90
+ const result = await store.writeNote(
91
+ spaceKey,
92
+ { name, description, type, body, origin },
93
+ { origin, sessionId, seq },
94
+ )
95
+ return {
96
+ ...result,
97
+ hint:
98
+ duplicate === undefined
99
+ ? undefined
100
+ : `existing note "${duplicate.name}" (${duplicate.file}) looks similar; consider updating it instead`,
101
+ }
102
+ }
103
+
104
+ async function remove({ spaceKey, file }) {
105
+ return { removed: await store.deleteNote(spaceKey, file) }
106
+ }
107
+
108
+ async function list({ spaceKey }) {
109
+ const notes = await store.listNotes(spaceKey)
110
+ return { count: notes.length, notes }
111
+ }
112
+
113
+ return { search, write, remove, list }
114
+ }
115
+
116
+ function normalizeSpaces(spaces, spaceKey) {
117
+ if (Array.isArray(spaces) && spaces.length > 0) {
118
+ return spaces
119
+ .filter(entry => entry !== null && typeof entry === 'object' && typeof entry.key === 'string')
120
+ .map(entry => ({ key: entry.key, scope: entry.scope === 'global' || entry.key === GLOBAL_SPACE ? 'global' : 'workspace' }))
121
+ }
122
+ return [{ key: spaceKey, scope: 'workspace' }]
123
+ }
124
+
125
+ function closeEnough(a, b) {
126
+ const left = String(a).toLowerCase().replace(/\s+/g, '')
127
+ const right = String(b).toLowerCase().replace(/\s+/g, '')
128
+ if (left === right) return true
129
+ if (left.length < 4 || right.length < 4) return false
130
+ if (left.includes(right) || right.includes(left)) return true
131
+ // Character-bigram overlap catches CJK paraphrases ("测试不用 mock" vs
132
+ // "测试不要 mock") that neither contains the other.
133
+ const grams = text => {
134
+ const set = new Set()
135
+ for (let i = 0; i < text.length - 1; i++) set.add(text.slice(i, i + 2))
136
+ return set
137
+ }
138
+ const leftGrams = grams(left)
139
+ const rightGrams = grams(right)
140
+ let shared = 0
141
+ for (const gram of leftGrams) if (rightGrams.has(gram)) shared += 1
142
+ const union = leftGrams.size + rightGrams.size - shared
143
+ return union > 0 && shared / union >= 0.4
144
+ }