@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/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,91 @@
|
|
|
1
|
+
## 0.6.6 (2026-10-27)
|
|
2
|
+
|
|
3
|
+
**升级注意**:这是一次**行为变更**——注入会变少。没有新增配置键、没有 store 格式变更,老 profile 直接升级。变化只在"什么时候允许全文注入":子代理提示词、其它工具的参数、后台任务 / 子代理通知,以及人类消息里的删除 / 清理 / 渲染 / 基准类词,不再触发全文注入。
|
|
4
|
+
|
|
5
|
+
### 修复:注入的"这一步在做什么"取错了来源
|
|
6
|
+
|
|
7
|
+
**证据**(用插件自己的审计日志复盘一次真实会话——作者在插件仓库里跑 30–40 分钟审计,含 4 个子代理):17 次注入 / 8,654 字符,可判定与本步任务无关 **6.2k(72%)**。其中:
|
|
8
|
+
|
|
9
|
+
- `find src client test scripts bench docs -type f` → `run-bench`(只是目录名 `bench`),4 条基准 procedure、1,777 字符;
|
|
10
|
+
- 子代理提示词里的"删除后的悬空状态""版本迁移" → 父会话 `file-delete` / `migrate` 连续 8 步;
|
|
11
|
+
- 子代理报告里的"发布 / 渲染" → `intent:release`(1,050 字符)/ `intent:渲染`(1,200 字符);
|
|
12
|
+
- 旧一代 shadow 日志 386 行里只有 **31 步(8%)**有非空 query:会话中段根本没有真人消息。
|
|
13
|
+
|
|
14
|
+
**根因与改法**:
|
|
15
|
+
|
|
16
|
+
1. `agent/pre-step` 的 `messages` 是宿主的 claimed **delta**,不是完整历史。旧实现把 delta 里最后一条 user 消息当"人的话",于是 `agent-message`(子代理报告)/ `subagent-settled` / `tool-jobs` / `time-context` 都成了查询。现在 `lastUserText` 只认 `source.kind === 'user'` 或无 source 的老宿主;每会话缓存最后一条真人消息(`session/event` + `user/message`),delta 里没有就回退到它。shadow 新增 `querySource: delta|session|none`。
|
|
17
|
+
2. 动作面只从**结构化工具调用**归一(`activityFromCalls`);`injectForStep` 不再把全部 observed 调用拼成 `actionText`。`subagent` / `remember` / `save_lesson` 的参数不再变成父会话的动作。
|
|
18
|
+
3. `classifyShellCommand` 改成**分段 + 命令头匹配**:剥 heredoc、跳过 `sudo` / `env` 包装、引号内的 `>` 不算重定向、`bash -c` 递归一层。目录名、grep pattern、`node -e` 正文里的词不再是动作。
|
|
19
|
+
4. 人类消息里的动作词分级:只有不可逆外部动作(`git-commit` / `git-push` / `npm-publish` / `release` / `deploy` / `go-public`)允许先发;`删除 / 清理 / 渲染 / 基准 / 取网页` 只记进 `opsIntent`(shadow 可见),不触发全文。观察到的 `rm` 仍然触发。
|
|
20
|
+
5. `buildReadinessContext` 不再被二次归一:`buildInjection` 收到已构建的上下文时只补 tags,避免第一遍的 `actions` 输出在第二遍被当成"调用方声明的动作"重新信任(否则散文里的 `file-delete` 会绕过过滤)。
|
|
21
|
+
|
|
22
|
+
**已知残留**(下一版,单独提交):legacy trigger 的 `keywords` 被归一成 `when.intents` 后仍会匹配散文("清理一下 README 的措辞"可能命中一条 `keywords:['清理']` 的条目)。把"legacy 派生词 → hint-only"需要重标 `readiness-eval` 与 `eval:injection` 基线。
|
|
23
|
+
|
|
24
|
+
### 修复:跨进程写的三条数据安全问题(多开 dsh)
|
|
25
|
+
|
|
26
|
+
**背景**:审计给出三条可复现缺陷,全部发生在"两个 dsh 实例共用一个 store"这个插件明确支持的场景里。
|
|
27
|
+
|
|
28
|
+
1. **锁可被抢,release 无所有权校验**。旧锁只有 mtime:持锁超过 10s 就被第二个进程当成死锁抢走;原持有者到点 release 又无条件 unlink,把对方的锁删掉,第三个进程随即进入——实测三者同时"持锁"。
|
|
29
|
+
现在锁内容带 `{pid, host, token, at}`:同机 pid 活着就绝不回收(Linux 上再用 `/proc/<pid>` 的启动时刻识别 pid 复用);release 校验 token,不删别人的锁。
|
|
30
|
+
2. **崩溃残留锁 + 重试预算 < staleMs → save 静默跳过,工具仍报成功**。旧逻辑 3 次重试 ≈ 8.3s,永远够不到 staleMs=10s;失败只 `console.error`,工具照样返回 "Saved …"(实测 `insights.json` 根本没生成)。
|
|
31
|
+
现在同机死 pid 的锁**立即回收**;`save()` / `GlobalStore.commit()` 返回失败并置 `lastSaveOk` / `lastCommitOk`,但**默认静默**——记忆写入是幂等的、失败成本低,终端与回复里的提示已经够多。**正确性不靠重试**:写路径默认同步等锁最多 **15s**(另一个进程的写通常只有毫秒级);仍失败才进入后台重试,并且进程退出 / 插件卸载时还有一次同步 flush(`src/util/flush.js`)——用户结束对话就会关 dsh,不会等 20s 的重试。需要排查时设 `DSH_PROJECT_MEMORY_DEBUG=1` 才打印一行(每个 store 每进程一次)。
|
|
32
|
+
3. **跨进程删除被复活**。A 加载后持有旧快照,B `forget` 落盘,A 下一次 save 把"磁盘没有但内存有"当成"本地新增"写回——"真删、无撤销"的承诺失效(任务同形;global 层同形)。
|
|
33
|
+
现在合并规则是:磁盘缺失的条目只有**本进程新建**的才补写,否则视为对方已删、从内存里丢掉。顺带修掉一个更直接的变体:`tasks` 合并从不清理 `_deletedTaskIds`,删任务会在**同一次 save 里**被自己刚读到的磁盘副本写回来。
|
|
34
|
+
|
|
35
|
+
**测试**:新增 `test/store-lock.test.mjs`(10 条,含两个真子进程的删除复活回归、同步等锁与退出 flush)。`npm test` **835 项 / 48 个文件**全绿。
|
|
36
|
+
|
|
37
|
+
### 新增:把用法做成宿主 skill
|
|
38
|
+
|
|
39
|
+
`skills/project-memory/`:`SKILL.md`(唯一事实源,frontmatter 提供 name / description,注册时剥掉)+ `scripts/pm-digest.mjs`(零依赖体检:store 大小、insight / 任务计数、trigger 覆盖、绑定数)。`apply()` 用 `ctx.inject(['skills'], …)` 注册,`resourceBase` 指向包内目录;没有 `skills` 服务的宿主静默跳过。`package.json files` 加 `skills`。
|
|
40
|
+
|
|
41
|
+
**测试**:`npm test` **825 项 / 48 个文件**全绿;`npm run typecheck` 通过。新增 `test/signal-source.test.mjs`(端到端:通知不算人话 / 回退会话缓存、subagent 参数不产 op、目录名不产 `run-bench`、散文删除只记录)与 `test/skill.test.mjs`。
|
|
42
|
+
|
|
43
|
+
### 性能:Windows / NTFS 上大量小文件(不 OOM,但会被"每次 save 的文件操作数"拖慢)
|
|
44
|
+
|
|
45
|
+
**实测**:同一份 400 个小文件,`WSL 挂 /mnt/c`(9p,NTFS 的**悲观**代理)与 ext4 对照:
|
|
46
|
+
|
|
47
|
+
| 指标 | 修复前 | 修复后 |
|
|
48
|
+
|---|---|---|
|
|
49
|
+
| 首次索引 400 文件 | 11.4 s(28.4 ms/文件) | 8.2–9.5 s(20–24 ms/文件) |
|
|
50
|
+
| 单文件"改 → 懒索引" p50 | 178 ms | 46 ms(−74%) |
|
|
51
|
+
| 同上,ext4 | 1 ms | 1 ms |
|
|
52
|
+
| `findProjectRoot`(每次懒索引都走) | 119 ms | 14 ms |
|
|
53
|
+
| watch 对 400 文件做 stat | 843 ms,事件循环被按住 834 ms | 74 ms,最大卡顿 1 ms |
|
|
54
|
+
| 3k / 10k 小文件索引峰值 RSS | — | 83–85 MB / 112 MB |
|
|
55
|
+
|
|
56
|
+
**改了什么**:
|
|
57
|
+
|
|
58
|
+
- `findProjectRoot`:每层祖先从"11 个 marker × 2 组标记各做一次 `existsSync`"改成**一次 readdir + 一趟向上遍历**(VCS 仍优先于 PROJECT;`a marker above the cwd still wins` 的契约由 root-guards 87 项守住)。
|
|
59
|
+
- 每次 save 里不必要的文件操作:`shards/` 的 `.tmp` 清扫 60 s 一次(store 根目录仍每次扫,崩溃残留立刻收);`.gitignore` 存在性只查一次;store / shards 目录 mkdir 只在首次执行;分片/辅助文件的原子写不再每次 mkdir(目录被外部删掉时按 ENOENT 补建重试)。
|
|
60
|
+
- `writeJsonAtomic`:`EPERM` / `EBUSY` / `EACCES` 重试 3 次(Windows 上杀毒软件与搜索索引器会瞬时占用 rename 目标)。
|
|
61
|
+
- watch 轮询:同步 `statSync` 循环改成 `fs/promises.stat` + 16 并发。**这是"卡"的主因**——同步循环会把整个 dsh 事件循环按住(400 文件 843 ms;12k 文件按比例是几十秒),异步后主线程只等 I/O。
|
|
62
|
+
- 新增 `npm run bench:edits`(`scripts/bench-edits.mjs`):任意目录跑首次索引 + M 次单文件更新,报 p50/p90/峰值 RSS。Windows 原生请 `--dir C:\Temp\xxx` 量真实数字;上面的 9p 数字是上界。
|
|
63
|
+
|
|
64
|
+
**OOM**:大量小文件不是 OOM 面(3k 文件峰值 ~85 MB、10k ~112 MB,线性 ~3 MB/1k 文件)。OOM 面仍是**单个大文件**(`maxFileSizeMb: 10` → 最坏 +300 MB RSS)与 PDF 首次解析的 ~175 MB 底座,见 README「单文件内存预算」。
|
|
65
|
+
|
|
66
|
+
**没做**:分片打包(仍是一文件一 shard:12k 文件在 NTFS 上就是 12k 个 4 KB 块 + 12k 次 write+rename,这是下一档结构性优化);watch 每轮仍用同步 `git ls-files` 子进程。
|
|
67
|
+
|
|
68
|
+
### 修复:非拉丁文字(俄语 / 西里尔)检索完全失效(issue #9)
|
|
69
|
+
|
|
70
|
+
**症状**:整句俄文查询切不出任何 token → 候选集恒为 0,提示通道与 `query_memory` 永不命中;俄文条目即使进了 store 也不可检索、不参与去重。阈值怎么调都没用,因为闸门前面没有输入。
|
|
71
|
+
|
|
72
|
+
**根因**:`tokenizeRaw` 只认 `[a-z0-9_]+` 与 CJK,西里尔在循环里不产生 token——"是不是词"被绑死成了"是不是这两种书写系统"。
|
|
73
|
+
|
|
74
|
+
**改法**:
|
|
75
|
+
|
|
76
|
+
- `src/util/ru.js`(新):切词 + 俄语虚词表 + **Snowball Russian 词干**。词干是逐句移植参考实现,并用 snowballstemmer 3.1.1 做了 8,354 个词形(含 6,000 个随机词)的逐词一致性对照。≤3 字符不词干(否则 `ИИ → и`)。
|
|
77
|
+
- `tokenizeRaw` 接入西里尔分支;**拉丁与 CJK 的输出逐字节不变**(老阈值不在这次重标定)。
|
|
78
|
+
- 闸门按文字系统分派:`gatedQueryText` 不再把 2 字母俄文当"短拉丁噪声";`isIntentWord` / `matchIntent` 改用 Unicode 词边界(`город` 不再命中 `городской`),长度门槛 ≥3。
|
|
79
|
+
- 索引迁移:`TOKENIZER_VERSION = 2` + doc 条目 `termsVersion`。旧 store 的 doc `terms` 会**一次性回填**(内容哈希未变也重抽),否则旧索引里的俄文永远补不上。
|
|
80
|
+
- leanvec `0.2.0`(optionalDependency 同步到 `^0.2.0`):词表**纯追加** 8,000 个西里尔行(77.0 → 84.8 MiB),并修了"只剩词边界 `▁` 时仍返回向量"的缺陷——未覆盖文字现在返回 `null`,不再出现"任意两条同脚本文字余弦恒为 1.0"进而被向量去重误覆盖。同版本把嵌入表改成**按行懒加载**:向量层常驻内存从约 126 MB 降到约 41 MB,加载耗时 119 → 46 ms(`src/vector-index.js` 传 8 MB 行缓存并在换模型时 `close()` 旧 fd)。
|
|
81
|
+
|
|
82
|
+
**升级注意**:
|
|
83
|
+
|
|
84
|
+
- 升级后首次索引/巡检会对旧 doc 条目做一次 `terms` 重抽(一次性 CPU 尖峰,文件内容不变);中文 / 英文的检索分数与行为不变。
|
|
85
|
+
- 俄文条目从此参与去重(`dedupOverlap` 是同一把尺子)。若老 store 里积了多条同义俄文笔记,升级后可能被合并/提示——这是修好的表现,不是新 bug。
|
|
86
|
+
- 未覆盖的文字(希腊 / 希伯来 / 阿拉伯 / 泰文)仍是纯词法,向量层对它们返回 `null`(明确降级,不猜)。
|
|
87
|
+
- **发布顺序**:leanvec `0.2.0` 必须先于本版发布。本版把 optionalDependency 提到 `^0.2.0`,若环境里仍是 `0.1.0`,俄文标题会被编码成同一个常量向量,向量去重可能误覆盖(正是 0.2.0 修掉的缺陷);词法检索不受影响。
|
|
88
|
+
|
|
1
89
|
## 0.6.5 (2026-10-24)
|
|
2
90
|
|
|
3
91
|
**升级注意**:`allowUnsafeRoots: true` 的作用面比 0.6.4 大。此前它只放开**显式**工具调用与 `autoIndexOnFirstUse`,懒索引、会话审计与 TaskBridge 即使开着也始终不动;现在它放开内置名单的**所有**根判定入口,这三条链路会在放行的目录里建 store、写审计。只想放开某个目录时用 `roots.allow`(精确匹配,不影响 `deny` / `exclude`);家目录、系统目录如非必要仍建议保持 `false`。
|
package/README.md
CHANGED
|
@@ -22,9 +22,11 @@ A persistent **project development memory** for [DeepSeek Harness](https://githu
|
|
|
22
22
|
- **Automatic, read-time memorization** — a file is memorized the moment the model reads it, so memory is a byproduct of normal work rather than an upfront scan, and files nobody reads are never indexed. A background poll re-memorizes changed files only.
|
|
23
23
|
- **Doc ↔ code cross-linking** — a document that mentions a symbol is surfaced when that symbol is queried. Links are resolved against the current symbol table, so they cannot go stale.
|
|
24
24
|
- **Hybrid recall** — ranked search over documents, symbols, experience notes and insights, with optional LLM query expansion. The experience/insight layers are re-ordered by cosine when `leanvec` is present — installed by default, absent ⇒ pure lexical. Tuned for CJK: phrase boost, a synonym table, and CJK-aware boundaries for doc↔symbol linking.
|
|
25
|
+
Russian (Cyrillic) is supported too: word splitting, a stopword list and Snowball stemming, so Russian queries hit Russian notes and take part in dedup.
|
|
25
26
|
- **Experience notes** — problems → solutions, deduplicated by overlap rather than repeated, bounded by project size, and surfaced both by search and by the same injection path as lessons.
|
|
26
27
|
- **Tiered insight memory (lessons / decisions / procedures)** — one entity across task, project and global scope. Near-duplicates merge or reinforce, and promotion moves an entry between scopes instead of copying it. Use is recorded, so decay and capacity rank by activity rather than age alone. The panel exposes a per-scope view for reviewing and editing entries. That list is ordered newest-first and loaded incrementally: 30 entries at a time, with the next page prefetched before the reader reaches the bottom and off-screen rows skipped by the renderer, so a large memory stays responsive.
|
|
27
|
-
- **Triggered injection** — an insight may carry an authored trigger: only `when` triggers, `guard` narrows it, and `prevents` records what breaks without the entry. Corpus text can never trigger an injection; the statistical channel is gated separately and silent by default.
|
|
28
|
+
- **Triggered injection** — an insight may carry an authored trigger: only `when` triggers, `guard` narrows it, and `prevents` records what breaks without the entry. Corpus text can never trigger an injection; the statistical channel is gated separately and silent by default. **Evidence is graded by source**: only host facts (structured tool calls, `fs`/`todo` events) and irreversible actions named by the human (commit / publish / release / push / deploy / go public) can inject full text; prose mentions of delete / clean up / render / benchmark only feed the hint channel, and subagent prompts plus notice-shaped messages never count as actions — in one real session they produced 72% of all injected characters.
|
|
29
|
+
- **Usage is a skill too** — it registers `project-memory` into the host `skills` registry (a directory bundle with `scripts/pm-digest.mjs`, `resourceBase` pointing inside the package). The model loads the query/write workflow on demand instead of carrying it in every prompt; hosts without a `skills` service skip it silently.
|
|
28
30
|
|
|
29
31
|
## Installation
|
|
30
32
|
|
|
@@ -99,7 +101,7 @@ The store is per-project and follows the codebase: changed files are re-extracte
|
|
|
99
101
|
- **Incremental** — a content hash per file; only changed files are re-extracted.
|
|
100
102
|
- **Cross-linking** — a returned document chunk resolves the symbols it mentions against the **current** symbol table and appends them as `references`, so a doc indexed before its symbols still links correctly.
|
|
101
103
|
- **Query expansion** — when enabled, `query_memory` asks the LLM to rewrite the query into several variants (synonyms, EN/CN, identifier guesses) and merges the scores; when off, queries never touch the LLM. Indexing itself is model-free.
|
|
102
|
-
- **Consistency** — the fact layer follows the codebase (hash re-extract / remove-on-delete); the experience layer is retrieval-only with supersede and `forget`. Writes take a cross-process directory lock (`.write.lock`) around a short read-modify-write, so two dsh instances can share one project store: shards converge by `indexedAt`,
|
|
104
|
+
- **Consistency** — the fact layer follows the codebase (hash re-extract / remove-on-delete); the experience layer is retrieval-only with supersede and `forget`. Writes take a cross-process directory lock (`.write.lock`) around a short read-modify-write, so two dsh instances can share one project store: shards converge by `indexedAt`, a save that cannot get the lock is deferred and retried (and reported as not persisted), and entries deleted by another process are not resurrected by a stale in-memory snapshot.
|
|
103
105
|
|
|
104
106
|
## Architecture (Task Panel)
|
|
105
107
|
|
|
@@ -240,6 +242,17 @@ Four corpora, one Linux machine (Node 24.19), each run twice with the **second,
|
|
|
240
242
|
|
|
241
243
|
> Generated code (~4–5 symbols/file), measured 2026-10-13. Reproduce with `npm run bench:synthetic -- 5000` (`scripts/bench-synthetic.mjs`). Pure indexing overhead, no LLM calls. The first query after a write rebuilds the IDF cache (**141 ms at 40k entries**, 68 ms at 20k, 17 ms at 4k); later queries hit it.
|
|
242
244
|
|
|
245
|
+
### Windows / many small files
|
|
246
|
+
|
|
247
|
+
On Windows (NTFS) the bottleneck is not CPU but the **number of file operations per write**, and watch's synchronous `stat` loop blocks the event loop. For 400 small files (WSL over NTFS, a pessimistic proxy): first index 8–10 s and a single-file edit p50 ≈ 46 ms; on ext4 the same work takes 60–90 ms and 1 ms. Indexing 3,000 / 10,000 small files peaks at ≈ 85 / 112 MB RSS — **many small files are not the OOM surface**; a single large file is.
|
|
248
|
+
|
|
249
|
+
```bash
|
|
250
|
+
npm run bench:edits -- --dir C:\\Temp\\pm-bench # native Windows
|
|
251
|
+
node scripts/bench-edits.mjs --dir /mnt/c/Users/Public/pm-bench --files 400
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
The script builds its corpus in a temporary directory and deletes it afterwards; it reports first-index cost, edit p50/p90/max and peak RSS.
|
|
255
|
+
|
|
243
256
|
### Reproduce it on your own project
|
|
244
257
|
|
|
245
258
|
The measurement ships with the repository **and with the published npm package** (`scripts/` is part of the tarball). It needs **no dsh instance, no network and no model calls**, and never touches your project's own store — results go to a temp directory and are removed afterwards:
|
|
@@ -264,7 +277,7 @@ Pass `--queries your-queries.json` to run the labeled-set method (hit@5 / hit@10
|
|
|
264
277
|
|
|
265
278
|
## Design tradeoffs
|
|
266
279
|
|
|
267
|
-
- **A short filesystem lock, not an embedded database** — each save holds an exclusive `.write.lock` only for the read-modify-write (parsing stays outside it), waits at most 2 s for a busy peer and then retries. Two dsh instances can share one store. No WAL, no daemon, no native dependency.
|
|
280
|
+
- **A short filesystem lock, not an embedded database** — each save holds an exclusive `.write.lock` only for the read-modify-write (parsing stays outside it), waits at most 2 s for a busy peer and then retries; a busy peer is waited on synchronously for up to 15 s (correctness comes from acquiring the lock, not from background retries); a write that still cannot land is registered for a synchronous flush when the process exits or the plugin is disposed, **without interrupting the user** — memory writes are idempotent and cheap to redo; set `DSH_PROJECT_MEMORY_DEBUG=1` for a one-line diagnostic. The lock carries `pid` / `host` / `token`: a live same-host holder is never preempted, release verifies ownership, and a crashed same-host lock is reclaimed immediately. Two dsh instances can share one store. No WAL, no daemon, no native dependency.
|
|
268
281
|
- **Watch: compute outside, commit inside** — no lock is held during parsing, and polling with mtime + content hash is used instead of `fs.watch`: it behaves identically on network drives, Docker volumes and WSL, without duplicate-trigger or missed-event failure modes.
|
|
269
282
|
- **Corrupt shards are quarantined, not repaired** — a shard that fails to parse is renamed and only that file is re-indexed, so there is no WAL or embedded database adding native dependencies, lock contention and failure modes of their own.
|
|
270
283
|
- **Vectors re-rank, they do not rank** — on a paraphrased-query set, pure vector replacement is worse than BM25 (hit@10 **53% vs 69%**) while weighted fusion helps at small k (hit@3 **53% vs 50%**), so the optional layer only re-orders the experience/insight layers and never gates. Lexical retrieval still answers the queries this plugin targets: on a real project with 29 labelled queries, file-level hit@5 is **96.6%**, and whole-chunk terms raise document term coverage from **27.3% to 100%** with MRR unchanged (**0.958** vs **0.955**).
|
|
@@ -281,7 +294,7 @@ These commands are for **maintaining the plugin code** — regular users do not
|
|
|
281
294
|
|
|
282
295
|
```bash
|
|
283
296
|
npm install
|
|
284
|
-
npm test #
|
|
297
|
+
npm test # 835 tests
|
|
285
298
|
npm run eval:injection # synthetic pool P/R: precision 0.93 / recall 1.00, + a 3-scenario hint-only group
|
|
286
299
|
npm run eval:injection -- --store .dsh-project-memory/insights.json # replay on YOUR store; control group is a hard gate
|
|
287
300
|
npm run selfcheck:triggers # which entries can still push, which declarations are dead (reads your local store)
|
package/README.zh-CN.md
CHANGED
|
@@ -20,10 +20,11 @@
|
|
|
20
20
|
- **代码符号记忆** — 零依赖扫描器提取函数、类、方法、接口与类型别名及其完整签名,覆盖 8 种语言。项目装了 `typescript` 时,可选第二层补推导返回类型、泛型与接口,后台执行、不阻塞索引。
|
|
21
21
|
- **读到即记忆、变更即刷新** — 文件在模型实际读取的瞬间被记忆,记忆是正常工作的副产品,而不是额外的一次全量扫描;从未读过的文件不会被记忆。后台轮询只重记变更过的文件。
|
|
22
22
|
- **文档 ↔ 代码交叉链接** — 文档提及的符号,在查询该符号时一并带出。链接按**当前**符号表解算,不会过期。
|
|
23
|
-
- **混合召回** — 对文档、符号、经验笔记与 insight 排序召回,可选 LLM 查询扩展。`leanvec` 是 optionalDependency:默认装上并按余弦重排经验/洞察两层,没装或 `vectorDir: 'off'` 则退回纯词法。针对 CJK
|
|
23
|
+
- **混合召回** — 对文档、符号、经验笔记与 insight 排序召回,可选 LLM 查询扩展。`leanvec` 是 optionalDependency:默认装上并按余弦重排经验/洞察两层,没装或 `vectorDir: 'off'` 则退回纯词法。针对 CJK 增强:短语加分、同义词表,以及文档↔符号链接的词边界处理。俄语(西里尔)同样支持:切词 + 虚词表 + Snowball 词干,俄文查询能命中俄文条目,也参与去重。
|
|
24
24
|
- **经验笔记** — 记录问题 → 方案;相似问题覆盖而不重复,数量随项目规模有界,与教训走同一条注入通道:检索与自动注入都能带出。
|
|
25
25
|
- **分层 insight 记忆(教训 / 决策 / 流程)** — 同一实体贯穿任务、项目、全局三级。近重复合并或强化;提升是更换归属而非复制。被使用会记账,因此衰减与容量按活跃度排序,而不是只按时间。面板提供分级的记忆视图用于审核与编辑;列表按新→旧排列并增量加载——每页 30 条,滚到底前就预取下一页,离屏行不参与渲染,记忆变多也不卡。
|
|
26
|
-
- **触发式注入** — insight 可携带 authored trigger:只有 `when` 能触发,`guard` 只能收窄,`prevents`
|
|
26
|
+
- **触发式注入** — insight 可携带 authored trigger:只有 `when` 能触发,`guard` 只能收窄,`prevents` 记下没有它会坏在哪。语料正文永远不能触发注入;统计通道另有独立门槛,默认沉默。**证据来源分级**:只有宿主事实(结构化工具调用、`fs`/`todo` 事件)与真人消息里的不可逆外部动作(提交 / 发布 / 发版 / 推送 / 部署 / 公开)能触发全文注入;散文里的"删除 / 清理 / 渲染 / 基准"只进提示通道,子代理提示词与通知类消息不参与动作判定——它们曾让一个真实会话 72% 的注入字符是噪音。
|
|
27
|
+
- **用法也是一个 skill** — 向宿主 `skills` 注册 `project-memory`(目录 bundle,含 `scripts/pm-digest.mjs`,`resourceBase` 指向包内目录)。模型按需加载查询 / 写入流程,不占常驻提示;没有 `skills` 服务的宿主静默跳过。
|
|
27
28
|
|
|
28
29
|
## 安装
|
|
29
30
|
|
|
@@ -239,6 +240,17 @@ dsh web --patch ./config.yml
|
|
|
239
240
|
|
|
240
241
|
> 合成基准:生成代码(~4–5 符号/文件),实测于 2026-10-13。复现命令 `npm run bench:synthetic -- 5000`(脚本 `scripts/bench-synthetic.mjs`)。测量纯索引开销,不含 LLM 调用。写入后的首次查询会重建 IDF 缓存(**40k 条目 141 ms**,20k 条目 68 ms,4k 条目 17 ms),后续查询命中缓存。
|
|
241
242
|
|
|
243
|
+
### Windows / 大量小文件
|
|
244
|
+
|
|
245
|
+
Windows(NTFS)的瓶颈不是 CPU,而是**每次写盘的文件操作数**;watch 的同步 `stat` 循环还会把 dsh 的事件循环按住。同一份 400 个小文件(WSL 挂 NTFS 的悲观代理):首次索引 8–10 s、单文件"改 → 懒索引" p50 约 46 ms;ext4 上分别是 60–90 ms 与 1 ms。3,000 / 10,000 个小文件索引的峰值 RSS 约 85 / 112 MB——**大量小文件不是 OOM 面**(单个大文件才是)。
|
|
246
|
+
|
|
247
|
+
```bash
|
|
248
|
+
npm run bench:edits -- --dir C:\\Temp\\pm-bench # Windows 原生
|
|
249
|
+
node scripts/bench-edits.mjs --dir /mnt/c/Users/Public/pm-bench --files 400
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
脚本在临时目录里造语料,跑完删除;报首次索引、单文件更新 p50/p90/max 与峰值 RSS。
|
|
253
|
+
|
|
242
254
|
### 自己复现这些数字
|
|
243
255
|
|
|
244
256
|
测量本身随仓库发布,**也随 npm 包一起发布**(`scripts/` 已包含在 tarball 中)。脚本**不需要 dsh 实例、不需要网络、不调用任何模型**,也**不碰被测项目自己的 store**——结果写进临时目录,跑完删除:
|
|
@@ -263,7 +275,7 @@ node scripts/bench.mjs /你的/项目路径 [--json] [--samples 100] [--no-pdf]
|
|
|
263
275
|
|
|
264
276
|
## 设计取舍
|
|
265
277
|
|
|
266
|
-
- **短时文件锁,而不是嵌入式数据库** — 每次保存只在读改写期间持有排他的 `.write.lock`(解析在锁外完成),最多等 2
|
|
278
|
+
- **短时文件锁,而不是嵌入式数据库** — 每次保存只在读改写期间持有排他的 `.write.lock`(解析在锁外完成),最多等 2 秒;对方忙时最多**同步等 15s**(写路径的正确性靠等到锁,不靠后台重试);仍失败会登记进退出 flush,关 dsh / 卸载插件时再同步写一次。全程**默认不打扰用户**——记忆写入幂等、失败成本低;需要排查时设 `DSH_PROJECT_MEMORY_DEBUG=1` 才会打印一行。锁内容带 `pid` / `host` / `token`:同机持有者活着就绝不抢,release 校验所有权、不删别人的锁;崩溃残留的同机死锁按 pid 立即回收。两个 dsh 实例因此可以共用一个存储。没有 WAL、没有常驻进程、没有原生依赖。
|
|
267
279
|
- **Watch:事务外计算,事务内提交** — 不持锁解析,也不用 `fs.watch`:轮询 + mtime/内容哈希在网络盘、Docker 卷、WSL 上行为一致,没有 `fs.watch` 的重复触发/漏事件问题。
|
|
268
280
|
- **损坏分片隔离,不自动修复** — 解析失败的分片改名、只重索引该文件;不引入 WAL 或嵌入式数据库,那会带来原生依赖、锁竞争与它们自己的新故障模式。
|
|
269
281
|
- **向量只重排,不做排序主力** — 在**改写成不含原词**的查询集上,纯向量替换差于 BM25(hit@10 **53% vs 69%**),加权融合只在**小 k** 上更好(hit@3 **53% vs 50%**),所以可选层只重排经验/洞察两层、绝不参与闸门。词法检索在本插件针对的查询上依然够用:真实项目 29 条标注查询的文件级 hit@5 为 **96.6%**,整 chunk 词项把文档词项覆盖从 **27.3% 提到 100%** 且 MRR 不变(**0.958** vs **0.955**)。
|
|
@@ -280,7 +292,7 @@ node scripts/bench.mjs /你的/项目路径 [--json] [--samples 100] [--no-pdf]
|
|
|
280
292
|
|
|
281
293
|
```bash
|
|
282
294
|
npm install
|
|
283
|
-
npm test #
|
|
295
|
+
npm test # 835 项测试
|
|
284
296
|
npm run eval:injection # 合成池 P/R:精确率 0.93 / 召回率 1.00,另有 3 个 hint-only 场景
|
|
285
297
|
npm run eval:injection -- --store .dsh-project-memory/insights.json # 用你自己的 store 重放;对照组是硬闸门
|
|
286
298
|
npm run selfcheck:triggers # 哪些条目还推得动、哪些声明是死的(读你本地的 store)
|
package/package.json
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yolk_vat-y/dsh-project-memory",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.6",
|
|
4
4
|
"description": "Persistent project memory for dsh agents: index docs (PDF/Markdown/text) and code symbols into a searchable per-workspace store, recall them with cited sources, and keep experience entries (problems -> solutions) searchable on demand.",
|
|
5
5
|
"author": "00080000 <3388065969@qq.com>",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "src/index.js",
|
|
8
8
|
"files": [
|
|
9
9
|
"src",
|
|
10
|
+
"skills",
|
|
10
11
|
"client",
|
|
11
12
|
"scripts",
|
|
12
13
|
"cordis.patch.yml",
|
|
@@ -19,7 +20,7 @@
|
|
|
19
20
|
"url": "https://github.com/00080000/dsh-project-memory.git"
|
|
20
21
|
},
|
|
21
22
|
"scripts": {
|
|
22
|
-
"test": "node test/run-test.mjs && node test/taskbridge.test.mjs && node test/insight-store.test.mjs && node test/reflection-pipeline.test.mjs && node test/auto-inject.test.mjs && node test/insight-actions.test.mjs && node test/insight-paging.test.mjs && node test/config-schema.test.mjs && node test/host-contract.test.mjs && node test/session-dir.test.mjs && node test/llm-route.test.mjs && node test/doc-index.test.mjs && node test/chunker.test.mjs && node test/client-hints.test.mjs && node test/client-paging.test.mjs && node test/client-task-sync.test.mjs && node test/recall.test.mjs && node test/recall-vector-fusion.test.mjs && node test/vector-index.test.mjs && node test/readiness.test.mjs && node test/insight-derive.test.mjs && node test/readiness-eval.test.mjs && node test/ops.test.mjs && node test/injection-audit.test.mjs && node test/injection-budget.test.mjs && node test/injection-scenarios.test.mjs && node test/bugfix-0.5.7.test.mjs && node test/client-icons.test.mjs && node test/client-slash.test.mjs && node test/client-toolview.test.mjs && node test/workflow-command.test.mjs && node test/client-session-id.test.mjs && node test/client-degraded.test.mjs && node test/watch-idle.test.mjs && node test/citation-paths.test.mjs && node test/task-view.test.mjs && node test/root-guards.test.mjs && node test/root-policy.test.mjs && node test/gitignore-index.test.mjs && node test/store-gitignore.test.mjs && node test/atomic-write.test.mjs && node test/store-cache.test.mjs && node test/store-concurrent.test.mjs && node test/tool-schema-size.test.mjs && node test/enhancer.test.mjs",
|
|
23
|
+
"test": "node test/run-test.mjs && node test/taskbridge.test.mjs && node test/insight-store.test.mjs && node test/reflection-pipeline.test.mjs && node test/auto-inject.test.mjs && node test/insight-actions.test.mjs && node test/insight-paging.test.mjs && node test/config-schema.test.mjs && node test/host-contract.test.mjs && node test/session-dir.test.mjs && node test/llm-route.test.mjs && node test/doc-index.test.mjs && node test/chunker.test.mjs && node test/client-hints.test.mjs && node test/client-paging.test.mjs && node test/client-task-sync.test.mjs && node test/recall.test.mjs && node test/recall-vector-fusion.test.mjs && node test/vector-index.test.mjs && node test/readiness.test.mjs && node test/insight-derive.test.mjs && node test/readiness-eval.test.mjs && node test/ops.test.mjs && node test/injection-audit.test.mjs && node test/signal-source.test.mjs && node test/skill.test.mjs && node test/injection-budget.test.mjs && node test/injection-scenarios.test.mjs && node test/bugfix-0.5.7.test.mjs && node test/client-icons.test.mjs && node test/client-slash.test.mjs && node test/client-toolview.test.mjs && node test/workflow-command.test.mjs && node test/client-session-id.test.mjs && node test/client-degraded.test.mjs && node test/watch-idle.test.mjs && node test/citation-paths.test.mjs && node test/task-view.test.mjs && node test/root-guards.test.mjs && node test/root-policy.test.mjs && node test/gitignore-index.test.mjs && node test/store-gitignore.test.mjs && node test/atomic-write.test.mjs && node test/store-cache.test.mjs && node test/store-concurrent.test.mjs && node test/store-lock.test.mjs && node test/tool-schema-size.test.mjs && node test/enhancer.test.mjs && node test/multilingual-ru.test.mjs",
|
|
23
24
|
"eval:injection": "node test/injection-scenarios.test.mjs",
|
|
24
25
|
"typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.client.json",
|
|
25
26
|
"selfcheck:triggers": "node test/injection-scenarios.test.mjs --selfcheck",
|
|
@@ -28,7 +29,8 @@
|
|
|
28
29
|
"bench:peak": "node --expose-gc scripts/file-peak.mjs",
|
|
29
30
|
"bench:store": "node scripts/bench-store.mjs",
|
|
30
31
|
"schema:size": "node scripts/tool-schema-size.mjs",
|
|
31
|
-
"build:client": "tsdown"
|
|
32
|
+
"build:client": "tsdown",
|
|
33
|
+
"bench:edits": "node scripts/bench-edits.mjs"
|
|
32
34
|
},
|
|
33
35
|
"keywords": [
|
|
34
36
|
"dsh",
|
|
@@ -111,6 +113,6 @@
|
|
|
111
113
|
"./cordis.patch.yml": "./cordis.patch.yml"
|
|
112
114
|
},
|
|
113
115
|
"optionalDependencies": {
|
|
114
|
-
"leanvec": "^0.
|
|
116
|
+
"leanvec": "^0.2.0"
|
|
115
117
|
}
|
|
116
118
|
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// 大量小文件的性能基准(不需要 dsh、不联网、不碰你自己的 store)。
|
|
3
|
+
//
|
|
4
|
+
// node scripts/bench-edits.mjs [--files 400] [--edits 30] [--dir <空目录>] [--keep]
|
|
5
|
+
//
|
|
6
|
+
// 量两件事:
|
|
7
|
+
// 1. 首次索引 N 个小文件(每个文件写一个分片);
|
|
8
|
+
// 2. 之后 M 次"单文件修改 → 懒索引"(每次一个 save:锁 + 分片 + 目录元数据)。
|
|
9
|
+
//
|
|
10
|
+
// 为什么单独有这个脚本:Windows/NTFS 上每次文件操作都要过过滤驱动,单文件更新的成本
|
|
11
|
+
// 由**文件操作次数**决定,而不是 CPU。Linux 上 p50 1ms 的路径到 NTFS 上可以是几十毫秒;
|
|
12
|
+
// 这个脚本用同一份代码量出差异,也用来守住"别在每次 save 里加 O(N) 扫描"。
|
|
13
|
+
//
|
|
14
|
+
// 用法示例(Windows 原生 / WSL 挂载盘):
|
|
15
|
+
// node scripts/bench-edits.mjs --dir C:\\Temp\\pm-bench
|
|
16
|
+
// node scripts/bench-edits.mjs --dir /mnt/c/Users/Public/pm-bench --files 400
|
|
17
|
+
import { mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
18
|
+
import { tmpdir } from 'node:os'
|
|
19
|
+
import path from 'node:path'
|
|
20
|
+
import { indexRepository } from '../src/tools/index-repo.js'
|
|
21
|
+
import { indexFile } from '../src/lazy.js'
|
|
22
|
+
|
|
23
|
+
const arg = (name, fallback) => {
|
|
24
|
+
const i = process.argv.indexOf(`--${name}`)
|
|
25
|
+
return i >= 0 && process.argv[i + 1] ? process.argv[i + 1] : fallback
|
|
26
|
+
}
|
|
27
|
+
const files = Number(arg('files', 400))
|
|
28
|
+
const edits = Number(arg('edits', 30))
|
|
29
|
+
const keep = process.argv.includes('--keep')
|
|
30
|
+
const parent = arg('dir', null)
|
|
31
|
+
const base = parent ? path.resolve(parent) : mkdtempSync(path.join(tmpdir(), 'pm-bench-'))
|
|
32
|
+
const root = path.join(base, `many-small-${Date.now().toString(36)}`)
|
|
33
|
+
if (parent) mkdirSync(base, { recursive: true })
|
|
34
|
+
|
|
35
|
+
const config = {
|
|
36
|
+
memoryDir: '.dsh-project-memory',
|
|
37
|
+
chunkChars: 3000,
|
|
38
|
+
maxChunksPerFile: 40,
|
|
39
|
+
maxFileSizeMb: 10,
|
|
40
|
+
maxPdfPages: 1000,
|
|
41
|
+
enableTypeScript: false,
|
|
42
|
+
}
|
|
43
|
+
const mb = (bytes) => (bytes / 1048576).toFixed(1)
|
|
44
|
+
|
|
45
|
+
mkdirSync(root, { recursive: true })
|
|
46
|
+
for (let i = 0; i < files; i++) {
|
|
47
|
+
writeFileSync(path.join(root, `m${i}.js`), `export function f${i}(a) {\n return a + ${i}\n}\n\nexport const v${i} = ${i}\n`)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const t0 = Date.now()
|
|
51
|
+
await indexRepository(null, config, root, {})
|
|
52
|
+
const indexMs = Date.now() - t0
|
|
53
|
+
|
|
54
|
+
const storeDir = path.join(root, config.memoryDir)
|
|
55
|
+
const shards = readdirSync(path.join(storeDir, 'shards'))
|
|
56
|
+
let contentBytes = 0
|
|
57
|
+
for (const name of readdirSync(storeDir)) {
|
|
58
|
+
const p = path.join(storeDir, name)
|
|
59
|
+
try {
|
|
60
|
+
const st = statSync(p)
|
|
61
|
+
if (st.isFile()) contentBytes += st.size
|
|
62
|
+
} catch {
|
|
63
|
+
/* 统计期间消失的临时文件 */
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const samples = []
|
|
68
|
+
for (let i = 0; i < edits; i++) {
|
|
69
|
+
const file = path.join(root, `m${i % files}.js`)
|
|
70
|
+
writeFileSync(file, `export function f${i % files}(a) {\n return a + ${i} // edit ${i}\n}\n`)
|
|
71
|
+
const started = Date.now()
|
|
72
|
+
await indexFile(null, config, file, null, root)
|
|
73
|
+
samples.push(Date.now() - started)
|
|
74
|
+
}
|
|
75
|
+
samples.sort((a, b) => a - b)
|
|
76
|
+
const pick = (r) => samples[Math.min(samples.length - 1, Math.floor(r * samples.length))]
|
|
77
|
+
|
|
78
|
+
console.log(JSON.stringify({
|
|
79
|
+
files,
|
|
80
|
+
edits,
|
|
81
|
+
root: keep ? root : '(deleted)',
|
|
82
|
+
index: { ms: indexMs, perFileMs: Number((indexMs / files).toFixed(2)), shards: shards.length, contentKB: Number((contentBytes / 1024).toFixed(1)) },
|
|
83
|
+
singleFileEditMs: { p50: pick(0.5), p90: pick(0.9), max: samples.at(-1) },
|
|
84
|
+
peakRssMB: Number(mb(process.resourceUsage().maxRSS * 1024)),
|
|
85
|
+
}, null, 2))
|
|
86
|
+
|
|
87
|
+
if (!keep) rmSync(root, { recursive: true, force: true })
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: project-memory
|
|
3
|
+
description: Recall and maintain this project's long-term memory — indexed docs and code symbols, lessons, decisions, procedures, and cross-session tasks. Use it before re-deriving project context or repeating a past mistake.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Project memory
|
|
7
|
+
|
|
8
|
+
This repository keeps a memory store at `.dsh-project-memory/` (path configurable). It holds three
|
|
9
|
+
kinds of things:
|
|
10
|
+
|
|
11
|
+
1. **Indexed corpus** — documents (Markdown / PDF / text) and code symbols, with `path:line`
|
|
12
|
+
citations.
|
|
13
|
+
2. **Insights** — lessons (`problem → fix`), decisions (`choice + reason`), procedures (steps), and
|
|
14
|
+
experience notes. These are written by agents, across sessions.
|
|
15
|
+
3. **Tasks** — cross-session work records with steps and hot files. A session can be bound to one.
|
|
16
|
+
|
|
17
|
+
Query it before re-deriving; write to it only after something has been verified.
|
|
18
|
+
|
|
19
|
+
## When to query
|
|
20
|
+
|
|
21
|
+
- Before asking the human to re-explain the project, a past decision, or "what were we doing".
|
|
22
|
+
- Before changing a subsystem: there may be a lesson about its failure modes.
|
|
23
|
+
- Before an irreversible action (commit / publish / release / push / deploy / migrate): the store may
|
|
24
|
+
know a prerequisite you would otherwise miss.
|
|
25
|
+
- When resuming: call `list_tasks`, then `select_task` if one matches the current work.
|
|
26
|
+
|
|
27
|
+
## Workflow
|
|
28
|
+
|
|
29
|
+
1. **Locate context**
|
|
30
|
+
- `query_memory` with `query` = what you actually need ("how are shards written", "why store
|
|
31
|
+
scope", "where is X implemented").
|
|
32
|
+
- `type`: `all` (default) / `doc` / `symbol` / `experience` / `insight` / `task`.
|
|
33
|
+
- Results carry ids and citations. Treat them as evidence: read the cited file when the answer
|
|
34
|
+
matters.
|
|
35
|
+
2. **Refresh the index if it looks empty or stale**
|
|
36
|
+
- `index_repo root:"<project>"` — incremental; unchanged files are skipped.
|
|
37
|
+
- `index_doc file_path:"…"` — one document, even outside the corpus.
|
|
38
|
+
- `memory_stats` — counts, last index time, per-file list.
|
|
39
|
+
3. **Write back what will still be true next session**
|
|
40
|
+
- `save_lesson` — one insight. Give `kind` (`lesson` / `decision` / `procedure`), a one-line
|
|
41
|
+
`title`, and the body: `pattern` + `fix`, or `choice` + `reason`, or `steps`.
|
|
42
|
+
- `remember problem solution` — shorthand for `kind: experience`.
|
|
43
|
+
- `files`: project-relative paths the conclusion is about.
|
|
44
|
+
- `trigger.when`: when this should be recalled. `ops` (action), `writes` (file about to change),
|
|
45
|
+
`intents` (words the human would use). `guard` only narrows; `prevents` records what breaks
|
|
46
|
+
without it. Do **not** write a trigger you have not seen fire.
|
|
47
|
+
- `scope`: `task` (needs a bound task), `project` (default), `global` (rarely).
|
|
48
|
+
4. **Correct or delete**
|
|
49
|
+
- Same `id` + new fields = in-place update (old value kept in `prev`).
|
|
50
|
+
- `forget id_or_query` is a real delete, no undo. Prefer ids; keyword deletes refuse when too many
|
|
51
|
+
entries match.
|
|
52
|
+
|
|
53
|
+
## Rules
|
|
54
|
+
|
|
55
|
+
- Memory is evidence, not authority. Re-check the file before acting on a citation.
|
|
56
|
+
- Do not save: progress narration, temporary state, secrets/credentials, anything derivable from the
|
|
57
|
+
code in one read.
|
|
58
|
+
- One durable entry beats five observations. Merge by updating the existing id.
|
|
59
|
+
- Write in the same language the project uses; keep titles short and searchable.
|
|
60
|
+
- The store self-ignores in git; do not commit it unless the human explicitly wants memory in the repo.
|
|
61
|
+
|
|
62
|
+
## Diagnostics
|
|
63
|
+
|
|
64
|
+
Run from a shell (no dsh required):
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
node <this-skill-dir>/scripts/pm-digest.mjs <project-root>
|
|
68
|
+
node <this-skill-dir>/scripts/pm-digest.mjs <project-root> --json
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
It prints store size, insight/task counts, trigger coverage, and staleness. Use it when memory looks
|
|
72
|
+
empty, suspiciously large, or when you need to explain what is stored.
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// 项目记忆的体检脚本(零依赖、不调模型、不写盘)。
|
|
3
|
+
//
|
|
4
|
+
// node pm-digest.mjs [项目根] [--json]
|
|
5
|
+
//
|
|
6
|
+
// 面向模型与人类各一半:模型拿它替代"先读三个 JSON 再数数"的多次工具往返;
|
|
7
|
+
// 人拿它看 store 是否异常增长、trigger 覆盖多少、任务是不是全归档了。
|
|
8
|
+
// 只输出计数与少量标题,不打印正文——避免把记忆内容再塞回上下文。
|
|
9
|
+
import { readFileSync, readdirSync, statSync } from 'node:fs'
|
|
10
|
+
import { homedir } from 'node:os'
|
|
11
|
+
import path from 'node:path'
|
|
12
|
+
|
|
13
|
+
const args = process.argv.slice(2)
|
|
14
|
+
const json = args.includes('--json')
|
|
15
|
+
const root = path.resolve(args.find((a) => !a.startsWith('--')) || process.cwd())
|
|
16
|
+
const memoryDir = path.join(root, '.dsh-project-memory')
|
|
17
|
+
|
|
18
|
+
const readJson = (file, fallback) => {
|
|
19
|
+
try {
|
|
20
|
+
return JSON.parse(readFileSync(file, 'utf8'))
|
|
21
|
+
} catch {
|
|
22
|
+
return fallback
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
const days = (iso) => {
|
|
26
|
+
const t = Date.parse(iso || '')
|
|
27
|
+
return Number.isFinite(t) ? Math.max(0, Math.round((Date.now() - t) / 86_400_000)) : null
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function shardStats(dir) {
|
|
31
|
+
try {
|
|
32
|
+
let files = 0
|
|
33
|
+
let bytes = 0
|
|
34
|
+
for (const name of readdirSync(dir)) {
|
|
35
|
+
if (!name.endsWith('.json')) continue
|
|
36
|
+
try {
|
|
37
|
+
const st = statSync(path.join(dir, name))
|
|
38
|
+
if (!st.isFile()) continue
|
|
39
|
+
files++
|
|
40
|
+
bytes += st.size
|
|
41
|
+
} catch {
|
|
42
|
+
/* 分片在统计途中消失:跳过 */
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return { files, bytes }
|
|
46
|
+
} catch {
|
|
47
|
+
return { files: 0, bytes: 0 }
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function insightStats(items) {
|
|
52
|
+
const kinds = {}
|
|
53
|
+
const scopes = {}
|
|
54
|
+
let archived = 0
|
|
55
|
+
let withTrigger = 0
|
|
56
|
+
let withFiles = 0
|
|
57
|
+
let stale90 = 0
|
|
58
|
+
let lastAt = null
|
|
59
|
+
for (const it of items) {
|
|
60
|
+
if (!it || typeof it !== 'object') continue
|
|
61
|
+
kinds[it.kind || '?'] = (kinds[it.kind || '?'] || 0) + 1
|
|
62
|
+
scopes[it.scope || '?'] = (scopes[it.scope || '?'] || 0) + 1
|
|
63
|
+
if (it.archived) archived++
|
|
64
|
+
if (it.trigger && it.trigger.when) withTrigger++
|
|
65
|
+
if (Array.isArray(it.files) && it.files.length) withFiles++
|
|
66
|
+
const age = days(it.updatedAt || it.createdAt)
|
|
67
|
+
if (age !== null && age > 90) stale90++
|
|
68
|
+
const at = it.updatedAt || it.createdAt
|
|
69
|
+
if (at && (!lastAt || at > lastAt)) lastAt = at
|
|
70
|
+
}
|
|
71
|
+
return { total: items.length, kinds, scopes, archived, withTrigger, withFiles, stale90, lastAt }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function taskStats(tasks) {
|
|
75
|
+
let archived = 0
|
|
76
|
+
let steps = 0
|
|
77
|
+
let files = 0
|
|
78
|
+
let withInsights = 0
|
|
79
|
+
const active = []
|
|
80
|
+
for (const t of tasks) {
|
|
81
|
+
if (!t || typeof t !== 'object') continue
|
|
82
|
+
if (t.archived) archived++
|
|
83
|
+
else if (t.title) active.push(String(t.title))
|
|
84
|
+
if (Array.isArray(t.steps)) steps += t.steps.length
|
|
85
|
+
if (Array.isArray(t.files)) files += t.files.length
|
|
86
|
+
if (Array.isArray(t.insights) && t.insights.length) withInsights++
|
|
87
|
+
}
|
|
88
|
+
return { total: tasks.length, archived, active: tasks.length - archived, steps, files, withInsights, activeTitles: active.slice(0, 3) }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const insDoc = readJson(path.join(memoryDir, 'insights.json'), null)
|
|
92
|
+
const taskDoc = readJson(path.join(memoryDir, 'tasks.json'), null)
|
|
93
|
+
const binding = readJson(path.join(memoryDir, 'binding.json'), null)
|
|
94
|
+
const globalFile = path.join(homedir(), '.config', 'dsh-project-memory', 'global.json')
|
|
95
|
+
const globalDoc = readJson(globalFile, null)
|
|
96
|
+
|
|
97
|
+
if (!insDoc && !taskDoc) {
|
|
98
|
+
const msg = `no memory store at ${memoryDir} (run index_repo or index_doc first)`
|
|
99
|
+
if (json) process.stdout.write(JSON.stringify({ root, memoryDir, store: false }, null, 2) + '\n')
|
|
100
|
+
else process.stdout.write(msg + '\n')
|
|
101
|
+
process.exit(0)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const shards = shardStats(path.join(memoryDir, 'shards'))
|
|
105
|
+
const insights = insightStats((insDoc && insDoc.items) || [])
|
|
106
|
+
const tasks = taskStats((Array.isArray(taskDoc) ? taskDoc : []) || [])
|
|
107
|
+
const summary = {
|
|
108
|
+
root,
|
|
109
|
+
memoryDir,
|
|
110
|
+
store: true,
|
|
111
|
+
shards,
|
|
112
|
+
insights,
|
|
113
|
+
tasks,
|
|
114
|
+
bindings: binding && typeof binding === 'object' ? Object.keys(binding).length : 0,
|
|
115
|
+
global: { items: globalDoc && Array.isArray(globalDoc.items) ? globalDoc.items.length : 0 },
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
if (json) {
|
|
119
|
+
process.stdout.write(JSON.stringify(summary, null, 2) + '\n')
|
|
120
|
+
process.exit(0)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const kb = (n) => (n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MB` : `${Math.round(n / 102.4) / 10} KB`)
|
|
124
|
+
const line = (label, value) => process.stdout.write(`${label.padEnd(12)} ${value}\n`)
|
|
125
|
+
line('project', root)
|
|
126
|
+
line('store', `${shards.files} shards · ${kb(shards.bytes)} · ${insights.total} insights · ${tasks.total} tasks`)
|
|
127
|
+
if (insights.total) {
|
|
128
|
+
const kinds = Object.entries(insights.kinds).map(([k, n]) => `${k} ${n}`).join(' · ')
|
|
129
|
+
line('insights', `${kinds}${insights.archived ? ` · archived ${insights.archived}` : ''}`)
|
|
130
|
+
line('triggers', `${insights.withTrigger}/${insights.total} with when · ${insights.withFiles} with files · ${insights.stale90} older than 90d`)
|
|
131
|
+
}
|
|
132
|
+
if (tasks.total) {
|
|
133
|
+
line('tasks', `${tasks.active} active · ${tasks.archived} archived · ${tasks.steps} steps · ${tasks.files} file links`)
|
|
134
|
+
if (tasks.activeTitles.length) line('active', tasks.activeTitles.join(' | '))
|
|
135
|
+
if (tasks.withInsights === 0) line('task memory', 'none — task-scoped insights are not used here')
|
|
136
|
+
}
|
|
137
|
+
line('bindings', `${summary.bindings} session(s) bound`)
|
|
138
|
+
line('global', `${summary.global.items} entries (~/.config/dsh-project-memory/global.json)`)
|
package/src/audit.js
CHANGED
|
@@ -111,7 +111,13 @@ export function shadowRecordFrom(input) {
|
|
|
111
111
|
// **实际用于评分**的查询文本(intent + 写目标的拼合)。它和 `query` 不是一回事:
|
|
112
112
|
// 写目标驱动的那些步 `query` 是空的、候选却非空。少了这一栏,判据无法离线重放。
|
|
113
113
|
scoreQuery: typeof input.scoreQuery === 'string' ? input.scoreQuery.slice(0, 300) : '',
|
|
114
|
+
// query 是从哪来的:本步 delta(delta)/ 会话缓存的最后一条真人消息(session)/ 没有(none)。
|
|
115
|
+
// 离线复盘必须先分清"这一步本来就没意图"与"意图取错了来源"。
|
|
116
|
+
querySource: ['delta', 'session'].includes(input.querySource) ? input.querySource : 'none',
|
|
114
117
|
ops: (Array.isArray(input.ops) ? input.ops : []).slice(0, 12),
|
|
118
|
+
// 人类消息里解析出的**全部**动作词(含被 `PRE_ACTION_OPS` 过滤掉的删除/清理/渲染…)。
|
|
119
|
+
// 留着才能回答"这条为什么没注入",以及"把某类散文动作放回准入后会发生什么"。
|
|
120
|
+
opsIntent: (Array.isArray(input.opsIntent) ? input.opsIntent : []).slice(0, 12),
|
|
115
121
|
writes: (Array.isArray(input.writes) ? input.writes : []).slice(0, 12),
|
|
116
122
|
injected: reasons.map((r) => ({ id: r.id, channel: r.channel, why: r.why })),
|
|
117
123
|
// 查询级支持度:语料能表示查询里多少个词(`terms` 是查询词数)—— 通道级沉默判据用的就是它。
|