@restregular/dsh-memory 0.22.3 → 0.23.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.
@@ -14,7 +14,7 @@
14
14
 
15
15
 
16
16
 
17
- import { MemoryStore, scopeFileName, } from './store.js'
17
+ import { MemoryStore, newId, scopeFileName, } from './store.js'
18
18
  import {
19
19
  canonicalWorkspacePath,
20
20
  isCustomScope,
@@ -34,6 +34,7 @@ import {
34
34
 
35
35
 
36
36
  } from './session-visibility.js'
37
+ import { WorkspaceBindingsStore } from './workspace-bindings.js'
37
38
  import { mergeInjectSettings, normalizeInjectSettings, } from './inject-settings.js'
38
39
  import { buildStats, lexicalScore, recordScore, tokenize, cosine, normalizeInPlace, hasStrongHit } from './scoring.js'
39
40
  import { EmbedClient } from './embed.js'
@@ -598,8 +599,10 @@ export class LocalMemoryService {
598
599
  names
599
600
  /** 注入设置(面板「设置」标签页可改;落盘在 <storeDir>/settings.json)。 */
600
601
  inject
601
- /** 会话级「记忆可见范围」覆盖;没有覆盖时沿用默认三路集合。 */
602
+ /** 会话级「记忆可见范围」覆盖;没有覆盖时沿用默认集合。 */
602
603
  visibility
604
+ /** 工作区级「绑定作用域」:默认范围会额外并入这些作用域。 */
605
+ bindings
603
606
  /** 可见域变更通知:下一次 pre-step 注入给 Agent 后删除(按会话)。 */
604
607
  visibilityNotices = new Map ()
605
608
  /** 普通限制下等待用户审批的范围外访问(按审批 id)。 */
@@ -624,6 +627,7 @@ export class LocalMemoryService {
624
627
  this.inject = this.loadInjectSettings((config ).inject)
625
628
  this.names = new ScopeNames(join(this.cfg.storeDir, 'scopes.json'))
626
629
  this.visibility = new SessionVisibilityStore({ root: this.cfg.storeDir })
630
+ this.bindings = new WorkspaceBindingsStore({ root: this.cfg.storeDir })
627
631
  this.rerankBudget = new DailyBudget(this.cfg.llm.dailyBudgetTokens)
628
632
  this.store = new MemoryStore(this.cfg.storeDir, { onWarn: (m) => console.warn(`[dsh-memory-local] ${m}`) })
629
633
  // Identity BEFORE the eager load (issue #1): ScopeStore skips its sidecar
@@ -1414,8 +1418,13 @@ export class LocalMemoryService {
1414
1418
  case 'session': if (!this.cfg.sessionEnabled) continue; break
1415
1419
  default: if (!this.cfg.customEnabled) continue; break
1416
1420
  }
1417
- // 0.19.1 起不再按记忆类型收窄:旧文件里的 kinds 忽略,只保留作用域。
1418
- out.push({ scope })
1421
+ // 0.19.1 起不再按记忆类型收窄:旧文件里的 kinds 忽略,只保留作用域;
1422
+ // 0.23.0 保留每个作用域的 read / write 状态(false 才落)。
1423
+ out.push({
1424
+ scope,
1425
+ ...(raw.read === false ? { read: false } : {}),
1426
+ ...(raw.write === false ? { write: false } : {}),
1427
+ })
1419
1428
  }
1420
1429
  return out
1421
1430
  }
@@ -1460,7 +1469,7 @@ export class LocalMemoryService {
1460
1469
  }
1461
1470
  }
1462
1471
 
