@restregular/dsh-memory 0.6.7 → 0.7.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/README.md +18 -2
- package/lib/client.js +11 -1
- package/lib/panel.js +1 -1
- package/lib/provider/index.js +38 -8
- package/lib/provider/scope-names.js +105 -0
- package/lib/provider/scope.js +5 -0
- package/lib/tools/index.js +45 -8
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -71,8 +71,9 @@ pnpm add @restregular/dsh-memory
|
|
|
71
71
|
```jsonc
|
|
72
72
|
memory_save({
|
|
73
73
|
"content": "本仓库用 pnpm 11 安装依赖,PATH 上的 pnpm 10 会踩 ERR_PNPM_UNEXPECTED_STORE", // 必填,自洽的一句话
|
|
74
|
-
"
|
|
75
|
-
"
|
|
74
|
+
"path": "D:/repositories/dsh-memory", // 可选:工作区目录 → 写入 project:<该路径>
|
|
75
|
+
"scope": "dsh-memory", // 配合 path 时 = 这个作用域的显示名(别名);不给就用路径本身
|
|
76
|
+
"kind": "fact", // fact / decision / preference / procedure / note / rule
|
|
76
77
|
"tags": ["pnpm", "toolchain"],
|
|
77
78
|
"importance": 0.8 // 0~1
|
|
78
79
|
})
|
|
@@ -84,11 +85,19 @@ memory_save({
|
|
|
84
85
|
| --- | --- |
|
|
85
86
|
| 省略 / `session` | **当前会话**(子代理共享父会话;拿不到会话信息时回退到当前项目) |
|
|
86
87
|
| `project` | 当前工作区(键是 `project:<cwd>`) |
|
|
88
|
+
| `path` + 可选 `scope` | **指定工作区目录**:写入 `project:<路径>`,`scope` 变成这个作用域的显示名(别名) |
|
|
87
89
|
| `global` | 所有项目共享 |
|
|
88
90
|
| `handbook`、`项目笔记` … | **自定义作用域**:任意名字,首次 `memory_save` 时自动创建 |
|
|
89
91
|
| `session:<id>` / `project:<path>` | 显式钉住某个会话 / 某个工作区 |
|
|
92
|
+
| `<已登记的别名>` | 读取时可以直接用别名找项目作用域 |
|
|
90
93
|
| `all` / `*` | **只在读取时可用**:跨所有已发现的作用域;写入会明确报错 |
|
|
91
94
|
|
|
95
|
+
**作用域重命名(别名)**:项目作用域的身份永远是 `project:<绝对路径>`,别名只影响显示与引用,不迁移数据。规则:
|
|
96
|
+
- 同一路径重复用同一个名字 = 幂等;换名字 = 覆盖原别名;
|
|
97
|
+
- **另一个路径抢同一个名字 → 拒绝保存**(`SCOPE_NAME_TAKEN`);
|
|
98
|
+
- 只有项目作用域能起别名(`global` / `session` 不支持,报 `SCOPE_NAME_UNSUPPORTED`);
|
|
99
|
+
- 别名落盘在 `<storeDir>/scopes.json`,面板的作用域筛选项显示别名。
|
|
100
|
+
|
|
92
101
|
**2. 检索**:`memory_search({ query: "pnpm 装依赖", topK: 5 })` —— 省略 `scope` = 会话 + 项目 + global 合并(按来源标注、按 id 去重);`scope: "all"` 查所有作用域;写具体名字则只查那一个。
|
|
93
102
|
**3. 按 id 取全文**:召回 / 摘要每行开头是 8 位 id 前缀,`memory_get({ ids: ["3f2a9c1d"] })` 直接拿原文,不用再检索。
|
|
94
103
|
**4. 列出 / 忘记**:`memory_list({ limit: 20 })`(默认只列当前会话,末尾附作用域清单 + 记录数)、`memory_forget({ id })` 或 `memory_forget({ query, scope })`(按内容删默认**只作用于当前会话**,防止跨作用域误删)。
|
|
@@ -111,6 +120,7 @@ memory_save({
|
|
|
111
120
|
| `<storeDir>/projects/<sha1(scope)>.jsonl` | 其它作用域(会话 / 项目 / 自定义)各一个文件;文件名是 scope 键的 SHA-1,所以名字里带路径分隔符也不可能穿越 |
|
|
112
121
|
| `<storeDir>/projects/<sha1(scope)>.vec` | 向量边车。首行是身份头 `#<model>\t<dims>`,后面每行 `id\t<base64 向量>` |
|
|
113
122
|
| `<storeDir>/settings.json` | 面板「设置」里改过的注入开关(配置里的值是默认值,这里覆盖它) |
|
|
123
|
+
| `<storeDir>/scopes.json` | 项目作用域的别名(显示名 → `project:<路径>`),同一路径同名幂等,不同路径同名拒绝 |
|
|
114
124
|
| `<installRoot>/llamacpp/` | llama-server 运行时(exe + 依赖 dll + `llama-server.log`) |
|
|
115
125
|
| `<installRoot>/models/` | 下载的 GGUF 模型 |
|
|
116
126
|
| `<installRoot>/selected-model.json` | 面板里选过哪一档(比配置优先级低) |
|
|
@@ -310,6 +320,12 @@ tools/build-single-package.mjs 构建(产物契约检查 + 可选加载验证)
|
|
|
310
320
|
|
|
311
321
|
## 版本
|
|
312
322
|
|
|
323
|
+
- **0.7.1** —— 「服务」页底部加了 Star / issue 入口:「觉得好用?⭐ 去 GitHub 点个 Star · 💬 反馈建议 / 提 issue」,两段都是外链(仓库主页 / 新建 issue)。
|
|
324
|
+
- **0.7.0** —— 作用域语义:**`path` 指定工作区,`scope` 用作作用域显示名(别名)**。
|
|
325
|
+
- `memory_save({ path: "D:/proj", scope: "我的项目" })` 写入 `project:D:/proj`;省略 `scope` 时名字就是路径。
|
|
326
|
+
- 项目作用域的身份仍是 `project:<绝对路径>`,别名只是显示/引用层,不迁移数据;别名支持在读路径直接使用。
|
|
327
|
+
- 同一路径同名幂等,不同路径同名**拒绝保存**(`SCOPE_NAME_TAKEN`);只有项目作用域可重命名(`global`/`session` 报 `SCOPE_NAME_UNSUPPORTED`);`path` 与 `scope:"global"/"session"` 组合报 `PATH_SCOPE_CONFLICT`。
|
|
328
|
+
- 相对 `path` 按会话 cwd 解析,末尾分隔符会被归一,别名落盘 `<storeDir>/scopes.json`。
|
|
313
329
|
- **0.6.7** —— 记录卡展开后显示**完整 id**(等宽字体,点击复制)与**标签**;折叠时只保留预览与徽标,列表更安静。
|
|
314
330
|
- **0.6.6** —— 记录卡显示**标签气泡**(之前标签只存不显示,新建后看不到,容易误以为没保存);“修正”关系双向标注:修正版显示「修正自 <旧 id 前 8 位>」,被覆盖的旧记录显示「已被修正」(旧记录仍可检索,只是排序降权 0.3×);面板 `/records` 补齐 `supersededBy` 反查;新建表单的标签输入加了标签名与示例。
|
|
315
331
|
- **0.6.5** —— 统计卡从「服务」移到「**记录**」页顶部(和记忆列表放在一起),滚动容器高度相应扣掉统计卡那一档。
|
package/lib/client.js
CHANGED
|
@@ -86,6 +86,9 @@ window.__ModuleLoader__.load({
|
|
|
86
86
|
'.memp .meta-id{font-family:ui-monospace,SFMono-Regular,Consolas,monospace;font-size:11.5px;padding:1px 6px;border-radius:5px;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-2);cursor:pointer;user-select:all}',
|
|
87
87
|
'.memp .meta-id:hover{color:var(--dsw-alias-brand-primary);border-color:var(--dsw-alias-brand-primary)}',
|
|
88
88
|
'.memp .meta-done{color:var(--dsw-alias-brand-primary);font-size:11.5px}',
|
|
89
|
+
'.memp .footer{display:flex;flex-wrap:wrap;align-items:center;gap:2px;margin-top:18px;padding-top:12px;border-top:1px solid var(--dsw-alias-border-l1);font-size:12px;color:var(--dsw-alias-label-secondary)}',
|
|
90
|
+
'.memp .footer a{color:var(--dsw-alias-brand-primary);text-decoration:none}',
|
|
91
|
+
'.memp .footer a:hover{text-decoration:underline}',
|
|
89
92
|
'.memp .pending{flex:none}',
|
|
90
93
|
'.memp .time{margin-left:auto;flex:none}',
|
|
91
94
|
'.memp .preview{margin-top:7px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--dsw-alias-label-secondary);line-height:1.5}',
|
|
@@ -1195,7 +1198,14 @@ window.__ModuleLoader__.load({
|
|
|
1195
1198
|
: h('div', { className: 'list' },
|
|
1196
1199
|
records.map((rec) => h(RecordCard, { key: rec.id, rec, vectorOn: configured && vectorEnabled, labels: labels, onSaved: () => load(), onDeleted: () => load() })))
|
|
1197
1200
|
|
|
1198
|
-
|
|
1201
|
+
// 服务页底部:一句号召 + 两个外链(Star / issue)。放在内容最后,不打扰上面的状态卡。
|
|
1202
|
+
const footer = h('div', { className: 'footer' },
|
|
1203
|
+
'觉得好用?',
|
|
1204
|
+
h('a', { href: 'https://github.com/RestRegular/dsh-memory', target: '_blank', rel: 'noreferrer' }, '⭐ 去 GitHub 点个 Star'),
|
|
1205
|
+
' · ',
|
|
1206
|
+
h('a', { href: 'https://github.com/RestRegular/dsh-memory/issues/new', target: '_blank', rel: 'noreferrer' }, '💬 反馈建议 / 提 issue'),
|
|
1207
|
+
)
|
|
1208
|
+
const overviewBody = h('div', { className: 'memp-body' }, serverCard, maintenanceCard, footer)
|
|
1199
1209
|
// 记录页:统计 + 工具栏 + 新建表单固定在上面,只有列表在滚动容器里 —— 记忆多了也不把面板撑长。
|
|
1200
1210
|
const dataBody = h('div', { className: 'memp-body' },
|
|
1201
1211
|
statsCard,
|
package/lib/panel.js
CHANGED
|
@@ -248,7 +248,7 @@ async function handle(ctx, routePath, req, res) {
|
|
|
248
248
|
// 其余直接用「会话 <id 前 8 位>」。列表本身**始终**完整(不受这个上限影响)。
|
|
249
249
|
const scopes = stats.map((s, index) => ({
|
|
250
250
|
...s,
|
|
251
|
-
label: index < TITLE_LOOKUP_LIMIT ? scopeLabel(ctx, s.scope) : fallbackScopeLabel(s.scope),
|
|
251
|
+
label: s.name ?? (index < TITLE_LOOKUP_LIMIT ? scopeLabel(ctx, s.scope) : fallbackScopeLabel(s.scope)),
|
|
252
252
|
}))
|
|
253
253
|
let embedServer = null
|
|
254
254
|
// older providers have no lifecycle API — the panel simply omits the card
|
package/lib/provider/index.js
CHANGED
|
@@ -24,6 +24,7 @@ import {
|
|
|
24
24
|
writeScopeForDefault,
|
|
25
25
|
|
|
26
26
|
} from './scope.js'
|
|
27
|
+
import { ScopeNames } from './scope-names.js'
|
|
27
28
|
import { mergeInjectSettings, normalizeInjectSettings, } from './inject-settings.js'
|
|
28
29
|
import { buildStats, lexicalScore, recordScore, tokenize, cosine, normalizeInPlace, hasStrongHit } from './scoring.js'
|
|
29
30
|
import { EmbedClient } from './embed.js'
|
|
@@ -489,12 +490,15 @@ export class LocalMemoryService {
|
|
|
489
490
|
projectScope
|
|
490
491
|
/** 上次发现磁盘 scope 的时间(限流用;0 = 还没发现过)。 */
|
|
491
492
|
discoveredAt = 0
|
|
493
|
+
/** 作用域别名(project:<路径> → 显示名),落盘 <storeDir>/scopes.json。 */
|
|
494
|
+
names
|
|
492
495
|
/** 注入设置(面板「设置」标签页可改;落盘在 <storeDir>/settings.json)。 */
|
|
493
496
|
inject
|
|
494
497
|
|
|
495
498
|
constructor(config = {}) {
|
|
496
499
|
this.cfg = resolveConfig(config)
|
|
497
500
|
this.inject = this.loadInjectSettings((config ).inject)
|
|
501
|
+
this.names = new ScopeNames(join(this.cfg.storeDir, 'scopes.json'))
|
|
498
502
|
this.rerankBudget = new DailyBudget(this.cfg.llm.dailyBudgetTokens)
|
|
499
503
|
this.store = new MemoryStore(this.cfg.storeDir, { onWarn: (m) => console.warn(`[dsh-memory-local] ${m}`) })
|
|
500
504
|
// Identity BEFORE the eager load (issue #1): ScopeStore skips its sidecar
|
|
@@ -1184,8 +1188,17 @@ export class LocalMemoryService {
|
|
|
1184
1188
|
async save(input ) {
|
|
1185
1189
|
// 省略 scope 时按当前会话落点 —— 会话上下文必须**从调用方带进来**
|
|
1186
1190
|
// (工具 handler 拿得到 exec.agent,provider 自己看不到)。
|
|
1187
|
-
const
|
|
1191
|
+
const requestedScope = input.scope ?? this.resolveWriteScope((input ).agent)
|
|
1192
|
+
const scope = this.canonicalScope(requestedScope)
|
|
1188
1193
|
this.assertScopeAllowed(scope)
|
|
1194
|
+
// 0.7.0:项目作用域可以带一个显示名(别名)。同一路径同名幂等,不同路径同名拒绝。
|
|
1195
|
+
const requestedName = (input ).name
|
|
1196
|
+
if (requestedName !== undefined && requestedName !== null && String(requestedName).trim() !== '') {
|
|
1197
|
+
if (!scope.startsWith('project:')) {
|
|
1198
|
+
throw memoryError('SCOPE_NAME_UNSUPPORTED', '只有项目作用域支持重命名(需要 path 或 project:<路径>)')
|
|
1199
|
+
}
|
|
1200
|
+
this.names.claim(scope, String(requestedName))
|
|
1201
|
+
}
|
|
1189
1202
|
// 自定义 scope 的**新建**受 scopes.custom.max 限制;写已存在的 scope 不受限。
|
|
1190
1203
|
this.assertCustomScopeBudget(scope)
|
|
1191
1204
|
let content = input.content?.trim()
|
|
@@ -1292,11 +1305,11 @@ export class LocalMemoryService {
|
|
|
1292
1305
|
// 候选 scope:显式 pin(单值)优先;否则用调用方给的合并集合(query.scopes,
|
|
1293
1306
|
// 工具 / 注入传"会话 + 项目 + global");两者都没有才退回旧的 project + global。
|
|
1294
1307
|
// `peek` 而不是 `scope`:读路径不创建,不存在的 scope 直接跳过。
|
|
1295
|
-
const wanted = query.scope
|
|
1308
|
+
const wanted = (query.scope
|
|
1296
1309
|
? [query.scope]
|
|
1297
1310
|
: (queryScopes ?? []).length > 0
|
|
1298
1311
|
? queryScopes
|
|
1299
|
-
: [this.defaultProjectScope, 'global']
|
|
1312
|
+
: [this.defaultProjectScope, 'global']).map((scope) => this.canonicalScope(scope))
|
|
1300
1313
|
const stores = []
|
|
1301
1314
|
const seen = new Set ()
|
|
1302
1315
|
for (const scope of wanted) {
|
|
@@ -1429,11 +1442,11 @@ export class LocalMemoryService {
|
|
|
1429
1442
|
} else if (input.query) {
|
|
1430
1443
|
// 按 query 删除的默认范围由工具层显式给出(默认只有当前会话);这里不再回退到
|
|
1431
1444
|
// provider 的默认 scope —— 那正是"以为删了会话记忆、其实删了 global"的来源。
|
|
1432
|
-
const targets = input.scope !== undefined
|
|
1445
|
+
const targets = (input.scope !== undefined
|
|
1433
1446
|
? [input.scope]
|
|
1434
1447
|
: (input.scopes ?? []).length > 0
|
|
1435
1448
|
? input.scopes
|
|
1436
|
-
: [this.defaultProjectScope]
|
|
1449
|
+
: [this.defaultProjectScope]).map((scope) => this.canonicalScope(scope))
|
|
1437
1450
|
const seen = new Set ()
|
|
1438
1451
|
for (const scope of targets) {
|
|
1439
1452
|
if (seen.has(scope)) continue
|
|
@@ -1456,11 +1469,11 @@ export class LocalMemoryService {
|
|
|
1456
1469
|
* 一律走 `peek`,所以列一个不存在的 scope 只会得到空数组,不会造出文件。
|
|
1457
1470
|
*/
|
|
1458
1471
|
async list(input = {}) {
|
|
1459
|
-
const wanted = input.scope !== undefined
|
|
1472
|
+
const wanted = (input.scope !== undefined
|
|
1460
1473
|
? [input.scope]
|
|
1461
1474
|
: (input.scopes ?? []).length > 0
|
|
1462
1475
|
? input.scopes
|
|
1463
|
-
: [this.defaultProjectScope]
|
|
1476
|
+
: [this.defaultProjectScope]).map((scope) => this.canonicalScope(scope))
|
|
1464
1477
|
const seen = new Set ()
|
|
1465
1478
|
let records = []
|
|
1466
1479
|
for (const scope of wanted) {
|
|
@@ -1619,6 +1632,22 @@ export class LocalMemoryService {
|
|
|
1619
1632
|
return { total, scopes }
|
|
1620
1633
|
}
|
|
1621
1634
|
|
|
1635
|
+
/** 作用域别名(没有则 undefined,调用方回退到路径/键本身)。 */
|
|
1636
|
+
scopeName(scope ) {
|
|
1637
|
+
return this.names.nameOf(scope)
|
|
1638
|
+
}
|
|
1639
|
+
|
|
1640
|
+
/** 名字 → 作用域键:读路径允许直接用别名找作用域。 */
|
|
1641
|
+
scopeKeyForName(name ) {
|
|
1642
|
+
return this.names.scopeOf(name)
|
|
1643
|
+
}
|
|
1644
|
+
|
|
1645
|
+
/** 自定义名可能是别名:统一转回真实键,读写口径共用。 */
|
|
1646
|
+
canonicalScope(scope ) {
|
|
1647
|
+
if (scope === 'global' || scope.startsWith('project:') || scope.startsWith('session:')) return scope
|
|
1648
|
+
return (this.names.scopeOf(scope) ) ?? scope
|
|
1649
|
+
}
|
|
1650
|
+
|
|
1622
1651
|
/**
|
|
1623
1652
|
* 作用域清单(名字 + 条数 + 待嵌入 + 最近活跃时间),给面板 /status 与 memory_list 的尾部清单用。
|
|
1624
1653
|
*
|
|
@@ -1626,11 +1655,12 @@ export class LocalMemoryService {
|
|
|
1626
1655
|
* 漏掉别的进程(上一次会话、另一个 agent)写下的作用域。
|
|
1627
1656
|
* 排序键是"最近活跃"(`updatedAt`):面板据此只给最近活跃的前 N 个会话 scope 查标题。
|
|
1628
1657
|
*/
|
|
1629
|
-
scopeStats()
|
|
1658
|
+
scopeStats() {
|
|
1630
1659
|
this.discoverScopes()
|
|
1631
1660
|
return this.store.allScopes()
|
|
1632
1661
|
.map((s) => ({
|
|
1633
1662
|
scope: s.scope,
|
|
1663
|
+
...(this.names.nameOf(s.scope) !== undefined ? { name: this.names.nameOf(s.scope) } : {}),
|
|
1634
1664
|
records: s.records.size,
|
|
1635
1665
|
pendingEmbeds: s.embedPending.size,
|
|
1636
1666
|
updatedAt: [...s.records.values()].reduce((max, r) => Math.max(max, r.updatedAt), 0),
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 作用域别名(重命名)。
|
|
3
|
+
*
|
|
4
|
+
* 语义(0.7.0 起):
|
|
5
|
+
* - 项目作用域的身份始终是 `project:<绝对路径>`,别名只影响显示与引用;
|
|
6
|
+
* - `memory_save({ path, scope })` 里的 `scope` 是这次写入的**别名**,
|
|
7
|
+
* 不给就用路径本身当名字;
|
|
8
|
+
* - 同一路径复用同名是幂等的;**不同路径抢同一个名字**直接拒绝(SCOPE_NAME_TAKEN);
|
|
9
|
+
* - 别名文件是 `<storeDir>/scopes.json`,与记忆数据同目录。
|
|
10
|
+
*/
|
|
11
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
12
|
+
import { dirname } from 'node:path'
|
|
13
|
+
import { normalizeScopeName } from './scope.js'
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
export class ScopeNames {
|
|
21
|
+
file
|
|
22
|
+
map
|
|
23
|
+
|
|
24
|
+
constructor(file ) {
|
|
25
|
+
this.file = file
|
|
26
|
+
this.map = this.load()
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
load() {
|
|
30
|
+
try {
|
|
31
|
+
if (!existsSync(this.file)) return {}
|
|
32
|
+
const raw = JSON.parse(readFileSync(this.file, 'utf8'))
|
|
33
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return {}
|
|
34
|
+
const out = {}
|
|
35
|
+
for (const [scope, value] of Object.entries(raw )) {
|
|
36
|
+
const name = (value )?.name
|
|
37
|
+
if (typeof name === 'string' && name.length > 0) {
|
|
38
|
+
out[scope] = { name, updatedAt: Number((value ).updatedAt) || 0 }
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return out
|
|
42
|
+
} catch {
|
|
43
|
+
return {}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** 该 scope 的别名(没有则 undefined,调用方回退到路径/键本身)。 */
|
|
48
|
+
nameOf(scope ) {
|
|
49
|
+
return this.map[scope]?.name
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** 名字 → scope 键(读路径可以把名字当 scope 用)。 */
|
|
53
|
+
scopeOf(name ) {
|
|
54
|
+
const wanted = normalizeScopeName(name)
|
|
55
|
+
if (!wanted.ok) return undefined
|
|
56
|
+
for (const [scope, entry] of Object.entries(this.map)) {
|
|
57
|
+
if (entry.name === wanted.name) return scope
|
|
58
|
+
}
|
|
59
|
+
return undefined
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* 给 scope 登记别名。同名同 scope → 幂等;不同 scope 同名 → SCOPE_NAME_TAKEN。
|
|
64
|
+
* 名字规则复用自定义作用域名(小写折叠、1~64 码点、禁止路径分隔符等)。
|
|
65
|
+
*/
|
|
66
|
+
claim(scope , rawName , now = Date.now()) {
|
|
67
|
+
const normalized = normalizeScopeName(rawName)
|
|
68
|
+
if (!normalized.ok) throw nameError('SCOPE_NAME_INVALID', normalized.message)
|
|
69
|
+
const name = normalized.name
|
|
70
|
+
const holder = this.scopeOf(name)
|
|
71
|
+
if (holder !== undefined && holder !== scope) {
|
|
72
|
+
throw nameError('SCOPE_NAME_TAKEN', `作用域名「${name}」已被 ${holder} 使用;换一个名字,或直接用路径作用域`)
|
|
73
|
+
}
|
|
74
|
+
const existing = this.map[scope]
|
|
75
|
+
if (existing?.name === name) return name
|
|
76
|
+
this.map[scope] = { name, updatedAt: now }
|
|
77
|
+
this.persist()
|
|
78
|
+
return name
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** 删除某个 scope 的别名(给未来的“取消重命名”用)。 */
|
|
82
|
+
release(scope ) {
|
|
83
|
+
if (!(scope in this.map)) return
|
|
84
|
+
delete this.map[scope]
|
|
85
|
+
this.persist()
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
persist() {
|
|
89
|
+
try {
|
|
90
|
+
mkdirSync(dirname(this.file), { recursive: true })
|
|
91
|
+
writeFileSync(this.file, `${JSON.stringify(this.map, null, 2)}\n`, 'utf8')
|
|
92
|
+
} catch (error) {
|
|
93
|
+
console.warn(`[dsh-memory-local] 无法写入作用域别名 ${this.file}: ${error instanceof Error ? error.message : String(error)}`)
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function nameError(code , message ) {
|
|
99
|
+
const error = new Error(message)
|
|
100
|
+
error.code = code
|
|
101
|
+
return error
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
//# sourceURL=source/memory-local/src/scope-names.ts
|
package/lib/provider/scope.js
CHANGED
|
@@ -114,6 +114,11 @@ function normalizePrefixed(key , label )
|
|
|
114
114
|
return { ok: true, key: `${label}:${value}` }
|
|
115
115
|
}
|
|
116
116
|
|
|
117
|
+
/** 作用域“显示名/别名”的校验:与自定义作用域名同一套规则(保留名也不许用)。 */
|
|
118
|
+
export function normalizeScopeName(raw ) {
|
|
119
|
+
return normalizeCustomName(raw)
|
|
120
|
+
}
|
|
121
|
+
|
|
117
122
|
/**
|
|
118
123
|
* 把模型 / HTTP query 传进来的原始字符串规范化。
|
|
119
124
|
*
|
package/lib/tools/index.js
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
* resolveReadScopes/resolveWriteScope —— 这里**不再**有任何"smoothing over"式的静默回退。
|
|
12
12
|
*/
|
|
13
13
|
|
|
14
|
+
import { isAbsolute, resolve } from 'node:path'
|
|
14
15
|
import { normalizeScopeInput, resolveScopeRef } from '../provider/scope.js'
|
|
15
16
|
|
|
16
17
|
/** Shape each tool shares: JSON-schema parameters + canonical output value. */
|
|
@@ -144,6 +145,8 @@ function resolveScope(
|
|
|
144
145
|
|
|
145
146
|
|
|
146
147
|
|
|
148
|
+
|
|
149
|
+
|
|
147
150
|
|
|
148
151
|
|
|
149
152
|
|
|
@@ -153,16 +156,32 @@ function resolveScope(
|
|
|
153
156
|
|
|
154
157
|
|
|
155
158
|
|
|
159
|
+
|
|
160
|
+
|
|
156
161
|
|
|
157
162
|
|
|
158
163
|
|
|
164
|
+
/**
|
|
165
|
+
* `path` → 绝对工作区路径。相对路径按会话 cwd 解析(拿不到就按进程 cwd),
|
|
166
|
+
* 去掉末尾分隔符 —— 同一个目录必须只有一种写法,否则 project:<路径> 会分叉。
|
|
167
|
+
*/
|
|
168
|
+
function resolveWorkspacePath(raw , agent ) {
|
|
169
|
+
const value = raw.trim()
|
|
170
|
+
if (value === '') throw new MemoryToolError('PATH_INVALID', 'path 不能为空')
|
|
171
|
+
const cwd = (agent )?.session?.header?.cwd
|
|
172
|
+
const base = typeof cwd === 'string' && cwd.length > 0 ? cwd : process.cwd()
|
|
173
|
+
const full = isAbsolute(value) ? value : resolve(base, value)
|
|
174
|
+
return full.replace(/[\\/]+$/u, '') || full
|
|
175
|
+
}
|
|
176
|
+
|
|
159
177
|
export function memorySaveTool(opts ) {
|
|
160
178
|
return {
|
|
161
179
|
name: 'memory_save',
|
|
162
180
|
description: 'Save a durable memory (fact, decision, preference, procedure, rule) for future sessions.',
|
|
163
181
|
parameters: {
|
|
164
182
|
content: { type: 'string', description: 'Self-contained declarative sentence, readable without context', required: true },
|
|
165
|
-
scope: { type: 'string', description: SCOPE_DESCRIPTION },
|
|
183
|
+
scope: { type: 'string', description: `${SCOPE_DESCRIPTION};配合 path 时表示该工作区作用域的显示名(别名)` },
|
|
184
|
+
path: { type: 'string', description: '工作区目录路径;给出后写入 project:<路径>,此时 scope 用作该作用域的显示名(别名,可省略 = 用路径本身)' },
|
|
166
185
|
kind: { type: 'string', enum: ['fact', 'decision', 'preference', 'procedure', 'note', 'rule'] },
|
|
167
186
|
tags: { type: 'array', items: { type: 'string' } },
|
|
168
187
|
importance: { type: 'number', description: '0~1, higher = more important' },
|
|
@@ -180,16 +199,34 @@ export function memorySaveTool(opts )
|
|
|
180
199
|
// project)。默认值的最终权威是 provider 的 `save` —— 省略时干脆不带 scope 字段,
|
|
181
200
|
// 但要把会话上下文(exec.agent)带过去,否则它没法知道"当前会话"是谁。
|
|
182
201
|
const requested = args.scope?.trim()
|
|
183
|
-
const explicit = requested === undefined || requested === ''
|
|
184
|
-
? undefined
|
|
185
|
-
: resolveScope(opts, service, exec, requested, 'write').scope
|
|
186
|
-
if (requested !== undefined && requested !== '' && explicit === undefined) {
|
|
187
|
-
throw new MemoryToolError('SCOPE_INVALID', 'scope could not be resolved')
|
|
188
|
-
}
|
|
189
202
|
const agent = agentOf(exec)
|
|
203
|
+
const pathArg = typeof args.path === 'string' ? args.path.trim() : ''
|
|
204
|
+
|
|
205
|
+
let explicit
|
|
206
|
+
let alias
|
|
207
|
+
if (pathArg !== '') {
|
|
208
|
+
// path 给出 = 项目作用域;scope 此时是它的显示名,不再当 scope 选择器用。
|
|
209
|
+
if (requested !== undefined && requested !== '' && requested !== 'project') {
|
|
210
|
+
if (requested === 'global' || requested === 'session' || requested === 'all') {
|
|
211
|
+
throw new MemoryToolError('PATH_SCOPE_CONFLICT', `path 只能配合项目作用域使用,不能再指定 scope="${requested}"`)
|
|
212
|
+
}
|
|
213
|
+
alias = requested
|
|
214
|
+
}
|
|
215
|
+
explicit = `project:${resolveWorkspacePath(pathArg, agent)}`
|
|
216
|
+
} else {
|
|
217
|
+
const resolved = requested === undefined || requested === ''
|
|
218
|
+
? undefined
|
|
219
|
+
: resolveScope(opts, service, exec, requested, 'write').scope
|
|
220
|
+
if (requested !== undefined && requested !== '' && resolved === undefined) {
|
|
221
|
+
throw new MemoryToolError('SCOPE_INVALID', 'scope could not be resolved')
|
|
222
|
+
}
|
|
223
|
+
explicit = resolved
|
|
224
|
+
}
|
|
225
|
+
|
|
190
226
|
try {
|
|
191
227
|
const record = await service.save({
|
|
192
228
|
...(explicit !== undefined ? { scope: explicit } : {}),
|
|
229
|
+
...(alias !== undefined ? { name: alias } : {}),
|
|
193
230
|
...(agent !== undefined ? { agent } : {}),
|
|
194
231
|
kind: args.kind ?? 'note',
|
|
195
232
|
content: args.content.trim(),
|
|
@@ -198,7 +235,7 @@ export function memorySaveTool(opts )
|
|
|
198
235
|
...(args.supersedes ? { supersedes: args.supersedes } : {}),
|
|
199
236
|
source: { origin: 'explicit' },
|
|
200
237
|
})
|
|
201
|
-
return { id: record.id, scope: record.scope, deduped: false }
|
|
238
|
+
return { id: record.id, scope: record.scope, ...(alias !== undefined ? { scopeName: alias } : {}), deduped: false }
|
|
202
239
|
} catch (error) {
|
|
203
240
|
throw toolError(error)
|
|
204
241
|
}
|