@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,76 @@
1
+ // Lexical relevance for recall. No model call and no DSH imports: deterministic,
2
+ // testable, and cheap enough to run on every user turn.
3
+
4
+ const CJK = /[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]/
5
+
6
+ /** Tokenize Latin words plus CJK uni/bigrams so both scripts match. */
7
+ export function tokenize(text) {
8
+ const source = String(text ?? '').toLowerCase()
9
+ const terms = []
10
+ for (const word of source.match(/[a-z0-9_]{2,}/g) ?? []) terms.push(word)
11
+ for (const run of source.match(/[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]+/g) ?? []) {
12
+ if (run.length === 1) terms.push(run)
13
+ for (let i = 0; i < run.length - 1; i++) terms.push(run.slice(i, i + 2))
14
+ }
15
+ return terms
16
+ }
17
+
18
+ function termCounts(text) {
19
+ const counts = new Map()
20
+ for (const term of tokenize(text)) counts.set(term, (counts.get(term) ?? 0) + 1)
21
+ return counts
22
+ }
23
+
24
+ /**
25
+ * Rank notes for a query with a small TF-IDF model.
26
+ * Name and description hits weigh more than body hits because they are what
27
+ * the author judged to be the note's identity.
28
+ * @param {string} query
29
+ * @param {Array<{file: string, name?: string, description?: string, body?: string}>} notes
30
+ * @returns {Array<{file: string, score: number}>} descending, zero scores dropped
31
+ */
32
+ export function rankNotes(query, notes) {
33
+ const queryTerms = [...new Set(tokenize(query))]
34
+ if (queryTerms.length === 0 || notes.length === 0) return []
35
+ const documents = notes.map(note => {
36
+ const name = String(note.name ?? '')
37
+ const description = String(note.description ?? '')
38
+ const body = String(note.body ?? '')
39
+ return {
40
+ file: note.file,
41
+ name: termCounts(name),
42
+ description: termCounts(description),
43
+ body: termCounts(body),
44
+ length: tokenize(`${name} ${description} ${body}`).length || 1,
45
+ }
46
+ })
47
+ const documentFrequency = new Map()
48
+ for (const term of queryTerms) {
49
+ let seen = 0
50
+ for (const doc of documents) {
51
+ if (doc.name.has(term) || doc.description.has(term) || doc.body.has(term)) seen += 1
52
+ }
53
+ documentFrequency.set(term, seen)
54
+ }
55
+ const total = documents.length
56
+ const scored = documents.map(doc => {
57
+ let score = 0
58
+ for (const term of queryTerms) {
59
+ const df = documentFrequency.get(term) ?? 0
60
+ if (df === 0) continue
61
+ const idf = Math.log(1 + total / df)
62
+ const inName = (doc.name.get(term) ?? 0) * 3
63
+ const inDescription = (doc.description.get(term) ?? 0) * 2
64
+ const inBody = doc.body.get(term) ?? 0
65
+ const tf = (inName + inDescription + inBody) / Math.sqrt(doc.length)
66
+ score += tf * idf
67
+ }
68
+ return { file: doc.file, score }
69
+ })
70
+ return scored.filter(item => item.score > 0).sort((a, b) => b.score - a.score)
71
+ }
72
+
73
+ /** True when the text contains a CJK character (used to keep tokenization honest). */
74
+ export function hasCjk(text) {
75
+ return CJK.test(String(text ?? ''))
76
+ }
@@ -0,0 +1,498 @@
1
+ // Workspace-scoped memory notes on disk.
2
+ //
3
+ // Authority is always the Markdown file: the in-memory cache below is derived
4
+ // and may be dropped at any time. This module imports nothing from
5
+ // @deepseek-ai/* on purpose — CI runs its tests without DSH installed.
6
+
7
+ import { INDEX_FILE, renderMemoryIndex } from './memoryIndex.mjs'
8
+ import { createHash, randomBytes } from 'node:crypto'
9
+ import { lstat, mkdir, readFile, readdir, realpath, rename, rm, stat, writeFile } from 'node:fs/promises'
10
+ import { basename, join, resolve, sep } from 'node:path'
11
+
12
+ export const MEMORY_TYPES = ['user', 'feedback', 'project', 'reference']
13
+ export const MEMORY_ORIGINS = ['agent', 'extract', 'dream']
14
+ export const GLOBAL_SPACE = '_global'
15
+ export const ENTRYPOINT_NAME = 'MEMORY.md'
16
+
17
+ const MAX_NAME = 120
18
+ const MAX_DESCRIPTION = 240
19
+ const MAX_BODY = 64 * 1024
20
+ const SAFE_FILE = /^[a-z0-9][a-z0-9._-]*\.md$/
21
+ const SAFE_SPACE = /^[a-z0-9][a-z0-9-]*$/
22
+
23
+ export class StoreError extends Error {
24
+ constructor(code, message) {
25
+ super(message)
26
+ this.name = 'StoreError'
27
+ this.code = code
28
+ }
29
+ }
30
+
31
+ /** Stable per-directory space key: readable slug plus a short hash. */
32
+ export function spaceKeyFor(dir) {
33
+ const abs = resolve(String(dir ?? ''))
34
+ const slug = abs
35
+ .replace(/[\\/]+$/, '')
36
+ .split(/[\\/]/)
37
+ .pop()
38
+ ?.toLowerCase()
39
+ .replace(/[^a-z0-9]+/g, '-')
40
+ .replace(/^-+|-+$/g, '')
41
+ .slice(0, 40)
42
+ const hash = createHash('sha1').update(abs).digest('hex').slice(0, 8)
43
+ return `${slug !== undefined && slug !== '' ? slug : 'space'}-${hash}`
44
+ }
45
+
46
+ /** ASCII slug for a note file name; empty/CJK-only names fall back to a hash. */
47
+ export function slugify(name) {
48
+ const ascii = String(name ?? '')
49
+ .toLowerCase()
50
+ .replace(/[^a-z0-9]+/g, '-')
51
+ .replace(/^-+|-+$/g, '')
52
+ .slice(0, 48)
53
+ if (ascii !== '') return ascii
54
+ const hash = createHash('sha1').update(String(name ?? '')).digest('hex').slice(0, 10)
55
+ return `note-${hash}`
56
+ }
57
+
58
+ export function isSafeSpaceKey(key) {
59
+ if (typeof key !== 'string' || key.length > 64) return false
60
+ // `_global` is the single reserved space key. Every other underscore-prefixed
61
+ // name stays invalid, and `_global` is accepted only as the complete key, so
62
+ // neither `_global-x` nor `_globalx` slips through.
63
+ if (key === GLOBAL_SPACE) return true
64
+ return key !== '.' && SAFE_SPACE.test(key)
65
+ }
66
+
67
+ export function isSafeFile(file) {
68
+ // `MEMORY.md` (uppercase) can never pass SAFE_FILE, so no explicit exclusion
69
+ // is needed; keeping one would wrongly reject a note literally named "memory".
70
+ return typeof file === 'string' && SAFE_FILE.test(file)
71
+ }
72
+
73
+ function quoteIfNeeded(value) {
74
+ const text = String(value ?? '')
75
+ return /[:#\n\r"'\\]/.test(text) ? JSON.stringify(text) : text
76
+ }
77
+
78
+ function unquote(raw) {
79
+ const text = raw.trim()
80
+ if (
81
+ (text.startsWith('"') && text.endsWith('"') && text.length >= 2) ||
82
+ (text.startsWith("'") && text.endsWith("'") && text.length >= 2)
83
+ ) {
84
+ const inner = text.slice(1, -1)
85
+ if (text.startsWith('"')) {
86
+ try {
87
+ return JSON.parse(text)
88
+ } catch {
89
+ return inner
90
+ }
91
+ }
92
+ return inner
93
+ }
94
+ return text
95
+ }
96
+
97
+ /** Parse `---` frontmatter. Flat `key: value` pairs only; no nesting. */
98
+ export function parseNoteFile(text) {
99
+ // Strip a UTF-8 BOM: without this the opening fence never matches and the
100
+ // whole file degrades to a body with no metadata.
101
+ const source = String(text ?? '').replace(/^\uFEFF/, '')
102
+ const match = /^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(source)
103
+ if (match === null) {
104
+ return { frontmatter: {}, body: source.trim(), raw: source }
105
+ }
106
+ const frontmatter = {}
107
+ for (const line of match[1].split(/\r?\n/)) {
108
+ const idx = line.indexOf(':')
109
+ if (idx <= 0) continue
110
+ const key = line.slice(0, idx).trim()
111
+ if (key === '') continue
112
+ frontmatter[key] = unquote(line.slice(idx + 1))
113
+ }
114
+ return {
115
+ frontmatter,
116
+ body: source.slice(match[0].length).trim(),
117
+ raw: source,
118
+ }
119
+ }
120
+
121
+ export function renderNoteFile(note) {
122
+ const lines = ['---']
123
+ lines.push(`name: ${quoteIfNeeded(note.name)}`)
124
+ lines.push(`description: ${quoteIfNeeded(note.description)}`)
125
+ lines.push(`type: ${note.type}`)
126
+ lines.push(`origin: ${note.origin}`)
127
+ lines.push(`created: ${note.created}`)
128
+ lines.push(`updated: ${note.updated}`)
129
+ if (note.sourceSession) lines.push(`source_session: ${quoteIfNeeded(note.sourceSession)}`)
130
+ if (note.sourceSeq !== undefined && note.sourceSeq !== null) {
131
+ lines.push(`source_seq: ${note.sourceSeq}`)
132
+ }
133
+ lines.push('---', '', note.body.trim(), '')
134
+ return lines.join('\n')
135
+ }
136
+
137
+ export function validateNote(note, { maxNoteBytes = 8192 } = {}) {
138
+ const value = note ?? {}
139
+ const name = String(value.name ?? '').trim()
140
+ if (name === '') throw new StoreError('INVALID_NAME', 'memory note needs a non-empty name')
141
+ if (/[\r\n]/.test(name)) throw new StoreError('INVALID_NAME', 'name must be a single line')
142
+ if (name.length > MAX_NAME) throw new StoreError('INVALID_NAME', `name must be at most ${MAX_NAME} characters`)
143
+ const description = String(value.description ?? '').trim()
144
+ if (description === '') {
145
+ throw new StoreError('INVALID_DESCRIPTION', 'memory note needs a one-line description used for recall')
146
+ }
147
+ if (/[\r\n]/.test(description)) {
148
+ throw new StoreError('INVALID_DESCRIPTION', 'description must be a single line')
149
+ }
150
+ if (description.length > MAX_DESCRIPTION) {
151
+ throw new StoreError('INVALID_DESCRIPTION', `description must be at most ${MAX_DESCRIPTION} characters`)
152
+ }
153
+ if (!MEMORY_TYPES.includes(value.type)) {
154
+ throw new StoreError('INVALID_TYPE', `type must be one of ${MEMORY_TYPES.join(', ')}`)
155
+ }
156
+ const origin = MEMORY_ORIGINS.includes(value.origin) ? value.origin : 'agent'
157
+ const body = String(value.body ?? '').trim()
158
+ if (body === '') throw new StoreError('INVALID_BODY', 'memory note needs a body')
159
+ if (body.length > MAX_BODY) throw new StoreError('INVALID_BODY', 'memory note body is too large')
160
+ const props = {
161
+ name,
162
+ description,
163
+ type: value.type,
164
+ origin,
165
+ body,
166
+ }
167
+ const rendered = renderNoteFile({
168
+ ...props,
169
+ created: '1970-01-01T00:00:00.000Z',
170
+ updated: '1970-01-01T00:00:00.000Z',
171
+ })
172
+ if (Buffer.byteLength(rendered) > maxNoteBytes) {
173
+ throw new StoreError('NOTE_TOO_LARGE', `rendered note exceeds ${maxNoteBytes} bytes; split it into smaller notes`)
174
+ }
175
+ return props
176
+ }
177
+
178
+ function toIso(input) {
179
+ const date = input instanceof Date ? input : new Date(input ?? Date.now())
180
+ return Number.isNaN(date.getTime()) ? new Date().toISOString() : date.toISOString()
181
+ }
182
+
183
+ /**
184
+ * @param {object} options
185
+ * @param {string} options.root absolute memory root (…/dsh-memory)
186
+ * @param {number} [options.maxNoteBytes]
187
+ * @param {number} [options.maxNotes]
188
+ * @param {() => Date} [options.now]
189
+ */
190
+ export function createStore({ root, maxNoteBytes = 8192, maxNotes = 200, now = () => new Date(), memoryIndex = {} } = {}) {
191
+ if (typeof root !== 'string' || root === '') throw new StoreError('INVALID_ROOT', 'memory root is required')
192
+ const spacesRoot = join(root, 'spaces')
193
+ const indexOptions = {
194
+ enabled: memoryIndex.enabled !== false,
195
+ maxEntries: Number.isFinite(memoryIndex.maxEntries) && memoryIndex.maxEntries > 0 ? Math.trunc(memoryIndex.maxEntries) : 100,
196
+ maxLineChars: Number.isFinite(memoryIndex.maxLineChars) && memoryIndex.maxLineChars > 40 ? Math.trunc(memoryIndex.maxLineChars) : 240,
197
+ maxChars: Number.isFinite(memoryIndex.maxChars) && memoryIndex.maxChars > 200 ? Math.trunc(memoryIndex.maxChars) : 12000,
198
+ }
199
+ /** @type {Map<string, Array<object>>} */
200
+ const cache = new Map()
201
+ /** @type {Map<string, Promise<unknown>>} */
202
+ const queues = new Map()
203
+
204
+ function spaceDir(spaceKey) {
205
+ if (!isSafeSpaceKey(spaceKey)) throw new StoreError('INVALID_SPACE', `invalid space key: ${spaceKey}`)
206
+ const dir = resolve(spacesRoot, spaceKey)
207
+ if (!dir.startsWith(resolve(spacesRoot) + sep)) {
208
+ throw new StoreError('INVALID_SPACE', 'space key escapes the memory root')
209
+ }
210
+ return dir
211
+ }
212
+
213
+ function notePath(spaceKey, file) {
214
+ if (!isSafeFile(file)) throw new StoreError('INVALID_FILE', `invalid note file: ${file}`)
215
+ const dir = spaceDir(spaceKey)
216
+ const target = resolve(dir, file)
217
+ if (!target.startsWith(dir + sep)) throw new StoreError('INVALID_FILE', 'note path escapes its space')
218
+ return target
219
+ }
220
+
221
+ /** Serialize writes per space so two callers cannot interleave a rename. */
222
+ function enqueue(spaceKey, task) {
223
+ const previous = queues.get(spaceKey) ?? Promise.resolve()
224
+ const next = previous.then(task, task)
225
+ queues.set(
226
+ spaceKey,
227
+ next.catch(() => {}),
228
+ )
229
+ return next
230
+ }
231
+
232
+ function indexPath(spaceKey) {
233
+ return join(spaceDir(spaceKey), INDEX_FILE)
234
+ }
235
+
236
+ /**
237
+ * Regenerate MEMORY.md atomically when its content differs. The index is
238
+ * derived state: failures are swallowed so they can never fail a note write.
239
+ */
240
+ async function syncIndex(spaceKey, notes) {
241
+ if (indexOptions.enabled !== true) return false
242
+ const dir = spaceDir(spaceKey)
243
+ const target = indexPath(spaceKey)
244
+ try {
245
+ if (!Array.isArray(notes) || notes.length === 0) {
246
+ await rm(target, { force: true })
247
+ return false
248
+ }
249
+ const rendered = renderMemoryIndex(notes, {
250
+ label: spaceKey,
251
+ maxEntries: indexOptions.maxEntries,
252
+ maxLineChars: indexOptions.maxLineChars,
253
+ maxChars: indexOptions.maxChars,
254
+ })
255
+ const existing = await readFile(target, 'utf8').catch(() => null)
256
+ if (existing === rendered) return false
257
+ const temporary = join(dir, `.${INDEX_FILE}.${randomBytes(4).toString('hex')}.tmp`)
258
+ await writeFile(temporary, rendered, { encoding: 'utf8', mode: 0o600 })
259
+ await rename(temporary, target)
260
+ return true
261
+ } catch {
262
+ return false
263
+ }
264
+ }
265
+
266
+ /** Lazy repair for spaces whose index was deleted or predates this version. */
267
+ async function ensureIndex(spaceKey, notes) {
268
+ if (indexOptions.enabled !== true) return
269
+ try {
270
+ await syncIndex(spaceKey, notes)
271
+ } catch {
272
+ // derived state only
273
+ }
274
+ }
275
+
276
+ async function ensureSpace(spaceKey) {
277
+ const dir = spaceDir(spaceKey)
278
+ await mkdir(dir, { recursive: true })
279
+ await assertRealDir(spaceKey, dir)
280
+ return dir
281
+ }
282
+
283
+ /**
284
+ * Resolve a space directory through realpath and require it to stay under the
285
+ * memory root. This is what stops `spaces/<key>` symlinks (pre-existing on
286
+ * disk) from turning reads or writes into arbitrary filesystem access.
287
+ */
288
+ async function assertRealDir(spaceKey, dir) {
289
+ const rootReal = await realpath(spacesRoot).catch(() => null)
290
+ if (rootReal === null) return null
291
+ const dirReal = await realpath(dir).catch(() => null)
292
+ if (dirReal === null) return null
293
+ if (dirReal !== rootReal && !dirReal.startsWith(rootReal + sep)) {
294
+ throw new StoreError('INVALID_SPACE', `space directory escapes the memory root: ${spaceKey}`)
295
+ }
296
+ return dirReal
297
+ }
298
+
299
+ async function readSpace(spaceKey) {
300
+ const dir = spaceDir(spaceKey)
301
+ const info = await stat(dir).catch(() => null)
302
+ // Directory mtime catches files added or removed by hand (the model may
303
+ // edit notes with ordinary fs tools). Our own writes also invalidate.
304
+ const stamp = info !== null && info.isDirectory() ? info.mtimeMs : null
305
+ const cached = cache.get(spaceKey)
306
+ if (cached !== undefined && cached.stamp === stamp) return cached.notes
307
+ if (stamp === null) {
308
+ cache.set(spaceKey, { notes: [], stamp })
309
+ return []
310
+ }
311
+ const dirReal = await assertRealDir(spaceKey, dir)
312
+ if (dirReal === null) {
313
+ cache.set(spaceKey, { notes: [], stamp })
314
+ return []
315
+ }
316
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => [])
317
+ const notes = []
318
+ for (const entry of entries) {
319
+ if (!entry.isFile()) continue // symlinks and directories never become notes
320
+ const file = entry.name
321
+ if (!file.endsWith('.md')) continue
322
+ // `MEMORY.md` (uppercase) is already rejected by isSafeFile; no special
323
+ // case here, so a note named "memory" is not silently shadowed.
324
+ if (!isSafeFile(file)) continue
325
+ const target = join(dir, file)
326
+ try {
327
+ const targetReal = await realpath(target)
328
+ if (!targetReal.startsWith(dirReal + sep)) continue
329
+ const fileInfo = await stat(targetReal)
330
+ if (!fileInfo.isFile() || fileInfo.size > maxNoteBytes + 1024) continue
331
+ const raw = await readFile(targetReal, 'utf8')
332
+ const { frontmatter, body } = parseNoteFile(raw)
333
+ notes.push({
334
+ file,
335
+ name: String(frontmatter.name ?? file.replace(/\.md$/, '')),
336
+ description: String(frontmatter.description ?? ''),
337
+ type: MEMORY_TYPES.includes(frontmatter.type) ? frontmatter.type : 'project',
338
+ origin: MEMORY_ORIGINS.includes(frontmatter.origin) ? frontmatter.origin : 'agent',
339
+ created: String(frontmatter.created ?? ''),
340
+ updated: String(frontmatter.updated ?? ''),
341
+ sourceSession: frontmatter.source_session ? String(frontmatter.source_session) : '',
342
+ sourceSeq: frontmatter.source_seq === undefined ? null : Number(frontmatter.source_seq),
343
+ bytes: Buffer.byteLength(raw),
344
+ body,
345
+ })
346
+ } catch {
347
+ // A single unreadable file must not hide the rest of the space.
348
+ }
349
+ }
350
+ notes.sort((a, b) => String(b.updated).localeCompare(String(a.updated)))
351
+ cache.set(spaceKey, { notes, stamp })
352
+ return notes
353
+ }
354
+
355
+ async function listSpaces() {
356
+ const entries = await readdir(spacesRoot, { withFileTypes: true }).catch(() => [])
357
+ const spaces = []
358
+ for (const entry of entries) {
359
+ if (!entry.isDirectory() || !isSafeSpaceKey(entry.name)) continue
360
+ const notes = await readSpace(entry.name).catch(() => [])
361
+ spaces.push({
362
+ key: entry.name,
363
+ count: notes.length,
364
+ updatedAt: notes[0]?.updated ?? '',
365
+ })
366
+ }
367
+ spaces.sort((a, b) => String(b.updatedAt).localeCompare(String(a.updatedAt)))
368
+ return spaces
369
+ }
370
+
371
+ async function listNotes(spaceKey) {
372
+ const notes = await readSpace(spaceKey)
373
+ await ensureIndex(spaceKey, notes)
374
+ return notes.map(({ body, ...rest }) => rest)
375
+ }
376
+
377
+ async function readNote(spaceKey, file) {
378
+ if (!isSafeFile(file)) throw new StoreError('INVALID_FILE', `invalid note file: ${file}`)
379
+ const dir = spaceDir(spaceKey)
380
+ const target = notePath(spaceKey, file)
381
+ const link = await lstat(target).catch(() => null)
382
+ if (link === null) throw new StoreError('NOT_FOUND', `note not found: ${file}`)
383
+ if (link.isSymbolicLink()) throw new StoreError('INVALID_FILE', `note may not be a symlink: ${file}`)
384
+ const dirReal = await assertRealDir(spaceKey, dir)
385
+ if (dirReal === null) throw new StoreError('NOT_FOUND', `space not found: ${spaceKey}`)
386
+ const targetReal = await realpath(target).catch(() => null)
387
+ if (targetReal === null || !targetReal.startsWith(dirReal + sep)) {
388
+ throw new StoreError('INVALID_FILE', `note resolves outside its space: ${file}`)
389
+ }
390
+ const info = await stat(targetReal)
391
+ if (!info.isFile()) throw new StoreError('NOT_FOUND', `note not found: ${file}`)
392
+ if (info.size > maxNoteBytes + 1024) throw new StoreError('NOTE_TOO_LARGE', 'note is larger than the configured limit')
393
+ const raw = await readFile(targetReal, 'utf8')
394
+ const { frontmatter, body } = parseNoteFile(raw)
395
+ return {
396
+ file,
397
+ frontmatter,
398
+ body,
399
+ markdown: raw,
400
+ bytes: Buffer.byteLength(raw),
401
+ }
402
+ }
403
+
404
+ async function writeNote(spaceKey, input, meta = {}) {
405
+ const note = validateNote(
406
+ { ...input, origin: meta.origin ?? input?.origin ?? 'agent' },
407
+ { maxNoteBytes },
408
+ )
409
+ return enqueue(spaceKey, async () => {
410
+ const dir = await ensureSpace(spaceKey)
411
+ const notes = await readSpace(spaceKey)
412
+ // "memory" would collide with the reserved MEMORY.md on case-insensitive
413
+ // filesystems; keep the note visible by shifting its file name.
414
+ const base = slugify(note.name) === 'memory' ? 'memory-note' : slugify(note.name)
415
+ let file = `${base}.md`
416
+ const existing = notes.find(item => item.name === note.name)
417
+ let created = false
418
+ if (existing !== undefined) {
419
+ file = existing.file
420
+ } else {
421
+ let counter = 2
422
+ while (notes.some(item => item.file === file)) {
423
+ file = `${base}-${counter}.md`
424
+ counter += 1
425
+ }
426
+ if (notes.length >= maxNotes) {
427
+ throw new StoreError('SPACE_FULL', `space already holds ${maxNotes} notes; consolidate before adding more`)
428
+ }
429
+ created = true
430
+ }
431
+ const previous = existing?.file === file ? await readNote(spaceKey, file).catch(() => null) : null
432
+ const timestamp = toIso(now())
433
+ const rendered = renderNoteFile({
434
+ ...note,
435
+ created: previous?.frontmatter?.created ?? timestamp,
436
+ updated: timestamp,
437
+ sourceSession: meta.sessionId ?? '',
438
+ sourceSeq: meta.seq ?? null,
439
+ })
440
+ if (Buffer.byteLength(rendered) > maxNoteBytes) {
441
+ throw new StoreError('NOTE_TOO_LARGE', `rendered note exceeds ${maxNoteBytes} bytes`)
442
+ }
443
+ const target = notePath(spaceKey, file)
444
+ const temporary = join(dir, `.${basename(file)}.${randomBytes(4).toString('hex')}.tmp`)
445
+ await writeFile(temporary, rendered, { encoding: 'utf8', mode: 0o600 })
446
+ await rename(temporary, target)
447
+ cache.delete(spaceKey)
448
+ const fresh = await readSpace(spaceKey)
449
+ await syncIndex(spaceKey, fresh)
450
+ return { file, created, bytes: Buffer.byteLength(rendered) }
451
+ })
452
+ }
453
+
454
+ async function deleteNote(spaceKey, file) {
455
+ return enqueue(spaceKey, async () => {
456
+ const target = notePath(spaceKey, file)
457
+ const info = await stat(target).catch(() => null)
458
+ if (info === null) return false
459
+ await rm(target, { force: true })
460
+ cache.delete(spaceKey)
461
+ const fresh = await readSpace(spaceKey)
462
+ await syncIndex(spaceKey, fresh)
463
+ return true
464
+ })
465
+ }
466
+
467
+ async function search(spaceKey, { text = '', type, limit = 20 } = {}) {
468
+ const notes = await readSpace(spaceKey)
469
+ const needle = String(text).toLowerCase().trim()
470
+ return notes
471
+ .filter(note => (type === undefined ? true : note.type === type))
472
+ .filter(note => {
473
+ if (needle === '') return true
474
+ return `${note.name}\n${note.description}\n${note.body}`.toLowerCase().includes(needle)
475
+ })
476
+ .slice(0, limit)
477
+ .map(({ body, ...rest }) => rest)
478
+ }
479
+
480
+ return {
481
+ root,
482
+ spaceDir,
483
+ ensureSpace,
484
+ listSpaces,
485
+ listNotes,
486
+ readNote,
487
+ writeNote,
488
+ deleteNote,
489
+ search,
490
+ indexPath,
491
+ async readIndex(spaceKey) {
492
+ return await readFile(indexPath(spaceKey), 'utf8').catch(() => '')
493
+ },
494
+ invalidate(spaceKey) {
495
+ cache.delete(spaceKey)
496
+ },
497
+ }
498
+ }