@restregular/dsh-memory 0.4.0 → 0.5.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.
@@ -0,0 +1,338 @@
1
+ /**
2
+ * 作用域(scope)规范 —— 纯函数,无 cordis / 无 fs 依赖。
3
+ *
4
+ * 为什么需要这一层:早先 scope 的解析分散在四个工具、provider、面板与注入里,规则还不一致
5
+ * (`tool-memory/src/index.ts` 的 scopeOr 把**任何**认不出的值静默回退成默认 scope,于是
6
+ * "写到了别的 scope"这种错永远不报);而 provider 自己的默认值又是 `global`,与工具的
7
+ * `project:<cwd>` 不一致 —— 读路径与写路径各说各话。现在只有一个入口:
8
+ *
9
+ * normalizeScopeInput(raw) 模型/HTTP 传进来的字符串 → 规范化的 scope 或明确错误
10
+ * resolveCurrentScopes(agent)宿主会话上下文 → 当前会话 / 当前项目两个 key
11
+ * resolveScopeRef(...) 把上面两者的 kind 落到具体 key(读 / 写两种口径)
12
+ *
13
+ * 保留名与键空间:
14
+ * global 所有项目共享(文件 global.jsonl)
15
+ * project:<cwd> 一个工作区(文件 projects/<sha1>.jsonl)
16
+ * session:<id> 一个会话(同一个 projects/<sha1>.jsonl 体系)
17
+ * <自定义名> 自由命名,内部键仍是自定义名本身
18
+ * 三者都由 `scopeFileName()` 映射到文件名,因此**自定义名里出现 ':' 一律拒绝**,否则
19
+ * `foo:bar` 会与保留前缀撞成同一个键空间,用户也能靠它伪造 `project:` 键。
20
+ */
21
+ import { createHash } from 'node:crypto'
22
+ import { isCustomScopeKey } from './store.js'
23
+
24
+ /** 作用域键:除 'global' 外的形态由 resolveCurrentScopes / normalizeScopeInput 产生。 */
25
+
26
+
27
+
28
+
29
+ /** normalizeScopeInput 的判别结果(scope 为 undefined 表示"未传")。 */
30
+
31
+
32
+                  
33
+
34
+
35
+
36
+
37
+
38
+
39
+
40
+ /** 自定义名长度上限(码点)。 */
41
+ export const MAX_SCOPE_NAME_CHARS = 64
42
+ /** project: / session: 前缀值的长度上限(路径与 uuid 都可能很长)。 */
43
+ export const MAX_PREFIXED_SCOPE_CHARS = 512
44
+
45
+ /** 保留名:不能作为自定义 scope,也不允许被自定义名覆盖(一律小写比较)。 */
46
+ export const RESERVED_SCOPE_NAMES = new Set(['global', 'project', 'session', 'all'])
47
+
48
+ const KEBAB = '-'
49
+
50
+ /** 控制字符(C0 + DEL + C1)一律拒绝:它们能进文件名映射的输入、也能把日志搅烂。 */
51
+ function hasControlChar(value ) {
52
+ for (const char of value) {
53
+ const code = char.codePointAt(0)
54
+ if (code < 0x20 || code === 0x7f || (code >= 0x80 && code <= 0x9f)) return true
55
+ }
56
+ return false
57
+ }
58
+
59
+ /**
60
+ * 自定义名允许的字符:Unicode 字母 / 数字(含中文)、空格、'-'、'_'、'.'。
61
+ * 用 `\p{L}\p{N}` 而不是 ASCII 白名单,是因为中文 scope 名("项目笔记")是预期用法;
62
+ * 文件名的歧义由 `scopeFileName()` 的 SHA-1 兜底,这里只负责禁止会造成键空间混淆的字符。
63
+ */
64
+ const CUSTOM_NAME_ALLOWED = /^[\p{L}\p{N} _.-]+$/u
65
+
66
+ /** 码点长度({ length } 会把 emoji 数成 2,K 说"按码点")。 */
67
+ function codePointLength(value ) {
68
+ return [...value].length
69
+ }
70
+
71
+ /**
72
+ * 规范化"自定义名"。
73
+ * - 内部空白(含制表/换行)折叠为单个空格;
74
+ * - 转小写(大小写折叠,免出 `Foo` 与 `foo` 两个 scope);
75
+ * - 长度 1~64 码点;
76
+ * - 禁止 ':'、路径分隔符、控制字符、'..'、纯点/空格组成的名字、保留名。
77
+ */
78
+ function normalizeCustomName(raw ) {
79
+ const collapsed = raw.replace(/\s+/gu, ' ').trim()
80
+ if (collapsed.length === 0) return { ok: false, message: 'scope name is empty after normalization' }
81
+ if (hasControlChar(collapsed)) return { ok: false, message: 'scope name must not contain control characters' }
82
+ const name = collapsed.toLowerCase()
83
+ if (codePointLength(name) > MAX_SCOPE_NAME_CHARS) {
84
+ return { ok: false, message: `scope name exceeds ${MAX_SCOPE_NAME_CHARS} characters` }
85
+ }
86
+ if (name === '..' || name === '.') return { ok: false, message: "scope name must not be '.' or '..'" }
87
+ if (/^[. ]+$/u.test(name)) return { ok: false, message: 'scope name must contain more than dots and spaces' }
88
+ if (name.includes('..')) return { ok: false, message: "scope name must not contain '..'" }
89
+ if (name.includes(':')) return { ok: false, message: "scope name must not contain ':'" }
90
+ if (name.includes('/') || name.includes('\\')) {
91
+ return { ok: false, message: 'scope name must not contain path separators' }
92
+ }
93
+ if (RESERVED_SCOPE_NAMES.has(name)) {
94
+ // 'global'/'project'/'session' 在到达这里之前已经各自命中保留分支,所以这里实际拦的是 'all'。
95
+ return { ok: false, message: `scope name "${name}" is reserved` }
96
+ }
97
+ if (!CUSTOM_NAME_ALLOWED.test(name)) {
98
+ return { ok: false, message: 'scope name may only contain letters, digits, spaces, "-", "_" and "."' }
99
+ }
100
+ return { ok: true, name }
101
+ }
102
+
103
+ /**
104
+ * 规范化 `project:` / `session:` 前缀值(旧键与宿主键,原样放行以便读写既有数据)。
105
+ * 只做最小清洗:trim、拒绝控制字符、拒绝空、限长 —— 绝不改写内容,否则旧文件再也找不到。
106
+ */
107
+ function normalizePrefixed(key , label ) {
108
+ const value = key.slice(`${label}:`.length).trim()
109
+ if (value.length === 0) return { ok: false, message: `${label}: scope requires a non-empty value` }
110
+ if (hasControlChar(value)) return { ok: false, message: `${label}: scope value must not contain control characters` }
111
+ if (codePointLength(key) > MAX_PREFIXED_SCOPE_CHARS) {
112
+ return { ok: false, message: `${label}: scope exceeds ${MAX_PREFIXED_SCOPE_CHARS} characters` }
113
+ }
114
+ return { ok: true, key: `${label}:${value}` }
115
+ }
116
+
117
+ /**
118
+ * 把模型 / HTTP query 传进来的原始字符串规范化。
119
+ *
120
+ * 关键语义:
121
+ * - `undefined` / 空串 → `kind: 'current-session'`(调用方按写/读口径决定落到哪里);
122
+ * - 'global' | 'project' | 'session' → 各自的**种类**,不在这里解析 cwd/会话(纯函数拿不到);
123
+ * - 'all' | '*' → 跨所有作用域(仅读路径合法,写路径由 assertWritableScope 拒绝);
124
+ * - 'project:*' | 'session:*' → 原样放行(显式 pin 某个项目 / 某个会话);
125
+ * - 其余 → 自定义名,严格校验。
126
+ *
127
+ * 不合法**不再静默回退**,一律返回 SCOPE_INVALID。
128
+ */
129
+ export function normalizeScopeInput(raw ) {
130
+ // NFC 归一化:同一个中文 scope 从不同输入法过来可能是不同码点序列,不归一化就会分裂成两个 scope。
131
+ const value = typeof raw === 'string' ? raw.normalize('NFC').trim() : ''
132
+ if (value.length === 0) return { ok: true, kind: 'current-session' }
133
+ if (value === '*') return { ok: true, kind: 'all' }
134
+ const lower = value.toLowerCase()
135
+ if (lower === 'global') return { ok: true, kind: 'global', scope: 'global' }
136
+ if (lower === 'project') return { ok: true, kind: 'current-project' }
137
+ if (lower === 'session') return { ok: true, kind: 'current-session' }
138
+ if (lower === 'all') return { ok: true, kind: 'all' }
139
+ if (lower.startsWith('project:')) {
140
+ const prefixed = normalizePrefixed(value, 'project')
141
+ return prefixed.ok
142
+ ? { ok: true, kind: 'project', scope: prefixed.key }
143
+ : { ok: false, code: 'SCOPE_INVALID', message: prefixed.message }
144
+ }
145
+ if (lower.startsWith('session:')) {
146
+ const prefixed = normalizePrefixed(value, 'session')
147
+ return prefixed.ok
148
+ ? { ok: true, kind: 'session', scope: prefixed.key }
149
+ : { ok: false, code: 'SCOPE_INVALID', message: prefixed.message }
150
+ }
151
+ const custom = normalizeCustomName(value)
152
+ return custom.ok
153
+ ? { ok: true, kind: 'custom', scope: custom.name }
154
+ : { ok: false, code: 'SCOPE_INVALID', message: custom.message }
155
+ }
156
+
157
+ /** scope 的种类(用于命名空间 / 阈值 / 排序);未知形态按自定义处理。 */
158
+ export function scopeKind(scope ) {
159
+ if (scope === 'global') return 'global'
160
+ if (scope.startsWith('project:')) return 'project'
161
+ if (scope.startsWith('session:')) return 'session'
162
+ return 'custom'
163
+ }
164
+
165
+ /** 自定义 scope 才计入 scopes.custom.max。 */
166
+ export function isCustomScope(scope ) {
167
+ return isCustomScopeKey(scope)
168
+ }
169
+
170
+ /** 跨 scope 合并排序时的稳定 tie-break:session > project > 自定义 > global。 */
171
+ export function scopeTier(scope ) {
172
+ switch (scopeKind(scope)) {
173
+ case 'session': return 0
174
+ case 'project': return 1
175
+ case 'custom': return 2
176
+ default: return 3
177
+ }
178
+ }
179
+
180
+ /** 写路径遇到只读 scope 时的错误码('all' 不能写)。 */
181
+ export const SCOPE_NOT_WRITABLE = 'SCOPE_NOT_WRITABLE'
182
+
183
+ // ------------------------------------------------------------------ 当前会话 / 当前项目
184
+
185
+ /** 宿主 agent 上我们真正会碰到的那几个字段(其余一律不碰)。 */
186
+
187
+
188
+
189
+
190
+
191
+
192
+
193
+ function asString(value ) {
194
+ return typeof value === 'string' && value.length > 0 ? value : undefined
195
+ }
196
+
197
+
198
+                  
199
+
200
+                
201
+
202
+
203
+
204
+ /**
205
+ * 从宿主的 agent 对象解析出"当前会话 / 当前项目"两个 key。
206
+ *
207
+ * - sessionId 优先 `agent.session.header.id`,退回 `agent.session.id`;
208
+ * - **子代理沿用父会话的记忆**:`header.origin === 'subagent'` 且有 `parentSession` 时,
209
+ * sessionId 取 parentSession(子代理是同一个任务的一部分,不该另起一个记忆作用域);
210
+ * - cwd 优先 `header.cwd`,退回 `projectScope` 配置,最后 `process.cwd()`;
211
+ * - 任何字段缺失都只降级、**绝不抛错**(注入路径上抛错会打断整个 agent 循环)。
212
+ */
213
+ export function resolveCurrentScopes(agent , opts = {}) {
214
+ let header
215
+ let sessionId
216
+ try {
217
+ const session = (agent )?.session
218
+ header = session?.header
219
+ sessionId = asString(header?.id) ?? asString(session?.id)
220
+ if (sessionId !== undefined && header?.origin === 'subagent') {
221
+ sessionId = asString(header.parentSession) ?? sessionId
222
+ }
223
+ } catch {
224
+ // 宿主对象形态意外:当作拿不到会话,继续走 project 回退
225
+ sessionId = undefined
226
+ }
227
+ const cwd = asString(header?.cwd)
228
+ const project = opts.projectScope ?? `project:${cwd ?? process.cwd()}`
229
+ return sessionId !== undefined ? { session: `session:${sessionId}`, project } : { project }
230
+ }
231
+
232
+ // ------------------------------------------------------------------ kind → 具体 key
233
+
234
+
235
+             
236
+
237
+       
238
+
239
+
240
+
241
+
242
+                    
243
+
244
+                 
245
+
246
+          
247
+
248
+
249
+                        
250
+                     
251
+                   
252
+
253
+
254
+
255
+
256
+
257
+
258
+
259
+
260
+ /**
261
+ * 把 normalizeScopeInput 的结果落到具体 key。
262
+ *
263
+ * 写路径(`mode: 'write'`):
264
+ * - `undefined`(字段省略)→ defaultScope 口径;'session' 拿不到会话时**回退 project**,不报错;
265
+ * - 'session' → 同上;'project' → 项目 key;'global' → 'global';
266
+ * - 'all' / '*' → 明确报错(只读);
267
+ * - 显式 'session:<id>' → 原样写入(允许显式 pin 某个会话)。
268
+ * 读路径(`mode: 'read'`):
269
+ * - `undefined` → `scope: undefined`(表示"由调用方决定合并集合",由工具层填三路合并);
270
+ * - 'session' 拿不到会话 → `scope: undefined`(等价于默认合并集合,而不是报错);
271
+ * - 'all' → `{ all: true }`。
272
+ */
273
+ export function resolveScopeRef(
274
+ input ,
275
+ refs ,
276
+ opts ,
277
+ ) {
278
+ if (!input.ok) return { ok: false, code: input.code, message: input.message }
279
+ if (input.kind === 'all') {
280
+ if (opts.mode === 'write') {
281
+ return { ok: false, code: SCOPE_NOT_WRITABLE, message: "scope 'all' is read-only; name one scope to write to" }
282
+ }
283
+ if (opts.allowAll === false) {
284
+ return { ok: false, code: SCOPE_NOT_WRITABLE, message: "scope 'all' is not allowed here; name one scope" }
285
+ }
286
+ return { ok: true, all: true }
287
+ }
288
+ if (input.kind === 'global') return { ok: true, scope: 'global' }
289
+ if (input.kind === 'current-project') return { ok: true, scope: refs.project }
290
+ if (input.kind === 'current-session') {
291
+ // 省略 scope:写路径按会话落点(拿不到会话 / 会话被关 → 回退项目);读路径交给
292
+ // 调用方的合并集合 —— 工具层要的是"会话 + 项目 + global",不是单个 key。
293
+ if (opts.mode === 'write') {
294
+ const current = opts.sessionEnabled === false ? undefined : refs.session
295
+ return { ok: true, scope: writeScopeForDefault(opts.defaultScope, { ...refs, session: current }) }
296
+ }
297
+ return { ok: true }
298
+ }
299
+ if (input.kind === 'session') {
300
+ // 显式 'session:<id>' 原样 pin(开关关掉时由 provider 报 SCOPE_DISABLED);裸 'session'
301
+ // 与省略等价:写按会话(被关则回退项目)、读交给合并集合。
302
+ if (input.scope !== undefined) return { ok: true, scope: input.scope }
303
+ const scope = opts.sessionEnabled === false ? undefined : refs.session
304
+ if (opts.mode === 'write') {
305
+ return { ok: true, scope: writeScopeForDefault(opts.defaultScope, { ...refs, session: scope }) }
306
+ }
307
+ return { ok: true }
308
+ }
309
+ // project / custom:scope 已经在 normalize 阶段确定
310
+ if (input.scope !== undefined) return { ok: true, scope: input.scope }
311
+ return { ok: false, code: 'SCOPE_INVALID', message: 'scope could not be resolved' }
312
+ }
313
+
314
+ /**
315
+ * 写路径的默认口径:model 省略 scope 时按 `tools.defaultScope` 落到哪个 scope。
316
+ * 'session' 拿不到会话 → project(不报错);'global' → global。
317
+ */
318
+ export function writeScopeForDefault(
319
+ defaultScope ,
320
+ refs ,
321
+ ) {
322
+ if (defaultScope === 'global') return 'global'
323
+ if (defaultScope === 'project') return refs.project
324
+ return refs.session ?? refs.project
325
+ }
326
+
327
+ // ------------------------------------------------------------------ 文件名与标签
328
+
329
+ /**
330
+ * 自定义 scope 的稳定短哈希(8 位)。仅用于**展示/调试**;真正的文件名映射仍是
331
+ * `scopeFileName()` 的完整 SHA-1,因此这里不参与任何寻址,不存在撞名风险。
332
+ */
333
+ export function scopeShortHash(scope ) {
334
+ return createHash('sha1').update(scope).digest('hex').slice(0, 8)
335
+ }
336
+
337
+
338
+ //# sourceURL=source/memory-local/src/scope.ts
@@ -3,7 +3,7 @@
3
3
  * atomic compaction (tmp + rename). Vectors live in memory for M1; the .vec
