@restregular/dsh-memory 0.18.0 → 0.19.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.
@@ -27,7 +27,13 @@ import {
27
27
 
28
28
  } from './scope.js'
29
29
  import { ScopeNames } from './scope-names.js'
30
- import { SessionVisibilityStore } from './session-visibility.js'
30
+ import {
31
+ SessionVisibilityStore,
32
+ cleanVisibilityRules,
33
+
34
+
35
+
36
+ } from './session-visibility.js'
31
37
  import { mergeInjectSettings, normalizeInjectSettings, } from './inject-settings.js'
32
38
  import { buildStats, lexicalScore, recordScore, tokenize, cosine, normalizeInPlace, hasStrongHit } from './scoring.js'
33
39
  import { EmbedClient } from './embed.js'
@@ -496,6 +502,46 @@ export function resolveConfig(config = {}) {
496
502
 
497
503
 
498
504
 
505
+ /** 生效中的可见域(已剔除被 scope 开关禁用的项)。 */
506
+
507
+
508
+
509
+
510
+
511
+ /** 一条"范围外"命中:给审批浮层展示的完整快照(不落盘,进程内存)。 */
512
+
513
+
514
+
515
+
516
+
517
+
518
+
519
+
520
+                                   
521
+
522
+
523
+
524
+
525
+
526
+
527
+
528
+                    
529
+
530
+
531
+
532
+
533
+
534
+
535
+
536
+
537
+
538
+
539
+
540
+ /** 普通限制下一次审批最多等多久;超时按拒绝处理(工具不会无限挂住)。 */
541
+ const VISIBILITY_APPROVAL_TTL_MS = 5 * 60_000
542
+ /** 审批浮层一次最多展示多少条范围外命中(工具侧仍会返回全部允许的命中)。 */
543
+ const VISIBILITY_APPROVAL_MAX_ITEMS = 20
544
+
499
545
  export class LocalMemoryService {
500
546
  cfg
501
547
  store
@@ -518,6 +564,11 @@ export class LocalMemoryService {
518
564
  inject
519
565
  /** 会话级「记忆可见范围」覆盖;没有覆盖时沿用默认三路集合。 */
520
566
  visibility
567
+ /** 可见域变更通知:下一次 pre-step 注入给 Agent 后删除(按会话)。 */
568
+ visibilityNotices = new Map ()
569
+ /** 普通限制下等待用户审批的范围外访问(按审批 id)。 */
570
+ pendingApprovals = new Map ()
571
+ approvalSeq = 0
521
572
  /**
522
573
  * 会话 id → live session 的只读查询(用于沿 parentSession 链继承可见范围)。
523
574
  * 宿主侧 apply.ts 注入;旧宿主 / 测试里没有时退化为只看当前会话。
@@ -695,8 +746,10 @@ export class LocalMemoryService {
695
746
  *
696
747
  * 默认排除已被 supersede 的旧记录;需要历史/审计时显式 includeSuperseded。
697
748
  */
698
- listSync(input = {}) {
749
+ listSync(input = {}) {
699
750
  const wanted = (input.scopes ?? []).map((scope) => this.canonicalScope(scope))
751
+ // 注入侧必须按可见域的类型白名单过滤;工具侧不传 agent(它需要范围外命中来发起审批)。
752
+ const visibleFilter = input.agent !== undefined ? this.visibilityFilterFor(input.agent) : undefined
700
753
  const seen = new Set ()
701
754
  const stores = []
702
755
  for (const scope of wanted) {
@@ -714,6 +767,7 @@ export class LocalMemoryService {
714
767
  // 过期 state 默认不参与任何自动注入/规则渲染;memory_get(id) 与面板仍可取。
715
768
  if (!input.includeExpired && rec.expiredAt !== undefined && rec.expiredAt < now) continue
716
769
  if (input.kind !== undefined && rec.kind !== input.kind) continue
770
+ if (visibleFilter !== undefined && !visibleFilter(rec.scope, rec.kind)) continue
717
771
  out.push(rec)
718
772
  }
719
773
  }
@@ -1313,29 +1367,30 @@ export class LocalMemoryService {
1313
1367
  }
1314
1368
 
1315
1369
  /** 只保留当前配置允许的 scope(覆盖集合里若含被禁用的 scope,静默剔除)。 */
1316
- filterEnabledScopes(scopes ) {
1317
- const out = []
1318
- for (const raw of scopes) {
1319
- const scope = this.canonicalScope(raw)
1320
- if (out.includes(scope)) continue
1370
+ filterEnabledRules(rules ) {
1371
+ const out = []
1372
+ for (const raw of rules) {
1373
+ const scope = this.canonicalScope(raw.scope)
1374
+ if (out.some((rule) => rule.scope === scope)) continue
1321
1375
  switch (scopeKind(scope)) {
1322
1376
  case 'global': if (!this.cfg.globalEnabled) continue; break
1323
1377
  case 'project': if (!this.cfg.projectEnabled) continue; break
1324
1378
  case 'session': if (!this.cfg.sessionEnabled) continue; break
1325
1379
  default: if (!this.cfg.customEnabled) continue; break
1326
1380
  }
1327
- out.push(scope)
1381
+ // 0.19.1 起不再按记忆类型收窄:旧文件里的 kinds 忽略,只保留作用域。
1382
+ out.push({ scope })
1328
1383
  }
1329
1384
  return out
1330
1385
  }
1331
1386
 
1332
1387
  /**
1333
- * 从会话 id 沿 parentSession 链找最近的显式可见范围。
1388
+ * 从会话 id 沿 parentSession 链找最近的显式可见域。
1334
1389
  *
1335
1390
  * 起点用**当前会话自己的 id**(不是 resolveCurrentScopes 映射后的父会话):
1336
1391
  * 子 Agent 自己也可以有一份覆盖;没有时才沿链继承父会话 / 根会话。
1337
1392
  */
1338
- visibilityForSession(sessionId ) {
1393
+ visibilityForSession(sessionId ) {
1339
1394
  let id = sessionId ?? ''
1340
1395
  const seen = new Set ()
1341
1396
  while (id !== '' && !seen.has(id)) {
@@ -1366,52 +1421,237 @@ export class LocalMemoryService {
1366
1421
  }
1367
1422
 
1368
1423
  /**
1369
- * 显式「记忆可见范围」:解析当前 agent(含子 Agent 的 parentSession 链)的覆盖。
1370
- * undefined = 没有覆盖(调用方沿用默认三路集合 / 不限制 memory_get);
1424
+ * 显式「记忆可见域」的完整策略(含等级与每个 scope 的类型白名单)。
1425
+ * undefined = 没有覆盖;level='none' 时 scopes 仍保留(供面板/下次切换),
1426
+ * 但**不参与**读取限制。
1427
+ */
1428
+ visibilityPolicy(agent ) {
1429
+ const explicit = this.visibilityForSession(this.rawSessionIdOf(agent))
1430
+ if (explicit === undefined) return undefined
1431
+ return { level: explicit.level, scopes: this.filterEnabledRules(explicit.scopes) }
1432
+ }
1433
+
1434
+ /**
1435
+ * 显式「记忆可见范围」的 scope 键列表。
1436
+ * undefined = 不限制(没有覆盖,或等级为 none);
1371
1437
  * [] = 显式设置了范围但全部被 scope 开关禁用,调用方必须按空处理。
1372
1438
  */
1373
1439
  visibleScopes(agent ) {
1374
- const explicit = this.visibilityForSession(this.rawSessionIdOf(agent))
1375
- return explicit === undefined ? undefined : this.filterEnabledScopes(explicit)
1440
+ const policy = this.visibilityPolicy(agent)
1441
+ if (policy === undefined || policy.level === 'none') return undefined
1442
+ return policy.scopes.map((rule) => this.canonicalScope(rule.scope))
1443
+ }
1444
+
1445
+ /** 某个 scope 下允许的记忆类型;undefined = 不限制(可见且没有类型白名单)。 */
1446
+ visibleKinds(agent , scope ) {
1447
+ const policy = this.visibilityPolicy(agent)
1448
+ if (policy === undefined || policy.level === 'none') return undefined
1449
+ const key = this.canonicalScope(scope)
1450
+ const rule = policy.scopes.find((item) => this.canonicalScope(item.scope) === key)
1451
+ if (rule === undefined) return []
1452
+ return rule.kinds !== undefined && rule.kinds.length > 0 ? [...rule.kinds] : undefined
1453
+ }
1454
+
1455
+ /** 一条记录(scope + kind)是否落在当前可见域内;等级 none / 无覆盖时恒为 true。 */
1456
+ isRecordVisible(agent , scope , kind ) {
1457
+ const policy = this.visibilityPolicy(agent)
1458
+ if (policy === undefined || policy.level === 'none') return true
1459
+ const key = this.canonicalScope(scope)
1460
+ const rule = policy.scopes.find((item) => this.canonicalScope(item.scope) === key)
1461
+ if (rule === undefined) return false
1462
+ if (rule.kinds === undefined || rule.kinds.length === 0) return true
1463
+ return rule.kinds.includes(kind)
1464
+ }
1465
+
1466
+ /**
1467
+ * 批量过滤用的可见域判定(策略只解析一次,避免每条记录都走一遍 parentSession 链)。
1468
+ * undefined = 不限制。
1469
+ */
1470
+ visibilityFilterFor(agent ) {
1471
+ const policy = this.visibilityPolicy(agent)
1472
+ if (policy === undefined || policy.level === 'none') return undefined
1473
+ const byScope = new Map ()
1474
+ for (const rule of policy.scopes) {
1475
+ byScope.set(this.canonicalScope(rule.scope), rule.kinds !== undefined && rule.kinds.length > 0 ? rule.kinds : undefined)
1476
+ }
1477
+ return (scope, kind) => {
1478
+ const key = this.canonicalScope(scope)
1479
+ if (!byScope.has(key)) return false
1480
+ const kinds = byScope.get(key)
1481
+ return kinds === undefined || kinds.includes(kind)
1482
+ }
1376
1483
  }
1377
1484
 
1378
1485
  /** 面板:读取某会话自己的覆盖(null = 没有覆盖,继续用默认集合)。 */
1379
- sessionVisibility(sessionId ) {
1486
+ sessionVisibility(sessionId ) {
1380
1487
  if (typeof sessionId !== 'string' || sessionId.trim() === '') return null
1381
- const scopes = this.visibility.get(sessionId.trim())
1382
- return scopes === undefined ? null : [...scopes]
1488
+ const config = this.visibility.get(sessionId.trim())
1489
+ return config === undefined ? null : config
1383
1490
  }
1384
1491
 
1385
- /** 面板:写入/清除某会话的覆盖。null = 恢复默认。 */
1386
- setSessionVisibility(sessionId , scopes ) {
1492
+ /**
1493
+ * 面板:写入/清除某会话的覆盖。null = 恢复默认。
1494
+ * 也接受 0.18 的 `string[]`(按绝对限制 + 全部类型),避免外部调用方升级即断。
1495
+ */
1496
+ setSessionVisibility(sessionId , config ) {
1387
1497
  if (typeof sessionId !== 'string' || sessionId.trim() === '') return null
1388
- const cleaned = scopes === null ? null : this.normalizeVisibilityScopes(scopes)
1389
- if (cleaned !== null && cleaned.length === 0) {
1498
+ const normalized = config === null
1499
+ ? null
1500
+ : Array.isArray(config)
1501
+ ? { scopes: (config ).map((scope) => ({ scope })), level: 'absolute' }
1502
+ : config
1503
+ const cleaned = normalized === null ? null : this.normalizeVisibilityConfig(normalized)
1504
+ const written = this.visibility.set(sessionId.trim(), cleaned)
1505
+ // 变更通知:下一次 pre-step 以 user 消息注入,让 Agent 知道新范围与新规则。
1506
+ this.visibilityNotices.set(sessionId.trim(), { config: written, at: Date.now() })
1507
+ return written
1508
+ }
1509
+
1510
+ /** 校验并规范化面板提交的可见域(必须是具体作用域键;不接受 all/current-*)。 */
1511
+ normalizeVisibilityConfig(config ) {
1512
+ const rules = cleanVisibilityRules(config.scopes)
1513
+ if (rules === undefined || rules.length === 0) {
1390
1514
  throw memoryError('SCOPE_EMPTY', '至少选择一个可见的记忆范围')
1391
1515
  }
1392
- return this.visibility.set(sessionId.trim(), cleaned)
1393
- }
1394
-
1395
- /** 校验并规范化面板提交的 scope 键(必须是具体键;不接受 all/current-*)。 */
1396
- normalizeVisibilityScopes(scopes ) {
1397
- const out = []
1398
- for (const raw of scopes) {
1399
- const normalized = normalizeScopeInput(raw)
1516
+ const out = []
1517
+ for (const rule of rules) {
1518
+ const normalized = normalizeScopeInput(rule.scope)
1400
1519
  if (!normalized.ok) throw memoryError(normalized.code, normalized.message)
1401
1520
  if (normalized.kind === 'all' || normalized.kind === 'current-session' || normalized.kind === 'current-project') {
1402
- throw memoryError('SCOPE_INVALID', `可见范围必须是具体作用域键: ${JSON.stringify(raw)}`)
1521
+ throw memoryError('SCOPE_INVALID', `可见范围必须是具体作用域键: ${JSON.stringify(rule.scope)}`)
1522
+ }
1523
+ if (normalized.scope === undefined) continue
1524
+ const scope = this.canonicalScope(normalized.scope)
1525
+ if (out.some((item) => item.scope === scope)) continue
1526
+ // 不再支持按记忆类型收窄:提交里的 kinds 一律忽略。
1527
+ out.push({ scope })
1528
+ }
1529
+ if (out.length === 0) throw memoryError('SCOPE_EMPTY', '至少选择一个可见的记忆范围')
1530
+ const level = config.level === 'normal' || config.level === 'none' ? config.level : 'absolute'
1531
+ return { scopes: out, level }
1532
+ }
1533
+
1534
+ /**
1535
+ * 取出并删除某会话待注入的「可见域变更」通知。
1536
+ * 沿 parentSession 链找:子 Agent 继承父会话的范围,也应该收到父会话的变更。
1537
+ */
1538
+ takeVisibilityNotice(agent ) {
1539
+ let id = this.rawSessionIdOf(agent) ?? ''
1540
+ const seen = new Set ()
1541
+ while (id !== '' && !seen.has(id)) {
1542
+ seen.add(id)
1543
+ const found = this.visibilityNotices.get(id)
1544
+ if (found !== undefined) {
1545
+ this.visibilityNotices.delete(id)
1546
+ return { config: found.config }
1547
+ }
1548
+ let parent
1549
+ try {
1550
+ const session = this.sessionLookup?.(id)
1551
+ parent = typeof session?.header?.parentSession === 'string' && session.header.parentSession !== ''
1552
+ ? session.header.parentSession
1553
+ : undefined
1554
+ } catch { parent = undefined }
1555
+ id = parent ?? ''
1556
+ }
1557
+ return undefined
1558
+ }
1559
+
1560
+ /** 每个 scope 下按类型统计条数(面板「类型」选择器用)。 */
1561
+ scopeKindStats() {
1562
+ const out = []
1563
+ for (const scope of this.store.allScopes()) {
1564
+ const counts = new Map ()
1565
+ for (const record of scope.records.values()) counts.set(record.kind, (counts.get(record.kind) ?? 0) + 1)
1566
+ for (const [kind, records] of [...counts].sort((a, b) => a[0].localeCompare(b[0]))) {
1567
+ out.push({ scope: scope.scope, kind, records })
1403
1568
  }
1404
- if (normalized.scope !== undefined && !out.includes(normalized.scope)) out.push(normalized.scope)
1405
1569
  }
1406
1570
  return out
1407
1571
  }
1408
1572
 
1573
+ /** 普通限制:范围外命中时创建一条待审批,等待面板回答(超时按拒绝)。 */
1574
+ requestOutOfScope(
1575
+ agent ,
1576
+ input ,
1577
+ ) {
1578
+ if (input.items.length === 0) return Promise.resolve('allowed-once')
1579
+ if (input.signal?.aborted) return Promise.resolve('rejected')
1580
+ const sessionId = this.rawSessionIdOf(agent) ?? ''
1581
+ const id = `vis-${Date.now().toString(36)}-${++this.approvalSeq}`
1582
+ const createdAt = Date.now()
1583
+ const expiresAt = createdAt + VISIBILITY_APPROVAL_TTL_MS
1584
+ return new Promise((resolve) => {
1585
+ let timer
1586
+ const onAbort = () => finish('rejected')
1587
+ const finish = (outcome ) => {
1588
+ const pending = this.pendingApprovals.get(id)
1589
+ if (pending === undefined) return
1590
+ this.pendingApprovals.delete(id)
1591
+ if (timer !== undefined) clearTimeout(timer)
1592
+ try { input.signal?.removeEventListener('abort', onAbort) } catch { /* 已卸载 */ }
1593
+ pending.resolve(outcome)
1594
+ }
1595
+ timer = setTimeout(() => finish('rejected'), VISIBILITY_APPROVAL_TTL_MS)
1596
+ timer.unref?.()
1597
+ this.pendingApprovals.set(id, {
1598
+ id,
1599
+ sessionId,
1600
+ tool: input.tool,
1601
+ query: input.query,
1602
+ items: input.items.slice(0, VISIBILITY_APPROVAL_MAX_ITEMS).map((item) => ({
1603
+ ...item,
1604
+ tags: [...item.tags],
1605
+ })),
1606
+ createdAt,
1607
+ expiresAt,
1608
+ resolve: resolve,
1609
+ timer,
1610
+ })
1611
+ try { input.signal?.addEventListener('abort', onAbort, { once: true }) } catch { /* 已中止 */ }
1612
+ })
1613
+ }
1614
+
1615
+ /** 面板:当前所有待审批(可按会话过滤)。 */
1616
+ pendingVisibilityApprovals(sessionId ) {
1617
+ const out = []
1618
+ for (const pending of this.pendingApprovals.values()) {
1619
+ if (sessionId !== undefined && sessionId !== '' && pending.sessionId !== sessionId) continue
1620
+ out.push({
1621
+ id: pending.id,
1622
+ sessionId: pending.sessionId,
1623
+ tool: pending.tool,
1624
+ query: pending.query,
1625
+ // 轮询载荷保持轻量:正文截到 1200 字,悬浮需要全文时面板再按 id 取一次。
1626
+ items: pending.items.map((item) => ({
1627
+ ...item,
1628
+ content: item.content.length > 1200 ? `${item.content.slice(0, 1200)}…` : item.content,
1629
+ tags: [...item.tags],
1630
+ })),
1631
+ createdAt: pending.createdAt,
1632
+ expiresAt: pending.expiresAt,
1633
+ })
1634
+ }
1635
+ return out.sort((a, b) => a.createdAt - b.createdAt)
1636
+ }
1637
+
1638
+ /** 面板:回答一条待审批。返回 false = 已经不存在/已超时。 */
1639
+ answerVisibilityApproval(id , outcome ) {
1640
+ const pending = this.pendingApprovals.get(id)
1641
+ if (pending === undefined) return false
1642
+ this.pendingApprovals.delete(id)
1643
+ if (pending.timer !== undefined) clearTimeout(pending.timer)
1644
+ pending.resolve(outcome)
1645
+ return true
1646
+ }
1647
+
1409
1648
  /**
1410
1649
  * 无显式 scope 时的**读取**合并集合:当前会话 + 当前项目 + global(各自开关生效、按 key 去重)。
1411
1650
  * 工具 / 注入都用它。会话设置了「可见范围」时以覆盖为准(不再并入默认集合)。
1412
1651
  */
1413
1652
  resolveReadScopes(agent ) {
1414
1653
  const explicit = this.visibleScopes(agent)
1654
+ // level='none' 时 visibleScopes 返回 undefined:不限制读取,继续用默认三路集合。
1415
1655
  if (explicit !== undefined) return explicit
1416
1656
  const refs = this.scopeRefs(agent)
1417
1657
  const out = []
@@ -1605,10 +1845,18 @@ export class LocalMemoryService {
1605
1845
  // 面板的语义检索复用这条流水线,但它是"看一眼"的浏览:不写访问计数,也不在
1606
1846
  // 没有任何向量时白跑一次嵌入请求。这两个开关只给面板的 searchForPanel 用,
1607
1847
  // 工具 / 注入调用不会传。
1608
- const internal = query
1848
+ const internal = query
1609
1849
  const allowVector = internal.vector !== false && this.cfg.vector.enabled && this.cfg.vector.configured
1610
1850
  const includeSuperseded = internal.includeSuperseded === true
1611
1851
  const includeExpired = internal.includeExpired === true
1852
+ // 注入侧按可见域的类型白名单检索(scope → 允许的类型;未列出的 scope 不限制)。
1853
+ // 工具侧不传 kinds:它需要看到范围外命中,才能发起审批。
1854
+ const kindFilter = internal.kinds === undefined
1855
+ ? undefined
1856
+ : (scope , kind ) => {
1857
+ const allowed = internal.kinds [this.canonicalScope(scope)]
1858
+ return allowed === undefined || allowed.length === 0 || allowed.includes(kind)
1859
+ }
1612
1860
 
1613
1861
  // 候选 scope:显式 pin(单值)优先;否则用调用方给的合并集合(query.scopes,
1614
1862
  // 工具 / 注入传"会话 + 项目 + global");两者都没有才退回旧的 project + global。
@@ -1652,6 +1900,7 @@ export class LocalMemoryService {
1652
1900
  const rec = all[i]
1653
1901
  if (!includeExpired && rec.expiredAt && rec.expiredAt < now) continue
1654
1902
  if (!includeSuperseded && retired.has(rec.id)) continue
1903
+ if (kindFilter !== undefined && !kindFilter(rec.scope, rec.kind)) continue
1655
1904
  const lex = lexicalScore(queryTokens, tokenSets[i] , stats)
1656
1905
  if (lex <= 0) continue
1657
1906
  // Weak-only overlap (no shared word/bigram) must clear the "real hit"
@@ -1690,6 +1939,7 @@ export class LocalMemoryService {
1690
1939
  const rec = this.findById(id)
1691
1940
  if (!rec) continue
1692
1941
  if (!includeExpired && rec.expiredAt !== undefined && rec.expiredAt < now) continue
1942
+ if (kindFilter !== undefined && !kindFilter(rec.scope, rec.kind)) continue
1693
1943
  if (!(rec.scope === 'global' && sim < this.cfg.globalThreshold)) {
1694
1944
  candidates.set(id, { record: rec, recallScore: sim, isGlobal: rec.scope === 'global' })
1695
1945
  }
@@ -1860,7 +2110,9 @@ export class LocalMemoryService {
1860
2110
  * 一律走 `peek`,所以列一个不存在的 scope 只会得到空数组,不会造出文件。
1861
2111
  */
1862
2112
  async list(input = {}) {
1863
- const internal = input
2113
+ const internal = input
2114
+ // 注入侧(摘要)传入 agent 时按可见域的类型白名单过滤;工具侧不传,以便处理范围外审批。
2115
+ const visibleFilter = internal.agent !== undefined ? this.visibilityFilterFor(internal.agent) : undefined
1864
2116
  // 显式空集合 = 无可见范围(见 search 的同口径说明)。
1865
2117
  if (input.scope === undefined && input.scopes !== undefined && input.scopes.length === 0) return []
1866
2118
  const wanted = (input.scope !== undefined
@@ -1887,6 +2139,7 @@ export class LocalMemoryService {
1887
2139
  }
1888
2140
  }
1889
2141
  if (input.kind) records = records.filter((r) => r.kind === input.kind)
2142
+ if (visibleFilter !== undefined) records = records.filter((r) => visibleFilter(r.scope, r.kind))
1890
2143
  records.sort((a, b) => b.updatedAt - a.updatedAt)
1891
2144
  return records.slice(0, input.limit ?? 50)
1892
2145
  }
@@ -12,10 +12,16 @@
12
12
  * 同一个 storeDir 可能被多个进程共用(见 store.ts 的 issue #3)。单文件 map 在并发
13
13
  * 写入时会互相覆盖;按会话分文件后,一个会话的写入不影响另一个会话。
14
14
  *
15
- * 语义:
16
- * - 文件存在且 scopes 非空 = 该会话显式指定了可见范围;
15
+ * 语义(0.19.0 起):
16
+ * - 文件存在 = 该会话显式指定了可见域;`level` 决定范围外访问怎么处理:
17
+ * absolute = 一律查不到;normal = 范围外命中时向用户发起一次审批;
18
+ * none = 不限制(选择仅作为下次切换的偏好保留)。
17
19
  * - 文件不存在 = 没有覆盖,继续用默认的三路集合(会话 + 项目 + global);
18
20
  * - scopes 为空数组视为"无覆盖"(面板在保存时也会拒绝空选择),不会把会话锁死。
21
+ * - 每个 scope 可以带 `kinds`:只允许这些记忆类型;省略/空数组 = 该 scope 全部类型。
22
+ *
23
+ * 向后兼容:0.18.x 的 v1 文件只有 `scopes: string[]`,按"绝对限制 + 全部类型"读取;
24
+ * 这样升级当天不会把原来被锁住的范围突然放开。
19
25
  *
20
26
  * 容错:读写失败都只退化为"没有覆盖",绝不把异常抛回检索/注入链路。
21
27
  */
@@ -23,7 +29,24 @@ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync
23
29
  import { join } from 'node:path'
24
30
  import { createHash } from 'node:crypto'
25
31
 
26
- const VERSION = 1
32
+ export const VISIBILITY_VERSION = 2
33
+
34
+ /** 范围外访问的处理方式。 */
35
+
36
+
37
+ export const VISIBILITY_LEVELS = ['absolute', 'normal', 'none']
38
+
39
+ /** 一个可见作用域;`kinds` 省略/为空 = 该作用域下所有类型都可见。 */
40
+
41
+
42
+
43
+
44
+
45
+ /** 一个会话的完整可见域配置。 */
46
+
47
+
48
+
49
+
27
50
 
28
51
 
29
52
                 
@@ -31,9 +54,10 @@ const VERSION = 1
31
54
 
32
55
 
33
56
 
34
-
57
+
35
58
 
36
59
 
60
+
37
61
 
38
62
 
39
63
 
@@ -46,7 +70,7 @@ function safeName(sessionId ) {
46
70
  }
47
71
 
48
72
  /** 只保留非空字符串并去重(顺序即用户勾选顺序);空数组返回 undefined。 */
49
- function cleanScopes(raw ) {
73
+ function cleanStrings(raw ) {
50
74
  if (!Array.isArray(raw)) return undefined
51
75
  const out = []
52
76
  for (const item of raw) {
@@ -58,11 +82,49 @@ function cleanScopes(raw ) {
58
82
  return out.length > 0 ? out : undefined
59
83
  }
60
84
 
85
+ function cleanLevel(raw , fallback = 'absolute') {
86
+ return raw === 'absolute' || raw === 'normal' || raw === 'none' ? raw : fallback
87
+ }
88
+
89
+ /**
90
+ * 规范化 scopes 字段。接受两种形状:
91
+ * - v2: `[{ scope, kinds? }]`
92
+ * - v1: `['project:<path>', 'global']`
93
+ * 非法项跳过;返回 undefined 表示没有任何有效范围。
94
+ */
95
+ export function cleanVisibilityRules(raw ) {
96
+ if (!Array.isArray(raw)) return undefined
97
+ const out = []
98
+ for (const item of raw) {
99
+ if (typeof item === 'string') {
100
+ const scope = item.trim()
101
+ if (scope !== '' && !out.some((rule) => rule.scope === scope)) out.push({ scope })
102
+ continue
103
+ }
104
+ if (item === null || typeof item !== 'object') continue
105
+ const scopeRaw = (item ).scope
106
+ if (typeof scopeRaw !== 'string') continue
107
+ const scope = scopeRaw.trim()
108
+ if (scope === '' || out.some((rule) => rule.scope === scope)) continue
109
+ const kinds = cleanStrings((item ).kinds)
110
+ out.push(kinds === undefined ? { scope } : { scope, kinds })
111
+ }
112
+ return out.length > 0 ? out : undefined
113
+ }
114
+
115
+ /** 读盘结果统一成不可变配置(拷贝一层数组,避免调用方改到缓存)。 */
116
+ function cloneConfig(config ) {
117
+ return {
118
+ level: config.level,
119
+ scopes: config.scopes.map((rule) => (rule.kinds === undefined ? { scope: rule.scope } : { scope: rule.scope, kinds: [...rule.kinds] })),
120
+ }
121
+ }
122
+
61
123
  export class SessionVisibilityStore {
62
124
  dir
63
125
  warn
64
- /** sessionId -> 显式范围;null = 已确认没有文件(避免反复 stat)。 */
65
- cache = new Map ()
126
+ /** sessionId -> 显式配置;null = 已确认没有文件(避免反复 stat)。 */
127
+ cache = new Map ()
66
128
 
67
129
  constructor(options ) {
68
130
  this.dir = join(options.root, 'visibility')
@@ -73,52 +135,64 @@ export class SessionVisibilityStore {
73
135
  return join(this.dir, `${safeName(sessionId)}.json`)
74
136
  }
75
137
 
76
- /** 显式可见范围;undefined = 没有覆盖(用默认集合)。 */
77
- get(sessionId ) {
138
+ /** 显式可见域;undefined = 没有覆盖(用默认集合)。 */
139
+ get(sessionId ) {
78
140
  if (sessionId === '') return undefined
79
141
  const cached = this.cache.get(sessionId)
80
- if (cached !== undefined) return cached ?? undefined
81
- let scopes
142
+ if (cached !== undefined) return cached === null ? undefined : cloneConfig(cached)
143
+ let config
82
144
  try {
83
145
  const file = this.fileOf(sessionId)
84
146
  if (existsSync(file)) {
85
- const parsed = JSON.parse(readFileSync(file, 'utf8'))
86
- scopes = cleanScopes(parsed?.scopes)
87
- if (parsed?.version !== undefined && parsed.version !== VERSION) {
88
- // 未知版本:读得出来就继续用,读不出来就按"无覆盖"处理。
89
- scopes = scopes ?? undefined
147
+ const parsed = JSON.parse(readFileSync(file, 'utf8'))
148
+ const rules = cleanVisibilityRules(parsed?.scopes)
149
+ if (rules !== undefined) {
150
+ // v1 没有 level:沿用旧的"白名单"语义(绝对限制),避免升级把范围放开。
151
+ config = { scopes: rules, level: cleanLevel(parsed?.level, 'absolute') }
90
152
  }
91
153
  }
92
154
  } catch (error) {
93
155
  // 损坏文件不应该让会话失去默认可见范围;只告警一次(缓存 null)。
94
156
  this.warn(`[dsh-memory-local] 忽略损坏的会话可见范围 ${this.fileOf(sessionId)}: ${error instanceof Error ? error.message : String(error)}`)
95
- scopes = undefined
157
+ config = undefined
96
158
  }
97
- this.cache.set(sessionId, scopes ?? null)
98
- return scopes
159
+ this.cache.set(sessionId, config ?? null)
160
+ return config === undefined ? undefined : cloneConfig(config)
99
161
  }
100
162
 
101
- /** 写入/清除显式范围。null 或空数组 = 清除(恢复默认)。返回写入后的值。 */
102
- set(sessionId , scopes ) {
163
+ /** 写入/清除显式配置。null 或空 scopes = 清除(恢复默认)。返回写入后的值。 */
164
+ set(sessionId , config ) {
103
165
  if (sessionId === '') return null
104
- const cleaned = scopes === null ? undefined : cleanScopes(scopes)
105
- try {
106
- const file = this.fileOf(sessionId)
107
- if (cleaned === undefined) {
108
- rmSync(file, { force: true })
166
+ const scopes = config === null ? undefined : cleanVisibilityRules(config.scopes)
167
+ if (config === null || scopes === undefined) {
168
+ try {
169
+ rmSync(this.fileOf(sessionId), { force: true })
109
170
  this.cache.set(sessionId, null)
110
171
  return null
172
+ } catch (error) {
173
+ this.warn(`[dsh-memory-local] 无法清除会话可见范围 ${this.fileOf(sessionId)}: ${error instanceof Error ? error.message : String(error)}`)
174
+ return this.cache.get(sessionId) ?? null
111
175
  }
176
+ }
177
+ const cleaned = { scopes, level: cleanLevel(config.level, 'normal') }
178
+ try {
179
+ const file = this.fileOf(sessionId)
112
180
  mkdirSync(this.dir, { recursive: true })
113
181
  const tmp = `${file}.${process.pid}.${Date.now()}.tmp`
114
- writeFileSync(tmp, `${JSON.stringify({ version: VERSION, scopes: cleaned, updatedAt: Date.now() }, null, 2)}\n`, 'utf8')
182
+ writeFileSync(tmp, `${JSON.stringify({
183
+ version: VISIBILITY_VERSION,
184
+ scopes: cleaned.scopes,
185
+ level: cleaned.level,
186
+ updatedAt: Date.now(),
187
+ }, null, 2)}\n`, 'utf8')
115
188
  renameSync(tmp, file)
116
- this.cache.set(sessionId, cleaned)
117
- return [...cleaned]
189
+ this.cache.set(sessionId, cloneConfig(cleaned))
190
+ return cloneConfig(cleaned)
118
191
  } catch (error) {
119
192
  // 写盘失败:内存里的旧值不清空,但也不能假装成功。调用方会看到旧值。
120
193
  this.warn(`[dsh-memory-local] 无法写入会话可见范围 ${this.fileOf(sessionId)}: ${error instanceof Error ? error.message : String(error)}`)
121
- return this.cache.get(sessionId) ?? null
194
+ const previous = this.cache.get(sessionId) ?? null
195
+ return previous === null ? null : cloneConfig(previous)
122
196
  }
123
197
  }
124
198