@restregular/dsh-memory 0.5.5 → 0.6.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/panel.js CHANGED
@@ -35,9 +35,16 @@ function writeJson(res, body, status = 200) {
35
35
  } catch { /* 客户端已断开 */ }
36
36
  }
37
37
 
38
+ /** provider 侧的"调用方输入有问题"错误码 → 400;其余未标注的仍算 500。 */
39
+ const CLIENT_ERROR_CODES = new Set([
40
+ 'SCOPE_INVALID', 'SCOPE_DISABLED', 'CONTENT_EMPTY', 'CONTENT_TOO_LONG',
41
+ 'SECRET_DETECTED', 'IMPORT_INVALID', 'IMPORT_TOO_LARGE', 'KIND_INVALID',
42
+ ])
43
+
38
44
  function writeError(res, error) {
39
- const status = Number(error?.status) || 500
40
- writeJson(res, { ok: false, error: { code: error?.code || 'internal', message: error?.message || String(error) } }, status)
45
+ const code = typeof error?.code === 'string' ? error.code : 'internal'
46
+ const status = Number(error?.status) || (CLIENT_ERROR_CODES.has(code) ? 400 : code === 'SCOPE_LIMIT' ? 409 : 500)
47
+ writeJson(res, { ok: false, error: { code, message: error?.message || String(error) } }, status)
41
48
  }
42
49
 