4
4
  * sidecar format arrives in M1.5.
5
5
  */
6
- import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from 'node:fs'
6
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from 'node:fs'
7
7
  import { createHash, randomUUID } from 'node:crypto'
8
8
  import { Buffer } from 'node:buffer'
9
9
  import { dirname, join } from 'node:path'
@@ -13,17 +13,30 @@ import { dirname, join } from 'node:path'
13
13
 
14
14
 
15
15
 
16
+ /** 文件存在且是普通文件(目录同名时 existsSync 也为 true,这里只认文件)。 */
17
+ function fileExists(file ) {
18
+ try {
19
+ return statSync(file).isFile()
20
+ } catch {
21
+ return false
22
+ }
23
+ }
24
+
25
+ /**
26
+ * scope 键 → 文件名。**保持不变**(数据兼容的硬约束):
27
+ * global → global.jsonl
28
+ * 其他任意键 → projects/<sha1(key)>.jsonl
29
+ * 哈希文件名的好处是结构上不可能路径穿越、也没有 Windows 保留名问题;代价是不可读,
30
+ * 所以面板用 /status 的 label 字段负责展示(见 memory-panel/lib/index.js)。
31
+ */
16
32
  export function scopeFileName(scope ) { if (scope === 'global') return 'global.jsonl'
17
33
  const hash = createHash('sha1').update(scope).digest('hex')
18
34
  return join('projects', `${hash}.jsonl`)
19
35
  }
