@zhangfeiyue/dsh-long-term-memory 0.0.0-stage → 1.1.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/index.js ADDED
@@ -0,0 +1,483 @@
1
+ /**
2
+ * Global long-term memory for DeepSeek Harness.
3
+ *
4
+ * This plugin gives every session, in every workspace, a persistent memory that
5
+ * survives restarts. It extends the harness only through documented extension
6
+ * points:
7
+ *
8
+ * - `ctx.tools.register` 鈥?five model-facing memory tools.
9
+ * - `agent/created` + `agent.ctx.systemPrompt.context` 鈥?a per-agent dynamic
10
+ * context block, so recall is scoped to the agent that asked for it and is
11
+ * removed when that agent is disposed.
12
+ * - `session/event` 鈥?a passive observer of the durable session log, which is
13
+ * where automatic extraction and task capture read from. Nothing here writes
14
+ * session events, so replay, fork and resume stay the harness's business.
15
+ *
16
+ * Failure containment is a hard rule: every listener and every context provider
17
+ * catches its own errors and degrades to "no memory", because a broken memory
18
+ * store must never break a conversation.
19
+ *
20
+ * @module dsh-long-term-memory
21
+ */
22
+
23
+ import { dueForConsolidation, consolidate } from './lib/consolidate.js'
24
+ import { resolveSettings, writeEffectiveConfig } from './lib/config.js'
25
+ import { BOARD_HEADER, EVENTS_PATH, MAX_BODY_BYTES, MUTATE_PATH, RECORD_PATH, SNAPSHOT_PATH, applyMutation, formatSse, recordView } from './lib/board.js'
26
+ import { buildSnapshot } from './lib/dashboard.js'
27
+ import { inferDomain } from './lib/domains.js'
28
+ import { extractFromUserMessage, planTaskCapture, todoKey } from './lib/extract.js'
29
+ import { migrateRecords } from './lib/profile.js'
30
+ import { saveMemory } from './lib/records.js'
31
+ import { renderMemoryBlock } from './lib/render.js'
32
+ import { createTools } from './lib/tools.js'
33
+ import { MemoryStore } from './lib/store.js'
34
+ import { workspaceKey, workspaceLabel } from './lib/util.js'
35
+
36
+ /** Cordis plugin name used by loader diagnostics. */
37
+ export const name = 'long-term-memory'
38
+
39
+ /**
40
+ * Services this plugin needs. `tools` and `systemPrompt` are core harness
41
+ * services present in every composed profile; declaring them keeps the plugin
42
+ * inactive rather than throwing in a profile that omits one.
43
+ */
44
+ export const inject = ['tools', 'systemPrompt']
45
+
46
+ /** The prompt-context registration name, stable so a reload replaces rather than duplicates. */
47
+ const PROMPT_CONTEXT_NAME = 'long-term-memory'
48
+
49
+ /** Where the board sits among runtime contexts: after policy facts, before harness paths. */
50
+ const PROMPT_CONTEXT_ORDER = 1500
51
+
52
+ /** Read a bounded JSON request body; `undefined` when it is oversized or malformed. */
53
+ function readJsonBody(request, limit) {
54
+ return new Promise((resolve) => {
55
+ /** @type {Buffer[]} */
56
+ const chunks = []
57
+ let size = 0
58
+ let settled = false
59
+ const settle = (value) => {
60
+ if (settled) return
61
+ settled = true
62
+ resolve(value)
63
+ }
64
+ request.on('data', (chunk) => {
65
+ size += chunk.length
66
+ if (size > limit) {
67
+ settle(undefined)
68
+ request.destroy()
69
+ return
70
+ }
71
+ chunks.push(chunk)
72
+ })
73
+ request.on('end', () => {
74
+ try {
75
+ settle(JSON.parse(Buffer.concat(chunks).toString('utf8')))
76
+ } catch {
77
+ settle(undefined)
78
+ }
79
+ })
80
+ request.on('error', () => settle(undefined))
81
+ })
82
+ }
83
+
84
+ /** Concatenate the text blocks of one message content array. */
85
+ function contentText(content) {
86
+ if (!Array.isArray(content)) return ''
87
+ const parts = []
88
+ for (const block of content) {
89
+ if (block !== null && typeof block === 'object' && block.type === 'text' && typeof block.text === 'string') {
90
+ parts.push(block.text)
91
+ }
92
+ }
93
+ return parts.join('\n').trim()
94
+ }
95
+
96
+ /** Session id of a Session object as a plain string. */
97
+ function sessionIdOf(session) {
98
+ const id = session?.id
99
+ return typeof id === 'string' ? id : String(id ?? '')
100
+ }
101
+
102
+ /** Absolute working directory recorded on a Session, when any. */
103
+ function sessionCwd(session) {
104
+ const cwd = session?.header?.cwd
105
+ return typeof cwd === 'string' && cwd.length > 0 ? cwd : null
106
+ }
107
+
108
+ /**
109
+ * Mount the plugin.
110
+ *
111
+ * @param {object} ctx - Cordis context for this plugin.
112
+ * @param {object} config - composition-row configuration (usually `{}`).
113
+ * @returns {Promise<void>} resolves once the store is loaded and tools are registered.
114
+ */
115
+ export async function apply(ctx, config) {
116
+ /** @type {string[]} */
117
+ const pendingWarnings = []
118
+ const settings = resolveSettings(config, message => {
119
+ // The store is not constructed yet on the first warning; buffer and flush.
120
+ pendingWarnings.push(message)
121
+ })
122
+ const store = new MemoryStore(settings)
123
+ store.load()
124
+ for (const warning of pendingWarnings) store.writeLogLine('warn', warning)
125
+
126
+ // Backfill profile fields on records written before the layers existed. The
127
+ // pass is idempotent and preserves each record's original timestamp.
128
+ const migration = migrateRecords(store)
129
+ if (migration.migrated > 0) store.writeLogLine('info', `migrated ${migration.migrated} records to profile layers`)
130
+
131
+ writeEffectiveConfig(settings)
132
+
133
+ /** @type {Map<string, {text: string, messageId: string, at: number}>} */
134
+ const sessionQueries = new Map()
135
+ /** @type {Map<string, {stampKey: string, at: number, text: string}>} */
136
+ const renderCache = new Map()
137
+ /** @type {Map<object, () => void>} */
138
+ const agentContextDisposers = new Map()
139
+
140
+ const changed = (reason) => {
141
+ // A memory write must be visible on the next step, not only after the next
142
+ // user message, so the per-session render cache is dropped. `search` is
143
+ // exempt: it only bumps a usage counter, and re-rendering on every lookup
144
+ // would churn the request prefix for no benefit.
145
+ if (reason === 'search') return
146
+ renderCache.clear()
147
+ }
148
+
149
+ // ---- tools -------------------------------------------------------------
150
+ const tools = createTools(store, settings, { onChanged: changed, log: message => store.writeLogLine('info', message) })
151
+ for (const tool of tools) {
152
+ try {
153
+ ctx.tools.register(tool)
154
+ } catch (error) {
155
+ store.writeLogLine('error', `failed to register tool ${tool.name}: ${error?.message ?? error}`)
156
+ }
157
+ }
158
+
159
+ // ---- board routes ------------------------------------------------------
160
+ // One snapshot for the initial paint, one SSE stream for live updates, and one
161
+ // mutation endpoint. The board is the only writer besides the tools, so its
162
+ // writes go through applyMutation, which validates fields, enforces optimistic
163
+ // concurrency and stamps an audit source.
164
+ const snapshotHandler = (request, response) => {
165
+ try {
166
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
167
+ response.writeHead(405, { 'allow': 'GET, HEAD', 'content-type': 'application/json; charset=utf-8' })
168
+ response.end(JSON.stringify({ error: 'method not allowed' }))
169
+ return
170
+ }
171
+ const body = JSON.stringify(buildSnapshot(store, settings))
172
+ response.writeHead(200, {
173
+ 'content-type': 'application/json; charset=utf-8',
174
+ 'cache-control': 'no-store',
175
+ 'content-length': Buffer.byteLength(body),
176
+ })
177
+ response.end(request.method === 'HEAD' ? undefined : body)
178
+ } catch (error) {
179
+ store.writeLogLine('error', `snapshot route failed: ${error?.message ?? error}`)
180
+ try {
181
+ response.writeHead(500, { 'content-type': 'application/json; charset=utf-8' })
182
+ response.end(JSON.stringify({ error: String(error?.message ?? error) }))
183
+ } catch {
184
+ // The response may already be gone.
185
+ }
186
+ }
187
+ }
188
+
189
+ const eventsHandler = (request, response) => {
190
+ if (request.method !== 'GET') {
191
+ response.writeHead(405, { 'allow': 'GET', 'content-type': 'application/json; charset=utf-8' })
192
+ response.end(JSON.stringify({ error: 'method not allowed' }))
193
+ return
194
+ }
195
+ response.writeHead(200, {
196
+ 'content-type': 'text/event-stream; charset=utf-8',
197
+ 'cache-control': 'no-store, no-transform',
198
+ connection: 'keep-alive',
199
+ 'x-accel-buffering': 'no',
200
+ })
201
+ response.write('retry: 3000\n\n')
202
+ let closed = false
203
+ let pending
204
+ const send = () => {
205
+ if (closed) return
206
+ try {
207
+ response.write(formatSse('snapshot', JSON.stringify(buildSnapshot(store, settings))))
208
+ } catch {
209
+ closed = true
210
+ }
211
+ }
212
+ // Coalesce a burst of writes into one frame: a consolidation pass touches
213
+ // hundreds of records and must not produce hundreds of snapshots.
214
+ const schedule = () => {
215
+ if (closed || pending !== undefined) return
216
+ pending = setTimeout(() => {
217
+ pending = undefined
218
+ send()
219
+ }, 150)
220
+ pending.unref?.()
221
+ }
222
+ send()
223
+ const unsubscribe = store.subscribe(schedule)
224
+ const heartbeat = setInterval(() => {
225
+ if (closed) return
226
+ try {
227
+ response.write(': ping\n\n')
228
+ } catch {
229
+ closed = true
230
+ }
231
+ }, 20_000)
232
+ heartbeat.unref?.()
233
+ const cleanup = () => {
234
+ if (closed) return
235
+ closed = true
236
+ clearInterval(heartbeat)
237
+ if (pending !== undefined) clearTimeout(pending)
238
+ unsubscribe()
239
+ }
240
+ request.on('close', cleanup)
241
+ response.on('close', cleanup)
242
+ response.on('error', cleanup)
243
+ }
244
+
245
+ const recordHandler = (request, response) => {
246
+ const reply = (status, payload) => {
247
+ try {
248
+ response.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
249
+ response.end(JSON.stringify(payload))
250
+ } catch {
251
+ // The response may already be gone.
252
+ }
253
+ }
254
+ if (request.method !== 'GET') return reply(405, { ok: false, error: 'method not allowed' })
255
+ let id
256
+ try {
257
+ id = new URL(request.url ?? '/', 'http://localhost').searchParams.get('id')
258
+ } catch {
259
+ id = null
260
+ }
261
+ const record = recordView(store, id)
262
+ if (record === undefined) return reply(404, { ok: false, error: `no memory with id ${String(id)}` })
263
+ return reply(200, { ok: true, record })
264
+ }
265
+
266
+ const mutateHandler = async (request, response) => {
267
+ const reply = (status, payload) => {
268
+ try {
269
+ response.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
270
+ response.end(JSON.stringify(payload))
271
+ } catch {
272
+ // The response may already be gone.
273
+ }
274
+ }
275
+ if (request.method !== 'POST') return reply(405, { ok: false, error: 'method not allowed' })
276
+ // Required header makes the request non-simple, so a foreign page cannot
277
+ // mutate the store with a blind cross-origin POST.
278
+ if (request.headers[BOARD_HEADER] !== '1') return reply(403, { ok: false, error: 'missing board header' })
279
+ const contentType = String(request.headers['content-type'] ?? '').split(';')[0].trim().toLowerCase()
280
+ if (contentType !== 'application/json') return reply(415, { ok: false, error: 'content-type must be application/json' })
281
+ const body = await readJsonBody(request, MAX_BODY_BYTES)
282
+ if (body === undefined) return reply(400, { ok: false, error: 'body must be valid JSON under 64 KiB' })
283
+ const result = applyMutation(store, body)
284
+ return reply(result.status, result.payload)
285
+ }
286
+
287
+ // The board needs a webserver, which a headless composition may not mount.
288
+ // `ctx.inject` loads this child only when the service exists, so the memory
289
+ // capability itself never depends on the web surface.
290
+ ctx.inject(['webServer'], (webCtx) => {
291
+ const disposers = []
292
+ try {
293
+ disposers.push(webCtx.webServer.register({ kind: 'exact', path: SNAPSHOT_PATH, handler: snapshotHandler }))
294
+ disposers.push(webCtx.webServer.register({ kind: 'exact', path: EVENTS_PATH, handler: eventsHandler }))
295
+ disposers.push(webCtx.webServer.register({ kind: 'exact', path: RECORD_PATH, handler: recordHandler }))
296
+ disposers.push(webCtx.webServer.register({ kind: 'exact', path: MUTATE_PATH, handler: mutateHandler }))
297
+ store.writeLogLine('info', `board routes registered: ${SNAPSHOT_PATH}, ${EVENTS_PATH}, ${RECORD_PATH}, ${MUTATE_PATH}`)
298
+ } catch (error) {
299
+ store.writeLogLine('warn', `board routes not registered: ${error?.message ?? error}`)
300
+ }
301
+ return () => {
302
+ for (const dispose of disposers) {
303
+ try {
304
+ dispose()
305
+ } catch {
306
+ // Already removed.
307
+ }
308
+ }
309
+ }
310
+ })
311
+
312
+ // ---- per-agent dynamic context ----------------------------------------
313
+ /**
314
+ * Render (or reuse) the memory block for one agent.
315
+ *
316
+ * Pure with respect to the store: this runs during prompt assembly, so it must
317
+ * not append log entries. The result is cached per session until the latest
318
+ * user message changes or the refresh interval elapses, which keeps the
319
+ * request prefix stable for provider cache reuse.
320
+ */
321
+ const memoryBlockFor = (agent) => {
322
+ const session = agent?.session
323
+ const id = sessionIdOf(session)
324
+ const cwd = sessionCwd(session)
325
+ const query = sessionQueries.get(id)
326
+ const stampKey = query?.messageId ?? ''
327
+ const cached = renderCache.get(id)
328
+ if (cached !== undefined && cached.stampKey === stampKey && Date.now() - cached.at < settings.injectRefreshMs) {
329
+ return cached.text
330
+ }
331
+ const { text } = renderMemoryBlock({
332
+ store,
333
+ workspace: cwd,
334
+ workspaceKey: workspaceKey(cwd),
335
+ domain: inferDomain(cwd, settings),
336
+ query: query?.text ?? '',
337
+ maxChars: settings.maxInjectChars,
338
+ limit: settings.injectLimit,
339
+ settings,
340
+ })
341
+ renderCache.set(id, { stampKey, at: Date.now(), text })
342
+ return text
343
+ }
344
+
345
+ ctx.on('agent/created', ({ agent }) => {
346
+ try {
347
+ if (agent === undefined || agent === null || agentContextDisposers.has(agent)) return
348
+ const dispose = ctx.effect(() => agent.ctx.systemPrompt.context({
349
+ name: PROMPT_CONTEXT_NAME,
350
+ order: PROMPT_CONTEXT_ORDER,
351
+ // Memory text is user and file content: never interpolate prompt
352
+ // variables from it, or a stray `{{...}}` would break assembly.
353
+ interpolate: false,
354
+ text: () => {
355
+ try {
356
+ return memoryBlockFor(agent)
357
+ } catch (error) {
358
+ store.writeLogLine('error', `prompt context failed: ${error?.message ?? error}`)
359
+ return ''
360
+ }
361
+ },
362
+ }), 'long-term-memory:prompt-context')
363
+ agentContextDisposers.set(agent, dispose)
364
+ } catch (error) {
365
+ store.writeLogLine('error', `failed to attach prompt context: ${error?.message ?? error}`)
366
+ }
367
+ })
368
+
369
+ ctx.on('agent/disposed', ({ agent }) => {
370
+ try {
371
+ const dispose = agentContextDisposers.get(agent)
372
+ if (dispose === undefined) return
373
+ agentContextDisposers.delete(agent)
374
+ dispose()
375
+ } catch (error) {
376
+ store.writeLogLine('warn', `prompt context cleanup failed: ${error?.message ?? error}`)
377
+ }
378
+ })
379
+
380
+ // ---- automatic extraction from the durable log ------------------------
381
+ /** Capture open todo items as resumable task memories. */
382
+ const captureTasks = (session, todos) => {
383
+ const cwd = sessionCwd(session)
384
+ const key = workspaceKey(cwd)
385
+ const sessionId = sessionIdOf(session)
386
+ const existing = new Map()
387
+ for (const record of store.all()) {
388
+ if (record.kind !== 'task') continue
389
+ if (record.sourceSession !== sessionId) continue
390
+ if ((record.workspaceKey ?? null) !== (key ?? null)) continue
391
+ existing.set(todoKey(record.text), record)
392
+ }
393
+ const plan = planTaskCapture(todos, {
394
+ workspace: key === null ? null : cwd,
395
+ workspaceLabel: cwd === null ? null : workspaceLabel(cwd),
396
+ sessionId,
397
+ source: { kind: 'todo-capture', sessionId },
398
+ }, existing)
399
+ for (const item of plan.upserts) {
400
+ const body = {
401
+ kind: 'task',
402
+ scope: item.scope,
403
+ text: item.text,
404
+ title: item.title,
405
+ status: item.status,
406
+ importance: item.importance,
407
+ tags: item.tags,
408
+ progress: item.progress,
409
+ sourceSession: item.sourceSession,
410
+ source: item.source ?? { kind: 'todo-capture', sessionId },
411
+ confidence: 0.9,
412
+ }
413
+ if (item.existingId !== null) {
414
+ const current = store.get(item.existingId)
415
+ if (current !== undefined && current.status === item.status) continue
416
+ store.update(item.existingId, body)
417
+ } else {
418
+ saveMemory(store, { ...body, workspace: cwd, workspaceLabelFallback: cwd === null ? null : workspaceLabel(cwd) }, {
419
+ workspace: cwd,
420
+ workspaceLabelFallback: cwd === null ? null : workspaceLabel(cwd),
421
+ })
422
+ }
423
+ }
424
+ for (const id of plan.dropped) store.update(id, { status: 'dropped' })
425
+ if (plan.upserts.length > 0 || plan.dropped.length > 0) changed('tasks')
426
+ }
427
+
428
+ ctx.on('session/event', (session, event) => {
429
+ try {
430
+ if (event?.type === 'user/message') {
431
+ const message = event.data
432
+ // Only genuine user input: injected context and other producers must not
433
+ // become the retrieval query or a memory of their own.
434
+ if (message?.source?.kind !== 'user') return
435
+ const text = contentText(message.content)
436
+ if (text.length === 0) return
437
+ const sessionId = sessionIdOf(session)
438
+ sessionQueries.set(sessionId, { text, messageId: String(message.id ?? ''), at: Date.now() })
439
+ if (!settings.autoExtract) return
440
+ for (const memory of extractFromUserMessage(text)) {
441
+ saveMemory(store, {
442
+ ...memory,
443
+ scope: 'global',
444
+ source: { kind: 'auto-extract', sessionId },
445
+ confidence: 0.7,
446
+ }, { workspace: sessionCwd(session), workspaceLabelFallback: null })
447
+ }
448
+ return
449
+ }
450
+ if (event?.type === 'todo/write' && settings.taskCapture) {
451
+ captureTasks(session, event.data?.todos)
452
+ }
453
+ } catch (error) {
454
+ store.writeLogLine('error', `session/event handling failed: ${error?.message ?? error}`)
455
+ }
456
+ })
457
+
458
+ // ---- periodic consolidation -------------------------------------------
459
+ const runConsolidation = (reason) => {
460
+ try {
461
+ const summary = consolidate(store, settings)
462
+ store.writeLogLine('info', `consolidated (${reason}): ${JSON.stringify(summary)}`)
463
+ changed('consolidate')
464
+ return summary
465
+ } catch (error) {
466
+ store.writeLogLine('error', `consolidation failed: ${error?.message ?? error}`)
467
+ return undefined
468
+ }
469
+ }
470
+
471
+ const interval = Math.max(60_000, settings.consolidateIntervalMs)
472
+ const timer = setInterval(() => runConsolidation('timer'), interval)
473
+ timer.unref?.()
474
+ ctx.effect(() => () => clearInterval(timer), 'long-term-memory:consolidation-timer')
475
+
476
+ const kickoff = setTimeout(() => {
477
+ if (dueForConsolidation(store, settings) || store.shouldCompact()) runConsolidation('startup')
478
+ }, 8000)
479
+ kickoff.unref?.()
480
+ ctx.effect(() => () => clearTimeout(kickoff), 'long-term-memory:consolidation-kickoff')
481
+
482
+ store.writeLogLine('info', `mounted: ${store.records.size} records in ${store.dir}`)
483
+ }
package/lib/board.js ADDED
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Board protocol: paths, the mutation contract, and SSE framing.
3
+ *
4
+ * The board is the only writer besides the agent tools, so its writes go through
5
+ * one validated function rather than ad-hoc route code. Two rules make that safe:
6
+ *
7
+ * - **Optimistic concurrency.** A mutation may carry `expectedUpdatedAt`; a
8
+ * mismatch is answered `409` with the current record, so a stale tab can never
9
+ * silently overwrite a newer memory.
10
+ * - **Audit.** Every board write stamps `source: { kind: 'board', at }`, so the
11
+ * append-only log always says who changed a memory and when.
12
+ *
13
+ * @module dsh-long-term-memory/board
14
+ */
15
+
16
+ import { STATUSES } from './records.js'
17
+
18
+ /** Paths the board uses. */
19
+ export const SNAPSHOT_PATH = '/long-term-memory/snapshot'
20
+ export const EVENTS_PATH = '/long-term-memory/events'
21
+ export const MUTATE_PATH = '/long-term-memory/mutate'
22
+ export const RECORD_PATH = '/long-term-memory/record'
23
+
24
+ /**
25
+ * One record, projected for an editor.
26
+ *
27
+ * The snapshot carries truncated text so the stream stays small; an edit needs
28
+ * the exact stored value, and saving a truncated copy would silently destroy the
29
+ * tail of a memory. The editor therefore loads the full record on demand.
30
+ */
31
+ export function recordView(store, id) {
32
+ if (typeof id !== 'string' || id.length === 0) return undefined
33
+ const record = store.get(id)
34
+ if (record === undefined) return undefined
35
+ return {
36
+ id: record.id,
37
+ kind: record.kind ?? 'note',
38
+ layer: record.layer ?? 'persona',
39
+ domain: record.domain ?? null,
40
+ facet: record.facet ?? null,
41
+ status: record.status ?? 'active',
42
+ title: record.title ?? '',
43
+ text: String(record.text ?? ''),
44
+ tags: Array.isArray(record.tags) ? record.tags : [],
45
+ importance: Number(record.importance) || 3,
46
+ pinned: record.pinned === true,
47
+ updatedAt: record.updatedAt ?? 0,
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Header a mutation must carry.
53
+ *
54
+ * It is not a secret: its purpose is to make the request non-simple for CORS, so
55
+ * a browser sends a preflight that this route never approves and a foreign page
56
+ * cannot mutate the store with a blind POST.
57
+ */
58
+ export const BOARD_HEADER = 'x-ltm-request'
59
+
60
+ /** Actions the board may perform. */
61
+ export const BOARD_ACTIONS = ['pin', 'unpin', 'update', 'delete']
62
+
63
+ /** Largest mutation body accepted, in bytes. */
64
+ export const MAX_BODY_BYTES = 64 * 1024
65
+
66
+ /** Fields a board update may set. */
67
+ const PATCHABLE = new Set(['text', 'title', 'status', 'importance', 'pinned', 'tags'])
68
+
69
+ /** Build a JSON response payload for one failure. */
70
+ function failure(status, error, extra = {}) {
71
+ return { status, payload: { ok: false, error, ...extra } }
72
+ }
73
+
74
+ /** Validate and narrow one update patch. */
75
+ function sanitizePatch(raw) {
76
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return { error: 'patch must be an object' }
77
+ const patch = {}
78
+ for (const [key, value] of Object.entries(raw)) {
79
+ if (!PATCHABLE.has(key)) return { error: `field "${key}" cannot be edited from the board` }
80
+ if (key === 'text') {
81
+ if (typeof value !== 'string') return { error: 'text must be a string' }
82
+ const text = value.trim()
83
+ if (text.length === 0) return { error: 'text must not be empty' }
84
+ patch.text = text.slice(0, 4000)
85
+ continue
86
+ }
87
+ if (key === 'title') {
88
+ if (typeof value !== 'string') return { error: 'title must be a string' }
89
+ patch.title = value.trim().slice(0, 120)
90
+ continue
91
+ }
92
+ if (key === 'status') {
93
+ if (!STATUSES.includes(value)) return { error: `unknown status "${String(value)}"` }
94
+ patch.status = value
95
+ continue
96
+ }
97
+ if (key === 'importance') {
98
+ const importance = Number(value)
99
+ if (!Number.isFinite(importance)) return { error: 'importance must be a number' }
100
+ patch.importance = Math.max(1, Math.min(5, Math.trunc(importance)))
101
+ continue
102
+ }
103
+ if (key === 'pinned') {
104
+ if (typeof value !== 'boolean') return { error: 'pinned must be a boolean' }
105
+ patch.pinned = value
106
+ continue
107
+ }
108
+ if (key === 'tags') {
109
+ if (!Array.isArray(value)) return { error: 'tags must be an array' }
110
+ patch.tags = value
111
+ .filter(tag => typeof tag === 'string' && tag.trim().length > 0)
112
+ .map(tag => tag.trim().toLowerCase().slice(0, 40))
113
+ .slice(0, 12)
114
+ }
115
+ }
116
+ return { patch }
117
+ }
118
+
119
+ /**
120
+ * Apply one board mutation.
121
+ *
122
+ * @param {object} store - the memory store.
123
+ * @param {unknown} body - parsed request body.
124
+ * @param {number} [nowValue] - clock, injected for tests.
125
+ * @returns {{status: number, payload: object}} HTTP status and JSON body.
126
+ */
127
+ export function applyMutation(store, body, nowValue = Date.now()) {
128
+ if (body === null || typeof body !== 'object' || Array.isArray(body)) {
129
+ return failure(400, 'body must be a JSON object')
130
+ }
131
+ const action = body.action
132
+ if (!BOARD_ACTIONS.includes(action)) {
133
+ return failure(400, `action must be one of ${BOARD_ACTIONS.join(', ')}`)
134
+ }
135
+ if (typeof body.id !== 'string' || body.id.length === 0) {
136
+ return failure(400, 'id is required')
137
+ }
138
+ const record = store.get(body.id)
139
+ if (record === undefined) {
140
+ return failure(404, `no memory with id ${body.id}`)
141
+ }
142
+
143
+ // Optimistic concurrency: a caller that read the record can say which version it
144
+ // saw. A newer write answers 409 instead of being overwritten.
145
+ if (body.expectedUpdatedAt !== undefined && body.expectedUpdatedAt !== null) {
146
+ const expected = Number(body.expectedUpdatedAt)
147
+ if (!Number.isFinite(expected)) return failure(400, 'expectedUpdatedAt must be a number')
148
+ if (expected !== record.updatedAt) {
149
+ return failure(409, 'the memory changed since it was read', {
150
+ record: { id: record.id, updatedAt: record.updatedAt, text: String(record.text ?? ''), status: record.status },
151
+ })
152
+ }
153
+ }
154
+
155
+ const source = { kind: 'board', at: nowValue }
156
+
157
+ if (action === 'delete') {
158
+ store.remove(body.id)
159
+ return { status: 200, payload: { ok: true, id: body.id, action, deleted: true } }
160
+ }
161
+
162
+ if (action === 'pin' || action === 'unpin') {
163
+ const updated = store.update(body.id, { pinned: action === 'pin', source })
164
+ return { status: 200, payload: { ok: true, id: body.id, action, updatedAt: updated.updatedAt } }
165
+ }
166
+
167
+ const { error, patch } = sanitizePatch(body.patch)
168
+ if (error !== undefined) return failure(400, error)
169
+ if (Object.keys(patch).length === 0) return failure(400, 'patch carries no editable field')
170
+
171
+ const updated = store.update(body.id, { ...patch, source })
172
+ return { status: 200, payload: { ok: true, id: body.id, action, updatedAt: updated.updatedAt } }
173
+ }
174
+
175
+ /** Frame one server-sent event. */
176
+ export function formatSse(event, data) {
177
+ return `event: ${event}\ndata: ${data}\n\n`
178
+ }