@yolk_vat-y/dsh-project-memory 0.6.5 → 0.6.6
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/CHANGELOG.md +88 -0
- package/README.md +17 -4
- package/README.zh-CN.md +16 -4
- package/package.json +6 -4
- package/scripts/bench-edits.mjs +87 -0
- package/skills/project-memory/SKILL.md +72 -0
- package/skills/project-memory/scripts/pm-digest.mjs +138 -0
- package/src/audit.js +6 -0
- package/src/auto-inject.js +61 -15
- package/src/doc-index.js +7 -5
- package/src/doc-pipeline.js +2 -0
- package/src/index.js +8 -0
- package/src/insight-store.js +56 -6
- package/src/ops.js +226 -36
- package/src/readiness.js +60 -9
- package/src/recall.js +5 -1
- package/src/skill.js +84 -0
- package/src/store.js +123 -28
- package/src/util/flush.js +62 -0
- package/src/util/fs.js +227 -34
- package/src/util/persist.js +27 -0
- package/src/util/ru.js +201 -0
- package/src/util/search.js +20 -0
- package/src/vector-index.js +4 -0
- package/src/watch.js +34 -8
package/src/readiness.js
CHANGED
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
import { FALLBACK_OPS, WEAK_OPS, activityFromText, opForLegacyAction } from './ops.js'
|
|
20
20
|
import { extractPathTokens } from './util/path-token.js'
|
|
21
21
|
import { CJK_RANGE, tokenize } from './util/search.js'
|
|
22
|
+
import { CYRILLIC_RANGE, RU_STOPWORDS, normalizeRuWord } from './util/ru.js'
|
|
22
23
|
|
|
23
24
|
/**
|
|
24
25
|
* 动作词典:动作 id → 匹配模式。命令形态与人类意图词都归一成同一套 id,
|
|
@@ -29,13 +30,28 @@ export const ACTION_LEXICON = [
|
|
|
29
30
|
['git-commit', [/git\s+commit\b/i, /提交/]],
|
|
30
31
|
['git-push', [/git\s+push\b/i, /推送/]],
|
|
31
32
|
['npm-publish', [/npm\s+publish\b/i, /发包/, /发布\s*到\s*npm/i]],
|
|
32
|
-
|
|
33
|
+
// 英文 `release` 只在带版本号时才算动作:`release notes` 是文档任务,不是发版。
|
|
34
|
+
['release', [/git\s+tag\b/i, /发版/, /发布版本/, /\brelease\s+v?\d/i]],
|
|
33
35
|
['go-public', [/公开/, /开源/, /对外/, /上线/]],
|
|
34
36
|
['delete', [/rm\s+-rf\b/, /git\s+rm\b/, /删除/, /清理/]],
|
|
35
37
|
['migrate', [/migrate\b/i, /迁移/]],
|
|
36
38
|
['deploy', [/\bdeploy\b/i, /部署/]],
|
|
37
39
|
]
|
|
38
40
|
|
|
41
|
+
/**
|
|
42
|
+
* 允许**人类消息里的动作词**触发全文注入的 op 白名单。
|
|
43
|
+
*
|
|
44
|
+
* 判据是"这条记忆必须在动作**之前**到达,晚了就没用,且动作不可逆":
|
|
45
|
+
* 提交 / 发 npm 包 / 发版 / 推远端 / 部署 / 公开仓库。这几个词在散文里也基本只有一种意思,
|
|
46
|
+
* 而且都发生在"动作之前才有用"的位置(提交后再说"检查公开面"就晚了)。
|
|
47
|
+
*
|
|
48
|
+
* 反过来,`删除 / 清理 / 渲染 / 基准 / 取网页 / 查询记忆` 这些词在人类消息里经常只是
|
|
49
|
+
* **提及**("删除后的悬空状态"、"清理一下 README 的措辞"、"这个渲染是错的"),
|
|
50
|
+
* 用它们做确定性全文注入实测代价是 1200 字符一条的无关 procedure。
|
|
51
|
+
* 这些动作仍可由**已观察到的工具调用**触发(`rm` 真的执行了、`soffice` 真的跑了)。
|
|
52
|
+
*/
|
|
53
|
+
export const PRE_ACTION_OPS = new Set(['npm-publish', 'release', 'git-commit', 'git-push', 'deploy', 'go-public'])
|
|
54
|
+
|
|
39
55
|
/**
|
|
40
56
|
* 文本 → 动作 id 列表(确定性、去重、词典序稳定)。
|
|
41
57
|
* @param {string} text - 人类消息或工具调用参数。
|
|
@@ -64,17 +80,27 @@ export function extractPaths(text) {
|
|
|
64
80
|
|
|
65
81
|
/**
|
|
66
82
|
* 组装就绪上下文:人类意图 + 已观察动作。三处来源都做动作/路径归一,调用方只需给文本。
|
|
83
|
+
*
|
|
84
|
+
* **证据来源决定准入**(2026-10-25):observed(结构化工具调用)可以触发全文注入;
|
|
85
|
+
* 人类消息里的动作词只允许 4 个"不可逆外部动作"触发全文(见 {@link PRE_ACTION_OPS}),
|
|
86
|
+
* 其余只进提示通道。原因见 PRE_ACTION_OPS 的注释。
|
|
67
87
|
* @param {object} input
|
|
68
88
|
* @param {string} [input.humanText] - 本轮人类消息(先发窗口)。
|
|
69
|
-
* @param {string} [input.actionText] -
|
|
89
|
+
* @param {string} [input.actionText] - 旧调用方的工具调用文本(测试/老宿主;生产路径不再传)。
|
|
90
|
+
* @param {string[]} [input.ops] - 结构化工具调用归一出的动作(可信)。
|
|
91
|
+
* @param {string[]} [input.targets] - 结构化写目标(可信)。
|
|
70
92
|
* @param {string[]} [input.actions] - 调用方已归一化的动作 id(可选,会被并集)。
|
|
71
93
|
* @param {string[]} [input.paths] - 调用方已归一化的路径(可选,会被并集)。
|
|
72
|
-
* @returns {{ humanText: string, actionText: string, actions: string[], paths: string[] }}
|
|
94
|
+
* @returns {{ humanText: string, actionText: string, actions: string[], paths: string[], humanPaths: string[], ops: string[], opsObserved: string[], intentOps: string[], targets: string[], hosts: string[], intent: string, tags: string[] }}
|
|
73
95
|
*/
|
|
74
96
|
export function buildReadinessContext(input = {}) {
|
|
75
97
|
const humanText = String(input.humanText ?? input.query ?? '')
|
|
76
98
|
const actionText = String(input.actionText || '')
|
|
77
|
-
|
|
99
|
+
// `input.actions` 是调用方**已归一化**的动作(测试/老宿主),当作已观察证据;
|
|
100
|
+
// 只有从 humanText 里现猜出来的词才受 PRE_ACTION_OPS 约束。
|
|
101
|
+
const declaredActions = new Set(input.actions || [])
|
|
102
|
+
const proseActions = detectActions(humanText)
|
|
103
|
+
const actions = new Set([...declaredActions, ...proseActions])
|
|
78
104
|
// 人类消息里提到的路径 = **动手前的写意图**("帮我改 src/x.js");动作文本里的路径不区分读写,
|
|
79
105
|
// 读一个文件不该算写目标(否则 `read README.md` 会命中 writes:['README.md'])。
|
|
80
106
|
// 两者对外仍合并成 `paths`(兼容既有语义),写通道单看 humanPaths。
|
|
@@ -87,11 +113,20 @@ export function buildReadinessContext(input = {}) {
|
|
|
87
113
|
const paths = new Set([...humanPaths, ...extractPaths(actionText)])
|
|
88
114
|
// 动作平面(S1):结构化调用优先;没有结构化调用时对 actionText 跑一遍 shell 规则兜底。
|
|
89
115
|
const fromText = activityFromText(actionText)
|
|
90
|
-
const
|
|
91
|
-
for (const a of
|
|
116
|
+
const opsObserved = new Set([...(input.ops || []), ...fromText.ops])
|
|
117
|
+
for (const a of declaredActions) {
|
|
92
118
|
const op = opForLegacyAction(a)
|
|
93
|
-
if (op)
|
|
119
|
+
if (op) opsObserved.add(op)
|
|
94
120
|
}
|
|
121
|
+
// 人类消息里的动作词:`删除/清理/渲染/基准/取网页` 在散文里太容易是**提及**
|
|
122
|
+
// (实测 "删除后的悬空状态"、"清理一下 README 的措辞" 都命中过 file-delete,
|
|
123
|
+
// 后者注入了一条 1200 字符的恢复 procedure)。只有没法等的不可逆外部动作才允许先发。
|
|
124
|
+
const intentOps = new Set()
|
|
125
|
+
for (const a of proseActions) {
|
|
126
|
+
const op = opForLegacyAction(a)
|
|
127
|
+
if (op) intentOps.add(op)
|
|
128
|
+
}
|
|
129
|
+
const ops = new Set([...opsObserved, ...[...intentOps].filter((op) => PRE_ACTION_OPS.has(op))])
|
|
95
130
|
const targets = new Set([...(input.targets || []), ...fromText.targets])
|
|
96
131
|
const hosts = new Set([...(input.hosts || []), ...fromText.hosts])
|
|
97
132
|
return {
|
|
@@ -101,6 +136,8 @@ export function buildReadinessContext(input = {}) {
|
|
|
101
136
|
paths: [...paths],
|
|
102
137
|
humanPaths: [...humanPaths],
|
|
103
138
|
ops: [...ops],
|
|
139
|
+
opsObserved: [...opsObserved],
|
|
140
|
+
intentOps: [...intentOps],
|
|
104
141
|
targets: [...targets],
|
|
105
142
|
hosts: [...hosts],
|
|
106
143
|
intent: intentText(humanText),
|
|
@@ -213,7 +250,7 @@ export function intentText(text) {
|
|
|
213
250
|
.replace(/[A-Za-z]:\\[^\s"']*/g, ' ')
|
|
214
251
|
.replace(/(?:[A-Za-z0-9_.@-]+\/)+[A-Za-z0-9_.@-]+/g, ' ')
|
|
215
252
|
// 带扩展名的**非 ASCII 文件名**(`示例调研.pptx` / `docs/示例.md`):
|
|
216
|
-
// 只挡 ASCII 路径不够——中文文件名整块留下,"调研""
|
|
253
|
+
// 只挡 ASCII 路径不够——中文文件名整块留下,"调研""演示"这类子串照样触发 when.intents,
|
|
217
254
|
// 正是引号剥离要防的那类假阳性。ASCII 裸名(如 notes.md)保持原语义,不在这里动。
|
|
218
255
|
.replace(/\S*[^\x00-\x7F]\S*\.[A-Za-z][A-Za-z0-9]{0,7}\b/g, ' ')
|
|
219
256
|
// 仓库里的裸文件名(README / CHANGELOG …)也是语料,不是意图
|
|
@@ -232,6 +269,13 @@ export function isIntentWord(word) {
|
|
|
232
269
|
const s = String(word || '').trim()
|
|
233
270
|
if (!s) return false
|
|
234
271
|
if (CJK_RANGE.test(s)) return s.length >= 2
|
|
272
|
+
// 俄语:作者写的意图词是**原形**,不经过检索侧的词干;只要 ≥3 字符、不是虚词、
|
|
273
|
+
// 不含路径/标识符字符即可。不能用拉丁的 ≥5:`мост` / `код` / `файл` 都是 3–4 字母的实义词,
|
|
274
|
+
// 而俄语的三字母词几乎都是实词(虚词已经被 RU_STOPWORDS 挡掉),没有拉丁那种缩写歧义。
|
|
275
|
+
if (CYRILLIC_RANGE.test(s)) {
|
|
276
|
+
const w = normalizeRuWord(s)
|
|
277
|
+
return w.length >= 3 && !RU_STOPWORDS.has(w) && !/[_./\\*]/.test(w) && !/\s/.test(w)
|
|
278
|
+
}
|
|
235
279
|
if (s.length < 5) return false
|
|
236
280
|
if (/[_./\\*]/.test(s)) return false
|
|
237
281
|
if (/\s/.test(s)) return s.length >= 8
|
|
@@ -258,8 +302,15 @@ export function matchIntent(word, text) {
|
|
|
258
302
|
const hay = String(text || '')
|
|
259
303
|
if (!w || !hay) return false
|
|
260
304
|
if (CJK_RANGE.test(w)) return w.length >= 2 && hay.includes(w)
|
|
261
|
-
if (w.length < 4) return false
|
|
262
305
|
const esc = w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
306
|
+
// 俄语用 Unicode 词边界:`[^A-Za-z0-9_]` 会把"俄文词内部的命中"当成边界
|
|
307
|
+
// (`город` 命中 `городской`),那正是这条匹配要防的假阳性。
|
|
308
|
+
// 长度门槛与 isIntentWord 保持一致(≥3),不套用拉丁的 ≥4。
|
|
309
|
+
if (CYRILLIC_RANGE.test(w)) {
|
|
310
|
+
if (w.length < 3) return false
|
|
311
|
+
return new RegExp(`(^|[^\\p{L}\\p{N}_])${esc}(?![\\p{L}\\p{N}_])`, 'iu').test(hay)
|
|
312
|
+
}
|
|
313
|
+
if (w.length < 4) return false
|
|
263
314
|
return new RegExp(`(^|[^A-Za-z0-9_])${esc}([^A-Za-z0-9_]|$)`, 'i').test(hay)
|
|
264
315
|
}
|
|
265
316
|
|
package/src/recall.js
CHANGED
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
* @module dsh-project-memory/recall
|
|
19
19
|
*/
|
|
20
20
|
import { rankEntriesMergedScored, rankEntriesStreaming, tokenizeRaw, CJK_RANGE } from './util/search.js'
|
|
21
|
+
import { CYRILLIC_RANGE } from './util/ru.js'
|
|
21
22
|
|
|
22
23
|
/**
|
|
23
24
|
* 短拉丁片段不算检索证据(只用于经验/洞察两层)。
|
|
@@ -28,11 +29,14 @@ import { rankEntriesMergedScored, rankEntriesStreaming, tokenizeRaw, CJK_RANGE }
|
|
|
28
29
|
*
|
|
29
30
|
* 为什么只在这两层:doc/symbol 层是代码与路径,`js` / `id` 这类短标识符本来就该命中
|
|
30
31
|
* (见上方 `matchedFloor` 的注释)。两种模式(有/无向量)一律适用——闸门不能随向量层开关变形。
|
|
32
|
+
*
|
|
33
|
+
* 西里尔(俄语)不吃这条规则:俄语没有"两字母缩写"这种噪声源,且 `ии` / `бд` 这类
|
|
34
|
+
* 两字母词是实义词;虚词在分词阶段已经由 `RU_STOPWORDS` 去掉了,这里再按长度砍只会误伤。
|
|
31
35
|
*/
|
|
32
36
|
const MIN_LATIN_QUERY_TERM = 3
|
|
33
37
|
function gatedQueryText(q) {
|
|
34
38
|
return tokenizeRaw(String(q ?? ''))
|
|
35
|
-
.filter((t) => CJK_RANGE.test(t) || t.length >= MIN_LATIN_QUERY_TERM)
|
|
39
|
+
.filter((t) => CJK_RANGE.test(t) || CYRILLIC_RANGE.test(t) || t.length >= MIN_LATIN_QUERY_TERM)
|
|
36
40
|
.join(' ')
|
|
37
41
|
}
|
|
38
42
|
|
package/src/skill.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// 把"怎么用 project-memory"作为宿主 skill 暴露,而不是文档里的一段说明。
|
|
2
|
+
//
|
|
3
|
+
// 为什么不写 `.dsh/skills/`:那会把文件写进用户项目或全局 home,且与插件版本脱钩
|
|
4
|
+
// (升级插件后 skill 还是旧的)。运行时注册随包升级,`resourceBase` 指向包内目录,
|
|
5
|
+
// 模型能按相对路径取 `scripts/pm-digest.mjs`。
|
|
6
|
+
//
|
|
7
|
+
// 宿主没有 `skills` 服务时静默跳过 —— 与 `/tasks` 同一套软依赖写法(顶层 inject 会让整个
|
|
8
|
+
// 半边在缺服务时**不挂载**,那是最坏的失败形态,见 src/client/services.ts 的同类注释)。
|
|
9
|
+
import { readFileSync } from 'node:fs'
|
|
10
|
+
import path from 'node:path'
|
|
11
|
+
import { fileURLToPath } from 'node:url'
|
|
12
|
+
|
|
13
|
+
export const SKILL_NAME = 'project-memory'
|
|
14
|
+
/** 包内目录:`skills/project-memory/`(npm files 白名单里有 `skills`)。 */
|
|
15
|
+
export const SKILL_DIR = fileURLToPath(new URL('../skills/project-memory/', import.meta.url))
|
|
16
|
+
|
|
17
|
+
const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* 拆 frontmatter 与正文。SKILL.md 是**唯一事实源**(name / description / 正文 / 资源目录),
|
|
21
|
+
* 注册时只解析它,避免"文件里一份、代码里一份"的漂移。
|
|
22
|
+
* @param {string} text
|
|
23
|
+
* @returns {{ meta: Record<string,string>, body: string }}
|
|
24
|
+
*/
|
|
25
|
+
export function parseSkillFile(text) {
|
|
26
|
+
const source = String(text || '')
|
|
27
|
+
const match = FRONTMATTER.exec(source)
|
|
28
|
+
const meta = {}
|
|
29
|
+
if (match) {
|
|
30
|
+
for (const line of match[1].split(/\r?\n/)) {
|
|
31
|
+
const at = line.indexOf(':')
|
|
32
|
+
if (at <= 0) continue
|
|
33
|
+
const key = line.slice(0, at).trim()
|
|
34
|
+
let value = line.slice(at + 1).trim()
|
|
35
|
+
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
|
|
36
|
+
value = value.slice(1, -1)
|
|
37
|
+
}
|
|
38
|
+
if (key) meta[key] = value
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return { meta, body: match ? source.slice(match[0].length) : source }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* 构造 `ctx.skills.register()` 接受的运行时 skill。
|
|
46
|
+
* @param {{ readFile?: (file: string, enc: string) => string, dir?: string }} [opts]
|
|
47
|
+
* @returns {{ name: string, description: string, whenToUse?: string, source: string, path: string, content: string, resourceBase: { kind: 'directory', path: string } }}
|
|
48
|
+
*/
|
|
49
|
+
export function buildProjectMemorySkill({ readFile = readFileSync, dir = SKILL_DIR } = {}) {
|
|
50
|
+
const file = path.join(dir, 'SKILL.md')
|
|
51
|
+
const { meta, body } = parseSkillFile(readFile(file, 'utf8'))
|
|
52
|
+
const skill = {
|
|
53
|
+
name: meta.name || SKILL_NAME,
|
|
54
|
+
description: meta.description || 'Recall and maintain this project\'s long-term memory: indexed docs and code symbols, lessons, decisions, procedures, and cross-session tasks.',
|
|
55
|
+
source: 'bundled',
|
|
56
|
+
path: file,
|
|
57
|
+
content: body.trim(),
|
|
58
|
+
resourceBase: { kind: 'directory', path: dir },
|
|
59
|
+
}
|
|
60
|
+
if (meta.whenToUse) skill.whenToUse = meta.whenToUse
|
|
61
|
+
return skill
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* 把 skill 注册进宿主。`ctx.inject(['skills'], …)` 是可选依赖:没有该服务时回调不执行,
|
|
66
|
+
* 插件其余部分照常工作;注册失败只告警,不影响工具与注入。
|
|
67
|
+
* @param {object} ctx
|
|
68
|
+
* @param {{ build?: () => object, log?: { error: Function } }} [opts]
|
|
69
|
+
*/
|
|
70
|
+
export function setupSkill(ctx, { build = buildProjectMemorySkill, log = console } = {}) {
|
|
71
|
+
const register = (skillsCtx) => {
|
|
72
|
+
try {
|
|
73
|
+
skillsCtx.skills.register(build())
|
|
74
|
+
} catch (err) {
|
|
75
|
+
log.error(`[dsh-project-memory] skill registration skipped: ${err?.message || err}`)
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
try {
|
|
79
|
+
if (typeof ctx.inject === 'function') ctx.inject(['skills'], register)
|
|
80
|
+
else if (typeof ctx.get === 'function' && ctx.get('skills')) register(ctx)
|
|
81
|
+
} catch (err) {
|
|
82
|
+
log.error(`[dsh-project-memory] skill registration skipped: ${err?.message || err}`)
|
|
83
|
+
}
|
|
84
|
+
}
|
package/src/store.js
CHANGED
|
@@ -3,6 +3,8 @@ import { mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unl
|
|
|
3
3
|
import path from 'node:path'
|
|
4
4
|
import { tokenizeRaw, makeSearchText } from './util/search.js'
|
|
5
5
|
import { acquireDirLock, writeJsonAtomic } from './util/fs.js'
|
|
6
|
+
import { debugPersistence } from './util/persist.js'
|
|
7
|
+
import { trackDirty, untrackDirty } from './util/flush.js'
|
|
6
8
|
import { backfillDerivedTriggers } from './readiness.js'
|
|
7
9
|
|
|
8
10
|
const FORMAT_FILE = 'format.json'
|
|
@@ -378,6 +380,22 @@ export class ProjectMemoryStore {
|
|
|
378
380
|
this._removedWatch = new Set()
|
|
379
381
|
/** 上次落盘/加载时的 insight id 集合:原地 splice 的删除也要能被合并逻辑看见。 */
|
|
380
382
|
this._baseInsightIds = new Set()
|
|
383
|
+
/**
|
|
384
|
+
* 本进程**新建**的条目。合并另一进程的磁盘状态时,"磁盘没有但内存有"有两种可能:
|
|
385
|
+
* 我新建的(要补写)或**对方删了**(不能写回)。没有这个集合,后者就会被复活
|
|
386
|
+
* (实测:B 真删、A 下一次注入记账触发 save,已删条目重新出现在磁盘上)。
|
|
387
|
+
*/
|
|
388
|
+
this._createdInsightIds = new Set()
|
|
389
|
+
this._createdTaskIds = new Set()
|
|
390
|
+
/** 上一次 save 是否真的落到盘上(锁竞争/权限失败时为 false)。 */
|
|
391
|
+
this.lastSaveOk = true
|
|
392
|
+
/** `shards/` 的 `.tmp` 清扫节流:NTFS 上 readdir(数千分片) 不便宜,不能每次 save 都扫。 */
|
|
393
|
+
this._lastShardTmpSweep = 0
|
|
394
|
+
/** 自我忽略文件已确认存在:省掉每次 save 的 existsSync(Windows 上每次都要过一次过滤驱动)。 */
|
|
395
|
+
this._selfIgnoreReady = false
|
|
396
|
+
/** store 目录 / shards 目录已确认存在:首次写之后不再每次 save 都 mkdir(9p 上每次 ~4ms)。 */
|
|
397
|
+
this._storeDirReady = false
|
|
398
|
+
this._shardsDirReady = false
|
|
381
399
|
this._lockWarned = false
|
|
382
400
|
this._conflictWarned = new Set()
|
|
383
401
|
/** 锁竞争跳过落盘后的有限次延迟重试;unref,避免拖住进程退出。 */
|
|
@@ -663,7 +681,7 @@ export class ProjectMemoryStore {
|
|
|
663
681
|
this.insights.migratedAt = now
|
|
664
682
|
try {
|
|
665
683
|
mkdirSync(this.dir, { recursive: true })
|
|
666
|
-
writeJsonAtomic(path.join(this.dir, INSIGHTS_FILE), this.insights)
|
|
684
|
+
writeJsonAtomic(path.join(this.dir, INSIGHTS_FILE), this.insights, { ensureDir: false })
|
|
667
685
|
} catch (err) {
|
|
668
686
|
// 没写进 insights.json 就**不能**把旧文件收走:那会真的丢数据。
|
|
669
687
|
console.error(`[dsh-project-memory] insights migration write failed, keeping ${EXPERIENCE_FILE}: ${err.message}`)
|
|
@@ -692,7 +710,10 @@ export class ProjectMemoryStore {
|
|
|
692
710
|
const next = new Set((items || []).map((it) => it?.id).filter(Boolean))
|
|
693
711
|
// 与上次落盘的基线比,而不是与当前数组比:调用方经常先原地 splice 再调用这里。
|
|
694
712
|
for (const id of this._baseInsightIds) if (!next.has(id)) this._deletedInsightIds.add(id)
|
|
695
|
-
for (const id of next)
|
|
713
|
+
for (const id of next) {
|
|
714
|
+
this._deletedInsightIds.delete(id)
|
|
715
|
+
if (!this._baseInsightIds.has(id)) this._createdInsightIds.add(id)
|
|
716
|
+
}
|
|
696
717
|
this.insights.items = items
|
|
697
718
|
this._baseInsightIds = next
|
|
698
719
|
this._dirtyInsights = true
|
|
@@ -708,9 +729,16 @@ export class ProjectMemoryStore {
|
|
|
708
729
|
this._auxVersion++
|
|
709
730
|
}
|
|
710
731
|
|
|
711
|
-
cleanStaleTmp() {
|
|
712
|
-
|
|
732
|
+
cleanStaleTmp({ force = false } = {}) {
|
|
733
|
+
// store 根目录只有几个文件,每次 save 扫一遍很便宜(崩溃遗留的 aux `.tmp` 立刻收走)。
|
|
734
|
+
// `shards/` 才是 O(N):12k 分片时每次单文件更新都 readdir 一遍,在 NTFS 上是实打实的卡顿。
|
|
735
|
+
// 分片里的 .tmp 只影响体积、不影响正确性,60s 扫一次足够;`force` 给测试/诊断用。
|
|
713
736
|
const now = Date.now()
|
|
737
|
+
const scanDirs = [this.dir]
|
|
738
|
+
if (force || now - this._lastShardTmpSweep >= 60_000) {
|
|
739
|
+
this._lastShardTmpSweep = now
|
|
740
|
+
scanDirs.push(path.join(this.dir, SHARDS_DIR))
|
|
741
|
+
}
|
|
714
742
|
for (const dir of scanDirs) {
|
|
715
743
|
let entries
|
|
716
744
|
try {
|
|
@@ -741,11 +769,16 @@ export class ProjectMemoryStore {
|
|
|
741
769
|
* 想把记忆跟着仓库提交:`git add -f .dsh-project-memory`——已跟踪的文件不受忽略规则影响。
|
|
742
770
|
*/
|
|
743
771
|
ensureSelfIgnore() {
|
|
772
|
+
if (this._selfIgnoreReady) return
|
|
744
773
|
if (!existsSafe(this.dir)) return
|
|
745
774
|
const file = path.join(this.dir, GITIGNORE_FILE)
|
|
746
|
-
if (existsSafe(file))
|
|
775
|
+
if (existsSafe(file)) {
|
|
776
|
+
this._selfIgnoreReady = true
|
|
777
|
+
return
|
|
778
|
+
}
|
|
747
779
|
try {
|
|
748
780
|
writeFileSync(file, '# dsh-project-memory: local by default. `git add -f` to commit it.\n*\n')
|
|
781
|
+
this._selfIgnoreReady = true
|
|
749
782
|
} catch {
|
|
750
783
|
// 旁路:写不进去不影响存储本身
|
|
751
784
|
}
|
|
@@ -762,7 +795,12 @@ export class ProjectMemoryStore {
|
|
|
762
795
|
|| this._dirtyWatch
|
|
763
796
|
}
|
|
764
797
|
|
|
765
|
-
|
|
798
|
+
/**
|
|
799
|
+
* @param {{ timeoutMs?: number }} [options] 等锁上限。默认 15s:写路径的正确性靠**同步等待**,
|
|
800
|
+
* 不靠后台重试——用户结束对话就会关 dsh,不会等重试。重试只是长驻进程的兜底。
|
|
801
|
+
* @returns {boolean} 是否真的落盘(无脏数据也算成功)
|
|
802
|
+
*/
|
|
803
|
+
save(options = {}) {
|
|
766
804
|
// 没有脏数据就不落盘。watch 每轮对每个根都无条件 commit → save;照旧执行的话,
|
|
767
805
|
// 末尾的 ID 缓存失效会打在跨实例共享的 store 上,等于每轮清空一次 IDF 复用(v0.3.4 的 20x)。
|
|
768
806
|
// 待压实队列不算"脏数据",但它需要有界推进,所以也走这条落盘路径。
|
|
@@ -776,27 +814,41 @@ export class ProjectMemoryStore {
|
|
|
776
814
|
this._dirtyBinding ||
|
|
777
815
|
this._dirtyWatch ||
|
|
778
816
|
!this._formatWritten
|
|
779
|
-
if (dirty
|
|
817
|
+
if (dirty && !this._storeDirReady) {
|
|
818
|
+
mkdirSync(this.dir, { recursive: true })
|
|
819
|
+
this._storeDirReady = true
|
|
820
|
+
}
|
|
780
821
|
// 崩溃遗留的 *.tmp 无论有没有脏数据都顺手清掉(两次 readdir,自带 try/catch)
|
|
781
822
|
this.cleanStaleTmp()
|
|
782
823
|
// 自我忽略也在无脏数据时执行:老版本建出来的 store 会在下一次 save 时补上。
|
|
783
824
|
this.ensureSelfIgnore()
|
|
784
|
-
if (!dirty)
|
|
785
|
-
|
|
786
|
-
|
|
825
|
+
if (!dirty) {
|
|
826
|
+
this.lastSaveOk = true
|
|
827
|
+
untrackDirty(this)
|
|
828
|
+
return true
|
|
829
|
+
}
|
|
830
|
+
// 跨进程:整段读改写放进目录锁。默认同步等待 15s——写路径的正确性靠"等到锁",
|
|
831
|
+
// 不靠后台重试(用户结束对话就关 dsh)。真拿不到时保持脏状态并登记退出 flush;
|
|
832
|
+
// 默认静默,不向用户/模型抛提示。
|
|
833
|
+
const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : 15000
|
|
834
|
+
const release = acquireDirLock(this.dir, { timeoutMs, ensureDir: false })
|
|
787
835
|
if (!release) {
|
|
836
|
+
this.lastSaveOk = false
|
|
837
|
+
trackDirty(this)
|
|
788
838
|
if (!this._lockWarned) {
|
|
789
839
|
this._lockWarned = true
|
|
790
|
-
|
|
840
|
+
debugPersistence(`[dsh-project-memory] store ${this.dir} is busy (another dsh process is writing); this write is pending.`)
|
|
791
841
|
}
|
|
792
842
|
this._scheduleSaveRetry()
|
|
793
|
-
return
|
|
843
|
+
return false
|
|
794
844
|
}
|
|
845
|
+
let wroteInsights = false
|
|
846
|
+
let wroteTasks = false
|
|
795
847
|
try {
|
|
796
848
|
// 先合并另一进程已落盘的小文档,再写;分片按“加载时 hash”做冲突检测。
|
|
797
849
|
this._mergeAuxFromDisk()
|
|
798
850
|
if (!this._formatWritten) {
|
|
799
|
-
writeJsonAtomic(path.join(this.dir, FORMAT_FILE), { version: 2, layout: 'sharded' })
|
|
851
|
+
writeJsonAtomic(path.join(this.dir, FORMAT_FILE), { version: 2, layout: 'sharded' }, { ensureDir: false })
|
|
800
852
|
this._formatWritten = true
|
|
801
853
|
}
|
|
802
854
|
// 存量压实:≤0.5.10 的分片带着派生字段,而那些字段只在分片被重写时才会从磁盘消失。
|
|
@@ -820,7 +872,8 @@ export class ProjectMemoryStore {
|
|
|
820
872
|
const localAt = Date.parse(this.files[rel].indexedAt || '') || 0
|
|
821
873
|
const diskAt = Date.parse(disk.record?.indexedAt || '') || 0
|
|
822
874
|
if (localAt > diskAt) {
|
|
823
|
-
|
|
875
|
+
this._ensureShardsDir()
|
|
876
|
+
writeJsonAtomic(shardRelPath(this.dir, rel), { relPath: rel, record: this.files[rel], entries: (this.entries[rel] || []).map(withoutPersistedDerived) }, { ensureDir: false })
|
|
824
877
|
this._baseFileSha.set(rel, nextSha)
|
|
825
878
|
continue
|
|
826
879
|
}
|
|
@@ -828,8 +881,8 @@ export class ProjectMemoryStore {
|
|
|
828
881
|
this._warnConflict(rel)
|
|
829
882
|
continue
|
|
830
883
|
}
|
|
831
|
-
|
|
832
|
-
writeJsonAtomic(shardRelPath(this.dir, rel), { relPath: rel, record: this.files[rel], entries: (this.entries[rel] || []).map(withoutPersistedDerived) })
|
|
884
|
+
this._ensureShardsDir()
|
|
885
|
+
writeJsonAtomic(shardRelPath(this.dir, rel), { relPath: rel, record: this.files[rel], entries: (this.entries[rel] || []).map(withoutPersistedDerived) }, { ensureDir: false })
|
|
833
886
|
this._baseFileSha.set(rel, nextSha)
|
|
834
887
|
} else {
|
|
835
888
|
this._removedShards.add(rel)
|
|
@@ -854,29 +907,40 @@ export class ProjectMemoryStore {
|
|
|
854
907
|
this._baseFileSha.delete(rel)
|
|
855
908
|
}
|
|
856
909
|
this._removedShards.clear()
|
|
857
|
-
|
|
910
|
+
wroteInsights = this._dirtyInsights
|
|
911
|
+
wroteTasks = this._dirtyTasks
|
|
912
|
+
if (wroteInsights) {
|
|
858
913
|
// v2 → v3 是纯语义升级(`kind:'experience'` 从"影子副本"变成一等实体),形状不变;
|
|
859
914
|
// 落盘即把版本推上去,老版本读到 v3 也照样按 v2 的字段解析(它只是排除 experience 影子)。
|
|
860
915
|
if (this.insights && this.insights.version !== 3) this.insights.version = 3
|
|
861
|
-
writeJsonAtomic(path.join(this.dir, INSIGHTS_FILE), this.insights)
|
|
916
|
+
writeJsonAtomic(path.join(this.dir, INSIGHTS_FILE), this.insights, { ensureDir: false })
|
|
862
917
|
this._dirtyInsights = false
|
|
863
918
|
}
|
|
864
919
|
if (this._dirtyTasks) {
|
|
865
|
-
writeJsonAtomic(path.join(this.dir, TASKS_FILE), this.tasks)
|
|
920
|
+
writeJsonAtomic(path.join(this.dir, TASKS_FILE), this.tasks, { ensureDir: false })
|
|
866
921
|
this._dirtyTasks = false
|
|
867
922
|
}
|
|
868
923
|
if (this._dirtyBinding) {
|
|
869
|
-
writeJsonAtomic(path.join(this.dir, BINDING_FILE), this.binding)
|
|
924
|
+
writeJsonAtomic(path.join(this.dir, BINDING_FILE), this.binding, { ensureDir: false })
|
|
870
925
|
this._dirtyBinding = false
|
|
871
926
|
}
|
|
872
927
|
if (this._dirtyWatch) {
|
|
873
|
-
writeJsonAtomic(path.join(this.dir, WATCH_FILE), this.watchlist)
|
|
928
|
+
writeJsonAtomic(path.join(this.dir, WATCH_FILE), this.watchlist, { ensureDir: false })
|
|
874
929
|
this._dirtyWatch = false
|
|
875
930
|
}
|
|
876
931
|
} finally {
|
|
877
932
|
release()
|
|
878
933
|
}
|
|
879
934
|
this._saveRetryAttempts = 0
|
|
935
|
+
this.lastSaveOk = true
|
|
936
|
+
untrackDirty(this)
|
|
937
|
+
// 落盘成功才推进基线:失败时保持"本进程新建"的标记,下一次 save 仍要补写。
|
|
938
|
+
if (wroteInsights) {
|
|
939
|
+
this._baseInsightIds = new Set(this.insights.items.map((it) => it?.id).filter(Boolean))
|
|
940
|
+
this._createdInsightIds.clear()
|
|
941
|
+
}
|
|
942
|
+
if (wroteTasks) this._createdTaskIds.clear()
|
|
943
|
+
return true
|
|
880
944
|
}
|
|
881
945
|
|
|
882
946
|
/**
|
|
@@ -910,18 +974,33 @@ export class ProjectMemoryStore {
|
|
|
910
974
|
}
|
|
911
975
|
}
|
|
912
976
|
|
|
977
|
+
/** 首次写分片前建一次 shards/;之后每次 save 都省掉一次 mkdir。 */
|
|
978
|
+
_ensureShardsDir() {
|
|
979
|
+
if (this._shardsDirReady) return
|
|
980
|
+
mkdirSync(path.join(this.dir, SHARDS_DIR), { recursive: true })
|
|
981
|
+
this._shardsDirReady = true
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
/** 退出/卸载路径的同步兜底(见 util/flush.js)。 */
|
|
985
|
+
flushPending(timeoutMs = 1500) {
|
|
986
|
+
return this.save({ timeoutMs })
|
|
987
|
+
}
|
|
988
|
+
|
|
913
989
|
/** 锁竞争后的有限次延迟重试;失败仍保持脏状态,下一次写继续尝试。 */
|
|
914
990
|
_scheduleSaveRetry() {
|
|
915
|
-
|
|
916
|
-
|
|
991
|
+
// 旧实现 3 次 × ~2s ≈ 8.3s,**永远小于** staleMs=10s:一个刚崩溃的跨机锁会让所有重试落空。
|
|
992
|
+
// 同机崩溃锁现在由 pid 判活立即回收(见 util/fs.js),这里的预算只兜跨机 stale 锁。
|
|
993
|
+
const delays = [100, 500, 2000, 6000, 12000]
|
|
994
|
+
if (this._saveRetryTimer || this._saveRetryAttempts >= delays.length) return
|
|
995
|
+
const delay = delays[this._saveRetryAttempts++]
|
|
917
996
|
this._saveRetryTimer = setTimeout(() => {
|
|
918
997
|
this._saveRetryTimer = null
|
|
919
998
|
try {
|
|
920
|
-
this.save()
|
|
999
|
+
this.save({ timeoutMs: 2000 })
|
|
921
1000
|
} catch (err) {
|
|
922
1001
|
console.error(`[dsh-project-memory] deferred save failed: ${err?.message || err}`)
|
|
923
1002
|
}
|
|
924
|
-
},
|
|
1003
|
+
}, delay)
|
|
925
1004
|
this._saveRetryTimer.unref?.()
|
|
926
1005
|
}
|
|
927
1006
|
|
|
@@ -955,7 +1034,12 @@ export class ProjectMemoryStore {
|
|
|
955
1034
|
continue
|
|
956
1035
|
}
|
|
957
1036
|
const prev = byId.get(it.id)
|
|
958
|
-
if (!prev
|
|
1037
|
+
if (!prev) {
|
|
1038
|
+
// 磁盘没有:本进程新建的才补写;否则是**对方删了**,丢掉内存里的旧副本。
|
|
1039
|
+
if (this._createdInsightIds.has(it.id)) byId.set(it.id, it)
|
|
1040
|
+
continue
|
|
1041
|
+
}
|
|
1042
|
+
if (newerIso(it.updatedAt, prev.updatedAt) >= 0) byId.set(it.id, it)
|
|
959
1043
|
}
|
|
960
1044
|
for (const id of this._deletedInsightIds) byId.delete(id)
|
|
961
1045
|
this.insights = { ...this.insights, items: [...byId.values()] }
|
|
@@ -974,8 +1058,16 @@ export class ProjectMemoryStore {
|
|
|
974
1058
|
continue
|
|
975
1059
|
}
|
|
976
1060
|
const prev = byId.get(t.id)
|
|
977
|
-
if (!prev
|
|
1061
|
+
if (!prev) {
|
|
1062
|
+
// 同 insights:磁盘缺失 = 对方删了,只有本进程新建的任务才补写。
|
|
1063
|
+
if (this._createdTaskIds.has(t.id)) byId.set(t.id, t)
|
|
1064
|
+
continue
|
|
1065
|
+
}
|
|
1066
|
+
if (newerIso(t.updatedAt || t.lastActiveAt, prev.updatedAt || prev.lastActiveAt) >= 0) byId.set(t.id, t)
|
|
978
1067
|
}
|
|
1068
|
+
// 本地删除必须从磁盘副本里剔除:`removeTask` 已把它从内存数组移除,上面的循环
|
|
1069
|
+
// 根本看不到它;少了这一行,删任务会在**同一次 save 里**被另一份磁盘快照写回来。
|
|
1070
|
+
for (const id of this._deletedTaskIds) byId.delete(id)
|
|
979
1071
|
this.tasks = [...byId.values()]
|
|
980
1072
|
this._auxVersion++
|
|
981
1073
|
}
|
|
@@ -1178,7 +1270,10 @@ export class ProjectMemoryStore {
|
|
|
1178
1270
|
|
|
1179
1271
|
addTask(task) {
|
|
1180
1272
|
this.tasks.push(task)
|
|
1181
|
-
if (task?.id)
|
|
1273
|
+
if (task?.id) {
|
|
1274
|
+
this._deletedTaskIds.delete(task.id)
|
|
1275
|
+
this._createdTaskIds.add(task.id)
|
|
1276
|
+
}
|
|
1182
1277
|
this._dirtyTasks = true
|
|
1183
1278
|
this._auxVersion++
|
|
1184
1279
|
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 退出/卸载前的最后一道写盘兜底。
|
|
3
|
+
*
|
|
4
|
+
* 为什么需要:保存失败后的后台重试**不能**当正确性保证——用户结束对话、关掉 dsh 时不会等
|
|
5
|
+
* 20s 的重试。正确性来自两点:① `save()` 在锁竞争时同步等待(见 store.js 的 LOCK_WAIT_MS);
|
|
6
|
+
* ② 万一仍失败,进程正常退出或插件卸载时再同步写一次。
|
|
7
|
+
*
|
|
8
|
+
* 注册的是脏 store(而不是所有 store):只有内存里还有未落盘变更的才需要 flush。
|
|
9
|
+
* `process.on('exit')` 只允许同步代码,`save()` 本身是同步的,所以这里直接调用。
|
|
10
|
+
* 信号导致的异常退出(SIGKILL / 未处理的 SIGINT)不保证走到这里——那是操作系统的边界。
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** @type {Set<{ flushPending?: (timeoutMs: number) => boolean }>} */
|
|
14
|
+
const pending = new Set()
|
|
15
|
+
let installed = false
|
|
16
|
+
|
|
17
|
+
function install() {
|
|
18
|
+
if (installed) return
|
|
19
|
+
installed = true
|
|
20
|
+
process.on('exit', () => {
|
|
21
|
+
flushDirtyStores({ timeoutMs: 1500 })
|
|
22
|
+
})
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* 标记"这个 store 有未落盘的变更"。
|
|
27
|
+
* @param {{ flushPending?: (timeoutMs: number) => boolean }} store
|
|
28
|
+
*/
|
|
29
|
+
export function trackDirty(store) {
|
|
30
|
+
pending.add(store)
|
|
31
|
+
install()
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* 落盘成功后取消标记。
|
|
36
|
+
* @param {object} store
|
|
37
|
+
*/
|
|
38
|
+
export function untrackDirty(store) {
|
|
39
|
+
pending.delete(store)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 同步 flush 所有脏 store。退出钩子与插件 disposer 共用;测试可直接调用。
|
|
44
|
+
* @param {{ timeoutMs?: number }} [opts] 每个 store 最多等锁多久(退出路径要短,避免"关不掉")
|
|
45
|
+
* @returns {number} 成功落盘的 store 数
|
|
46
|
+
*/
|
|
47
|
+
export function flushDirtyStores({ timeoutMs = 1500 } = {}) {
|
|
48
|
+
let saved = 0
|
|
49
|
+
for (const store of [...pending]) {
|
|
50
|
+
try {
|
|
51
|
+
if (typeof store.flushPending === 'function' && store.flushPending(timeoutMs)) saved++
|
|
52
|
+
} catch {
|
|
53
|
+
// 退出路径上的失败只能放弃:不抛、不打印,避免把关闭流程变成错误弹窗
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return saved
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** 仅供测试:当前还有多少个脏 store 挂着。 */
|
|
60
|
+
export function _pendingDirtyCountForTest() {
|
|
61
|
+
return pending.size
|
|
62
|
+
}
|