@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,131 @@
1
+ // Configuration defaults and normalization. Pure: no DSH imports, so tests run
2
+ // in CI without the harness installed.
3
+
4
+ import { homedir } from 'node:os'
5
+ import { join } from 'node:path'
6
+
7
+ export const DEFAULT_CONFIG = Object.freeze({
8
+ storage: { root: '', maxNoteBytes: 8192, maxNotes: 200 },
9
+ spaces: { global: false },
10
+ extract: { enabled: true, minNewChars: 1500, model: '', maxPerTurn: 3 },
11
+ recall: { enabled: true, strategy: 'lexical', topK: 3, maxNoteBytes: 4096, sessionBudgetBytes: 40960, timeoutMs: 400, llmTimeoutMs: 2000 },
12
+ dream: {
13
+ enabled: true,
14
+ minHours: 24,
15
+ minSessions: 5,
16
+ maxNotes: 60,
17
+ maxDeletes: 5,
18
+ model: '',
19
+ agent: true,
20
+ provider: 'spawn',
21
+ agentModel: '',
22
+ agentTimeoutMs: 180000,
23
+ backoffMinutes: 60,
24
+ },
25
+ memoryMd: {
26
+ enabled: true,
27
+ maxEntries: 100,
28
+ maxLineChars: 240,
29
+ maxChars: 12000,
30
+ inject: true,
31
+ injectMaxEntries: 20,
32
+ injectMaxChars: 2000,
33
+ },
34
+ ui: { enabled: true },
35
+ })
36
+
37
+ function number(value, fallback, { min = 0, max = Number.MAX_SAFE_INTEGER } = {}) {
38
+ const parsed = typeof value === 'number' ? value : Number(value)
39
+ if (!Number.isFinite(parsed)) return fallback
40
+ return Math.min(max, Math.max(min, Math.trunc(parsed)))
41
+ }
42
+
43
+ function bool(value, fallback) {
44
+ return typeof value === 'boolean' ? value : fallback
45
+ }
46
+
47
+ function text(value, fallback) {
48
+ return typeof value === 'string' ? value : fallback
49
+ }
50
+
51
+ /** Merge user config over defaults, dropping values that make no sense. */
52
+ export function normalizeConfig(raw) {
53
+ const input = raw ?? {}
54
+ const storage = input.storage ?? {}
55
+ const spaces = input.spaces ?? {}
56
+ const extract = input.extract ?? {}
57
+ const recall = input.recall ?? {}
58
+ const dream = input.dream ?? {}
59
+ const memoryMd = input.memoryMd ?? {}
60
+ const ui = input.ui ?? {}
61
+ return {
62
+ storage: {
63
+ root: text(storage.root, DEFAULT_CONFIG.storage.root),
64
+ maxNoteBytes: number(storage.maxNoteBytes, DEFAULT_CONFIG.storage.maxNoteBytes, {
65
+ min: 512,
66
+ max: 262144,
67
+ }),
68
+ maxNotes: number(storage.maxNotes, DEFAULT_CONFIG.storage.maxNotes, { min: 10, max: 2000 }),
69
+ },
70
+ spaces: {
71
+ global: bool(spaces.global, DEFAULT_CONFIG.spaces.global),
72
+ },
73
+ extract: {
74
+ enabled: bool(extract.enabled, DEFAULT_CONFIG.extract.enabled),
75
+ minNewChars: number(extract.minNewChars, DEFAULT_CONFIG.extract.minNewChars, { min: 0, max: 200000 }),
76
+ model: text(extract.model, DEFAULT_CONFIG.extract.model),
77
+ maxPerTurn: number(extract.maxPerTurn, DEFAULT_CONFIG.extract.maxPerTurn, { min: 1, max: 10 }),
78
+ },
79
+ recall: {
80
+ enabled: bool(recall.enabled, DEFAULT_CONFIG.recall.enabled),
81
+ strategy: recall.strategy === 'llm' ? 'llm' : DEFAULT_CONFIG.recall.strategy,
82
+ topK: number(recall.topK, DEFAULT_CONFIG.recall.topK, { min: 1, max: 10 }),
83
+ maxNoteBytes: number(recall.maxNoteBytes, DEFAULT_CONFIG.recall.maxNoteBytes, { min: 512, max: 16384 }),
84
+ sessionBudgetBytes: number(recall.sessionBudgetBytes, DEFAULT_CONFIG.recall.sessionBudgetBytes, {
85
+ min: 1024,
86
+ max: 1048576,
87
+ }),
88
+ timeoutMs: number(recall.timeoutMs, DEFAULT_CONFIG.recall.timeoutMs, { min: 50, max: 5000 }),
89
+ llmTimeoutMs: number(recall.llmTimeoutMs, DEFAULT_CONFIG.recall.llmTimeoutMs, { min: 200, max: 30000 }),
90
+ },
91
+ memoryMd: {
92
+ enabled: bool(memoryMd.enabled, DEFAULT_CONFIG.memoryMd.enabled),
93
+ maxEntries: number(memoryMd.maxEntries, DEFAULT_CONFIG.memoryMd.maxEntries, { min: 1, max: 1000 }),
94
+ maxLineChars: number(memoryMd.maxLineChars, DEFAULT_CONFIG.memoryMd.maxLineChars, { min: 40, max: 2000 }),
95
+ maxChars: number(memoryMd.maxChars, DEFAULT_CONFIG.memoryMd.maxChars, { min: 200, max: 200000 }),
96
+ inject: bool(memoryMd.inject, DEFAULT_CONFIG.memoryMd.inject),
97
+ injectMaxEntries: number(memoryMd.injectMaxEntries, DEFAULT_CONFIG.memoryMd.injectMaxEntries, { min: 1, max: 200 }),
98
+ injectMaxChars: number(memoryMd.injectMaxChars, DEFAULT_CONFIG.memoryMd.injectMaxChars, { min: 200, max: 20000 }),
99
+ },
100
+ dream: {
101
+ enabled: bool(dream.enabled, DEFAULT_CONFIG.dream.enabled),
102
+ minHours: number(dream.minHours, DEFAULT_CONFIG.dream.minHours, { min: 1, max: 8760 }),
103
+ minSessions: number(dream.minSessions, DEFAULT_CONFIG.dream.minSessions, { min: 1, max: 1000 }),
104
+ maxNotes: number(dream.maxNotes, DEFAULT_CONFIG.dream.maxNotes, { min: 1, max: 500 }),
105
+ maxDeletes: number(dream.maxDeletes, DEFAULT_CONFIG.dream.maxDeletes, { min: 0, max: 100 }),
106
+ model: text(dream.model, DEFAULT_CONFIG.dream.model),
107
+ agent: bool(dream.agent, DEFAULT_CONFIG.dream.agent),
108
+ provider: text(dream.provider, DEFAULT_CONFIG.dream.provider),
109
+ agentModel: text(dream.agentModel, DEFAULT_CONFIG.dream.agentModel),
110
+ agentTimeoutMs: number(dream.agentTimeoutMs, DEFAULT_CONFIG.dream.agentTimeoutMs, {
111
+ min: 5000,
112
+ max: 1800000,
113
+ }),
114
+ backoffMinutes: number(dream.backoffMinutes, DEFAULT_CONFIG.dream.backoffMinutes, {
115
+ min: 0,
116
+ max: 1440,
117
+ }),
118
+ },
119
+ ui: {
120
+ enabled: bool(ui.enabled, DEFAULT_CONFIG.ui.enabled),
121
+ },
122
+ }
123
+ }
124
+
125
+ /** Absolute memory root: explicit config wins, then $DSH_HOME, then ~/.dsh. */
126
+ export function resolveStorageRoot(config, env = process.env, home = homedir()) {
127
+ const configured = text(config?.storage?.root, '').trim()
128
+ if (configured !== '') return configured
129
+ const dshHome = text(env?.DSH_HOME, '').trim()
130
+ return join(dshHome !== '' ? dshHome : join(home, '.dsh'), 'dsh-memory')
131
+ }
@@ -0,0 +1,121 @@
1
+ // Conversation digest for end-of-turn extraction.
2
+ //
3
+ // The harness logs every model-visible message as a durable session event
4
+ // `{seq, type, data}`. We keep a bounded in-memory window per session and fold
5
+ // only user/assistant text — never reasoning, tool payloads, or images — so the
6
+ // extraction request stays small and free of secrets that live in tool output.
7
+ //
8
+ // The window budget is measured in UTF-8 bytes (`maxBytes`), so `digestChars`
9
+ // reports the retained byte size. Extraction thresholds are configured in
10
+ // characters, so `digestCharsSince` counts characters newer than a cursor.
11
+ //
12
+ // In-memory state is a cache, not authority: a resumed session simply starts
13
+ // with a fresh window, and extraction waits for the next turns.
14
+
15
+ export const DIGEST_STATE_VERSION = 1
16
+ export const DEFAULT_DIGEST_MAX_BYTES = 16384
17
+
18
+ export function createDigest({ maxBytes = DEFAULT_DIGEST_MAX_BYTES } = {}) {
19
+ const limit = Number.isFinite(maxBytes) ? Math.max(0, Math.trunc(maxBytes)) : DEFAULT_DIGEST_MAX_BYTES
20
+ return { entries: [], bytes: 0, maxBytes: limit }
21
+ }
22
+
23
+ function blocksToText(content) {
24
+ if (typeof content === 'string') return content.trim()
25
+ if (!Array.isArray(content)) return ''
26
+ const parts = []
27
+ for (const block of content) {
28
+ if (block === null || typeof block !== 'object') continue
29
+ if (block.type !== 'text' || typeof block.text !== 'string') continue
30
+ const text = block.text.trim()
31
+ if (text !== '') parts.push(text)
32
+ }
33
+ return parts.join('\n')
34
+ }
35
+
36
+ function entriesOf(state) {
37
+ return state !== null && typeof state === 'object' && Array.isArray(state.entries) ? state.entries : []
38
+ }
39
+
40
+ function byteLength(text) {
41
+ return Buffer.byteLength(text, 'utf8')
42
+ }
43
+
44
+ /** Append one session event; returns the same state when the event is ignored. */
45
+ export function appendDigest(state, event) {
46
+ if (state === null || typeof state !== 'object' || !Array.isArray(state.entries)) return state
47
+ if (event === null || typeof event !== 'object') return state
48
+ const type = event.type
49
+ if (type !== 'user/message' && type !== 'assistant/message') return state
50
+ const data = event.data ?? {}
51
+ // Never feed our own recall block back into the extraction prompt: it would be
52
+ // re-summarised into a new note and grow a little every turn.
53
+ const source = data.source ?? data.message?.source
54
+ if (source !== null && typeof source === 'object' && source.kind === 'dsh-memory') return state
55
+ const text = blocksToText(data.content ?? data.message?.content)
56
+ if (text === '' || text.startsWith('<memory-context>')) return state
57
+ const entry = {
58
+ role: type === 'user/message' ? 'user' : 'assistant',
59
+ seq: typeof event.seq === 'number' && Number.isFinite(event.seq) ? event.seq : null,
60
+ text,
61
+ }
62
+ const maxBytes = Number.isFinite(state.maxBytes) ? state.maxBytes : DEFAULT_DIGEST_MAX_BYTES
63
+ const entries = [...state.entries, entry]
64
+ let bytes = (Number.isFinite(state.bytes) ? state.bytes : 0) + byteLength(text)
65
+ while (bytes > maxBytes && entries.length > 1) {
66
+ const dropped = entries.shift()
67
+ bytes -= byteLength(dropped.text)
68
+ }
69
+ return { entries, bytes, maxBytes }
70
+ }
71
+
72
+ /** Render entries as plain conversation text, keeping the newest `maxChars`. */
73
+ function renderEntries(entries, { maxChars = 8000 } = {}) {
74
+ if (!Array.isArray(entries) || entries.length === 0) return ''
75
+ const lines = []
76
+ for (const entry of entries) {
77
+ if (entry === null || typeof entry !== 'object' || typeof entry.text !== 'string') continue
78
+ const label = entry.role === 'user' ? 'User' : 'Assistant'
79
+ lines.push(`${label}: ${entry.text}`)
80
+ }
81
+ const text = lines.join('\n\n')
82
+ const limit = Number.isFinite(maxChars) ? Math.max(0, Math.trunc(maxChars)) : 8000
83
+ if (limit === 0) return ''
84
+ return text.length > limit ? text.slice(text.length - limit) : text
85
+ }
86
+
87
+ /** Render the window as plain conversation text for the extraction prompt. */
88
+ export function digestText(state, options = {}) {
89
+ return renderEntries(entriesOf(state), options)
90
+ }
91
+
92
+ /**
93
+ * Render only the conversation newer than `seq` (the last extraction cursor).
94
+ * Incremental extraction sends this tail instead of the whole retained window.
95
+ */
96
+ export function digestTextSince(state, seq, options = {}) {
97
+ return renderEntries(digestSince(state, seq), options)
98
+ }
99
+
100
+ /** Retained window size in bytes (the unit of the `maxBytes` budget). */
101
+ export function digestChars(state) {
102
+ return entriesOf(state).reduce((sum, entry) => sum + byteLength(entry.text), 0)
103
+ }
104
+
105
+ export function lastSeq(state) {
106
+ const entries = entriesOf(state)
107
+ if (entries.length === 0) return null
108
+ return entries[entries.length - 1].seq
109
+ }
110
+
111
+ /** Split the window into the part already extracted and the new tail. */
112
+ export function digestSince(state, seq) {
113
+ const entries = entriesOf(state)
114
+ if (seq === null || seq === undefined) return entries
115
+ return entries.filter(entry => entry.seq !== null && entry.seq > seq)
116
+ }
117
+
118
+ /** Characters of conversation newer than a cursor; the unit of `minNewChars`. */
119
+ export function digestCharsSince(state, seq) {
120
+ return digestSince(state, seq).reduce((sum, entry) => sum + entry.text.length, 0)
121
+ }
@@ -0,0 +1,385 @@
1
+ // /dream —— 手工跨会话记忆整理,只包含纯逻辑,不接宿主。
2
+ //
3
+ // 宿主(index.js,由 Lead 装配)在 `/dream` 命令 handler 里调用
4
+ // buildDreamPrompt 生成一段提示,通过 `agent.followup(...)` 发进当前会话;
5
+ // 模型随后用 memory_note / memory_forget / 文件工具完成整理。整理结果由宿主
6
+ // 从工具调用里汇总,再交给 summarizeDreamApply 渲染成一行命令回执。
7
+ //
8
+ // 本模块不 import 任何 @deepseek-ai/*,也不读写磁盘:sessionQuery 由调用方
9
+ // 传入,提示文本与回执都是纯函数,因此在没有 DSH 的环境里可以直接测试。
10
+ //
11
+ // 导出:
12
+ // buildDreamPrompt({ memoryDir, spaceLabel, globalEnabled, focus,
13
+ // sessionHints, maxNotes, maxNoteBytes, globalDir }) -> string
14
+ // collectDreamHints({ sessionQuery, currentSessionId, limit })
15
+ // -> Promise<Array<{ id, title?, updatedAt? }>>
16
+ // summarizeDreamApply({ written, deleted, errors }) -> string
17
+
18
+ export const DREAM_MAX_NOTES = 200
19
+ export const DREAM_MAX_NOTE_BYTES = 8192
20
+
21
+ const DEFAULT_HINT_LIMIT = 5
22
+ const MAX_HINT_LIMIT = 50
23
+ const MAX_PROMPT_HINTS = 20
24
+ const MAX_FOCUS_CHARS = 500
25
+
26
+ // sessionQuery 的宿主接口并不固定,按最可能到最不可能的顺序尝试。
27
+ const SESSION_QUERY_METHODS = ['listRecent', 'recent', 'list', 'query', 'search']
28
+ // 查询结果可能直接是数组,也可能包在这些字段里。
29
+ const HINT_ARRAY_KEYS = ['sessions', 'items', 'results', 'hints', 'entries']
30
+
31
+ /**
32
+ * 生成 `/dream` 的整理提示。提示里不含易变内容(日期、随机串),
33
+ * 同一组入参必须得到同一段文本,方便快照测试与排查。
34
+ */
35
+ export function buildDreamPrompt(options = {}) {
36
+ const input = options ?? {}
37
+ const memoryDir = stringOf(input.memoryDir) || '<memory notes directory>'
38
+ const spaceLabel = stringOf(input.spaceLabel) || 'this workspace'
39
+ const globalEnabled = input.globalEnabled === true
40
+ const focus = blockText(input.focus, MAX_FOCUS_CHARS)
41
+ const sessionHints = Array.isArray(input.sessionHints) ? input.sessionHints : []
42
+ const maxNotes = positiveInt(input.maxNotes, DREAM_MAX_NOTES)
43
+ const maxNoteBytes = positiveInt(input.maxNoteBytes, DREAM_MAX_NOTE_BYTES)
44
+ const maxKb = Math.max(1, Math.round(maxNoteBytes / 1024))
45
+ const noteCount = Number.isInteger(input?.noteCount) && input.noteCount >= 0 ? input.noteCount : null
46
+ const globalDir = globalEnabled
47
+ ? stringOf(input.globalDir) || deriveGlobalDir(memoryDir)
48
+ : ''
49
+
50
+ const blocks = []
51
+
52
+ blocks.push(`# /dream — consolidate memory notes
53
+
54
+ The user ran \`/dream\`: a manual cross-session consolidation pass over this workspace's memory notes. This is not a normal turn. Do the pass now with your memory and file tools, then finish with a short report. Every change must go through a tool call so it stays visible in the conversation.
55
+
56
+ Memory space: ${spaceLabel}
57
+ Notes directory: \`${memoryDir}\`${globalDir === '' ? '' : `\nGlobal notes directory: \`${globalDir}\``}`)
58
+
59
+ blocks.push(`## This pass consolidates; it does not capture
60
+
61
+ A normal turn adds notes. \`/dream\` makes the existing notes accurate, non-duplicated, and small. Prefer updating or deleting an existing note over writing a new one; a new note is justified only when several notes are merged into one or a note must be fully rewritten. Delete the superseded file in the same pass. Do not use this pass to dump new facts.
62
+
63
+ Keep the same four types as always: \`user\`, \`feedback\` (body carries "**Why:**" and "**How to apply:**"), \`project\`, \`reference\`. Keep the same exclusions as always:
64
+ - code patterns, conventions, architecture, file paths, or project structure — read the project instead;
65
+ - git history or who-changed-what — \`git log\` and \`git blame\` are authoritative;
66
+ - debugging recipes — the fix lives in the code and its commit message;
67
+ - anything already stated in the AGENTS.md or CLAUDE.md files;
68
+ - ephemeral task state: in-progress work, temporary notes, this conversation.`)
69
+
70
+ if (focus !== '') {
71
+ blocks.push(`## Focus for this pass
72
+
73
+ ${focus}
74
+
75
+ Treat the focus as the scope of this pass: consolidate and prune only notes that match it, and leave every other note untouched. You may still read everything and mention out-of-scope problems in the report.`)
76
+ }
77
+
78
+ blocks.push(`## Phase 1 — Orient
79
+
80
+ 1. List the notes directory and read every note file, frontmatter included.
81
+ 2. Build an inventory: file, name, description, type, updated, and the claims the note actually makes.
82
+ 3. Group the inventory by topic and mark duplicates, contradictions, stale claims, oversized notes${focus === '' ? '' : ', and notes outside the focus'}. Change nothing yet.
83
+
84
+ If the directory holds no notes, say so in your report and stop — there is nothing to consolidate.`)
85
+
86
+ const hintLines = formatHintLines(sessionHints)
87
+ const hintsText =
88
+ hintLines.length === 0
89
+ ? 'The host collected no session hints for this workspace; skip this phase and go on to Phase 3.'
90
+ : `The host collected these recent sessions for this workspace (newest first):\n\n${hintLines.join('\n')}`
91
+ blocks.push(`## Phase 2 — Gather
92
+
93
+ ${hintsText}
94
+
95
+ Treat these hints only as leads. When a note looks stale or incomplete, search the matching session (session search tools) to see what actually happened after the note was written. Do not inspect the codebase, and do not copy transcripts into notes. If the hints are empty or unhelpful, move on to Phase 3; do not stall.`)
96
+
97
+ blocks.push(`## Phase 3 — Consolidate
98
+
99
+ - Merge duplicates and near-duplicates into one note: keep the better file, combine the claims, save the merged note, and delete the extra file. Two files about the same topic are a bug, not two notes.
100
+ - Convert every relative date ("yesterday", "last night", "last week", "上周") to an absolute date. Today's date is in your session context.
101
+ - Delete claims that are now false or were superseded (a fixed bug, a changed decision, a removed flag) and rewrite the note; delete the note when nothing true remains.
102
+ - Keep one note per topic. A note is a claim a future session can trust, not a log of what happened.
103
+ - Keep frontmatter valid (\`name\`, \`description\`, \`type\`, \`origin\`). Do not rename a file unless the rename is part of a merge.`)
104
+
105
+ blocks.push(`## Phase 4 — Prune
106
+
107
+ - Keep this space at or below ${maxNotes} notes and each note at or below ${maxKb} KB (the rendered file, frontmatter included).
108
+ - When over budget, delete the least valuable notes first: one-off task details, duplicated claims, status snapshots a future session does not need.
109
+ - Drop what a future session can re-derive instead of remembering: paths that move, line numbers, transient progress. Age alone is not a reason to delete a note.
110
+ - Never delete the last remaining note. If the only note is stale, rewrite it into the most useful durable summary instead of deleting it.${noteCount === null || noteCount === 0 ? '' : ` This space currently holds ${noteCount} note(s); leaving it empty is a failure of this pass, not a cleanup.`}`)
111
+
112
+ const outside = globalEnabled && globalDir !== '' ? ' or the global notes directory' : ''
113
+ blocks.push(`## How to change a note
114
+
115
+ - Update with \`memory_note\`; the same name updates the note in place. Keep \`description\` to one specific sentence — it is the key future sessions use to decide relevance.
116
+ - Delete with \`memory_forget\`, passing the exact file name.
117
+ - You may also edit or delete the Markdown files directly with your file tools; keep the frontmatter valid and keep the file name stable.
118
+ - Never touch files outside the notes directory${outside}.`)
119
+
120
+ blocks.push(
121
+ globalEnabled
122
+ ? globalSpaceEnabledText(globalDir)
123
+ : `## Global space
124
+
125
+ The shared global space is disabled for this workspace. Do not write to \`_global\` and do not pass \`scope: "global"\` to \`memory_note\`; every change stays inside the notes directory above. A cross-project rule that you find here stays here for now.`,
126
+ )
127
+
128
+ blocks.push(`## Report
129
+
130
+ Finish with a short report, no preamble:
131
+ - updated: the file names you changed
132
+ - deleted: the file names you removed
133
+ - left alone: anything you deliberately skipped, and why (only if it mattered)
134
+
135
+ If nothing needed to change, say so plainly.`)
136
+
137
+ return `${blocks.join('\n\n')}\n`
138
+ }
139
+
140
+ function globalSpaceEnabledText(globalDir) {
141
+ const where =
142
+ globalDir === ''
143
+ ? 'the `_global` space directory next to the notes directory'
144
+ : `\`${globalDir}\``
145
+ return `## Global space
146
+
147
+ The shared \`_global\` space is enabled; notes explicitly marked global are visible to every workspace. In Phase 1, also list and read the global notes in ${where} and fold them into your inventory. Use it only for facts that hold across projects — the user's standing preferences, environment facts, tooling conventions. Workspace-specific details stay in this workspace's notes. Write a global note with \`memory_note\` and \`scope: "global"\`; delete one with \`memory_forget\` and the same scope, using the exact file name. When the same fact exists in both places, keep the global copy and remove the workspace duplicate.`
148
+ }
149
+
150
+ /**
151
+ * 尽力收集近期会话线索,供 Phase 2 使用。
152
+ *
153
+ * sessionQuery 由宿主传入,接口可能是函数,也可能是带 recent/list/search 等
154
+ * 方法的服务对象;也可能尚未实现。任何缺失或异常都只返回空数组,绝不抛错,
155
+ * 因为「拿不到会话线索」只应让整理少一步,不应让 `/dream` 失败。
156
+ */
157
+ export async function collectDreamHints({ sessionQuery, currentSessionId = '', limit = 5 } = {}) {
158
+ const max = normalizeHintLimit(limit)
159
+ if (max === 0) return []
160
+ const currentId = sanitizeInline(currentSessionId, 200)
161
+
162
+ let raw = null
163
+ try {
164
+ raw = await querySessions(sessionQuery, max)
165
+ } catch {
166
+ return []
167
+ }
168
+
169
+ const seen = new Set()
170
+ const hints = []
171
+ for (const item of hintsArray(raw)) {
172
+ const hint = normalizeHint(item)
173
+ if (hint === null) continue
174
+ if (currentId !== '' && hint.id === currentId) continue
175
+ if (seen.has(hint.id)) continue
176
+ seen.add(hint.id)
177
+ hints.push(hint)
178
+ if (hints.length >= max) break
179
+ }
180
+ return hints
181
+ }
182
+
183
+ /**
184
+ * 把整理结果渲染成一行命令回执。written / deleted / errors 可以是数组,
185
+ * 也可以是数字;没有任何变化时返回固定文案,便于调用方直接展示。
186
+ */
187
+ export function summarizeDreamApply(applied = {}) {
188
+ const input = applied !== null && typeof applied === 'object' ? applied : {}
189
+ const written = countOf(input.written)
190
+ const deleted = countOf(input.deleted)
191
+ const errors = countOf(input.errors)
192
+
193
+ if (written === 0 && deleted === 0 && errors === 0) return '记忆已经很整洁'
194
+
195
+ const parts = []
196
+ if (written > 0) parts.push(`写入 ${written} 条`)
197
+ if (deleted > 0) parts.push(`删除 ${deleted} 条`)
198
+ if (errors > 0) parts.push(`${errors} 个错误`)
199
+
200
+ const prefix = errors === 0 ? '整理完成' : written + deleted === 0 ? '整理未完成' : '整理部分完成'
201
+ return `${prefix}:${parts.join(' · ')}`
202
+ }
203
+
204
+ async function querySessions(sessionQuery, limit) {
205
+ if (sessionQuery === null || sessionQuery === undefined) return null
206
+ if (Array.isArray(sessionQuery)) return sessionQuery
207
+ if (typeof sessionQuery === 'function') return await sessionQuery({ limit })
208
+ if (typeof sessionQuery !== 'object') return null
209
+
210
+ // 服务对象的接口不可预知:逐个尝试已知形状,某个方法抛错就换下一个。
211
+ for (const name of SESSION_QUERY_METHODS) {
212
+ const method = sessionQuery[name]
213
+ if (typeof method !== 'function') continue
214
+ try {
215
+ const value = await method.call(sessionQuery, { limit })
216
+ if (value !== undefined && value !== null) return value
217
+ } catch {
218
+ // 接口不匹配,继续尝试其它方法。
219
+ }
220
+ }
221
+ return null
222
+ }
223
+
224
+ function hintsArray(raw) {
225
+ if (Array.isArray(raw)) return raw
226
+ if (raw === null || typeof raw !== 'object') return []
227
+ for (const key of HINT_ARRAY_KEYS) {
228
+ if (Array.isArray(raw[key])) return raw[key]
229
+ }
230
+ return []
231
+ }
232
+
233
+ /** 归一化一条会话线索,丢弃没有 id 的条目。 */
234
+ function normalizeHint(item) {
235
+ if (typeof item === 'string' || typeof item === 'number') {
236
+ const id = sanitizeInline(item, 200)
237
+ return id === '' ? null : { id }
238
+ }
239
+ if (item === null || typeof item !== 'object') return null
240
+
241
+ const nested = item.session !== null && typeof item.session === 'object' ? item.session : null
242
+ const session = nested ?? item
243
+ const header = session.header !== null && typeof session.header === 'object' ? session.header : {}
244
+ const id = firstText(
245
+ item.id,
246
+ item.sessionId,
247
+ item.session_id,
248
+ item.key,
249
+ typeof item.session === 'string' ? item.session : '',
250
+ session.id,
251
+ header.id,
252
+ )
253
+ if (id === '') return null
254
+
255
+ const title = firstText(item.title, item.name, item.summary, session.title, header.title, header.name)
256
+ const updatedAt = firstDate(
257
+ item.updatedAt,
258
+ item.updated_at,
259
+ item.lastActiveAt,
260
+ item.last_active_at,
261
+ item.mtime,
262
+ session.updatedAt,
263
+ session.updated_at,
264
+ header.updatedAt,
265
+ )
266
+
267
+ const hint = { id }
268
+ if (title !== '') hint.title = title
269
+ if (updatedAt !== '') hint.updatedAt = updatedAt
270
+ return hint
271
+ }
272
+
273
+ function normalizeHintLimit(limit) {
274
+ if (limit === null || limit === undefined || limit === '') return DEFAULT_HINT_LIMIT
275
+ const parsed = typeof limit === 'number' ? limit : Number(limit)
276
+ if (!Number.isFinite(parsed)) return DEFAULT_HINT_LIMIT
277
+ return Math.min(MAX_HINT_LIMIT, Math.max(0, Math.trunc(parsed)))
278
+ }
279
+
280
+ function countOf(value) {
281
+ if (Array.isArray(value)) return value.length
282
+ if (typeof value === 'number' && Number.isFinite(value)) return Math.max(0, Math.trunc(value))
283
+ return 0
284
+ }
285
+
286
+ function formatHintLines(sessionHints) {
287
+ const lines = []
288
+ for (const hint of sessionHints) {
289
+ const line = formatHintLine(hint)
290
+ if (line === '') continue
291
+ lines.push(line)
292
+ if (lines.length >= MAX_PROMPT_HINTS) break
293
+ }
294
+ return lines
295
+ }
296
+
297
+ function formatHintLine(hint) {
298
+ // 会话 id 在宿主侧都是字符串;其它原始类型视为脏数据丢弃。
299
+ if (typeof hint === 'string') {
300
+ const id = sanitizeInline(hint, 200)
301
+ return id === '' ? '' : `- ${id}`
302
+ }
303
+ if (hint === null || typeof hint !== 'object') return ''
304
+ const id = sanitizeInline(hint.id, 200)
305
+ if (id === '') return ''
306
+ const title = sanitizeInline(hint.title, 120)
307
+ const updatedAt = sanitizeInline(hint.updatedAt, 40)
308
+ const date = /^\d{4}-\d{2}-\d{2}/.test(updatedAt) ? `${updatedAt.slice(0, 10)} · ` : ''
309
+ return `- ${date}${title === '' ? id : `${title} (${id})`}`
310
+ }
311
+
312
+ /** 从 `…/spaces/<key>` 推出全局空间目录;形状不符时返回空串。 */
313
+ function deriveGlobalDir(memoryDir) {
314
+ const dir = memoryDir.replace(/[\\/]+$/, '')
315
+ if (dir === '') return ''
316
+ const index = Math.max(dir.lastIndexOf('/'), dir.lastIndexOf('\\'))
317
+ if (index <= 0) return ''
318
+ const parent = dir.slice(0, index)
319
+ if (!/(^|[\\/])spaces$/.test(parent)) return ''
320
+ return `${parent}/_global`
321
+ }
322
+
323
+ function firstText(...values) {
324
+ for (const value of values) {
325
+ const text = sanitizeInline(value, 200)
326
+ if (text !== '') return text
327
+ }
328
+ return ''
329
+ }
330
+
331
+ function firstDate(...values) {
332
+ for (const value of values) {
333
+ const text = isoDate(value)
334
+ if (text !== '') return text
335
+ }
336
+ return ''
337
+ }
338
+
339
+ function isoDate(value) {
340
+ if (value instanceof Date) {
341
+ return Number.isNaN(value.getTime()) ? '' : value.toISOString()
342
+ }
343
+ if (typeof value === 'number' && Number.isFinite(value)) {
344
+ // 会话时间戳可能是毫秒,也可能是秒。
345
+ const ms = value >= 1e11 ? value : value * 1000
346
+ const date = new Date(ms)
347
+ return Number.isNaN(date.getTime()) ? '' : date.toISOString()
348
+ }
349
+ const text = sanitizeInline(value, 64)
350
+ if (text === '') return ''
351
+ const parsed = Date.parse(text)
352
+ return Number.isNaN(parsed) ? text : new Date(parsed).toISOString()
353
+ }
354
+
355
+ /** 单行化:去控制字符、折叠空白、截断,避免外部文本破坏提示结构。 */
356
+ function sanitizeInline(value, maxLength) {
357
+ if (typeof value !== 'string' && typeof value !== 'number') return ''
358
+ const text = String(value)
359
+ .replace(/[\u0000-\u001f\u007f]+/g, ' ')
360
+ .replace(/\s+/g, ' ')
361
+ .trim()
362
+ if (text === '') return ''
363
+ return text.length > maxLength ? `${text.slice(0, maxLength - 1)}…` : text
364
+ }
365
+
366
+ /** 多行文本(focus):保留换行,去掉其它控制字符,截断超长内容。 */
367
+ function blockText(value, maxLength) {
368
+ if (typeof value !== 'string') return ''
369
+ const text = value
370
+ .replace(/\r\n/g, '\n')
371
+ .replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, '')
372
+ .trim()
373
+ if (text === '') return ''
374
+ return text.length > maxLength ? `${text.slice(0, maxLength - 1)}…` : text
375
+ }
376
+
377
+ function stringOf(value) {
378
+ return typeof value === 'string' ? value.trim() : ''
379
+ }
380
+
381
+ function positiveInt(value, fallback) {
382
+ const parsed = typeof value === 'number' ? value : Number(value)
383
+ if (!Number.isFinite(parsed) || parsed <= 0) return fallback
384
+ return Math.trunc(parsed)
385
+ }