dsh-memory-metabolism 0.2.0 → 0.2.1

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/api.js CHANGED
@@ -2,6 +2,7 @@ import { writeFileSync } from 'node:fs'
2
2
  import { listChatModels } from './chat/model.js'
3
3
  import { runChatTurn } from './chat/agent.js'
4
4
  import { join } from 'node:path'
5
+ import { previewProjections } from './preview.js'
5
6
 
6
7
  const PREFIX = '/api/memory-metabolism'
7
8
 
@@ -107,7 +108,7 @@ function queryValue(url, key) {
107
108
  }
108
109
  }
109
110
 
110
- export function registerRoutes({ ctx, hostCtx, service, store, config, chatStore }) {
111
+ export function registerRoutes({ ctx, hostCtx, service, store, config, chatStore, organizer }) {
111
112
  const activeChats = new Map()
112
113
  let gateCtx
113
114
  const gateScope = ctx.inject(['connection', 'connection.authentication'], (loginCtx) => {
@@ -138,7 +139,28 @@ export function registerRoutes({ ctx, hostCtx, service, store, config, chatStore
138
139
 
139
140
  register('/status', async (request, response) => {
140
141
  if (request.method !== 'GET' && request.method !== 'HEAD') return sendJson(response, 405, { ok: false, error: 'GET only' })
141
- return sendJson(response, 200, service.status())
142
+ return sendJson(response, 200, { ...service.status(), organizer: organizer?.status?.() || store.readOrganizer?.() || {} })
143
+ })
144
+
145
+ register('/diagnostics', async (request, response) => {
146
+ if (request.method !== 'GET' && request.method !== 'HEAD') return sendJson(response, 405, { ok: false, error: 'GET only' })
147
+ const status = service.status()
148
+ const project = queryValue(request.url, 'project') || status.lastProject || ''
149
+ const preview = previewProjections({ store, config, projectKey: project })
150
+ const trace = service.trace().filter((row) => row.kind === 'inject').slice(-8).reverse().map((row) => ({
151
+ ...row,
152
+ chars: (row.ids || []).reduce((sum, id) => sum + String(service.locate(id)?.text || '').length, 0),
153
+ }))
154
+ return sendJson(response, 200, {
155
+ ok: true,
156
+ project,
157
+ status,
158
+ paths: service.paths(project),
159
+ preview,
160
+ lastInjections: trace,
161
+ organizer: organizer?.status?.() || store.readOrganizer?.() || {},
162
+ errors: store.readErrors?.() || [],
163
+ })
142
164
  })
143
165
 
144
166
  register('/entries', async (request, response) => {
@@ -195,6 +217,22 @@ export function registerRoutes({ ctx, hostCtx, service, store, config, chatStore
195
217
  return sendJson(response, 200, result)
196
218
  })
197
219
 
220
+ register('/reclassify', async (request, response) => {
221
+ if (request.method !== 'POST') return sendJson(response, 405, { ok: false, error: 'POST only' })
222
+ const body = await readBody(request)
223
+ const result = await service.reclassify(body)
224
+ if (!result.ok) return sendJson(response, 400, result)
225
+ return sendJson(response, 200, result)
226
+ })
227
+
228
+ register('/open', async (request, response) => {
229
+ if (request.method !== 'POST') return sendJson(response, 405, { ok: false, error: 'POST only' })
230
+ const body = await readBody(request)
231
+ const result = service.openPath(body.kind, body.project)
232
+ if (!result.ok) return sendJson(response, 400, result)
233
+ return sendJson(response, 200, result)
234
+ })
235
+
198
236
  register('/consolidate', async (request, response) => {
199
237
  if (request.method !== 'POST') return sendJson(response, 405, { ok: false, error: 'POST only' })
200
238
  return sendJson(response, 200, service.consolidate())
@@ -321,7 +359,7 @@ export function registerRoutes({ ctx, hostCtx, service, store, config, chatStore
321
359
  }
322
360
  if (request.method !== 'POST') return sendJson(response, 405, { ok: false, error: 'GET or POST only' })
323
361
  const body = await readBody(request)
324
- const allowed = ['writeThreshold', 'candidateThreshold', 'maxInjectionChars', 'retrieveTopK', 'staleDays', 'archiveRetrievability', 'assistantMaxInputChars', 'chatHistoryChars', 'chatMaxRounds']
362
+ const allowed = ['writeThreshold', 'candidateThreshold', 'maxInjectionChars', 'retrieveTopK', 'staleDays', 'archiveRetrievability', 'assistantMaxInputChars', 'chatHistoryChars', 'chatMaxRounds', 'autoOrganizeDelayMs', 'autoOrganizeMaxChars', 'autoOrganizeMinChars']
325
363
  const patch = {}
326
364
  for (const key of allowed) {
327
365
  if (body[key] === undefined) continue
@@ -329,6 +367,8 @@ export function registerRoutes({ ctx, hostCtx, service, store, config, chatStore
329
367
  if (Number.isFinite(value)) patch[key] = value
330
368
  }
331
369
  if (typeof body.assistantModel === 'string') patch.assistantModel = body.assistantModel.trim()
370
+ if (typeof body.autoOrganizeModel === 'string') patch.autoOrganizeModel = body.autoOrganizeModel.trim()
371
+ if (typeof body.autoOrganize === 'boolean') patch.autoOrganize = body.autoOrganize
332
372
  Object.assign(config, patch)
333
373
  writeFileSync(join(store.dirs.root, 'config.json'), JSON.stringify(config, null, 2) + '\n', 'utf8')
334
374
  return sendJson(response, 200, { ok: true, config: service.status().config })
package/lib/config.js CHANGED
@@ -13,6 +13,13 @@ export const DEFAULT_CONFIG = Object.freeze({
13
13
  staleDays: 30,
14
14
  archiveRetrievability: 0.2,
15
15
  autoProject: true,
16
+ globalNoForget: true,
17
+ projectStorage: 'local',
18
+ autoOrganize: true,
19
+ autoOrganizeModel: '',
20
+ autoOrganizeDelayMs: 2500,
21
+ autoOrganizeMaxChars: 12000,
22
+ autoOrganizeMinChars: 40,
16
23
  assistantModel: '',
17
24
  assistantMaxInputChars: 120000,
18
25
  chatHistoryChars: 24000,
@@ -30,10 +37,14 @@ export function normalizeConfig(input = {}) {
30
37
  const value = Number(merged[key])
31
38
  merged[key] = Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : DEFAULT_CONFIG[key]
32
39
  }
33
- for (const key of ['maxInjectionChars', 'retrieveTopK', 'staleDays', 'assistantMaxInputChars', 'chatHistoryChars', 'chatMaxRounds']) {
40
+ for (const key of ['maxInjectionChars', 'retrieveTopK', 'staleDays', 'assistantMaxInputChars', 'chatHistoryChars', 'chatMaxRounds', 'autoOrganizeDelayMs', 'autoOrganizeMaxChars', 'autoOrganizeMinChars']) {
34
41
  const value = Number(merged[key])
35
42
  merged[key] = Number.isFinite(value) && value > 0 ? Math.floor(value) : DEFAULT_CONFIG[key]
36
43
  }
44
+ merged.globalNoForget = merged.globalNoForget !== false
45
+ merged.projectStorage = merged.projectStorage === 'central' ? 'central' : 'local'
46
+ merged.autoOrganize = merged.autoOrganize !== false
47
+ merged.autoOrganizeModel = typeof merged.autoOrganizeModel === 'string' ? merged.autoOrganizeModel : ''
37
48
  merged.assistantModel = typeof merged.assistantModel === 'string' ? merged.assistantModel : ''
38
49
  return merged
39
50
  }
package/lib/context.js CHANGED
@@ -30,7 +30,7 @@ const RULES = [
30
30
  '- 只在“下一个会话不做就会做错 / 返工 / 重踩坑”时写;过程流水、一次性状态不写。',
31
31
  '- 一次一条,结论先行;路径只写可复用的入口,不写行号。',
32
32
  '- 用户明确说“记住”时,直接写,不要只回复“好的”。',
33
- '- 人格与协作约定是只读上下文,不要用记忆工具修改。',
33
+ '- 人格与协作约定由用户维护;助手不要用记忆工具改写,改动前先征得用户同意。',
34
34
  '- 计划模式不要写记忆。',
35
35
  ].join('\n')
36
36
 
@@ -84,13 +84,13 @@ export function buildProjections({ service, store, config, session }) {
84
84
 
85
85
  const persona = readText(join(store.dirs.root, 'persona.md'))
86
86
  if (persona) {
87
- const message = projection(budgetClip(persona, Math.min(config.maxInjectionChars, 4000)), '# 人格(只读)')
87
+ const message = projection(budgetClip(persona, Math.min(config.maxInjectionChars, 4000)), '# 人格(用户维护)')
88
88
  if (message) out.push(message)
89
89
  }
90
90
 
91
91
  const conventions = readText(join(store.dirs.root, 'conventions.md'))
92
92
  if (conventions) {
93
- const message = projection(budgetClip(conventions, Math.min(config.maxInjectionChars, 3000)), '# 协作约定(只读,改动需用户确认)')
93
+ const message = projection(budgetClip(conventions, Math.min(config.maxInjectionChars, 3000)), '# 协作约定(用户维护,助手不自动改写)')
94
94
  if (message) out.push(message)
95
95
  }
96
96
 
@@ -1,5 +1,6 @@
1
1
  import { search, maxScore, tokenSet, jaccard } from './bm25.js'
2
2
  import { retrievability } from '../shared/fsrs.js'
3
+ import { isPinned } from '../meta.js'
3
4
 
4
5
  function trustOf(meta) {
5
6
  const alpha = Math.max(0, Number(meta?.trustAlpha) || 2)
@@ -23,7 +24,7 @@ export function rank(query, entries, metaIndex, config = {}) {
23
24
  const retention = retrievability(meta, now)
24
25
  const importance = Number(meta.importance) || 0.5
25
26
  const trust = trustOf(meta)
26
- const pin = meta.pinned === true ? 1 : 0
27
+ const pin = isPinned(entry, meta, config) ? 1 : 0
27
28
  const score = 0.50 * relevance + 0.15 * retention + 0.15 * importance + 0.10 * trust + 0.10 * pin
28
29
  candidates.push({ entry, score, parts: { relevance, retention, importance, trust, pin } })
29
30
  }
package/lib/meta.js CHANGED
@@ -44,10 +44,16 @@ export function syncMeta(meta, entries) {
44
44
  return meta
45
45
  }
46
46
 
47
+ export function isPinned(entry, item, config = {}) {
48
+ if (item?.pinned === true) return true
49
+ return entry?.scope === 'global' && item?.pinned !== false && config.globalNoForget !== false
50
+ }
51
+
47
52
  export function statusOf(meta, entry, config = {}) {
48
53
  const item = metaFor(meta, entry)
49
54
  if (item.excluded === true) return 'excluded'
50
55
  if (item.status === 'archived' || item.status === 'disputed' || item.status === 'candidate') return item.status
56
+ if (isPinned(entry, item, config)) return 'active'
51
57
  const retention = retrievability(item)
52
58
  const threshold = Number(config.archiveRetrievability) || 0.2
53
59
  if (retention < threshold && Number(item.importance) < 0.65) return 'fading'
package/lib/open.js ADDED
@@ -0,0 +1,39 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { existsSync, statSync } from 'node:fs'
3
+ import { dirname } from 'node:path'
4
+ import { platform } from 'node:os'
5
+
6
+ function isDirectory(path) {
7
+ try { return statSync(path).isDirectory() } catch { return false }
8
+ }
9
+
10
+ export function revealPath(target, { reveal = false } = {}) {
11
+ if (typeof target !== 'string' || target === '') return { ok: false, error: 'path is empty' }
12
+ const kind = platform()
13
+ let launch
14
+ let args
15
+ if (kind === 'win32') {
16
+ launch = 'explorer.exe'
17
+ args = reveal && !isDirectory(target) ? ['/select,' + target] : [target]
18
+ } else if (kind === 'darwin') {
19
+ launch = 'open'
20
+ args = reveal && !isDirectory(target) ? ['-R', target] : [target]
21
+ } else {
22
+ launch = 'xdg-open'
23
+ args = [reveal && !isDirectory(target) ? dirname(target) : target]
24
+ }
25
+ try {
26
+ const child = spawn(launch, args, { detached: true, stdio: 'ignore', windowsHide: true })
27
+ child.on('error', () => { /* the caller still gets the path */ })
28
+ child.unref()
29
+ return { ok: true, path: target, reveal }
30
+ } catch (error) {
31
+ return { ok: false, error: error?.message || String(error), path: target }
32
+ }
33
+ }
34
+
35
+ export function existingTarget(target) {
36
+ if (existsSync(target)) return target
37
+ const parent = dirname(target)
38
+ return existsSync(parent) ? parent : null
39
+ }
@@ -0,0 +1,269 @@
1
+ import { resolveChatModel } from './chat/model.js'
2
+
3
+ const TURN_BUFFER_MAX = 40
4
+ const PROPOSAL_MAX = 5
5
+ const MIN_CONTENT = 8
6
+ const MAX_CONTENT = 600
7
+
8
+ function clip(value, length) {
9
+ const text = String(value ?? '')
10
+ return text.length > length ? text.slice(0, length) + '\n[truncated]' : text
11
+ }
12
+
13
+ function extractText(event) {
14
+ const data = event?.data
15
+ if (typeof data?.text === 'string') return data.text
16
+ if (Array.isArray(data?.content)) {
17
+ return data.content.filter((block) => block && block.type === 'text' && typeof block.text === 'string').map((block) => block.text).join('\n')
18
+ }
19
+ if (typeof data?.message?.text === 'string') return data.message.text
20
+ return ''
21
+ }
22
+
23
+ function stripFence(text) {
24
+ return String(text || '').replace(/^\s*```(?:json)?\s*/i, '').replace(/\s*```\s*$/, '').trim()
25
+ }
26
+
27
+ export function parseProposals(text) {
28
+ const raw = stripFence(text)
29
+ if (!raw) return []
30
+ const start = raw.indexOf('[')
31
+ const end = raw.lastIndexOf(']')
32
+ if (start < 0 || end < start) return []
33
+ let parsed
34
+ try { parsed = JSON.parse(raw.slice(start, end + 1)) } catch { return [] }
35
+ if (!Array.isArray(parsed)) return []
36
+ return parsed.filter((item) => item && typeof item.content === 'string' && item.content.trim().length >= MIN_CONTENT)
37
+ }
38
+
39
+ function normalizeProposal(item) {
40
+ const content = String(item.content || '').trim().slice(0, MAX_CONTENT)
41
+ if (content.length < MIN_CONTENT) return null
42
+ const scope = item.scope === 'global' ? 'global' : 'project'
43
+ const section = String(item.section || (scope === 'global' ? '用户偏好' : '项目约定')).trim().slice(0, 60)
44
+ const type = ['fact', 'preference', 'decision', 'pitfall', 'convention', 'reference'].includes(item.type) ? item.type : 'fact'
45
+ const importance = Math.max(0, Math.min(1, Number(item.importance) || 0.5))
46
+ return { content, scope, section, type, importance }
47
+ }
48
+
49
+ function systemPrompt() {
50
+ return [
51
+ '你是后台记忆整理器,只负责从来回对话中提炼长期有效的记忆。',
52
+ '只输出 JSON 数组,不要 Markdown、解释或代码围栏。',
53
+ '每一项格式:{"content":"一句结论先行的事实/偏好/决策/踩坑/约定","scope":"project|global","section":"章节名","type":"fact|preference|decision|pitfall|convention","importance":0..1}',
54
+ '规则:宁少勿多;不写对话流水、工具输出、一次性状态、密钥、密码、token、临时路径;不写已经显而易见的内容;没有值得记的就输出 []。',
55
+ '用户明确说“记住/记下”的内容才值得高置信;其余只作为候选。',
56
+ '项目事实用 project;跨项目偏好或硬约束用 global。',
57
+ ].join('\n')
58
+ }
59
+
60
+ function sessionProject(service, session) {
61
+ const cwd = session?.header?.cwd
62
+ if (cwd) {
63
+ try { return service.projectKey(cwd) } catch { /* fall through */ }
64
+ }
65
+ return service.status().lastProject || ''
66
+ }
67
+
68
+ export function createAutoOrganizer({ ctx, service, store, config, host }) {
69
+ const buffers = new Map()
70
+ const timers = new Map()
71
+ const running = new Set()
72
+ let lastState = store.readOrganizer?.() || {}
73
+
74
+ function recordState(state) {
75
+ lastState = state
76
+ try { store.writeOrganizer?.(state) } catch { /* diagnostics only */ }
77
+ }
78
+
79
+ function recordError(stage, message, meta = {}) {
80
+ try { store.appendError?.({ stage, message: String(message || '').slice(0, 1200), ...meta }) } catch { /* diagnostics only */ }
81
+ }
82
+
83
+ function bucketOf(sid) {
84
+ const id = sid || '__nosession__'
85
+ let bucket = buffers.get(id)
86
+ if (!bucket) {
87
+ bucket = { items: [], session: null }
88
+ buffers.set(id, bucket)
89
+ }
90
+ return bucket
91
+ }
92
+
93
+ function push(session, event) {
94
+ const type = event?.type
95
+ if (type !== 'user/message' && type !== 'assistant/message' && type !== 'tool/result') return
96
+ if (type === 'user/message') {
97
+ const sourceKind = event?.data?.source?.kind
98
+ if (sourceKind && sourceKind !== 'user') return
99
+ }
100
+ const text = extractText(event)
101
+ if (!text.trim()) return
102
+ const sid = session?.id || '__nosession__'
103
+ const bucket = bucketOf(sid)
104
+ bucket.session = session || bucket.session
105
+ if (type === 'user/message' && bucket.items.length > 0) {
106
+ const previous = bucket.items
107
+ bucket.items = []
108
+ clearTimeout(timers.get(sid))
109
+ timers.delete(sid)
110
+ void settle(sid, { items: previous, session: bucket.session })
111
+ }
112
+ bucket.items.push({ role: type === 'tool/result' ? 'tool' : type === 'user/message' ? 'user' : 'assistant', text })
113
+ const total = bucket.items.reduce((sum, item) => sum + item.text.length, 0)
114
+ if (bucket.items.length > TURN_BUFFER_MAX || total > config.autoOrganizeMaxChars) {
115
+ bucket.items = bucket.items.slice(-Math.min(TURN_BUFFER_MAX, 12))
116
+ }
117
+ }
118
+
119
+ function schedule(sid) {
120
+ if (!config.autoOrganize) return
121
+ const id = sid || '__nosession__'
122
+ const previous = timers.get(id)
123
+ if (previous) clearTimeout(previous)
124
+ const delay = Math.max(100, Number(config.autoOrganizeDelayMs) || 2500)
125
+ const timer = setTimeout(() => {
126
+ timers.delete(id)
127
+ void settle(id)
128
+ }, delay)
129
+ timer.unref?.()
130
+ timers.set(id, timer)
131
+ }
132
+
133
+ function handle(session, event) {
134
+ if (!config.autoOrganize) return
135
+ if (event?.type === 'turn/end') {
136
+ if (event?.data?.reason?.kind === 'error') {
137
+ recordError('organizer', 'turn ended with an error', { sessionId: session?.id || null })
138
+ }
139
+ schedule(session?.id)
140
+ return
141
+ }
142
+ push(session, event)
143
+ }
144
+
145
+ async function runModel(model, transcript) {
146
+ const kit = host || await import('@deepseek-ai/dsh-llm')
147
+ const createUserMessage = kit.createUserMessage
148
+ if (typeof ctx?.llm?.stream !== 'function' || typeof createUserMessage !== 'function') throw new Error('model stream is unavailable')
149
+ const signal = AbortSignal.timeout?.(60_000)
150
+ const stream = ctx.llm.stream({
151
+ provider: model.provider,
152
+ model: model.model,
153
+ system: systemPrompt(),
154
+ messages: [createUserMessage({ content: [{ type: 'text', text: transcript }], source: { kind: 'plugin:dsh-memory-metabolism' } })],
155
+ purpose: 'memory-organizer',
156
+ signal,
157
+ })
158
+ let output = ''
159
+ for await (const chunk of stream) {
160
+ if (chunk?.type === 'text-delta' && typeof chunk.text === 'string') output += chunk.text
161
+ if (chunk?.type === 'finish' && chunk.reason?.kind === 'error') throw new Error(chunk.reason?.failure?.message || 'model call failed')
162
+ }
163
+ return output
164
+ }
165
+
166
+ async function settle(sid, snapshot) {
167
+ const id = sid || '__nosession__'
168
+ if (running.has(id)) return null
169
+ const bucket = snapshot || buffers.get(id)
170
+ if (!bucket || bucket.items.length === 0) return null
171
+ if (!snapshot) buffers.delete(id)
172
+ running.add(id)
173
+ const started = Date.now()
174
+ const project = sessionProject(service, bucket.session)
175
+ const transcriptText = bucket.items.map((item) => (item.role === 'user' ? '用户:' : item.role === 'tool' ? '工具:' : '助手:') + item.text).join('\n\n')
176
+ if (transcriptText.trim().length < (Number(config.autoOrganizeMinChars) || 40)) {
177
+ recordState({ time: new Date().toISOString(), sessionId: id, project, status: 'skipped', reason: 'too short', durationMs: Date.now() - started })
178
+ running.delete(id)
179
+ return null
180
+ }
181
+ try {
182
+ if (typeof service.isPlanMode === 'function' && service.isPlanMode(id)) {
183
+ recordState({ time: new Date().toISOString(), sessionId: id, project, status: 'skipped', reason: 'plan mode', durationMs: Date.now() - started })
184
+ return null
185
+ }
186
+ if (store.appendDailyLog && project) {
187
+ try { store.appendDailyLog(project, transcriptText) } catch (error) { recordError('organizer', 'daily log write failed: ' + error.message, { sessionId: id, project }) }
188
+ }
189
+ const model = await resolveChatModel(ctx, { ...config, assistantModel: config.autoOrganizeModel || config.assistantModel }, service)
190
+ if (!model) {
191
+ recordState({ time: new Date().toISOString(), sessionId: id, project, status: 'skipped', reason: 'no model', durationMs: Date.now() - started })
192
+ running.delete(id)
193
+ return null
194
+ }
195
+ const userText = bucket.items.filter((item) => item.role === 'user').map((item) => item.text).join('\n')
196
+ const explicit = /(记住|记下|保存为记忆|remember\s+(this|that))/i.test(userText)
197
+ const raw = await runModel(model, clip(transcriptText, Number(config.autoOrganizeMaxChars) || 12000))
198
+ const proposals = parseProposals(raw).slice(0, PROPOSAL_MAX).map(normalizeProposal).filter(Boolean)
199
+ let written = 0
200
+ let candidates = 0
201
+ let skipped = 0
202
+ for (const proposal of proposals) {
203
+ const result = await service.write({
204
+ content: proposal.content,
205
+ scope: proposal.scope,
206
+ section: proposal.section,
207
+ type: proposal.type,
208
+ importance: proposal.importance,
209
+ project: proposal.scope === 'project' ? project : undefined,
210
+ source: 'model',
211
+ explicit,
212
+ sessionId: id,
213
+ })
214
+ if (!result.ok) skipped++
215
+ else if (result.created === false) skipped++
216
+ else if (result.entry?.status === 'candidate') candidates++
217
+ else written++
218
+ }
219
+ const state = {
220
+ time: new Date().toISOString(),
221
+ sessionId: id,
222
+ project,
223
+ status: 'ok',
224
+ model: model.provider + '/' + model.model,
225
+ durationMs: Date.now() - started,
226
+ proposals: proposals.length,
227
+ written,
228
+ candidates,
229
+ skipped,
230
+ reason: proposals.length === 0 ? 'no durable memory' : null,
231
+ }
232
+ recordState(state)
233
+ return state
234
+ } catch (error) {
235
+ const state = { time: new Date().toISOString(), sessionId: id, project, status: 'error', error: String(error?.message || error), durationMs: Date.now() - started }
236
+ recordState(state)
237
+ recordError('organizer', state.error, { sessionId: id, project })
238
+ return state
239
+ } finally {
240
+ running.delete(id)
241
+ }
242
+ }
243
+
244
+ function register() {
245
+ if (typeof ctx?.on !== 'function') return () => {}
246
+ const listener = (session, event) => {
247
+ try { handle(session, event) } catch (error) { recordError('organizer', error?.message || String(error), { sessionId: session?.id || null }) }
248
+ }
249
+ ctx.on('session/event', listener)
250
+ return () => {
251
+ for (const timer of timers.values()) clearTimeout(timer)
252
+ timers.clear()
253
+ }
254
+ }
255
+
256
+ async function flush(sid) {
257
+ const id = sid || '__nosession__'
258
+ const timer = timers.get(id)
259
+ if (timer) clearTimeout(timer)
260
+ timers.delete(id)
261
+ return settle(id)
262
+ }
263
+
264
+ function status() {
265
+ return lastState || {}
266
+ }
267
+
268
+ return { register, handle, flush, status, settle }
269
+ }
package/lib/preview.js ADDED
@@ -0,0 +1,44 @@
1
+ import { existsSync, readFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { budgetClip, stripDeletedLines, toHomeShort } from './shared/text.js'
4
+
5
+ function readText(file) {
6
+ try { return readFileSync(file, 'utf8') } catch { return '' }
7
+ }
8
+
9
+ function section(title, raw, limit, source) {
10
+ const text = budgetClip(raw, limit)
11
+ return {
12
+ title,
13
+ source,
14
+ chars: String(raw || '').length,
15
+ clippedChars: String(text || '').length,
16
+ truncated: String(raw || '').length > String(text || '').length,
17
+ text,
18
+ }
19
+ }
20
+
21
+ export function previewProjections({ store, config, projectKey }) {
22
+ const key = String(projectKey || '')
23
+ const limit = Math.max(1, Number(config.maxInjectionChars) || 6000)
24
+ const sections = []
25
+ const persona = readText(join(store.dirs.root, 'persona.md'))
26
+ if (persona.trim()) sections.push(section('人格', persona, Math.min(limit, 4000), join(store.dirs.root, 'persona.md')))
27
+ const conventions = readText(join(store.dirs.root, 'conventions.md'))
28
+ if (conventions.trim()) sections.push(section('协作约定', conventions, Math.min(limit, 3000), join(store.dirs.root, 'conventions.md')))
29
+
30
+ const global = store.read('global', null)
31
+ if (global.text.trim()) {
32
+ sections.push({ ...section('全局记忆', stripDeletedLines(global.text), limit, toHomeShort(global.file)), ids: global.entries.map((entry) => entry.id) })
33
+ }
34
+ const project = key ? store.read('project', key) : { text: '', file: '', entries: [] }
35
+ if (project.text.trim()) {
36
+ sections.push({ ...section('项目记忆', stripDeletedLines(project.text), limit, toHomeShort(project.file)), ids: project.entries.map((entry) => entry.id), project: key })
37
+ }
38
+ if (store.listProjectKeys().length > 0 || store.listReferenceNames().length > 0) {
39
+ const index = ['# 记忆索引', '项目:' + store.listProjectKeys().join(', '), '参考:' + store.listReferenceNames().join(', '), '当前项目:' + key].join('\n')
40
+ sections.push(section('记忆索引', index, Math.min(limit, 2000), 'index'))
41
+ }
42
+ const totalChars = sections.reduce((sum, item) => sum + item.clippedChars, 0)
43
+ return { project: key, budget: limit, totalChars, sections }
44
+ }
package/lib/project.js CHANGED
@@ -35,7 +35,7 @@ export function resolveProjectKey(cwd, config = {}) {
35
35
  const file = join(dir, marker)
36
36
  if (existsSync(file)) {
37
37
  const key = readMarker(file)
38
- if (key !== null) return { key, source: 'marker', file }
38
+ if (key !== null) return { key, source: 'marker', file, root: dir }
39
39
  }
40
40
  }
41
41
  }
@@ -44,7 +44,7 @@ export function resolveProjectKey(cwd, config = {}) {
44
44
  for (const item of mappings) {
45
45
  if (!item || typeof item !== 'object') continue
46
46
  if (typeof item.prefix === 'string' && base.toLowerCase().startsWith(resolve(item.prefix).toLowerCase())) {
47
- return { key: slugify(item.key), source: 'config' }
47
+ return { key: slugify(item.key), source: 'config', root: base }
48
48
  }
49
49
  if (typeof item.pattern === 'string') {
50
50
  try {
@@ -61,7 +61,7 @@ export function resolveProjectKey(cwd, config = {}) {
61
61
  }
62
62
  }
63
63
 
64
- return { key: slugify(basename(base)), source: 'basename' }
64
+ return { key: slugify(basename(base)), source: 'basename', root: base }
65
65
  }
66
66
 
67
67
  export function projectDisplayName(key, cwd) {