20
36
 
21
- /** Derive the scope for records loaded from a file path. */
22
- export function scopeFromFile(file , knownScopes ) {
23
- if (file.endsWith('global.jsonl')) return 'global'
24
- const base = file.split(/[\\/]/).pop() ?? ''
25
- for (const [scope, name] of knownScopes) if (name === base) return scope
26
- return null
37
+ /** 自定义 scope(既不是 global,也不是 project:/session: 前缀)。 */
38
+ export function isCustomScopeKey(scope ) {
39
+ return scope !== 'global' && !scope.startsWith('project:') && !scope.startsWith('session:')
27
40
  }
28
41
 
29
42
  /**
@@ -278,7 +291,7 @@ export class MemoryStore {
278
291
 
279
292
  loadScope(scope ) {
280
293
  const file = this.fileFor(scope)
281
- if (!existsSync(file)) return
294
+ if (!fileExists(file)) return
282
295
  let text
283
296
  try {
284
297
  text = readFileSync(file, 'utf8')
@@ -326,6 +339,38 @@ export class MemoryStore {
326
339
  return s
327
340
  }
328
341
 
342
+ /**
343
+ * 读路径的 scope 访问:已加载就返回;**磁盘上有数据**就加载并返回;都没有则 `undefined`。
344
+ *
345
+ * 与 `scope()` 的区别是这里绝不创建:早先 `search`/`list`/`forget`/面板 /records 都走
346
+ * `scope()`,于是"查一个不存在的 scope"会在内存里造出一个空 store,`allScopes()` 立刻把它
347
+ * 算进"作用域数",后续任何一次 flush 还会给它落一个空文件。读路径必须无副作用。
348
+ */
349
+ peek(scope ) {
350
+ const existing = this.scopes.get(scope)
351
+ if (existing) return existing
352
+ const file = join(this.root, scopeFileName(scope))
353
+ if (!fileExists(file)) return undefined
354
+ return this.scope(scope)
355
+ }
356
+
357
+ /** 自定义 scope 数(去重后);用于 scopes.custom.max 限额,会话/项目/global 不计入。 */
358
+ customScopeCount() {
359
+ const seen = new Set ()
360
+ for (const s of this.scopes.values()) {
361
+ if (isCustomScopeKey(s.scope)) seen.add(s.scope)
362
+ }
363
+ const projDir = join(this.root, 'projects')
364
+ if (existsSync(projDir)) {
365
+ for (const file of readdirSync(projDir)) {
366
+ if (!file.endsWith('.jsonl')) continue
367
+ const scope = firstScopeInFile(join(projDir, file))
368
+ if (scope !== null && isCustomScopeKey(scope)) seen.add(scope)
369
+ }
370
+ }
371
+ return seen.size
372
+ }
373
+
329
374
  allScopes() {
330
375
  return [...this.scopes.values()]
331
376
  }
@@ -440,7 +485,9 @@ export class MemoryStore {
440
485
 
441
486
  /** Substring match over normalized content, used by forget-by-query. */
442
487
  findIdsByQuery(scope , query ) {
443
- const s = this.scope(scope)
488
+ // 读/删路径:用 peek,不存在的 scope 返回空,绝不创建。
489
+ const s = this.peek(scope)
490
+ if (!s) return []
444
491
  const needle = normalizeContent(query)
445
492
  if (!needle) return []
446
493
  const ids = []