1463
- /** 没有显式覆盖时的默认可见域范围(当前会话 + 当前项目 + global,各自开关生效)。 */
1472
+ /** 没有显式覆盖时的默认可见域范围(会话 + 项目 + global + 工作区绑定的作用域)。 */
1464
1473
  defaultReadScopes(agent ) {
1465
1474
  const refs = this.scopeRefs(agent)
1466
1475
  const out = []
@@ -1471,9 +1480,26 @@ export class LocalMemoryService {
1471
1480
  push(refs.session, this.cfg.sessionEnabled)
1472
1481
  push(refs.project, this.cfg.projectEnabled)
1473
1482
  push('global', this.cfg.globalEnabled)
1483
+ // 0.23.0:工作区绑定的作用域默认可见。会话作用域不能绑定,这里再守一次。
1484
+ for (const raw of this.bindings.get(refs.project)) {
1485
+ const scope = this.canonicalScope(raw)
1486
+ if (scopeKind(scope) === 'session') continue
1487
+ if (!this.scopeEnabled(scope)) continue
1488
+ push(scope, true)
1489
+ }
1474
1490
  return out
1475
1491
  }
1476
1492
 
1493
+ /** 某个具体作用域在当前配置下是否启用(global/project/session/custom 各自开关)。 */
1494
+ scopeEnabled(scope ) {
1495
+ switch (scopeKind(scope)) {
1496
+ case 'global': return this.cfg.globalEnabled
1497
+ case 'project': return this.cfg.projectEnabled
1498
+ case 'session': return this.cfg.sessionEnabled
1499
+ default: return this.cfg.customEnabled
1500
+ }
1501
+ }
1502
+
1477
1503
  /**
1478
1504
  * 生效的「记忆可见域」。**永远有值**(0.20.0 起):没有显式覆盖时返回默认策略。
1479
1505
  * level='none' 时 scopes 仍保留(供面板/下次切换),但**不参与**读写限制。
@@ -1503,7 +1529,9 @@ export class LocalMemoryService {
1503
1529
  visibleScopes(agent ) {
1504
1530
  const resolved = this.resolveVisibility(this.rawSessionIdOf(agent))
1505
1531
  if (resolved === undefined || resolved.config.level === 'none') return undefined
1506
- return this.filterEnabledRules(resolved.config.scopes).map((rule) => this.canonicalScope(rule.scope))
1532
+ return this.filterEnabledRules(resolved.config.scopes)
1533
+ .filter((rule) => rule.read !== false)
1534
+ .map((rule) => this.canonicalScope(rule.scope))
1507
1535
  }
1508
1536
 
1509
1537
  /** 某个 scope 下允许的记忆类型;undefined = 不限制(可见且没有类型白名单)。 */
@@ -1513,6 +1541,7 @@ export class LocalMemoryService {
1513
1541
  const key = this.canonicalScope(scope)
1514
1542
  const rule = policy.scopes.find((item) => this.canonicalScope(item.scope) === key)
1515
1543
  if (rule === undefined) return []
1544
+ if (rule.read === false) return []
1516
1545
  return rule.kinds !== undefined && rule.kinds.length > 0 ? [...rule.kinds] : undefined
1517
1546
  }
1518
1547
 
@@ -1522,20 +1551,35 @@ export class LocalMemoryService {
1522
1551
  if (policy.level === 'none') return true
1523
1552
  const key = this.canonicalScope(scope)
1524
1553
  const rule = policy.scopes.find((item) => this.canonicalScope(item.scope) === key)
1525
- if (rule === undefined) return false
1554
+ if (rule === undefined || rule.read === false) return false
1526
1555
  if (rule.kinds === undefined || rule.kinds.length === 0) return true
1527
1556
  return rule.kinds.includes(kind)
1528
1557
  }
1529
1558
 
1530
- /**
1531
- * 一个作用域是否可读**且可写**(0.20.0 起「可见范围 = 可操作范围」,
1532
- * save / forget 与读取共用这一份口径)。等级 none 时恒为 true。
1533
- */
1534
- isScopeOperable(agent , scope ) {
1559
+ /** 某个作用域是否可读(0.23.0:read 开关);等级 none 时恒为 true。 */
1560
+ isScopeReadable(agent , scope ) {
1535
1561
  const policy = this.visibilityPolicy(agent)
1536
1562
  if (policy.level === 'none') return true
1537
1563
  const key = this.canonicalScope(scope)
1538
- return policy.scopes.some((item) => this.canonicalScope(item.scope) === key)
1564
+ const rule = policy.scopes.find((item) => this.canonicalScope(item.scope) === key)
1565
+ return rule !== undefined && rule.read !== false
1566
+ }
1567
+
1568
+ /** 某个作用域是否可写(0.23.0:write 开关);等级 none 时恒为 true。 */
1569
+ isScopeWritable(agent , scope ) {
1570
+ const policy = this.visibilityPolicy(agent)
1571
+ if (policy.level === 'none') return true
1572
+ const key = this.canonicalScope(scope)
1573
+ const rule = policy.scopes.find((item) => this.canonicalScope(item.scope) === key)
1574
+ return rule !== undefined && rule.write !== false
1575
+ }
1576
+
1577
+ /**
1578
+ * 一个作用域是否可写。0.20 的旧名保留给旧调用方;0.23 起 write 开关独立于 read,
1579
+ * 权威判断见 `isScopeWritable`。
1580
+ */
1581
+ isScopeOperable(agent , scope ) {
1582
+ return this.isScopeWritable(agent, scope)
1539
1583
  }
1540
1584
 
1541
1585
  /**
@@ -1545,15 +1589,18 @@ export class LocalMemoryService {
1545
1589
  visibilityFilterFor(agent ) {
1546
1590
  const policy = this.visibilityPolicy(agent)
1547
1591
  if (policy.level === 'none') return undefined
1548
- const byScope = new Map ()
1592
+ const byScope = new Map ()
1549
1593
  for (const rule of policy.scopes) {
1550
- byScope.set(this.canonicalScope(rule.scope), rule.kinds !== undefined && rule.kinds.length > 0 ? rule.kinds : undefined)
1594
+ byScope.set(this.canonicalScope(rule.scope), {
1595
+ kinds: rule.kinds !== undefined && rule.kinds.length > 0 ? rule.kinds : undefined,
1596
+ read: rule.read !== false,
1597
+ })
1551
1598
  }
1552
1599
  return (scope, kind) => {
1553
1600
  const key = this.canonicalScope(scope)
1554
- if (!byScope.has(key)) return false
1555
- const kinds = byScope.get(key)
1556
- return kinds === undefined || kinds.includes(kind)
1601
+ const entry = byScope.get(key)
1602
+ if (entry === undefined || !entry.read) return false
1603
+ return entry.kinds === undefined || entry.kinds.includes(kind)
1557
1604
  }
1558
1605
  }
1559
1606
 
@@ -1582,6 +1629,51 @@ export class LocalMemoryService {
1582
1629
  return written
1583
1630
  }
1584
1631
 
1632
+ /** 当前工作区 key(= 会话 cwd 解析出的 project scope)。 */
1633
+ workspaceKeyFor(agent ) {
1634
+ return this.scopeRefs(agent).project
1635
+ }
1636
+
1637
+ /** 面板:当前工作区绑定的作用域(默认可见范围会额外并入它们)。 */
1638
+ workspaceBindings(agent ) {
1639
+ const workspace = this.workspaceKeyFor(agent)
1640
+ return this.bindings.get(workspace).map((scope) => this.canonicalScope(scope))
1641
+ }
1642
+
1643
+ /**
1644
+ * 面板:设置当前工作区绑定的作用域。
1645
+ *
1646
+ * 绑定只接受具体作用域键;会话作用域不能绑定(它属于某一次会话,不属于工作区)。
1647
+ * 空数组 = 取消全部绑定。写入后给当前会话发一条可见域变更通知,下一次 pre-step
1648
+ * 让 Agent 知道默认范围可能变了。
1649
+ */
1650
+ setWorkspaceBindings(agent , scopes ) {
1651
+ const workspace = this.workspaceKeyFor(agent)
1652
+ const out = []
1653
+ for (const raw of scopes) {
1654
+ const normalized = normalizeScopeInput(typeof raw === 'string' ? raw : '')
1655
+ if (!normalized.ok) throw memoryError(normalized.code, normalized.message)
1656
+ if (normalized.kind === 'all' || normalized.kind === 'current-session' || normalized.kind === 'current-project' || normalized.scope === undefined) {
1657
+ throw memoryError('SCOPE_INVALID', `绑定必须是具体作用域键: ${JSON.stringify(raw)}`)
1658
+ }
1659
+ const scope = this.canonicalScope(normalized.scope)
1660
+ if (scopeKind(scope) === 'session') {
1661
+ throw memoryError('SCOPE_INVALID', '会话作用域不能绑定到工作区(它只属于某一次会话)')
1662
+ }
1663
+ if (!this.scopeEnabled(scope)) throw memoryError('SCOPE_DISABLED', `作用域 ${scope} 已被禁用,不能绑定`)
1664
+ if (out.includes(scope)) continue
1665
+ out.push(scope)
1666
+ }
1667
+ const written = this.bindings.set(workspace, out)
1668
+ const sessionId = this.rawSessionIdOf(agent)
1669
+ if (sessionId !== undefined) {
1670
+ // 通知的载荷是"本会话自己的覆盖";绑定变化不属于覆盖,但 Agent 需要知道
1671
+ // 默认范围/状态变了,所以仍触发一次(配置取当前自己的覆盖)。
1672
+ this.visibilityNotices.set(sessionId, { config: this.visibility.get(sessionId) ?? null, at: Date.now() })
1673
+ }
1674
+ return written.map((scope) => this.canonicalScope(scope))
1675
+ }
1676
+
1585
1677
  /** 校验并规范化面板提交的可见域(必须是具体作用域键;不接受 all/current-*)。 */
1586
1678
  normalizeVisibilityConfig(config ) {
1587
1679
  const rules = cleanVisibilityRules(config.scopes)
@@ -1598,8 +1690,12 @@ export class LocalMemoryService {
1598
1690
  if (normalized.scope === undefined) continue
1599
1691
  const scope = this.canonicalScope(normalized.scope)
1600
1692
  if (out.some((item) => item.scope === scope)) continue
1601
- // 不再支持按记忆类型收窄:提交里的 kinds 一律忽略。
1602
- out.push({ scope })
1693
+ // 不再支持按记忆类型收窄:提交里的 kinds 一律忽略;read/write 只保留 false。
1694
+ out.push({
1695
+ scope,
1696
+ ...(rule.read === false ? { read: false } : {}),
1697
+ ...(rule.write === false ? { write: false } : {}),
1698
+ })
1603
1699
  }
1604
1700
  if (out.length === 0) throw memoryError('SCOPE_EMPTY', '至少选择一个可见的记忆范围')
1605
1701
  const level = config.level === 'normal' || config.level === 'none' ? config.level : 'absolute'
@@ -1767,18 +1863,22 @@ export class LocalMemoryService {
1767
1863
  }
1768
1864
 
1769
1865
  /**
1770
- * 写入/删除护栏(0.20.0):可见范围 = 可操作范围。
1866
+ * 写入/删除护栏(0.20.0,0.23.0 起区分 read / write 状态)。
1771
1867
  *
1772
- * - absolute:范围外一律拒绝,而且**不暴露**这是可见域限制(视为不存在);
1773
- * - normal:没经过审批就拒绝(工具层会用 `requestOutOfScope` 先问一次,
1774
- * 批准后带 `visibilityApproved` 再调进来);
1775
- * - none:不限制。
1868
+ * - 作用域在范围内但 `write:false` → SCOPE_READ_ONLY,说明是「可写」开关关掉了;
1869
+ * - absolute 且作用域不在范围内 → SCOPE_NOT_WRITABLE,明确告诉 Agent 是绝对限制;
1870
+ * - normal 且作用域不在范围内 → VISIBILITY_APPROVAL_REQUIRED(工具层先审批);
1871
+ * - none:不限制。
1776
1872
  */
1777
1873
  assertOperable(agent , scope ) {
1778
- if (this.isScopeOperable(agent, scope)) return
1779
- const level = this.visibilityPolicy(agent).level
1780
- if (level === 'absolute') {
1781
- throw memoryError('SCOPE_NOT_WRITABLE', `作用域 ${scope} 不存在或不可写`)
1874
+ if (this.isScopeWritable(agent, scope)) return
1875
+ const policy = this.visibilityPolicy(agent)
1876
+ const rule = policy.scopes.find((item) => this.canonicalScope(item.scope) === this.canonicalScope(scope))
1877
+ if (rule !== undefined) {
1878
+ throw memoryError('SCOPE_READ_ONLY', `作用域 ${scope} 在本会话记忆范围里被标记为「不可写」(可读/可写按钮),本次写入/删除没有执行。如需写入,请让用户打开该作用域的「可写」状态。`)
1879
+ }
1880
+ if (policy.level === 'absolute') {
1881
+ throw memoryError('SCOPE_NOT_WRITABLE', `作用域 ${scope} 不在本会话可见范围内(限制等级:绝对限制),本次写入/删除没有执行。如需写入,请让用户调整「记忆范围」后重试。`)
1782
1882
  }
1783
1883
  throw memoryError('VISIBILITY_APPROVAL_REQUIRED', `作用域 ${scope} 不在本会话的可操作范围内,需要用户审批`)
1784
1884
  }
@@ -2340,6 +2440,83 @@ export class LocalMemoryService {
2340
2440
  } )
2341
2441
  }
2342
2442
 
2443
+ /**
2444
+ * 面板编辑(0.23.0):**不原地改旧记录**,而是新建一条修正版并在 `supersedes`
2445
+ * 指向旧记录。旧记录保留(面板历史 / memory_get 仍可取,检索默认隐藏它)。
2446
+ *
2447
+ * 返回 `{ record, superseded }`。内容为空 / 超长 / 命中凭据扫描时的行为与 save 一致。
2448
+ */
2449
+ async reviseRecord(input
2450
+
2451
+
2452
+
2453
+
2454
+
2455
+
2456
+                       
2457
+
2458
+                 
2459
+
2460
+ ) {
2461
+ this.discoverScopes()
2462
+ let found
2463
+ for (const store of this.store.allScopes()) {
2464
+ const record = store.records.get(input.id)
2465
+ if (record !== undefined) { found = { store, record }; break }
2466
+ }
2467
+ if (found === undefined) throw memoryError('RECORD_NOT_FOUND', `no record ${input.id}`)
2468
+ const { store, record: old } = found
2469
+ let content = input.content !== undefined ? String(input.content).trim() : old.content
2470
+ if (content === '') throw memoryError('CONTENT_EMPTY', 'content must be a non-empty string')
2471
+ if (content.length > this.cfg.maxRecordChars) {
2472
+ throw memoryError('CONTENT_TOO_LONG', `content exceeds ${this.cfg.maxRecordChars} chars`)
2473
+ }
2474
+ if (this.cfg.secrets.enabled) {
2475
+ const findings = scanSecrets(content)
2476
+ if (findings.length > 0) {
2477
+ if (this.cfg.secrets.mode === 'refuse') {
2478
+ throw memoryError('SECRET_DETECTED', `content matches credential denylist: ${[...new Set(findings.map((f) => f.kind))].join(', ')}`)
2479
+ }
2480
+ content = redactSecrets(content)
2481
+ }
2482
+ }
2483
+ const now = Date.now()
2484
+ const kind = (input.kind !== undefined ? String(input.kind) : old.kind)
2485
+ const next = {
2486
+ id: newId(),
2487
+ scope: old.scope,
2488
+ kind,
2489
+ content,
2490
+ tags: input.tags !== undefined ? input.tags.map(String) : [...old.tags],
2491
+ source: { origin: 'explicit' },
2492
+ createdAt: now,
2493
+ updatedAt: now,
2494
+ lastAccessedAt: now,
2495
+ accessCount: 0,
2496
+ importance: input.importance !== undefined
2497
+ ? Math.min(1, Math.max(0, Number(input.importance) || 0))
2498
+ : old.importance,
2499
+ supersedes: old.id,
2500
+ }
2501
+ const triggers = input.triggers !== undefined
2502
+ ? input.triggers.map(String)
2503
+ : (old ).triggers
2504
+ if (Array.isArray(triggers)) (next ).triggers = [...triggers]
2505
+ if (input.expiresAt === null) {
2506
+ // 显式清除:不设置 expiredAt。
2507
+ } else if (typeof input.expiresAt === 'number' && Number.isFinite(input.expiresAt)) {
2508
+ next.expiredAt = input.expiresAt
2509
+ } else if (typeof input.ttlMs === 'number' && Number.isFinite(input.ttlMs) && input.ttlMs > 0) {
2510
+ next.expiredAt = now + input.ttlMs
2511
+ } else if (old.expiredAt !== undefined) {
2512
+ next.expiredAt = old.expiredAt
2513
+ }
2514
+ store.insert(next)
2515
+ this.store.scheduleFlush()
2516
+ void this.embedRecord(next).catch(() => {})
2517
+ return { record: next, superseded: old.id }
2518
+ }
2519
+
2343
2520
  /**
2344
2521
  * 导出全部记忆为**纯文本**文档(不含向量)。向量在导入时按当前模型重新算,
2345
2522
  * 所以换过模型也照样导得回去。
@@ -18,7 +18,10 @@
18
18
  * none = 不限制(选择仅作为下次切换的偏好保留)。
19
19
  * - 文件不存在 = 没有覆盖,继续用默认的三路集合(会话 + 项目 + global);
20
20
  * - scopes 为空数组视为"无覆盖"(面板在保存时也会拒绝空选择),不会把会话锁死。
21
- * - 每个 scope 可以带 `kinds`:只允许这些记忆类型;省略/空数组 = 该 scope 全部类型。
21
+ * - 每个 scope 可以带 `read` / `write`:该作用域在本会话里是否可读 / 可写。
22
+ * 省略 = 都可(向后兼容);`read:false` 的作用域不会进入读取集合,`write:false`
23
+ * 的作用域写入 / 删除会被拒绝(工具会把真实原因告诉 Agent)。
24
+ * - 每个 scope 仍可带旧的 `kinds`(0.19.1 起 provider 忽略,只为兼容旧文件)。
22
25
  *
23
26
  * 向后兼容:0.18.x 的 v1 文件只有 `scopes: string[]`,按"绝对限制 + 全部类型"读取;
24
27
  * 这样升级当天不会把原来被锁住的范围突然放开。
@@ -29,16 +32,20 @@ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync
29
32
  import { join } from 'node:path'
30
33
  import { createHash } from 'node:crypto'
31
34
 
32
- export const VISIBILITY_VERSION = 2
35
+ export const VISIBILITY_VERSION = 3
33
36
 
34
37
  /** 范围外访问的处理方式。 */
35
38
 
36
39
 
37
40
  export const VISIBILITY_LEVELS = ['absolute', 'normal', 'none']
38
41
 
39
- /** 一个可见作用域;`kinds` 省略/为空 = 该作用域下所有类型都可见。 */
42
+ /** 一个可见作用域;`read` / `write` 省略 = 都可;`kinds` 省略/为空 = 所有类型。 */
40
43
 
41
44
 
45
+                     
46
+
47
+                    
48
+
42
49
 
43
50
 
44
51
 
@@ -106,8 +113,13 @@ export function cleanVisibilityRules(raw )
106
113
  if (typeof scopeRaw !== 'string') continue
107
114
  const scope = scopeRaw.trim()
108
115
  if (scope === '' || out.some((rule) => rule.scope === scope)) continue
116
+ const rule = { scope }
117
+ // 只落"false"这两档:省略 = 默认可读可写,旧文件因此不需要迁移。
118
+ if ((item ).read === false) rule.read = false
119
+ if ((item ).write === false) rule.write = false
109
120
  const kinds = cleanStrings((item ).kinds)
110
- out.push(kinds === undefined ? { scope } : { scope, kinds })
121
+ if (kinds !== undefined) rule.kinds = kinds
122
+ out.push(rule)
111
123
  }
112
124
  return out.length > 0 ? out : undefined
113
125
  }