43
50
  class ApiError extends Error {
@@ -241,11 +248,50 @@ async function handle(ctx, routePath, req, res) {
241
248
  let embedServer = null
242
249
  // older providers have no lifecycle API — the panel simply omits the card
243
250
  try { embedServer = (await memory.embedServerStatus?.()) ?? null } catch { embedServer = null }
244
- writeJson(res, { ok: true, value: { scopes, embedServer } })
251
+ let rules = null
252
+ try { rules = typeof memory.ruleStats === 'function' ? memory.ruleStats() : null } catch { rules = null }
253
+ writeJson(res, { ok: true, value: { scopes, embedServer, rules } })
254
+ return
255
+ }
256
+ if (method === 'GET' && path === '/settings') {
257
+ if (typeof memory.injectSettings !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供注入设置接口(请升级 @restregular/dsh-memory)')
258
+ writeJson(res, { ok: true, value: memory.injectSettings() })
259
+ return
260
+ }
261
+ if (method === 'POST' && path === '/settings') {
262
+ if (typeof memory.updateInjectSettings !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供注入设置接口(请升级 @restregular/dsh-memory)')
263
+ const body = await readJsonBody(req)
264
+ writeJson(res, { ok: true, value: memory.updateInjectSettings(body) })
265
+ return
266
+ }
267
+ if (method === 'POST' && path === '/create') {
268
+ if (typeof memory.createRecord !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供新建接口(请升级 @restregular/dsh-memory)')
269
+ const body = await readJsonBody(req)
270
+ const record = await memory.createRecord({
271
+ ...(typeof body.scope === 'string' ? { scope: body.scope } : {}),
272
+ ...(typeof body.kind === 'string' ? { kind: body.kind } : {}),
273
+ ...(typeof body.content === 'string' ? { content: body.content } : {}),
274
+ ...(Array.isArray(body.tags) ? { tags: body.tags.map(String) } : {}),
275
+ ...(typeof body.importance === 'number' ? { importance: body.importance } : {}),
276
+ })
277
+ console.log(`[dsh-memory-panel] 新建 ${record.kind} @ ${record.scope}: ${record.id}`)
278
+ writeJson(res, { ok: true, value: { record } })
279
+ return
280
+ }
281
+ if (method === 'GET' && path === '/export') {
282
+ if (typeof memory.exportAll !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供导出接口(请升级 @restregular/dsh-memory)')
283
+ writeJson(res, { ok: true, value: memory.exportAll() })
284
+ return
285
+ }
286
+ if (method === 'POST' && path === '/import') {
287
+ if (typeof memory.importRecords !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供导入接口(请升级 @restregular/dsh-memory)')
288
+ const body = await readJsonBody(req)
289
+ const result = await memory.importRecords(body)
290
+ console.log(`[dsh-memory-panel] 导入完成: 新增 ${result.imported} / 跳过 ${result.skipped} / 失败 ${result.rejected}`)
291
+ writeJson(res, { ok: true, value: result })
245
292
  return
246
293
  }
247
- if (method === 'GET' && path === '/embed/status') {
248
- if (typeof memory.embedServerStatus !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供向量服务管理接口')
294
+ if (method === 'GET' && path === '/embed/status') { if (typeof memory.embedServerStatus !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供向量服务管理接口')
249
295
  writeJson(res, { ok: true, value: await memory.embedServerStatus() })
250
296
  return
251
297
  }
@@ -120,6 +120,45 @@ export class CordisMemoryService extends Service {
120
120
  return this.impl.list(input)
121
121
  }
122
122
 
123
+ /** 面板新建记忆 / 规则。 */
124
+ createRecord(input ) {
125
+ return this.impl.createRecord(input)
126
+ }
127
+
128
+ /** 面板导出:纯文本 + 元数据,不含向量。 */
129
+ exportAll() {
130
+ return this.impl.exportAll()
131
+ }
132
+
133
+ /** 面板导入:逐条 save(自动重新嵌入),失败不中断。 */
134
+ importRecords(input ) {
135
+ return this.impl.importRecords(input)
136
+ }
137
+
138
+ /** 设置页显示规则条数。 */
139
+ ruleStats() {
140
+ return this.impl.ruleStats()
141
+ }
142
+
143
+ /** 同步列记录(系统提示里的规则段用,不能等异步 list)。 */
144
+ listSync(input ) {
145
+ return this.impl.listSync(input)
146
+ }
147
+
148
+ /** 注入设置(面板「设置」标签页读它)。 */
149
+ injectSettings() {
150
+ return this.impl.injectSettings()
151
+ }
152
+
153
+ /** 面板改设置:落盘后广播,注入半边下一步就能按新设置跑。 */
154
+ updateInjectSettings(patch ) {
155
+ const next = this.impl.updateInjectSettings(patch)
156
+ try {
157
+ this.ctx.emit('memory/inject-settings', next)
158
+ } catch { /* 广播失败不影响设置本身 */ }
159
+ return next
160
+ }
161
+
123
162
  /**
124
163
  * 当前 agent 上下文 → 默认合并读取范围(会话 + 项目 + global,按开关与 key 去重)。
125
164
  * 工具与召回注入都走它,保证与 `resolveWriteScope` 是同一套口径。
@@ -133,6 +172,11 @@ export class CordisMemoryService extends Service {
133
172
  return this.impl.resolveWriteScope(agent, requested)
134
173
  }
135
174
 
175
+ /** 当前项目 key(会话 cwd 优先)。工具层解析 `scope:'project'` 时用它,口径与读写一致。 */
176
+ projectKeyFor(agent ) {
177
+ return this.impl.projectKeyFor(agent)
178
+ }
179
+
136
180
  /** 作用域清单(名字 + 条数),面板 /status 与 memory_list 共用。 */
137
181
  scopeStats() {
138
182
  return this.impl.scopeStats()
@@ -158,10 +202,12 @@ export function apply(ctx , config = {}) {
158
202
  class ScopedMemoryService extends CordisMemoryService {
159
203
  constructor(ctx2 ) {
160
204
  super(ctx2, config)
161
- // 写路径默认口径来自 tools 小节(defaultScope 缺省 = 会话);项目键缺省
162
- // project:<cwd>,即 DSH 进程的启动目录 = 这个 profile 目录。
205
+ // 写路径默认口径来自 tools 小节(defaultScope 缺省 = 会话)。项目键**只在显式配置**
206
+ // 时才固定下来;缺省由每次调用的 `session.header.cwd` 解析(那才是工作区)。
207
+ // 以前这里写成 `?? project:${process.cwd()}`,而 DSH 服务进程的 cwd 是 profile 目录,
208
+ // 等于把"当前项目"钉成了 profile —— 项目级记忆于是跨项目混在一起。
163
209
  const tools = (config ).tools
164
- this.impl.setProjectScope((tools?.projectScope ?? `project:${process.cwd()}`) )
210
+ if (tools?.projectScope !== undefined) this.impl.setProjectScope(tools.projectScope )
165
211
  if (tools?.defaultScope !== undefined) this.impl.setDefaultScope(tools.defaultScope)
166
212
  }
167
213
  }
@@ -17,12 +17,14 @@
17
17
  import { MemoryStore, scopeFileName, } from './store.js'
18
18
  import {
19
19
  isCustomScope,
20
+ normalizeScopeInput,
20
21
  resolveCurrentScopes,
21
22
  scopeKind,
22
23
  scopeTier,
23
24
  writeScopeForDefault,
24
25
 
25
26
  } from './scope.js'
27
+ import { mergeInjectSettings, normalizeInjectSettings, } from './inject-settings.js'
26
28
  import { buildStats, lexicalScore, recordScore, tokenize, cosine, normalizeInPlace, hasStrongHit } from './scoring.js'
27
29
  import { EmbedClient } from './embed.js'
28
30
  import { DailyBudget, blendScores, rerank, } from './rerank.js'
@@ -483,13 +485,16 @@ export class LocalMemoryService {
483
485
  llmInvoke = null
484
486
  /** 写路径的默认口径(tools.defaultScope);'session' 拿不到会话时回退 project。 */
485
487
  defaultWriteScope = 'session'
486
- /** 当前项目 scope 键;缺省 project:<启动 cwd>。 */
487
- projectScope = `project:${process.cwd()}`
488
+ /** 显式配置的项目 scope 键(未配置 = undefined,由 resolveCurrentScopes 按会话 cwd 决定)。 */
489
+ projectScope
488
490
  /** 上次发现磁盘 scope 的时间(限流用;0 = 还没发现过)。 */
489
491
  discoveredAt = 0
492
+ /** 注入设置(面板「设置」标签页可改;落盘在 <storeDir>/settings.json)。 */
493
+ inject
490
494
 
491
495
  constructor(config = {}) {
492
496
  this.cfg = resolveConfig(config)
497
+ this.inject = this.loadInjectSettings((config ).inject)
493
498
  this.rerankBudget = new DailyBudget(this.cfg.llm.dailyBudgetTokens)
494
499
  this.store = new MemoryStore(this.cfg.storeDir, { onWarn: (m) => console.warn(`[dsh-memory-local] ${m}`) })
495
500
  // Identity BEFORE the eager load (issue #1): ScopeStore skips its sidecar
@@ -501,8 +506,10 @@ export class LocalMemoryService {
501
506
  // 会话 scope 是按会话动态生成的,**不能**在这里 eager 加载(加载谁?);只预载
502
507
  // project 与 global 这两个稳定作用域。其余按需 peek/loadDiscovered。
503
508
  // eager 只加载"已存在"的 scope(peek),不会为不存在的 scope 建空文件。
509
+ // 项目键此刻还看不到会话(没传 agent),所以这里只能预载"没有显式配置时的兜底键"
510
+ // (= project:<process.cwd()>);真正的项目键在每次调用时按会话 cwd 解析。
504
511
  const eager = []
505
- if (this.cfg.projectEnabled) eager.push(this.projectScope)
512
+ if (this.cfg.projectEnabled) eager.push(this.defaultProjectScope)
506
513
  if (this.cfg.globalEnabled) eager.push('global')
507
514
  for (const scope of eager) this.store.peek(scope)
508
515
  this.embed = new EmbedClient({
@@ -515,8 +522,63 @@ export class LocalMemoryService {
515
522
  this.startEmbedServer()
516
523
  }
517
524
 
518
- /** Own the embedding backend's lifetime: spawn on activation, stop on dispose. */
519
- startEmbedServer() {
525
+ /** 设置文件:与记忆数据同目录,便于一起备份/清理。 */
526
+ get settingsPath() {
527
+ return join(this.cfg.storeDir, 'settings.json')
528
+ }
529
+
530
+ /** 读取注入设置(归一化后的快照)。 */
531
+ injectSettings() {
532
+ return normalizeInjectSettings(this.inject, this.inject)
533
+ }
534
+
535
+ /** 面板改设置:合并补丁 → 落盘 → 返回新值。写盘失败只告警,不影响运行中的设置。 */
536
+ updateInjectSettings(patch ) {
537
+ this.inject = mergeInjectSettings(this.inject, patch)
538
+ try {
539
+ mkdirSync(this.cfg.storeDir, { recursive: true })
540
+ writeFileSync(this.settingsPath, `${JSON.stringify(this.inject, null, 2)}\n`, 'utf8')
541
+ } catch (error) {
542
+ console.warn(`[dsh-memory-local] 无法写入注入设置 ${this.settingsPath}: ${error instanceof Error ? error.message : String(error)}`)
543
+ }
544
+ return this.injectSettings()
545
+ }
546
+
547
+ /** 配置先给底,磁盘上的 settings.json 覆盖它;坏文件忽略而不是启动失败。 */
548
+ loadInjectSettings(fromConfig ) {
549
+ const base = normalizeInjectSettings(fromConfig)
550
+ try {
551
+ if (existsSync(this.settingsPath)) {
552
+ return mergeInjectSettings(base, JSON.parse(readFileSync(this.settingsPath, 'utf8')))
553
+ }
554
+ } catch (error) {
555
+ console.warn(`[dsh-memory-local] 忽略损坏的注入设置 ${this.settingsPath}: ${error instanceof Error ? error.message : String(error)}`)
556
+ }
557
+ return base
558
+ }
559
+
560
+ /**
561
+ * 同步列记录(只读、不触发磁盘发现)。系统提示里的「硬性规则」段每步都要
562
+ * 渲染,必须是同步的;这里直接读已加载 scope 的内存快照。
563
+ */
564
+ listSync(input = {}) {
565
+ const seen = new Set ()
566
+ const out = []
567
+ for (const scope of input.scopes ?? []) {
568
+ if (seen.has(scope)) continue
569
+ seen.add(scope)
570
+ const s = this.store.peek(scope)
571
+ if (!s) continue
572
+ for (const rec of s.records.values()) {
573
+ if (input.kind !== undefined && rec.kind !== input.kind) continue
574
+ out.push(rec)
575
+ }
576
+ }
577
+ out.sort((a, b) => b.updatedAt - a.updatedAt)
578
+ return out.slice(0, input.limit ?? 100)
579
+ }
580
+
581
+ /** Own the embedding backend's lifetime: spawn on activation, stop on dispose. */ startEmbedServer() {
520
582
  // Nothing configured and retrieval switched off → do not even build the
521
583
  // manager, so no probe, no spawn attempt, no misleading panel state.
522
584
  if (!this.cfg.vector.enabled || !this.cfg.vector.configured) return
@@ -992,11 +1054,19 @@ export class LocalMemoryService {
992
1054
  this.projectScope = scope
993
1055
  }
994
1056
 
995
- /** 固定项目 scope(默认 project:<启动 cwd>);宿主装配用它对齐 session.header.cwd。 */
1057
+ /** 固定项目 scope(只有**显式配置**才调);缺省由会话 cwd 决定。 */
996
1058
  setProjectScope(scope ) {
997
1059
  this.projectScope = scope
998
1060
  }
999
1061
 
1062
+ /**
1063
+ * 拿不到会话时的项目键:显式配置优先,否则 `project:<process.cwd()>`
1064
+ * (用于构造期预载、以及任何没有 agent 上下文的兜底读写)。
1065
+ */
1066
+ get defaultProjectScope() {
1067
+ return (this.projectScope ?? `project:${process.cwd()}`)
1068
+ }
1069
+
1000
1070
  /**
1001
1071
  * Provide the one-shot LLM caller used by the rerank stage. Passing null
1002
1072
  * (or never calling) keeps retrieval on recall-order only. The cordis
@@ -1012,8 +1082,12 @@ export class LocalMemoryService {
1012
1082
  return this.defaultWriteScope
1013
1083
  }
1014
1084
 
1085
+ /**
1086
+ * 当前项目键(诊断/测试用)。没有会话时就是兜底键 —— 真实调用请用 `scopeRefs(agent)`,
1087
+ * 那里的优先级是 会话 cwd > 显式配置 > process.cwd()。
1088
+ */
1015
1089
  get activeProjectScope() {
1016
- return this.projectScope
1090
+ return this.defaultProjectScope
1017
1091
  }
1018
1092
 
1019
1093
  assertScopeAllowed(scope ) {
@@ -1081,6 +1155,15 @@ export class LocalMemoryService {
1081
1155
  return resolveCurrentScopes(agent, { projectScope: this.projectScope })
1082
1156
  }
1083
1157
 
1158
+ /**
1159
+ * 当前项目 key(= `scopeRefs(agent).project`)。工具层用它解析 `scope:'project'`,保证与服务端
1160
+ * 读/写口径**同一处** —— 0.5.5 及以前工具层自己算了一份 `project:<process.cwd()>`,于是同一个
1161
+ * 概念在两个层各有各的答案。
1162
+ */
1163
+ projectKeyFor(agent ) {
1164
+ return this.scopeRefs(agent).project
1165
+ }
1166
+
1084
1167
  /**
1085
1168
  * 无显式 scope 时的**读取**合并集合:当前会话 + 当前项目 + global(各自开关生效、按 key 去重)。
1086
1169
  * 工具 / 注入都用它,保证"写进会话的东西,默认读得回来"。
@@ -1213,7 +1296,7 @@ export class LocalMemoryService {
1213
1296
  ? [query.scope]
1214
1297
  : (queryScopes ?? []).length > 0
1215
1298
  ? queryScopes
1216
- : [this.projectScope, 'global']
1299
+ : [this.defaultProjectScope, 'global']
1217
1300
  const stores = []
1218
1301
  const seen = new Set ()
1219
1302
  for (const scope of wanted) {
@@ -1350,7 +1433,7 @@ export class LocalMemoryService {
1350
1433
  ? [input.scope]
1351
1434
  : (input.scopes ?? []).length > 0
1352
1435
  ? input.scopes
1353
- : [this.projectScope]
1436
+ : [this.defaultProjectScope]
1354
1437
  const seen = new Set ()
1355
1438
  for (const scope of targets) {
1356
1439
  if (seen.has(scope)) continue
@@ -1377,7 +1460,7 @@ export class LocalMemoryService {
1377
1460
  ? [input.scope]
1378
1461
  : (input.scopes ?? []).length > 0
1379
1462
  ? input.scopes
1380
- : [this.projectScope]
1463
+ : [this.defaultProjectScope]
1381
1464
  const seen = new Set ()
1382
1465
  let records = []
1383
1466
  for (const scope of wanted) {
@@ -1391,6 +1474,127 @@ export class LocalMemoryService {
1391
1474
  return records.slice(0, input.limit ?? 50)
1392
1475
  }
1393
1476
 
1477
+ /**
1478
+ * 面板新建一条记忆 / 规则。scope 必须是**明确的键**(global / project:<路径> /
1479
+ * session:<id> / 自定义名)—— 面板拿不到会话上下文,'project'/'session' 这种
1480
+ * 相对写法没法解析,直接拒绝比猜一个错的强。
1481
+ */
1482
+ async createRecord(input
1483
+
1484
+
1485
+
1486
+
1487
+
1488
+ ) {
1489
+ const normalized = normalizeScopeInput(input.scope)
1490
+ if (!normalized.ok) throw memoryError('SCOPE_INVALID', normalized.message)
1491
+ if (normalized.scope === undefined) {
1492
+ throw memoryError('SCOPE_INVALID', '面板写入需要明确的 scope(global / project:<路径> / session:<id> / 自定义名)')
1493
+ }
1494
+ return this.save({
1495
+ scope: normalized.scope ,
1496
+ kind: (input.kind ?? 'note') ,
1497
+ content: String(input.content ?? ''),
1498
+ ...(input.tags !== undefined ? { tags: input.tags } : {}),
1499
+ ...(input.importance !== undefined ? { importance: input.importance } : {}),
1500
+ })
1501
+ }
1502
+
1503
+ /**
1504
+ * 导出全部记忆为**纯文本**文档(不含向量)。向量在导入时按当前模型重新算,
1505
+ * 所以换过模型也照样导得回去。
1506
+ */
1507
+ exportAll(now = Date.now())
1508
+
1509
+
1510
+
1511
+
1512
+
1513
+
1514
+
1515
+
1516
+
1517
+
1518
+
1519
+ {
1520
+ this.discoverScopes()
1521
+ const records = []
1522
+ for (const s of this.store.allScopes()) {
1523
+ for (const rec of s.records.values()) {
1524
+ records.push({
1525
+ scope: rec.scope,
1526
+ kind: rec.kind,
1527
+ content: rec.content,
1528
+ tags: rec.tags,
1529
+ importance: rec.importance,
1530
+ createdAt: rec.createdAt,
1531
+ updatedAt: rec.updatedAt,
1532
+ })
1533
+ }
1534
+ }
1535
+ records.sort((a, b) => a.scope.localeCompare(b.scope) || a.createdAt - b.createdAt)
1536
+ return { version: 1, exportedAt: now, records }
1537
+ }
1538
+
1539
+ /**
1540
+ * 导入文本记忆。逐条走 `save()`(凭据扫描 / 上限 / 去重 / 向量回填都在那条路上),
1541
+ * 所以导入的记录会自动按当前模型重新嵌入。返回计数,失败不中断其余条目。
1542
+ */
1543
+ async importRecords(input ) {
1544
+ const list = Array.isArray(input)
1545
+ ? input
1546
+ : (input && typeof input === 'object' && Array.isArray((input ).records))
1547
+ ? (input ).records
1548
+ : null
1549
+ if (list === null) throw memoryError('IMPORT_INVALID', '导入格式不对:需要 {version, records:[...]} 或记录数组')
1550
+ if (list.length > 5000) throw memoryError('IMPORT_TOO_LARGE', `一次最多导入 5000 条(收到 ${list.length} 条)`)
1551
+
1552
+ let imported = 0
1553
+ let skipped = 0
1554
+ let rejected = 0
1555
+ const errors = []
1556
+ for (const [index, raw] of list.entries()) {
1557
+ try {
1558
+ const rec = raw
1559
+ const content = typeof rec.content === 'string' ? rec.content : ''
1560
+ if (content.trim().length === 0) throw new Error('content 为空')
1561
+ const normalized = normalizeScopeInput(typeof rec.scope === 'string' ? rec.scope : undefined)
1562
+ if (!normalized.ok) throw new Error(normalized.message)
1563
+ if (normalized.scope === undefined) throw new Error('缺少明确的 scope')
1564
+ const scope = normalized.scope
1565
+ if (this.store.hasContent(scope, content)) {
1566
+ skipped += 1
1567
+ continue
1568
+ }
1569
+ await this.save({
1570
+ scope,
1571
+ kind: (typeof rec.kind === 'string' && rec.kind.length > 0 ? rec.kind : 'note') ,
1572
+ content,
1573
+ ...(Array.isArray(rec.tags) ? { tags: rec.tags.map(String) } : {}),
1574
+ ...(typeof rec.importance === 'number' ? { importance: rec.importance } : {}),
1575
+ })
1576
+ imported += 1
1577
+ } catch (error) {
1578
+ rejected += 1
1579
+ if (errors.length < 20) errors.push(`#${index}: ${error instanceof Error ? error.message : String(error)}`)
1580
+ }
1581
+ }
1582
+ this.store.scheduleFlush()
1583
+ return { imported, skipped, rejected, errors }
1584
+ }
1585
+
1586
+ /** 规则条数(面板设置页显示;只数已加载/已发现的作用域)。 */
1587
+ ruleStats() {
1588
+ this.discoverScopes()
1589
+ let total = 0
1590
+ let scopes = 0
1591
+ for (const s of this.store.allScopes()) {
1592
+ const n = [...s.records.values()].filter((r) => r.kind === 'rule').length
1593
+ if (n > 0) { total += n; scopes += 1 }
1594
+ }
1595
+ return { total, scopes }
1596
+ }
1597
+
1394
1598
  /**
1395
1599
  * 作用域清单(名字 + 条数 + 待嵌入 + 最近活跃时间),给面板 /status 与 memory_list 的尾部清单用。
1396
1600
  *
@@ -0,0 +1,133 @@
1
+ /**
2
+ * 注入相关的运行时设置 —— 面板「记忆 → 设置」里能开关的那些东西。
3
+ *
4
+ * 为什么放在 provider 侧:设置要落盘(进程重启后还在)、要能通过面板 HTTP
5
+ * 接口读写,而注入半边只是一组纯函数 + 一个 pre-step 监听器。所以 provider
6
+ * 负责存与发事件,注入半边只负责"每步读一次"。
7
+ */
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+         
17
+
18
+
19
+
20
+
21
+
22
+                                
23
+
24
+
25
+
26
+
27
+
28
+                   
29
+
30
+
31
+
32
+
33
+                       
34
+
35
+
36
+
37
+
38
+
39
+
40
+                                   
41
+
42
+
43
+
44
+
45
+
46
+
47
+
48
+
49
+
50
+
51
+
52
+
53
+ export const defaultInjectSettings = {
54
+ recall: { enabled: true, topK: 5, tokenBudget: 500 },
55
+ digest: { enabled: true, topK: 8, tokenBudget: 400 },
56
+ impression: { enabled: true, chars: 120 },
57
+ policy: { enabled: true },
58
+ rules: { enabled: true, maxItems: 10, tokenBudget: 300 },
59
+ turnEnd: { enabled: false },
60
+ }
61
+
62
+ const clampInt = (value , min , max , fallback ) => {
63
+ const n = typeof value === 'number' ? value : Number(value)
64
+ if (!Number.isFinite(n)) return fallback
65
+ return Math.min(max, Math.max(min, Math.round(n)))
66
+ }
67
+
68
+ const bool = (value , fallback ) =>
69
+ typeof value === 'boolean' ? value : fallback
70
+
71
+ /** 容错读取:未知字段忽略、越界值夹紧,配置/面板发来脏数据也不该把注入搞崩。 */
72
+ export function normalizeInjectSettings(raw , base = defaultInjectSettings) {
73
+ let r = (raw && typeof raw === 'object' ? raw : {})
74
+ // 0.5.x 的 inject 小节只有 enabled / topK / tokenBudget(召回),继续认它们。
75
+ const legacy = r
76
+ if (legacy.enabled !== undefined || legacy.topK !== undefined || legacy.tokenBudget !== undefined) {
77
+ r = {
78
+ ...r,
79
+ recall: {
80
+ ...(legacy.enabled !== undefined ? { enabled: legacy.enabled } : {}),
81
+ ...(legacy.topK !== undefined ? { topK: legacy.topK } : {}),
82
+ ...(legacy.tokenBudget !== undefined ? { tokenBudget: legacy.tokenBudget } : {}),
83
+ ...((r.recall && typeof r.recall === 'object' ? r.recall : {}) ),
84
+ },
85
+ }
86
+ }
87
+ const section = (key ) => {
88
+ const value = r[key]
89
+ return (value && typeof value === 'object' ? value : {})
90
+ }
91
+ const recall = section('recall')
92
+ const digest = section('digest')
93
+ const impression = section('impression')
94
+ const policy = section('policy')
95
+ const rules = section('rules')
96
+ const turnEnd = section('turnEnd')
97
+ return {
98
+ recall: {
99
+ enabled: bool(recall.enabled, base.recall.enabled),
100
+ topK: clampInt(recall.topK, 1, 20, base.recall.topK),
101
+ tokenBudget: clampInt(recall.tokenBudget, 50, 4000, base.recall.tokenBudget),
102
+ },
103
+ digest: {
104
+ enabled: bool(digest.enabled, base.digest.enabled),
105
+ topK: clampInt(digest.topK, 1, 30, base.digest.topK),
106
+ tokenBudget: clampInt(digest.tokenBudget, 50, 4000, base.digest.tokenBudget),
107
+ },
108
+ impression: {
109
+ enabled: bool(impression.enabled, base.impression.enabled),
110
+ chars: clampInt(impression.chars, 40, 800, base.impression.chars),
111
+ },
112
+ policy: { enabled: bool(policy.enabled, base.policy.enabled) },
113
+ rules: {
114
+ enabled: bool(rules.enabled, base.rules.enabled),
115
+ maxItems: clampInt(rules.maxItems, 1, 40, base.rules.maxItems),
116
+ tokenBudget: clampInt(rules.tokenBudget, 50, 4000, base.rules.tokenBudget),
117
+ },
118
+ turnEnd: { enabled: bool(turnEnd.enabled, base.turnEnd.enabled) },
119
+ }
120
+ }
121
+
122
+ /** 把面板发来的补丁合并进当前设置(只认已知字段,其余忽略)。 */
123
+ export function mergeInjectSettings(current , patch ) {
124
+ const p = (patch && typeof patch === 'object' ? patch : {})
125
+ const merged = { ...current }
126
+ for (const key of Object.keys(defaultInjectSettings) ) {
127
+ if (p[key] && typeof p[key] === 'object') merged[key] = { ...current[key], ...(p[key] ) }
128
+ }
129
+ return normalizeInjectSettings(merged, current)
130
+ }
131
+
132
+
133
+ //# sourceURL=source/memory-local/src/inject-settings.ts
@@ -225,10 +225,27 @@ export function resolveCurrentScopes(agent , opts
225
225
  sessionId = undefined
226
226
  }
227
227
  const cwd = asString(header?.cwd)
228
- const project = opts.projectScope ?? `project:${cwd ?? process.cwd()}`
228
+ // 项目 key 的优先级:**会话 cwd** > 显式配置的 projectScope > process.cwd()。
229
+ // cwd 必须排第一:`session.header.cwd` 是宿主给的"canonical primary workspace",
230
+ // 而 DSH 服务进程的 process.cwd() 是**profile 目录**(~/.dsh/profiles/<name>),
231
+ // 与工作区无关 —— 0.5.5 及以前把 `project:${process.cwd()}` 当成"配置"先传进来,
232
+ // 结果所有项目的项目级记忆都挤进同一个桶,`project:` 这个作用域等于失效。
233
+ const project = `project:${cwd ?? stripProjectPrefix(opts.projectScope) ?? process.cwd()}`
229
234
  return sessionId !== undefined ? { session: `session:${sessionId}`, project } : { project }
230
235
  }
231
236
 
237
+ /**
238
+ * `project:/x` → `/x`;不是字符串或空串 → undefined(交给下一级回退)。
239
+ *
240
+ * 显式配置按文档写成 `project:/abs/path`(见 tool-memory/cordis.patch.yml),所以拼接前缀前
241
+ * 必须先脱掉已经带上的那一层,否则会得到 `project:project:/x` —— 与配置、与真实落点都对不上。
242
+ */
243
+ function stripProjectPrefix(value ) {
244
+ const s = asString(value)
245
+ if (s === undefined) return undefined
246
+ return (s.startsWith('project:') ? s.slice('project:'.length) : s) || undefined
247
+ }
248
+
232
249
  // ------------------------------------------------------------------ kind → 具体 key
233
250
 
234
251
 
@@ -528,6 +528,17 @@ export class MemoryStore {
528
528
  return { record, deduped: false }
529
529
  }
530
530
 
531
+ /** 该 scope 里是否已有相同内容(导入去重计数用;只读,不建文件)。 */
532
+ hasContent(scope , content ) {
533
+ const s = this.peek(scope)
534
+ if (!s) return false
535
+ const hash = contentHash(scope, content)
536
+ for (const rec of s.records.values()) {
537
+ if (contentHash(rec.scope, rec.content) === hash) return true
538
+ }
539
+ return false
540
+ }
541
+
531
542
  /** Substring match over normalized content, used by forget-by-query. */
532
543
  findIdsByQuery(scope , query ) {
533
544
  // 读/删路径:用 peek,不存在的 scope 返回空,绝不创建。