@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/lib/extract.js ADDED
@@ -0,0 +1,198 @@
1
+ /**
2
+ * Automatic memory extraction from the durable session log.
3
+ *
4
+ * Two sources, both conservative by design:
5
+ *
6
+ * 1. **Explicit instruction phrases.** A user sentence that asks the agent to
7
+ * remember something ("remember that…", "from now on…", "记住…") becomes a
8
+ * memory. Everything else is left to the agent's explicit `memory_save` call,
9
+ * because silently mining every sentence is how a memory store fills with
10
+ * noise that later pollutes every prompt.
11
+ * 2. **Committee-free task capture.** A `todo/write` event is already the user's
12
+ * and agent's agreed task list, so it is the reliable source for "what was I
13
+ * doing". Open items become `task` memories keyed per workspace and session,
14
+ * which is what makes resuming unfinished work possible after a restart.
15
+ *
16
+ * @module dsh-long-term-memory/extract
17
+ */
18
+
19
+ import { normalizeText, truncate } from './util.js'
20
+
21
+ /**
22
+ * Phrases that mark an explicit request to remember something.
23
+ *
24
+ * These are deliberately narrow. An earlier version matched the bare word
25
+ * "preference" (and the Chinese "偏好"), which meant a structured prompt that
26
+ * merely *talked about* preferences — an agent's own instructions, a spec, a
27
+ * pasted document — was mined for fragments and stored as memories. A trigger
28
+ * must now be phrased as an instruction addressed to the agent: "I prefer…",
29
+ * "always use…", "记住…".
30
+ */
31
+ const MEMORY_TRIGGERS = [
32
+ /\bremember(?:\s+that)?\b/i,
33
+ /\bkeep\s+in\s+mind\b/i,
34
+ /\bfrom\s+now\s+on\b/i,
35
+ /\bgoing\s+forward\b/i,
36
+ /\bnote\s+that\b/i,
37
+ /\bi\s+(?:really\s+)?prefer\b/i,
38
+ /\bi\s+(?:always|never)\s+(?:want|use|prefer|commit|push|write)\b/i,
39
+ /\bplease\s+(?:always|never)\s+/i,
40
+ /\b(?:always|never)\s+(?:use|run|call|commit|push|write|add|avoid|do)\b/i,
41
+ /\bdo\s+not\s+(?:ever\s+)?(?:use|run|call|commit|push|write|add)\b/i,
42
+ /记住|记一下|记下|请记|以后都|以后请|今后|往后|每次都要|每次都|不要再用|不要用|别用|优先用|优先使用|我偏好|务必|严禁|永远不要/,
43
+ ]
44
+
45
+ /** Longest message that may be mined; longer messages are documents, not requests. */
46
+ const MAX_EXTRACT_MESSAGE_CHARS = 4000
47
+
48
+ /** Longest sentence that may become a memory. */
49
+ const MAX_INSTRUCTION_CHARS = 300
50
+
51
+ /**
52
+ * Whether a sentence looks like structured data rather than prose.
53
+ *
54
+ * Pathological case this guards: an agent prompt that lists memory arguments as
55
+ * `kind=`preference`, scope=`global`…` contains an instruction-looking phrase and
56
+ * a lot of punctuation. Storing those fragments pollutes recall, so anything
57
+ * with code spans, assignments or JSON punctuation is skipped.
58
+ */
59
+ function looksStructured(sentence) {
60
+ if (/`[^`]*`/.test(sentence)) return true
61
+ if (/\b(?:kind|scope|tags|importance|status|text|id)\s*=/.test(sentence)) return true
62
+ if (/[{}[\]]/.test(sentence) && /[:=]/.test(sentence)) return true
63
+ if ((sentence.match(/=/g) ?? []).length >= 2) return true
64
+ if (/=>|::|\|\s*\|/.test(sentence)) return true
65
+ // A snake_case identifier names a tool or a parameter. A sentence that names
66
+ // one is meta-instruction addressed to an agent ("do not use todo_write"), not
67
+ // a durable requirement of the user — and storing it would silently change how
68
+ // every future session behaves.
69
+ if (/\b[a-z][a-z0-9]*_[a-z0-9_]+\b/.test(sentence)) return true
70
+ return false
71
+ }
72
+
73
+ /**
74
+ * Meta-vocabulary of instruction written *about* an agent rather than *to the
75
+ * user's benefit*: "do not use any tool other than…", "in the next step…".
76
+ *
77
+ * A sentence containing these is part of an operating procedure (typically a
78
+ * prompt one agent wrote for another), not a durable requirement. Keeping one
79
+ * would silently change how every later session behaves, which is far worse than
80
+ * missing an occasional genuine preference — and the agent can still record that
81
+ * explicitly with `memory_save`.
82
+ */
83
+ const META_VOCABULARY = /\b(?:tool|tools|agent|agents|subagent|subagents|prompt|prompts|session|sessions|step|steps|schema|json)\b|工具|子代理|会话|提示词|步骤/i
84
+
85
+ /** Whether a sentence reads as operating procedure rather than a durable rule. */
86
+ function looksLikeAgentMeta(sentence) {
87
+ return META_VOCABULARY.test(sentence)
88
+ }
89
+
90
+ /** A sentence that only looks like a question is not a durable instruction. */
91
+ function isQuestion(sentence) {
92
+ return /[??]\s*$/.test(sentence)
93
+ }
94
+
95
+ /** Split a message into sentences without pulling in a tokenizer dependency. */
96
+ export function splitSentences(text) {
97
+ return String(text ?? '')
98
+ .split(/(?<=[.!?。!?;;\n])\s*/u)
99
+ .map(part => part.trim())
100
+ .filter(part => part.length > 0)
101
+ }
102
+
103
+ /** Strip the leading conversational filler from a captured instruction. */
104
+ function cleanInstruction(sentence) {
105
+ return sentence
106
+ .replace(/^(?:please\s+|pls\s+|also\s+|ok(?:ay)?[,:]\s*)/i, '')
107
+ .replace(/^(?:请|麻烦|另外|还有|你)[,,::\s]*/u, '')
108
+ .replace(/\s+/g, ' ')
109
+ .trim()
110
+ }
111
+
112
+ /** Whether one sentence is an explicit memory instruction. */
113
+ export function isMemoryInstruction(sentence) {
114
+ if (sentence.length < 6 || sentence.length > MAX_INSTRUCTION_CHARS) return false
115
+ if (isQuestion(sentence)) return false
116
+ if (looksStructured(sentence)) return false
117
+ if (looksLikeAgentMeta(sentence)) return false
118
+ return MEMORY_TRIGGERS.some(pattern => pattern.test(sentence))
119
+ }
120
+
121
+ /**
122
+ * Extract explicit memories from a user message.
123
+ *
124
+ * @param {string} text - the user message text.
125
+ * @param {number} limit - maximum memories to extract from one message.
126
+ * @returns {Array<{text: string, kind: string, title: string, importance: number}>}
127
+ */
128
+ export function extractFromUserMessage(text, limit = 3) {
129
+ const found = []
130
+ const message = String(text ?? '')
131
+ // A long message is a document, a spec or a pasted log, not a spoken request;
132
+ // mining it produces fragments that later pollute every prompt.
133
+ if (message.length > MAX_EXTRACT_MESSAGE_CHARS) return found
134
+ const seen = new Set()
135
+ for (const sentence of splitSentences(message)) {
136
+ if (!isMemoryInstruction(sentence)) continue
137
+ const instruction = cleanInstruction(sentence)
138
+ const key = normalizeText(instruction)
139
+ if (instruction.length < 6 || seen.has(key)) continue
140
+ seen.add(key)
141
+ found.push({
142
+ text: truncate(instruction, 600),
143
+ kind: 'preference',
144
+ title: truncate(instruction, 72),
145
+ importance: 4,
146
+ tags: ['auto-extracted'],
147
+ })
148
+ if (found.length >= limit) break
149
+ }
150
+ return found
151
+ }
152
+
153
+ /** Normalise a todo entry to a stable comparison key. */
154
+ export function todoKey(content) {
155
+ return normalizeText(content).slice(0, 200)
156
+ }
157
+
158
+ /**
159
+ * Derive task-memory writes from one `todo/write` snapshot.
160
+ *
161
+ * @param {object[]} todos - the committed todo list.
162
+ * @param {object} context - capture context.
163
+ * @param {string|null} context.workspace - absolute workspace directory.
164
+ * @param {string|null} context.workspaceLabel - display name of the workspace.
165
+ * @param {object} existing - existing task records for this session.
166
+ * @returns {{upserts: object[], dropped: string[]}} planned changes.
167
+ */
168
+ export function planTaskCapture(todos, context, existing) {
169
+ const present = new Set()
170
+ const upserts = []
171
+ for (const todo of Array.isArray(todos) ? todos : []) {
172
+ const content = String(todo?.content ?? '').trim()
173
+ if (content.length === 0) continue
174
+ const key = todoKey(content)
175
+ if (present.has(key)) continue
176
+ present.add(key)
177
+ const status = todo.status === 'completed' ? 'done' : todo.status === 'in_progress' ? 'open' : 'open'
178
+ const previous = existing.get(key)
179
+ upserts.push({
180
+ existingId: previous?.id ?? null,
181
+ kind: 'task',
182
+ scope: context.workspace === null ? 'global' : 'workspace',
183
+ text: content,
184
+ title: truncate(content, 120),
185
+ status,
186
+ importance: todo.status === 'in_progress' ? 4 : 3,
187
+ tags: ['todo'],
188
+ progress: todo.status,
189
+ sourceSession: context.sessionId ?? null,
190
+ source: previous?.source ?? context.source ?? null,
191
+ })
192
+ }
193
+ const dropped = []
194
+ for (const [key, record] of existing) {
195
+ if (!present.has(key) && (record.status === 'open' || record.status === 'blocked')) dropped.push(record.id)
196
+ }
197
+ return { upserts, dropped }
198
+ }
package/lib/profile.js ADDED
@@ -0,0 +1,167 @@
1
+ /**
2
+ * Profile synthesis: turning evidence records into bounded, readable profiles.
3
+ *
4
+ * This is the layer that makes "memory" into a "profile". Facts accumulate; a
5
+ * profile is the distilled, conflict-free, size-bounded description of a person
6
+ * or a field of work, recomputed from those facts.
7
+ *
8
+ * Synthesis is deterministic on purpose: no model call in the request path, the
9
+ * same store always produces the same profile, and every line is traceable to a
10
+ * record id that can be corrected or removed.
11
+ *
12
+ * @module dsh-long-term-memory/profile
13
+ */
14
+
15
+ import { containment, tokenSet } from './retrieval.js'
16
+ import { defaultFacet, facetsOf, FACET_LABELS, inferLayer, isDomain, normalizeDomain } from './domains.js'
17
+ import { truncate } from './util.js'
18
+
19
+ /** Two lines saying the same thing are collapsed above this containment. */
20
+ const DEDUPE_THRESHOLD = 0.9
21
+
22
+ /** Maximum lines kept per facet, so one chatty facet cannot crowd the profile. */
23
+ const MAX_ITEMS_PER_FACET = 4
24
+
25
+ /** Whether a record is strong enough to enter a profile. */
26
+ export function isProfileEligible(record, layer, settings) {
27
+ if (record.layer !== layer) return false
28
+ if (record.status !== 'active') return false
29
+ if (record.pinned === true) return true
30
+ if ((Number(record.confirmations) || 1) >= 2) return true
31
+ const floor = layer === 'persona'
32
+ ? Number(settings?.personaMinImportance ?? 4)
33
+ : Number(settings?.workMinImportance ?? 3)
34
+ return (Number(record.importance) || 3) >= floor
35
+ }
36
+
37
+ /** Display order index of a facet within its layer. */
38
+ function facetOrder(layer, facet) {
39
+ const order = facetsOf(layer)
40
+ const index = order.indexOf(facet)
41
+ return index < 0 ? order.length : index
42
+ }
43
+
44
+ /** Rank one record inside its facet: pinned first, then importance, recency, reuse. */
45
+ function compareRecords(left, right) {
46
+ const pinned = (right.pinned === true ? 1 : 0) - (left.pinned === true ? 1 : 0)
47
+ if (pinned !== 0) return pinned
48
+ const importance = (Number(right.importance) || 3) - (Number(left.importance) || 3)
49
+ if (importance !== 0) return importance
50
+ const updated = (right.updatedAt ?? 0) - (left.updatedAt ?? 0)
51
+ if (updated !== 0) return updated
52
+ return (Number(right.useCount) || 0) - (Number(left.useCount) || 0)
53
+ }
54
+
55
+ /**
56
+ * Build one profile document.
57
+ *
58
+ * @param {object} store - the memory store.
59
+ * @param {object} options - profile request.
60
+ * @param {'persona'|'work'} options.layer - which profile.
61
+ * @param {string} [options.domain] - required for the `work` layer.
62
+ * @param {object} options.settings - resolved settings (admission thresholds).
63
+ * @param {number} [options.maxChars] - character budget.
64
+ * @returns {{text: string, ids: string[], count: number, facets: string[]}}
65
+ */
66
+ export function buildProfile(store, options) {
67
+ const { layer, domain, settings, maxChars = 600 } = options
68
+ if (layer !== 'persona' && layer !== 'work') return { text: '', ids: [], entries: [], count: 0, facets: [] }
69
+ const wantedDomain = layer === 'work' ? normalizeDomain(domain) : null
70
+
71
+ /** @type {Map<string, object[]>} */
72
+ const byFacet = new Map()
73
+ for (const record of store.all()) {
74
+ if (!isProfileEligible(record, layer, settings)) continue
75
+ if (layer === 'work' && normalizeDomain(record.domain) !== wantedDomain) continue
76
+ const facet = record.facet ?? defaultFacet(layer, record.kind, record.text)
77
+ const bucket = byFacet.get(facet) ?? []
78
+ bucket.push({ record, facet })
79
+ byFacet.set(facet, bucket)
80
+ }
81
+ if (byFacet.size === 0) return { text: '', ids: [], entries: [], count: 0, facets: [] }
82
+
83
+ const facets = [...byFacet.keys()].sort((left, right) => facetOrder(layer, left) - facetOrder(layer, right))
84
+ const lines = []
85
+ const entries = []
86
+ const ids = []
87
+ let used = 0
88
+ for (const facet of facets) {
89
+ const kept = []
90
+ const seen = []
91
+ for (const entry of [...byFacet.get(facet)].sort((left, right) => compareRecords(left.record, right.record))) {
92
+ const tokens = tokenSet(entry.record.text)
93
+ if (seen.some(other => containment(tokens, other) >= DEDUPE_THRESHOLD)) continue
94
+ seen.push(tokens)
95
+ kept.push(entry.record)
96
+ if (kept.length >= MAX_ITEMS_PER_FACET) break
97
+ }
98
+ for (const record of kept) {
99
+ const label = FACET_LABELS[facet] ?? facet
100
+ // Profile lines are deliberately shorter than record lines: a profile is a
101
+ // scannable summary, and a 300-character sentence would consume the whole
102
+ // section budget while showing exactly one item.
103
+ const text = truncate(String(record.text ?? '').replace(/\s+/g, ' ').trim(), 140)
104
+ const line = `- ${label}: ${text} (id: ${record.id})`
105
+ if (used + line.length + 1 > maxChars) {
106
+ return { text: lines.join('\n'), ids, entries, count: ids.length, facets }
107
+ }
108
+ lines.push(line)
109
+ entries.push({
110
+ id: record.id,
111
+ facet,
112
+ label,
113
+ text,
114
+ // The board needs a version for optimistic concurrency on pin/unpin.
115
+ updatedAt: record.updatedAt ?? 0,
116
+ importance: record.importance ?? 3,
117
+ pinned: record.pinned === true,
118
+ })
119
+ ids.push(record.id)
120
+ used += line.length + 1
121
+ }
122
+ }
123
+ return { text: lines.join('\n'), ids, entries, count: ids.length, facets }
124
+ }
125
+
126
+ /**
127
+ * Backfill the profile fields on records written before the profile layers
128
+ * existed.
129
+ *
130
+ * Idempotent: records that already carry a `layer` are skipped. The original
131
+ * `updatedAt` is preserved so a migration does not make every old memory look
132
+ * freshly written.
133
+ *
134
+ * @param {object} store - the memory store.
135
+ * @returns {{migrated: number}}
136
+ */
137
+ export function migrateRecords(store) {
138
+ let migrated = 0
139
+ for (const record of store.all()) {
140
+ if (typeof record.layer === 'string') continue
141
+ const domain = isDomain(record.domain) ? record.domain : null
142
+ const layer = inferLayer(record.kind, record.scope, domain, record.text)
143
+ store.update(record.id, {
144
+ layer,
145
+ domain: layer === 'work' ? normalizeDomain(domain) : null,
146
+ facet: defaultFacet(layer, record.kind, record.text),
147
+ pinned: record.pinned === true,
148
+ confirmations: Number(record.confirmations) || 1,
149
+ updatedAt: record.updatedAt,
150
+ })
151
+ migrated += 1
152
+ }
153
+ return { migrated }
154
+ }
155
+
156
+ /** Summary of every profile, for the admin tool and diagnostics. */
157
+ export function profileSummary(store, settings, domains) {
158
+ const rows = []
159
+ const persona = buildProfile(store, { layer: 'persona', settings, maxChars: 10_000 })
160
+ rows.push({ layer: 'persona', domain: null, lines: persona.count, facets: persona.facets })
161
+ for (const domain of domains) {
162
+ const work = buildProfile(store, { layer: 'work', domain, settings, maxChars: 10_000 })
163
+ if (work.count === 0) continue
164
+ rows.push({ layer: 'work', domain, lines: work.count, facets: work.facets })
165
+ }
166
+ return rows
167
+ }
package/lib/records.js ADDED
@@ -0,0 +1,197 @@
1
+ /**
2
+ * Record shapes, normalisation, and duplicate-aware writes.
3
+ *
4
+ * Every memory is one plain JSON record. Writing goes through
5
+ * {@link saveMemory}, which merges near-identical records instead of appending
6
+ * duplicates — the main source of memory-store rot when an agent saves the same
7
+ * preference in several sessions.
8
+ *
9
+ * @module dsh-long-term-memory/records
10
+ */
11
+
12
+ import { normalizeText, truncate, workspaceKey } from './util.js'
13
+ import { containment, tokenSet } from './retrieval.js'
14
+ import { defaultFacet, inferLayer, isDomain, LAYERS, normalizeDomain, normalizeFacet } from './domains.js'
15
+
16
+ /** Memory kinds the plugin recognises. */
17
+ export const KINDS = ['preference', 'project', 'decision', 'solution', 'fact', 'task', 'capability', 'note']
18
+
19
+ /** Statuses a record may hold. */
20
+ export const STATUSES = ['active', 'open', 'blocked', 'done', 'superseded', 'dropped', 'archived']
21
+
22
+ /** Completion states valid for `task` records. */
23
+ export const TASK_STATUSES = ['open', 'blocked', 'done', 'dropped']
24
+
25
+ /** Default status per kind. */
26
+ export function defaultStatus(kind) {
27
+ return kind === 'task' ? 'open' : 'active'
28
+ }
29
+
30
+ /** Human-facing label of one record, used in injected context and tool output. */
31
+ export function recordLabel(record) {
32
+ const title = typeof record.title === 'string' && record.title.trim().length > 0
33
+ ? record.title.trim()
34
+ : truncate(String(record.text ?? '').replace(/\s+/g, ' ').trim(), 80)
35
+ return title
36
+ }
37
+
38
+ /** Normalise a tag list: lowercase, trimmed, unique, bounded. */
39
+ export function normalizeTags(tags) {
40
+ if (!Array.isArray(tags)) return []
41
+ const seen = new Set()
42
+ const result = []
43
+ for (const raw of tags) {
44
+ if (typeof raw !== 'string') continue
45
+ const tag = raw.trim().toLowerCase().slice(0, 40)
46
+ if (tag.length === 0 || seen.has(tag)) continue
47
+ seen.add(tag)
48
+ result.push(tag)
49
+ if (result.length >= 12) break
50
+ }
51
+ return result
52
+ }
53
+
54
+ /**
55
+ * Build a record body from caller input.
56
+ *
57
+ * `scope: 'auto'` means: a workspace is known and the kind is workspace-shaped
58
+ * (`project`, `task`, `solution`) → workspace-scoped; otherwise global. An
59
+ * explicit `scope` always wins.
60
+ */
61
+ export function buildRecord(input, context) {
62
+ const { workspace = null, workspaceLabelFallback = null } = context ?? {}
63
+ const text = String(input.text ?? '').trim()
64
+ if (text.length === 0) throw new Error('memory text must not be empty')
65
+ const kind = KINDS.includes(input.kind) ? input.kind : 'note'
66
+ const requestedScope = input.scope === 'global' || input.scope === 'workspace' ? input.scope : 'auto'
67
+ const workspaceShaped = kind === 'project' || kind === 'task' || kind === 'solution'
68
+ const scopedToWorkspace = requestedScope === 'workspace' || (requestedScope === 'auto' && workspaceShaped)
69
+ const key = scopedToWorkspace ? workspaceKey(workspace) : null
70
+ const effectiveScope = key === null ? 'global' : 'workspace'
71
+ const status = STATUSES.includes(input.status) ? input.status : defaultStatus(kind)
72
+ const requestedLayer = LAYERS.includes(input.layer) ? input.layer : undefined
73
+ const domainHint = isDomain(input.domain) ? input.domain : undefined
74
+ const layer = requestedLayer ?? inferLayer(kind, key === null ? 'global' : 'workspace', domainHint, text)
75
+ // A work-layer record always carries a domain, defaulting to `general` so the
76
+ // profile for that domain is complete rather than silently missing entries.
77
+ const domain = layer === 'work' ? normalizeDomain(domainHint) : null
78
+ const facet = normalizeFacet(layer, input.facet) ?? defaultFacet(layer, kind, text)
79
+ return {
80
+ kind,
81
+ layer,
82
+ domain,
83
+ facet,
84
+ pinned: input.pinned === true,
85
+ confirmations: Math.max(1, Number(input.confirmations) || 1),
86
+ scope: effectiveScope,
87
+ workspace: effectiveScope === 'workspace' ? workspace : null,
88
+ workspaceKey: key,
89
+ workspaceLabel: effectiveScope === 'workspace' ? (workspaceLabelFallback ?? null) : null,
90
+ title: typeof input.title === 'string' && input.title.trim().length > 0
91
+ ? truncate(input.title.trim(), 120)
92
+ : truncate(text.replace(/\s+/g, ' ').trim(), 72),
93
+ text: truncate(text, 4000),
94
+ tags: normalizeTags(input.tags),
95
+ importance: Math.max(1, Math.min(5, Number(input.importance) || 3)),
96
+ status,
97
+ confidence: Math.max(0, Math.min(1, Number(input.confidence) || 0.8)),
98
+ useCount: 0,
99
+ lastUsedAt: null,
100
+ source: input.source ?? null,
101
+ // Task identity. Carried through explicitly: task capture keys records by the
102
+ // session that produced the todo list, and without `sourceSession` on the
103
+ // stored record the next snapshot cannot find its own tasks to update or drop.
104
+ sourceSession: typeof input.sourceSession === 'string' ? input.sourceSession : null,
105
+ progress: typeof input.progress === 'string' ? input.progress : null,
106
+ supersedes: null,
107
+ mergedInto: null,
108
+ }
109
+ }
110
+
111
+ /** Containment above which two records are treated as the same memory. */
112
+ const DUPLICATE_THRESHOLD = 0.95
113
+
114
+ /**
115
+ * Find an existing record that already says the same thing.
116
+ *
117
+ * Matching is scoped to the same kind, status family and partition, so a global
118
+ * preference never absorbs a project-specific fact.
119
+ */
120
+ export function findDuplicate(store, candidate) {
121
+ const candidateTokens = tokenSet(`${candidate.title} ${candidate.text}`)
122
+ const candidateText = normalizeText(candidate.text)
123
+ let best
124
+ let bestScore = 0
125
+ for (const record of store.all()) {
126
+ if (record.kind !== candidate.kind) continue
127
+ if (record.scope !== candidate.scope) continue
128
+ // Layer and domain are part of identity: the same sentence as personal
129
+ // knowledge and as a development convention are two different memories.
130
+ if ((record.layer ?? null) !== (candidate.layer ?? null)) continue
131
+ if (candidate.layer === 'work' && normalizeDomain(record.domain) !== normalizeDomain(candidate.domain)) continue
132
+ if (record.scope === 'workspace' && record.workspaceKey !== candidate.workspaceKey) continue
133
+ // Tasks are per-session work items: the same wording in another session is a
134
+ // different piece of work, not a duplicate to merge into.
135
+ if (candidate.kind === 'task' && (record.sourceSession ?? null) !== (candidate.sourceSession ?? null)) continue
136
+ if (normalizeText(record.text) === candidateText) return record
137
+ const score = containment(candidateTokens, tokenSet(`${record.title} ${record.text}`))
138
+ if (score > bestScore) {
139
+ bestScore = score
140
+ best = record
141
+ }
142
+ }
143
+ return bestScore >= DUPLICATE_THRESHOLD ? best : undefined
144
+ }
145
+
146
+ /**
147
+ * Save a memory, merging into an existing near-duplicate when one exists.
148
+ *
149
+ * A merge refreshes the durable record (text, tags, importance, status) rather
150
+ * than writing a second copy, which keeps retrieval results clean and makes the
151
+ * store self-healing under repeated agent saves.
152
+ *
153
+ * @returns {{record: object, merged: boolean}}
154
+ */
155
+ export function saveMemory(store, input, context) {
156
+ const candidate = buildRecord(input, context)
157
+ const duplicate = findDuplicate(store, candidate)
158
+ if (duplicate === undefined) {
159
+ return { record: store.put(candidate), merged: false }
160
+ }
161
+ const mergedTags = normalizeTags([...(duplicate.tags ?? []), ...(candidate.tags ?? [])])
162
+ const record = store.update(duplicate.id, {
163
+ title: candidate.title.length > (duplicate.title ?? '').length ? candidate.title : duplicate.title,
164
+ text: candidate.text.length >= (duplicate.text ?? '').length ? candidate.text : duplicate.text,
165
+ tags: mergedTags,
166
+ importance: Math.max(Number(duplicate.importance) || 3, candidate.importance),
167
+ status: candidate.status,
168
+ confidence: Math.max(Number(duplicate.confidence) || 0.8, candidate.confidence),
169
+ // Restating a memory is a confirmation of it, which is what lets a record
170
+ // earn its way into the persona profile without an explicit pin.
171
+ confirmations: (Number(duplicate.confirmations) || 1) + 1,
172
+ pinned: duplicate.pinned === true || candidate.pinned === true,
173
+ facet: duplicate.pinned === true ? (duplicate.facet ?? candidate.facet) : candidate.facet,
174
+ source: candidate.source ?? duplicate.source ?? null,
175
+ })
176
+ return { record, merged: true }
177
+ }
178
+
179
+ /** Record the fact that a memory was actually used to answer something. */
180
+ export function markUsed(store, ids) {
181
+ const timestamp = Date.now()
182
+ for (const id of ids) {
183
+ const record = store.get(id)
184
+ if (record === undefined) continue
185
+ store.update(id, {
186
+ useCount: (Number(record.useCount) || 0) + 1,
187
+ lastUsedAt: timestamp,
188
+ })
189
+ }
190
+ }
191
+
192
+ /** Compact one budgeted line for injected context. */
193
+ export function formatLine(record, maxText = 220) {
194
+ const status = record.status && record.status !== 'active' ? ` (${record.status})` : ''
195
+ const kind = record.kind ?? 'note'
196
+ return `- [${kind}${status}] ${truncate(String(record.text ?? '').replace(/\s+/g, ' ').trim(), maxText)} (id: ${record.id})`
197
+ }