@@ -116,7 +128,12 @@ export function cleanVisibilityRules(raw )
116
128
  function cloneConfig(config ) {
117
129
  return {
118
130
  level: config.level,
119
- scopes: config.scopes.map((rule) => (rule.kinds === undefined ? { scope: rule.scope } : { scope: rule.scope, kinds: [...rule.kinds] })),
131
+ scopes: config.scopes.map((rule) => ({
132
+ scope: rule.scope,
133
+ ...(rule.read === false ? { read: false } : {}),
134
+ ...(rule.write === false ? { write: false } : {}),
135
+ ...(rule.kinds === undefined ? {} : { kinds: [...rule.kinds] }),
136
+ })),
120
137
  }
121
138
  }
122
139
 
@@ -0,0 +1,128 @@
1
+ /**
2
+ * 工作区级「绑定作用域」的持久化(0.23.0)。
3
+ *
4
+ * 语义:用户在「记忆范围」面板里可以把若干具体作用域(`global` / 其它项目 /
5
+ * 自定义名)绑定到**当前工作区**。绑定不改变当前会话的显式覆盖,而是让这个
6
+ * 工作区里**没有显式覆盖**的会话,在默认可见范围里额外包含这些作用域。
7
+ *
8
+ * 为什么按工作区分文件:
9
+ * - storeDir 可能被多个进程共用,单个 map 文件并发写会互相覆盖;
10
+ * - 一个工作区一份文件,读写都只碰自己那份,和 session-visibility 同款策略。
11
+ *
12
+ * 文件位置:`<storeDir>/bindings/<hash>.json`,内容
13
+ * `{ version: 1, workspace: 'project:<规范化路径>', scopes: string[], updatedAt }`
14
+ *
15
+ * 容错:读写失败都只退化为「没有绑定」,绝不把异常抛回检索/面板链路。
16
+ */
17
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
18
+ import { createHash } from 'node:crypto'
19
+ import { join } from 'node:path'
20
+
21
+ export const WORKSPACE_BINDINGS_VERSION = 1
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+ function cleanScopes(raw ) {
31
+ if (!Array.isArray(raw)) return []
32
+ const out = []
33
+ for (const item of raw) {
34
+ if (typeof item !== 'string') continue
35
+ const scope = item.trim()
36
+ if (scope === '' || out.includes(scope)) continue
37
+ out.push(scope)
38
+ }
39
+ return out
40
+ }
41
+
42
+ /** 工作区 key 可能包含路径分隔符/中文;用 hash 做文件名,避免平台差异。 */
43
+ function fileNameFor(workspace ) {
44
+ return `${createHash('sha1').update(workspace).digest('hex').slice(0, 20)}.json`
45
+ }
46
+
47
+
48
+                
49
+
50
+
51
+
52
+
53
+ export class WorkspaceBindingsStore {
54
+ dir
55
+ warn
56
+ /** workspace key -> 绑定集合;undefined = 还没读过。 */
57
+ cache = new Map ()
58
+
59
+ constructor(options ) {
60
+ this.dir = join(options.root, 'bindings')
61
+ this.warn = options.warn ?? ((message) => console.warn(message))
62
+ }
63
+
64
+ fileOf(workspace ) {
65
+ return join(this.dir, fileNameFor(workspace))
66
+ }
67
+
68
+ /** 某个工作区绑定的作用域(拷贝)。 */
69
+ get(workspace ) {
70
+ if (typeof workspace !== 'string' || workspace.trim() === '') return []
71
+ const key = workspace.trim()
72
+ const cached = this.cache.get(key)
73
+ if (cached !== undefined) return [...cached]
74
+ let scopes = []
75
+ try {
76
+ const file = this.fileOf(key)
77
+ if (existsSync(file)) {
78
+ const parsed = JSON.parse(readFileSync(file, 'utf8'))
79
+ // 文件里记录的工作区必须与查询一致:hash 碰撞时宁可当没有,也不串工作区。
80
+ if (typeof parsed?.workspace === 'string' && parsed.workspace === key) {
81
+ scopes = cleanScopes(parsed.scopes)
82
+ }
83
+ }
84
+ } catch (error) {
85
+ this.warn(`[dsh-memory-local] 忽略损坏的工作区绑定 ${this.fileOf(key)}: ${error instanceof Error ? error.message : String(error)}`)
86
+ scopes = []
87
+ }
88
+ this.cache.set(key, scopes)
89
+ return [...scopes]
90
+ }
91
+
92
+ /** 写入某个工作区的绑定;空数组 = 清除。返回写入后的值。 */
93
+ set(workspace , scopes ) {
94
+ if (typeof workspace !== 'string' || workspace.trim() === '') return []
95
+ const key = workspace.trim()
96
+ const cleaned = cleanScopes([...scopes])
97
+ try {
98
+ const file = this.fileOf(key)
99
+ if (cleaned.length === 0) {
100
+ rmSync(file, { force: true })
101
+ this.cache.set(key, [])
102
+ return []
103
+ }
104
+ mkdirSync(this.dir, { recursive: true })
105
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`
106
+ writeFileSync(tmp, `${JSON.stringify({
107
+ version: WORKSPACE_BINDINGS_VERSION,
108
+ workspace: key,
109
+ scopes: cleaned,
110
+ updatedAt: Date.now(),
111
+ }, null, 2)}\n`, 'utf8')
112
+ renameSync(tmp, file)
113
+ this.cache.set(key, cleaned)
114
+ return [...cleaned]
115
+ } catch (error) {
116
+ this.warn(`[dsh-memory-local] 无法写入工作区绑定 ${this.fileOf(key)}: ${error instanceof Error ? error.message : String(error)}`)
117
+ return this.get(key)
118
+ }
119
+ }
120
+
121
+ /** 清掉缓存(下一次 get 重新读盘);测试/维护用。 */
122
+ invalidate(workspace ) {
123
+ this.cache.delete(workspace.trim())
124
+ }
125
+ }
126
+
127
+
128
+ //# sourceURL=source/memory-local/src/workspace-bindings.ts