@yolk_vat-y/dsh-project-memory 0.6.9 → 0.6.10

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 CHANGED
@@ -1,3 +1,31 @@
1
+ ## 0.6.10 (2026-11-04)
2
+
3
+ **兼容**:无新增配置键,无 store 格式变更。一处判据变化:`memoryDir` 只接受项目根内的相对路径,越界值(`.`、`..`、含 `..` 段、绝对路径)回落到默认目录并告警一次(此前会静默把 store 放到根上或根外)。
4
+
5
+ ### 性能
6
+
7
+ - **CJK 分词从「逐字符判断」改成「整段匹配」**:`tokenizeRaw` 此前对整篇文本逐码点调用 `CJK_RANGE.test()` 并累积字符串,纯英文文档也要跑满整篇。现在用一条从 `CJK_RANGE` 派生的正则一次取出所有连续段,再按原有规则结算(段长 1 产单字、≥2 产全部相邻二元组)。**输出逐字节一致**,所以 `TOKENIZER_VERSION` 不动、旧 store 不需要回填;等价性由 `test/tokenizer-equivalence.test.mjs` 差分守住(冻结旧实现当标尺 + 固定输出契约 + 18 个边界串 + 5 个真实文件 + 2000 组固定种子随机拼接 + `stem` 两态)。
8
+ - **同会话 A/B**(Node 24.19 / WSL2 / 20 vCPU,同一小时内交替跑、每个版本两遍,引用页缓存已热的那遍):TypeScript 整树(14,528 文件 / 95,316 条目)首次查询的 IDF 重建 **1.44–1.53 s → 0.94–0.96 s**(约 −35%),抽取 9.42–9.51 s → 8.79–8.95 s(−6%),冷索引 10.66 s → 10.00 s(−6%);文档为主的语料(249 文件 / 889 条目)抽取 242–252 ms → 216–219 ms(−13%)、IDF 58–59 ms → 43–44 ms(−26%)。查询 p50 无可测变化(在噪声内)。
9
+ - **已知代价**:极端构造输入(CJK 单字与拉丁字母逐字交替,如 `中a文a` 重复)实测 **0.97×**——段长恒为 1 时,正则产出的段数组比逐字累积多一层分配;真实代码与文档里不出现这个密度。README 的性能表是 2026-10-13 的历史测量口径,本轮未重测。
10
+
11
+ ### 修复
12
+
13
+ - **`save_lesson` 带 `id` 更新时静默改 `kind`**:`kind` 的 `'lesson'` 默认值此前也作用于就地更新,改一条 decision/procedure 的 `fix`/`reason` 会把它降级成 lesson;现在只在新建时补默认值,更新只覆盖调用方显式传入的字段。
14
+ - **watch / lazy 对超过 `maxFileSizeMb` 的文件只跳过、不摘旧条目**:文件涨过阈值后旧 entries 会永久可检索(watch 还把 `mtime:size` 写进快照,永远不再重试)。两处现在与 `index_repo` 一样走 `drop`;watch 轮询发现根已被删除时也不再经 `save()` 把根重新创建出来。
15
+ - **`archive_task` 归档后不解绑**:绑定会话下一步仍会注入归档任务卡与任务级 insights,任务级记忆也继续被召回;现在工具与 `/tasks archive` 一样清掉所有绑定,注入/召回侧同时挡 `task.archived`。
16
+ - **`autoContext.maxTokens: 0` 仍注入 root notice**:`buildInjection` 已零预算,但 `injectForStep` 在预算外补了“记忆根是推定的”提示;现在 0 预算时连状态声明也不发,真正零注入。
17
+ - **`watch_repo({watch:false})` 对已不存在的 root 重新创建目录**:stop 路径不再 load/commit 缺失根;避免 `save()` 的 `mkdirSync` 把用户刚停掉的路径复活。
18
+ - **宿主的 `str_replace_editor` 不被识别**:`ops` 现在按 `path` + `command` 把 create/str_replace/insert 归一成 `file-write`,`view` 不算写;TaskBridge 也把它的写/读分别记入任务热点文件。
19
+ - **面板 promote/demote 丢使用痕迹**:手工提升/降级此前直接走 `normalizeInsight`,丢掉 `triggerDerived`/`prev`/`lastHitAt`,也不执行 `maxProject`/`maxGlobalProcedures`;现在与自动提升共用 `carryUsageFields` 并收口容量。
20
+ - **空任务列表的 `/tasks` payload 缺 `root`**:跨标签页同步按项目根过滤,空列表时 root 为 null 会让本页失去项目作用域;现在空/非空两条路径都带 root。
21
+ - **`memoryDir` 为空 / `.` / `..` / 绝对路径时 store 落错位置**:空串与 `.` 让 `path.join(root, …)` 等于项目根本身,`save()` 的自我忽略会在那里写内容为 `*` 的 `.gitignore`(整个仓库从 git 视角消失),`format.json` / `shards/` 也会污染源码树;`..` 则把 store 写到根外。现在 `safeMemoryDirName()` 是读写两侧唯一的归一入口:空/空白、`.`、`..`、含 `..` 段、绝对路径(POSIX `/x`、Windows `C:\x`)一律回落到默认目录并告警一次;根内的嵌套目录(`a/b`)仍允许。
22
+ - **POSIX 上把 Windows 盘符路径当项目内相对路径**:`normalizeCitationFiles()` 现在丢弃 `C:\...` 这类在本平台不是绝对路径的盘符路径,避免生成 `C:/...` 的假引用。
23
+ - **`GlobalStore` 缓存键大小写未归一**:Windows/macOS 上同一 `global.json` 的两种写法会建两个实例;现在与项目 store 一样走 `storeKey()`。
24
+ - `save_lesson` 的 `scope` 描述改为与实现一致:绑定任务时默认 `task`,否则 `project`。
25
+ - **体检脚本读不到自定义 `memoryDir`**:`skills/project-memory/scripts/pm-digest.mjs` 把 store 目录写死成 `<root>/.dsh-project-memory`,配了自定义 `memoryDir` 的项目只会得到「no memory store」。现在依次按 `--memory-dir <name>` / `DSH_PROJECT_MEMORY_DIR` / 默认名解析;都没命中时在项目根下一层按 `format.json` 标记找唯一候选并标注 `auto-detected`,多个候选不猜、报错点名怎么传参。
26
+
27
+ **测试**:新增 `test/audit-2026-11-02.test.mjs`(13 项:save_lesson kind 保留、watch/lazy 超限摘旧条目、archive_task 解绑与注入/召回守卫、maxTokens 0 零注入、watch stop/poll 不重建缺失根、str_replace_editor 的 ops/TaskBridge、手工 promote 保留字段与容量、空任务 payload root、空 memoryDir 归一、POSIX 盘符路径丢弃)与 `test/tokenizer-equivalence.test.mjs`(5 项:固定输出契约、18 个边界串、5 个真实语料文件、2000 组固定种子随机拼接、`stem` 两态——全部与冻结的旧实现逐字节比对)与 `test/memorydir-guard.test.mjs`(4 项:空/`.`/`..`/含 `..` 段/绝对路径回落默认目录且不移动 store、嵌套相对目录仍允许、默认告警对同一坏值只发一次、`memoryDir: '.'` 不把 `*` 写进项目根);`test/skill.test.mjs` 补 1 项(自定义 `memoryDir` 的三种解析路径 + 多候选不猜)。`npm test` **956 项 / 57 个文件**全绿、`npm run typecheck` 通过。
28
+
1
29
  ## 0.6.9 (2026-11-02)
2
30
 
3
31
  **兼容**:无新增配置键,无 store 格式变更(启动时会顺手把 `watch.json` 里大小写重复的根条目合并成一条;文件格式不变)。三个既有键——`watchInterval` / `autoIndexOnFirstUse` / `llmQueryExpansion`——在 `Config` 里标成 `.volatile()`:这是宿主设置表单的准入条件(只有 volatile 字段能被 settings 接口写入),也让它们在运行中原地更新而不重启插件。profile / 命令行的写法完全不变。插件内部读取统一走 `cfgValue()`:volatile 字段在运行时是 ref(`.get()`),直接把 ref 当布尔会读错。升级后**需要重启一次 dsh**——volatile 元数据只在装配期解析。两处**行为变化**:① 扫描与懒索引都跳过隐藏路径(任一段以 `.` 开头,如 `.env` / `.github/**`),显式 `index_doc` 仍可索引(已存在的隐藏路径条目会在下一次完整扫描被清理);② `autoContext.maxTokens: 0` 现在真的零注入(此前被 `|| 400` 顶回默认值)。
package/README.md CHANGED
@@ -61,7 +61,7 @@ In a git work tree the corpus is whatever `git ls-files --cached --others --excl
61
61
  | `query_memory query` | Ranked search over documents, symbols, experience and insights, optionally query-expanded by the LLM. `type` selects a layer (`all` / `doc` / `symbol` / `experience` / `insight` / `task`). Returns hits with relative scores, sources or insight ids, and doc→symbol references. |
62
62
  | `list_tasks` | List task records for the project (archived marked). Call first in a new session before continuing work. |
63
63
  | `select_task` | Bind the session to a task so its todo list and file reads sync into it. Exact `taskId`, or exact `title` (multiple matches return candidates; no match creates a new task). Pass `title` with `taskId` to rename. Auto-unarchives. |
64
- | `archive_task` | Archive a task (hide from default views, exclude from capacity, stop syncing). `select_task` restores it. |
64
+ | `archive_task` | Archive a task (hide from default views, exclude from capacity, stop syncing, unbind the sessions that had it selected; archived tasks are also skipped by injection and recall). `select_task` restores it. |
65
65
  | `show_task_panel` | Show the task panel in the UI. Call when the user asks to see the task list or when you want to display the panel. |
66
66
  | `/tasks` (typed by the user, not the model) | The only user command: shows the task stack and drives the workflow card. Every other action is a **sub-verb** invoked by card buttons: `switch` / `archive` / `unbind` / `rename` / `todos …` / `step` / `step-move` / `step-text` for tasks, `insight list [scope] [offset] [limit]` / `confirm` / `promote` / `demote` / `archive` / `restore` / `delete` / `save` / `edit` for memory. |
67
67
  | `remember problem solution` | Save an experience note. It is a `kind: 'experience'` insight — same store, same dedup and same delete path as lessons / decisions / procedures. Similar problems merge or overwrite instead of duplicating. |
@@ -123,9 +123,9 @@ The workflow panel is collapsible, adapts to dsh and theme plugin styles, and of
123
123
 
124
124
  | Key | Default | Meaning |
125
125
  |---|---|---|
126
- | `memoryDir` | `.dsh-project-memory` | store directory inside each indexed root |
126
+ | `memoryDir` | `.dsh-project-memory` | store directory inside each indexed root. Must stay a relative path inside the root: `.`, `..`, any `..` segment or an absolute path falls back to the default with one warning (otherwise the store lands outside the root, or on the root itself and self-ignores the whole repository) |
127
127
  | `chunkChars` / `maxChunksPerFile` | 3000 / 40 | max chars per document chunk, max chunks per document |
128
- | `maxFileSizeMb` | 10 | skip documents (incl. PDF) and code files larger than this (MB); see the per-file memory budget below |
128
+ | `maxFileSizeMb` | 10 | skip documents (incl. PDF) and code files larger than this (MB); entries of an already-indexed file that later grows past the cap are dropped on the next scan / watch pass; see the per-file memory budget below |
129
129
  | `maxPdfPages` | 1000 | PDF page cap |
130
130
  | `maxOutputChars` | 8000 | cap for `query_memory` result text (chars) |
131
131
  | `lazyIndexing` | true | index files the moment the model reads them |
@@ -243,7 +243,7 @@ Four corpora, one Linux machine (Node 24.19), each run twice with the **second,
243
243
  | Cold load | 10,000 files | 117 ms |
244
244
  | Hot lazy re-index (single file) | 10k files | p50 5.5 ms / max 8.4 ms |
245
245
 
246
- > 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.
246
+ > 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. Those IDF figures are the pre-0.6.10 baseline — the 0.6.10 tokenizer rewrite makes that rebuild roughly a third faster on the same corpus (same-session A/B, numbers in the CHANGELOG).
247
247
 
248
248
  ### Reproduce it on your own project
249
249
 
@@ -285,7 +285,7 @@ These commands are for **maintaining the plugin code** — regular users do not
285
285
 
286
286
  ```bash
287
287
  npm install
288
- npm test # 930 tests
288
+ npm test # 956 tests
289
289
  npm run eval:injection # synthetic pool P/R: precision 0.93 / recall 1.00, + a 3-scenario hint-only group
290
290
  npm run eval:injection -- --store .dsh-project-memory/insights.json # replay on YOUR store; control group is a hard gate
291
291
  npm run selfcheck:triggers # which entries can still push, which declarations are dead (reads your local store)
package/README.zh-CN.md CHANGED
@@ -59,7 +59,7 @@ dsh plugin --profile web add @yolk_vat-y/dsh-project-memory -w
59
59
  | `query_memory query` | 对文档、符号、经验与 insight 执行排序检索,可选 LLM 查询扩展。`type` 选择层(`all` / `doc` / `symbol` / `experience` / `insight` / `task`)。返回带相对分数、引用或 insight id、以及文档→符号链接的结果。 |
60
60
  | `list_tasks` | 列出本项目任务记录(含归档,带标记)。新会话/续接前先调用。 |
61
61
  | `select_task` | 将会话绑定到某任务(此后 todo 清单与读文件同步进该任务)。按 `taskId` 精确绑定,或按 `title` 完全匹配(多个同名返回候选;无则新建)。带 title 可改名;自动解归档。 |
62
- | `archive_task` | 归档任务(隐藏默认视图、不占容量、停止同步)。`select_task` 可恢复。 |
62
+ | `archive_task` | 归档任务(隐藏默认视图、不占容量、停止同步、清掉选中它的会话绑定;归档任务也不再参与注入与召回)。`select_task` 可恢复。 |
63
63
  | `show_task_panel` | 在 UI 中打开任务面板。用户要求查看任务列表或你想展示面板时调用。 |
64
64
  | `/tasks`(用户输入,不经模型) | 唯一的用户命令:展示任务栈并驱动工作流卡片。其余动作是它的**子动词**,由卡片按钮调用:`switch` / `archive` / `unbind` / `rename` / `todos …` / `step` / `step-move` / `step-text` 为任务动作,`insight list [scope] [offset] [limit]` / `confirm` / `promote` / `demote` / `archive` / `restore` / `delete` / `save` / `edit` 为记忆动作。 |
65
65
  | `remember problem solution` | 保存经验笔记。它就是 `kind: 'experience'` 的 insight——与教训 / 决策 / 流程同库、同去重、同删除入口。相似问题合并或覆盖而非重复。 |
@@ -121,9 +121,9 @@ TaskPanel (Container)
121
121
 
122
122
  | 键 | 默认值 | 含义 |
123
123
  |---|---|---|
124
- | `memoryDir` | `.dsh-project-memory` | 每个被索引根目录内的存储目录 |
124
+ | `memoryDir` | `.dsh-project-memory` | 每个被索引根目录内的存储目录。必须是根内的相对路径:`.`、`..`、含 `..` 段或绝对路径都会回落到默认目录并告警一次(否则 store 会落到根外,或落到根上并把整个仓库自我忽略掉) |
125
125
  | `chunkChars` / `maxChunksPerFile` | 3000 / 40 | 每个文档块最大字符数、每文档最大块数 |
126
- | `maxFileSizeMb` | 10 | 大于该值(MB)的文档(含 PDF)/代码文件跳过;峰值系数见下文「单文件内存预算」 |
126
+ | `maxFileSizeMb` | 10 | 大于该值(MB)的文档(含 PDF)/代码文件跳过;已经索引过的文件后来涨过阈值,旧条目会在下一轮扫描 / watch 时摘掉;峰值系数见下文「单文件内存预算」 |
127
127
  | `maxPdfPages` | 1000 | PDF 页数上限 |
128
128
  | `maxOutputChars` | 8000 | `query_memory` 返回文本上限(字符) |
129
129
  | `lazyIndexing` | true | 模型读取文件的瞬间即索引 |
@@ -241,7 +241,7 @@ dsh web --patch ./config.yml
241
241
  | 冷加载 | 10,000 文件 | 117 ms |
242
242
  | 热路径懒记忆 | 单文件重记忆+落盘 | p50 5.5 ms / 最大 8.4 ms (10k) |
243
243
 
244
- > 合成基准:生成代码(~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),后续查询命中缓存。
244
+ > 合成基准:生成代码(~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),后续查询命中缓存。这组 IDF 数字是 0.6.10 之前的基线——0.6.10 的分词重写在同一语料上把这次重建缩短约三分之一(同会话 A/B,数字见 CHANGELOG)。
245
245
 
246
246
  ### 自己复现这些数字
247
247
 
@@ -283,7 +283,7 @@ node scripts/bench.mjs /你的/项目路径 [--json] [--samples 100] [--no-pdf]
283
283
 
284
284
  ```bash
285
285
  npm install
286
- npm test # 930 项测试
286
+ npm test # 956 项测试
287
287
  npm run eval:injection # 合成池 P/R:精确率 0.93 / 召回率 1.00,另有 3 个 hint-only 场景
288
288
  npm run eval:injection -- --store .dsh-project-memory/insights.json # 用你自己的 store 重放;对照组是硬闸门
289
289
  npm run selfcheck:triggers # 哪些条目还推得动、哪些声明是死的(读你本地的 store)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yolk_vat-y/dsh-project-memory",
3
- "version": "0.6.9",
3
+ "version": "0.6.10",
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",
@@ -20,7 +20,7 @@
20
20
  "url": "https://github.com/00080000/dsh-project-memory.git"
21
21
  },
22
22
  "scripts": {
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/settings-card.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/windows-compat.test.mjs && node test/tool-schema-size.test.mjs && node test/enhancer.test.mjs && node test/multilingual-ru.test.mjs && node test/lazy-batch.test.mjs && node test/pdfjs-host.test.mjs && node test/index-failures.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/settings-card.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/windows-compat.test.mjs && node test/tool-schema-size.test.mjs && node test/enhancer.test.mjs && node test/multilingual-ru.test.mjs && node test/tokenizer-equivalence.test.mjs && node test/lazy-batch.test.mjs && node test/pdfjs-host.test.mjs && node test/index-failures.test.mjs && node test/audit-2026-11-02.test.mjs && node test/memorydir-guard.test.mjs",
24
24
  "eval:injection": "node test/injection-scenarios.test.mjs",
25
25
  "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.client.json",
26
26
  "selfcheck:triggers": "node test/injection-scenarios.test.mjs --selfcheck",
@@ -66,7 +66,11 @@ Run from a shell (no dsh required):
66
66
  ```bash
67
67
  node <this-skill-dir>/scripts/pm-digest.mjs <project-root>
68
68
  node <this-skill-dir>/scripts/pm-digest.mjs <project-root> --json
69
+ node <this-skill-dir>/scripts/pm-digest.mjs <project-root> --memory-dir <name>
69
70
  ```
70
71
 
71
72
  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.
73
+ empty, suspiciously large, or when you need to explain what is stored. The store directory is usually
74
+ `.dsh-project-memory`; if the project configures another `memoryDir`, pass it with `--memory-dir`
75
+ (or `DSH_PROJECT_MEMORY_DIR`) — without either, a single store-shaped directory directly under the
76
+ root is picked up and reported as `auto-detected`, and the "no memory store" message says how to pass it.
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  // 项目记忆的体检脚本(零依赖、不调模型、不写盘)。
3
3
  //
4
- // node pm-digest.mjs [项目根] [--json]
4
+ // node pm-digest.mjs [项目根] [--json] [--memory-dir <name>]
5
5
  //
6
6
  // 面向模型与人类各一半:模型拿它替代"先读三个 JSON 再数数"的多次工具往返;
7
7
  // 人拿它看 store 是否异常增长、trigger 覆盖多少、任务是不是全归档了。
@@ -10,10 +10,61 @@ import { readFileSync, readdirSync, statSync } from 'node:fs'
10
10
  import { homedir } from 'node:os'
11
11
  import path from 'node:path'
12
12
 
13
+ const DEFAULT_MEMORY_DIR = '.dsh-project-memory'
14
+ const STORE_MARKER = 'format.json'
15
+
13
16
  const args = process.argv.slice(2)
14
17
  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')
18
+ // store 目录名 = config 的 memoryDir;显式 --memory-dir / 环境变量优先。
19
+ let memoryDirName = process.env.DSH_PROJECT_MEMORY_DIR || ''
20
+ const positional = []
21
+ for (let i = 0; i < args.length; i++) {
22
+ const arg = args[i]
23
+ if (arg === '--json') continue
24
+ if (arg === '--memory-dir') {
25
+ memoryDirName = args[++i] || ''
26
+ continue
27
+ }
28
+ if (arg.startsWith('--memory-dir=')) {
29
+ memoryDirName = arg.slice('--memory-dir='.length)
30
+ continue
31
+ }
32
+ if (arg.startsWith('--')) continue
33
+ positional.push(arg)
34
+ }
35
+ const root = path.resolve(positional[0] || process.cwd())
36
+
37
+ const isFile = (file) => {
38
+ try {
39
+ return statSync(file).isFile()
40
+ } catch {
41
+ return false
42
+ }
43
+ }
44
+
45
+ /**
46
+ * store 目录。写死默认名在自定义 `memoryDir` 的项目上会报"没有 store",
47
+ * 而脚本读不到宿主 profile,所以:显式名 → 默认名 → 根下一层按 `format.json` 标记找**唯一**候选。
48
+ * 0 个或多个候选都不猜,沿用默认名并在报错里点名怎么传。
49
+ */
50
+ function resolveMemoryDir(root, name) {
51
+ if (name) return { dir: path.join(root, name), name }
52
+ const fallback = path.join(root, DEFAULT_MEMORY_DIR)
53
+ if (isFile(path.join(fallback, STORE_MARKER))) return { dir: fallback, name: DEFAULT_MEMORY_DIR }
54
+ let candidates = []
55
+ try {
56
+ candidates = readdirSync(root, { withFileTypes: true })
57
+ .filter((entry) => entry.isDirectory() && isFile(path.join(root, entry.name, STORE_MARKER)))
58
+ .map((entry) => entry.name)
59
+ } catch {
60
+ candidates = []
61
+ }
62
+ if (candidates.length === 1) return { dir: path.join(root, candidates[0]), name: candidates[0], detected: true }
63
+ return { dir: fallback, name: DEFAULT_MEMORY_DIR }
64
+ }
65
+
66
+ const resolved = resolveMemoryDir(root, memoryDirName)
67
+ const memoryDir = resolved.dir
17
68
 
18
69
  const readJson = (file, fallback) => {
19
70
  try {
@@ -94,8 +145,15 @@ const binding = readJson(path.join(memoryDir, 'binding.json'), null)
94
145
  const globalFile = path.join(homedir(), '.config', 'dsh-project-memory', 'global.json')
95
146
  const globalDoc = readJson(globalFile, null)
96
147
 
97
- if (!insDoc && !taskDoc) {
98
- const msg = `no memory store at ${memoryDir} (run index_repo or index_doc first)`
148
+ // 有没有 store:`format.json` 标记(走过一次 save)或已有的 insights/tasks 都算。
149
+ // 只看后两者会把"只索引了文档、还没写洞察/任务"的项目误报成没有 store。
150
+ const hasStore = isFile(path.join(memoryDir, STORE_MARKER)) || Boolean(insDoc || taskDoc)
151
+
152
+ if (!hasStore) {
153
+ const hint = resolved.detected || memoryDirName
154
+ ? ''
155
+ : '; if `memoryDir` is customized, pass --memory-dir <name>'
156
+ const msg = `no memory store at ${memoryDir} (run index_repo or index_doc first)${hint}`
99
157
  if (json) process.stdout.write(JSON.stringify({ root, memoryDir, store: false }, null, 2) + '\n')
100
158
  else process.stdout.write(msg + '\n')
101
159
  process.exit(0)
@@ -107,6 +165,7 @@ const tasks = taskStats((Array.isArray(taskDoc) ? taskDoc : []) || [])
107
165
  const summary = {
108
166
  root,
109
167
  memoryDir,
168
+ ...(resolved.detected ? { detected: true } : {}),
110
169
  store: true,
111
170
  shards,
112
171
  insights,
@@ -123,6 +182,9 @@ if (json) {
123
182
  const kb = (n) => (n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MB` : `${Math.round(n / 102.4) / 10} KB`)
124
183
  const line = (label, value) => process.stdout.write(`${label.padEnd(12)} ${value}\n`)
125
184
  line('project', root)
185
+ if (resolved.name !== DEFAULT_MEMORY_DIR || resolved.detected) {
186
+ line('location', `${resolved.name}${resolved.detected ? ' (auto-detected)' : ''}`)
187
+ }
126
188
  line('store', `${shards.files} shards · ${kb(shards.bytes)} · ${insights.total} insights · ${tasks.total} tasks`)
127
189
  if (insights.total) {
128
190
  const kinds = Object.entries(insights.kinds).map(([k, n]) => `${k} ${n}`).join(' · ')
@@ -426,7 +426,9 @@ function scoreHints({ cands, query, humanText, hintQuery, cfg, dropped, rerank =
426
426
  * @returns {{ text: string, labels: string[], reasons: object[], dropped: object[] }}
427
427
  */
428
428
  export function buildInjection(opts) {
429
- const { query, task, globalStore, cfg } = opts
429
+ const { query, globalStore, cfg } = opts
430
+ // 归档任务不是“当前任务”:即使调用方还拿着旧绑定,也不能回声任务卡或任务级 insights。
431
+ const task = opts.task && !opts.task.archived ? opts.task : null
430
432
  const store = opts.store || null
431
433
  const tags = opts.projectTagsList || []
432
434
  // 就绪上下文可能**已经构建过**(injectForStep 先构建、再传给这里)。二次构建会把第一遍的
@@ -767,8 +769,9 @@ async function injectForStep({ payload, decision, config, cfg, audit, shadow, se
767
769
  }), shadow, root)
768
770
 
769
771
  // 记忆根通告:根是**推定**的(会话工作目录且无任何项目标记)时,第一次注入前告诉模型"记忆存在哪、
770
- // 怎么改"。它是状态声明(与常驻任务卡同类),只发一次、不占条目额度。
771
- const notice = rootNotice({ root, sessionId, sessions, config })
772
+ // 怎么改"。它是状态声明(与常驻任务卡同类),只发一次、不占条目额度;但 maxTokens: 0
773
+ // 的契约是"完全不注入",状态声明也不能绕过。
774
+ const notice = cfg.maxTokens > 0 ? rootNotice({ root, sessionId, sessions, config }) : null
772
775
 
773
776
  const fp = built.text ? fingerprint(built.dedupeText ?? built.text) : fingerprint(notice || '')
774
777
  const injectedText = notice ? (built.text ? `${notice}\n${built.text}` : notice) : built.text
@@ -4,10 +4,15 @@
4
4
  // (命令 handler:store.commit + gs.commit)统一负责,便于单测。
5
5
  import { ProjectMemoryStore } from '../store.js'
6
6
  import { memoryRootFor, normalizeCitationFiles } from '../util/fs.js'
7
- import { cfgInsight, GlobalStore, normalizeInsight, defaultGlobalFile, saveInsight, recordDeleted, INSIGHT_KINDS } from '../insight-store.js'
7
+ import { cfgInsight, GlobalStore, normalizeInsight, defaultGlobalFile, saveInsight, recordDeleted, carryUsageFields, pruneItems, INSIGHT_KINDS } from '../insight-store.js'
8
8
  import { NO_PROJECT_ROOT_NOTE, projectRootFor } from '../setup/taskbridge.js'
9
9
  import { fencedJson, invocationContext } from './invocation.js'
10
10
 
11
+ /** 容量旋钮的防御性取值:cfg 可能只带显式测试字段。 */
12
+ function capOf(value, fallback) {
13
+ return typeof value === 'number' && Number.isFinite(value) ? value : fallback
14
+ }
15
+
11
16
  /**
12
17
  * 记忆列表单页上限。面板每页只请求 30 条(客户端 PAGE_SIZE),远小于它——
13
18
  * 封顶只用于挡住畸形/滥用调用,避免单个响应被抓成超大载荷。
@@ -163,16 +168,22 @@ export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
163
168
  return { ok: true, text: `已${act === 'archive' ? '归档' : '恢复'}` }
164
169
  }
165
170
  if (act === 'promote') {
166
- // task → project(手动提升,无视自动阈值)
171
+ // task → project(手动提升,无视自动阈值)。必须和自动提升一样保留使用痕迹:
172
+ // normalizeInsight 只复制白名单字段,triggerDerived/prev/lastHitAt 要显式带回。
173
+ const now = new Date().toISOString()
167
174
  const items = store.insightItems()
168
- const copy = normalizeInsight(insight, { scope: 'project', source: insight.source, nowIso: new Date().toISOString() })
175
+ const copy = carryUsageFields(
176
+ normalizeInsight(insight, { scope: 'project', source: insight.source, nowIso: now }),
177
+ insight,
178
+ )
169
179
  copy.id = id
170
180
  copy.draft = false
171
181
  copy.confidence = Math.max(insight.confidence || 0, (cfg && cfg.promoteConfidence) || 0.7)
172
- copy.movedFrom = { scope: 'task', id, at: new Date().toISOString() }
182
+ copy.movedFrom = { scope: 'task', id, at: now }
173
183
  copy.createdAt = insight.createdAt || copy.createdAt
174
184
  copy.hitCount = insight.hitCount || 0
175
185
  items.push(copy)
186
+ pruneItems(items, capOf(cfg?.maxProject, 100), now)
176
187
  store.replaceInsightItems(items)
177
188
  task.insights = (task.insights || []).filter((i) => i.id !== id)
178
189
  store.markTasksDirty()
@@ -202,13 +213,17 @@ export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
202
213
  // project → global
203
214
  if (!gs) return { ok: false, text: 'global 存储不可用' }
204
215
  const now = new Date().toISOString()
205
- const copy = normalizeInsight(ins, { scope: 'global', source: ins.source, nowIso: now })
216
+ const copy = carryUsageFields(
217
+ normalizeInsight(ins, { scope: 'global', source: ins.source, nowIso: now }),
218
+ ins,
219
+ )
206
220
  copy.id = id
207
221
  copy.draft = false
208
222
  copy.movedFrom = { scope: 'project', id, at: now }
209
223
  copy.createdAt = ins.createdAt || copy.createdAt
210
224
  copy.hitCount = ins.hitCount || 0
211
225
  gs.items().push(copy)
226
+ pruneItems(gs.items(), capOf(cfg?.maxGlobalProcedures, 200), now)
212
227
  gs.markDirty()
213
228
  items.splice(idx, 1)
214
229
  store.replaceInsightItems(items)
@@ -219,7 +234,10 @@ export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
219
234
  const task = store.getTask(taskId)
220
235
  if (!task) return { ok: false, text: '降级到任务需要 taskId' }
221
236
  const now = new Date().toISOString()
222
- const copy = normalizeInsight(ins, { scope: 'task', source: ins.source, nowIso: now })
237
+ const copy = carryUsageFields(
238
+ normalizeInsight(ins, { scope: 'task', source: ins.source, nowIso: now }),
239
+ ins,
240
+ )
223
241
  copy.id = `${id}_d${Date.now().toString(36)}`
224
242
  copy.movedFrom = { scope: 'project', id, at: now }
225
243
  copy.createdAt = ins.createdAt || copy.createdAt
@@ -255,11 +273,15 @@ export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
255
273
  // global → project
256
274
  const now = new Date().toISOString()
257
275
  const pjItems = store.insightItems()
258
- const copy = normalizeInsight(ins, { scope: 'project', source: ins.source, nowIso: now })
276
+ const copy = carryUsageFields(
277
+ normalizeInsight(ins, { scope: 'project', source: ins.source, nowIso: now }),
278
+ ins,
279
+ )
259
280
  copy.id = `${id}_d${Date.now().toString(36)}`
260
281
  copy.movedFrom = { scope: 'global', id, at: now }
261
282
  copy.createdAt = ins.createdAt || copy.createdAt
262
283
  pjItems.push(copy)
284
+ pruneItems(pjItems, capOf(cfg?.maxProject, 100), now)
263
285
  store.replaceInsightItems(pjItems)
264
286
  items.splice(idx, 1)
265
287
  gs.markDirty()
@@ -42,7 +42,7 @@ export function renderTaskSnapshot(config, cwd, sid) {
42
42
  const bound = boundId ? tasks.find((t) => t.id === boundId) : null
43
43
 
44
44
  if (!active.length) {
45
- const payload = buildTaskPayload([], boundId, archived)
45
+ const payload = buildTaskPayload([], boundId, archived, root)
46
46
  const note = `项目 ${root}\n任务记录: 0 套${archived ? `(归档 ${archived})` : ''}。让模型开始干活并维护 todo 清单后会自动建档。`
47
47
  return { kind: 'success', text: fencedJson(note, payload) }
48
48
  }
@@ -7,7 +7,7 @@ import { readFileSync, renameSync } from 'node:fs'
7
7
  import path from 'node:path'
8
8
  import os from 'node:os'
9
9
  import { normalizedTokenOverlap, findBestOverlapMatch, insightMatchText } from './similarity.js'
10
- import { acquireDirLock, writeJsonAtomic } from './util/fs.js'
10
+ import { acquireDirLock, storeKey, writeJsonAtomic } from './util/fs.js'
11
11
  import { debugPersistence } from './util/persist.js'
12
12
  import { trackDirty, untrackDirty } from './util/flush.js'
13
13
  import { backfillDerivedTriggers } from './readiness.js'
@@ -509,7 +509,9 @@ export class GlobalStore {
509
509
  load() {
510
510
  // 整份文档读改写:同一路径必须共用实例,否则两个工具/会话交错时后写覆盖先写。
511
511
  // 与 ProjectMemoryStore 的 storeCache 同语义,这里只按路径缓存。
512
- const key = path.resolve(this.file)
512
+ // Windows/macOS 大小写不敏感:同一个 global.json 的两种写法不能并存两个实例。
513
+ // 项目 store 已有同名归一(storeCacheAlias),这里此前漏了。
514
+ const key = storeKey(path.resolve(this.file))
513
515
  const hot = globalStoreCache.get(key)
514
516
  if (hot) {
515
517
  this.doc = hot.doc
package/src/lazy.js CHANGED
@@ -178,7 +178,12 @@ export async function indexObservedBatch(config, items, watchManager = null) {
178
178
  continue
179
179
  }
180
180
  clearIndexFailure(cand.root, cand.rel)
181
- if (plan.key === OVERSIZE) continue
181
+ if (plan.key === OVERSIZE) {
182
+ // 与 index_repo 同一语义:文件涨过阈值后,旧条目必须摘掉,而不是只跳过本轮。
183
+ updates.push({ rel: cand.rel, drop: true })
184
+ results.set(cand.filePath, false)
185
+ continue
186
+ }
182
187
  updates.push(toFileUpdate(cand.rel, plan, cand.record))
183
188
  if (plan.key !== DROP && plan.type === 'code') onFileObserved(store, cand.rel, cand.filePath, config, root)
184
189
  results.set(cand.filePath, plan.key !== DROP)
package/src/ops.js CHANGED
@@ -391,6 +391,19 @@ export function classifyToolCall(name, argsText) {
391
391
  const tool = String(name || '').toLowerCase()
392
392
  const { command, path } = argsFields(argsText)
393
393
  if (SHELL_TOOLS.has(tool)) return classifyShellCommand(command || String(argsText || ''))
394
+ // 宿主的 `str_replace_editor` 用 path + command(view/create/str_replace/insert),
395
+ // 不是 file_path;view 是读,其余三个才是写。漏掉它时文件编辑既不产 file-write,也进不了
396
+ // TaskBridge 的热点文件。
397
+ if (tool === 'str_replace_editor') {
398
+ const obj = safeJson(argsText) || {}
399
+ const filePath = typeof obj.path === 'string' ? obj.path : ''
400
+ const cmd = typeof obj.command === 'string' ? obj.command.toLowerCase() : ''
401
+ if (!filePath || !['create', 'str_replace', 'insert'].includes(cmd)) {
402
+ return { ops: [], targets: [], hosts: [] }
403
+ }
404
+ const targets = [filePath, ...extractPathTokens(filePath)]
405
+ return { ops: ['file-write'], targets: [...new Set(targets)], hosts: [] }
406
+ }
394
407
  if (READ_IMAGE_TOOLS.has(tool)) return { ops: ['read-image'], targets: [], hosts: [] }
395
408
  if (INDEX_TOOLS.has(tool)) return { ops: ['index-doc'], targets: [], hosts: [] }
396
409
  if (FETCH_TOOLS.has(tool)) return { ops: ['fetch-web'], targets: [], hosts: [] }
package/src/recall.js CHANGED
@@ -152,7 +152,8 @@ export function visibleInsights({ store = null, globalStore = null, boundTaskId
152
152
  }
153
153
  if (boundTaskId && store && typeof store.getTask === 'function') {
154
154
  const task = store.getTask(boundTaskId)
155
- for (const it of (task && task.insights) || []) {
155
+ // 归档任务不再向绑定会话提供任务级记忆(与 buildInjection 的 task 守卫同一判据)。
156
+ for (const it of (task && !task.archived && task.insights) || []) {
156
157
  if (!it || it.archived) continue
157
158
  // 任务级也要挡草稿:reflection 写的是 draft:true,未确认前不该被召回。
158
159
  if (it.draft === true) continue
@@ -9,7 +9,7 @@ import { ProjectMemoryStore } from '../store.js'
9
9
  import { BoundedMap } from '../util/session-cache.js'
10
10
  import { stepContent, stepStatus } from '../util/task-view.js'
11
11
 
12
- const FS_FILE_TOOLS = new Set(['read', 'write', 'edit', 'read_image'])
12
+ const FS_FILE_TOOLS = new Set(['read', 'write', 'edit', 'read_image', 'str_replace_editor'])
13
13
  const WRITE_TOOLS = new Set(['write', 'edit']) // 编辑/写入 = 高热点
14
14
  const READ_TOOLS = new Set(['read', 'read_image'])
15
15
  const MAX_FILES_PER_TASK = 100
@@ -266,11 +266,21 @@ export function onSessionEvent(config, session, event, meta, ctx) {
266
266
  } catch {
267
267
  return
268
268
  }
269
- const raw = typeof args?.file_path === 'string' ? args.file_path : null
269
+ // read/write/edit/read_image 用 file_path;宿主的 str_replace_editor 用 path。
270
+ const raw = typeof args?.file_path === 'string'
271
+ ? args.file_path
272
+ : typeof args?.path === 'string' ? args.path : null
270
273
  if (!raw) return
271
274
  const rel = normalizeRelFile(root, raw)
272
275
  if (!rel) return
273
- const kind = WRITE_TOOLS.has(data.name) ? 'write' : READ_TOOLS.has(data.name) ? 'read' : null
276
+ let kind = null
277
+ if (data.name === 'str_replace_editor') {
278
+ const cmd = typeof args?.command === 'string' ? args.command.toLowerCase() : ''
279
+ if (cmd === 'view') kind = 'read'
280
+ else if (['create', 'str_replace', 'insert'].includes(cmd)) kind = 'write'
281
+ } else {
282
+ kind = WRITE_TOOLS.has(data.name) ? 'write' : READ_TOOLS.has(data.name) ? 'read' : null
283
+ }
274
284
  if (!kind) return
275
285
  // 文件工具调用是最高频的写口:每次 commit 都落盘会把 tasks.json 写成“每读一个文件一次”。
276
286
  // 这里只改内存 + 标脏,回合结束(turn/end)或会话销毁时统一 flush。
@@ -12,7 +12,7 @@ import { createWriteCosine } from '../auto-inject.js'
12
12
  export function lessonTool(config) {
13
13
  const kindDesc = 'lesson(坑→改法) | decision(选择+理由) | procedure(步骤) | experience(问题→解法);默认 lesson。'
14
14
  const scopeDesc =
15
- 'task(任务私有) | project(项目资产) | global(跨项目);默认 project;给 id 时就地更新。'
15
+ 'task(任务私有) | project(项目资产) | global(跨项目);默认:绑定任务时 task,否则 project;给 id 时就地更新。'
16
16
  return defineTool({
17
17
  name: 'save_lesson',
18
18
  description:
@@ -100,7 +100,9 @@ export function lessonTool(config) {
100
100
  if (!args.id && !raw.title && !raw.pattern && !raw.choice) {
101
101
  return truncate(JSON.stringify({ success: false, error: '需要 title / pattern / choice 之一(或给 id 做就地更新)' }), config.maxOutputChars || 8000)
102
102
  }
103
- if (!INSIGHT_KINDS.includes(raw.kind)) raw.kind = 'lesson'
103
+ // 只有新建才补默认 kind;带 id 的就地更新必须“只覆盖传了的字段”,
104
+ // 否则一次改 fix/reason 会把 decision/procedure 静默降级成 lesson。
105
+ if (!args.id && !INSIGHT_KINDS.includes(raw.kind)) raw.kind = 'lesson'
104
106
 
105
107
  let scope = args.scope
106
108
  if (!scope) scope = taskId ? 'task' : 'project'
@@ -182,6 +182,10 @@ export function archiveTaskTool(config, host) {
182
182
  if (task.archived) return truncate(JSON.stringify({ success: false, error: 'Already archived' }), config.maxOutputChars)
183
183
  task.archived = true
184
184
  task.updatedAt = new Date().toISOString()
185
+ // 归档 = 停止续做:绑定必须在同一事务里清掉,否则本会话(以及别的会话)下一次
186
+ // 注入仍会拿到这张归档任务卡,task 级 insights 也继续可见;下一次 load 的
187
+ // _pruneBindings() 会自愈,但用户已经在中间几步看到了错误状态。
188
+ store.removeBindingsForTask(task.id)
185
189
  store.markTasksDirty()
186
190
  store.save()
187
191
  // 反思钩子:归档即收割最终教训(默认关)
@@ -1,4 +1,5 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
+ import { existsSync } from 'node:fs'
2
3
  import path from 'node:path'
3
4
  import { assertIndexRoot, assertSafeRoot, memoryRootFor, resolveIndexRoot, rootRejection, sessionMemoryRootOrNull, storeKey } from '../util/fs.js'
4
5
  import { ProjectMemoryStore } from '../store.js'
@@ -60,7 +61,9 @@ export function watchRepoTool(watchManager, config) {
60
61
  // (这正是要修的场景),而写它会在家目录里造出 .dsh-project-memory。那份
61
62
  // watch.json 现在也没有任何启动路径会读取(restorePersisted 只认会话 cwd),
62
63
  // 留着即可;会话侧的镜像条目照常摘掉。
63
- if (!rootRejection(root, config)) {
64
+ // 根可能早已被删除:这时**不能** load/commit,否则 save() 的 mkdirSync 会把
65
+ // watch_repo 刚停掉的路径重新创建出来。watch.json 的清理只对仍存在的根有意义。
66
+ if (existsSync(root) && !rootRejection(root, config)) {
64
67
  new ProjectMemoryStore(memoryDir).load().commit((s) => s.removeWatch(root))
65
68
  }
66
69
  await mirrorSessionWatchlist(false)
package/src/util/fs.js CHANGED
@@ -742,6 +742,13 @@ export function normalizeCitationFiles(files, root) {
742
742
  const value = raw.trim().replace(/\\/g, '/')
743
743
  if (!value) continue
744
744
  const looksAbsolute = value.startsWith('/') || /^[A-Za-z]:\//.test(value)
745
+ // Windows 盘符路径在 POSIX 上 `path.isAbsolute()` 是 false:不能把它当项目内相对路径
746
+ // 落成 `C:/...`(那会生成一个永远不存在的引用)。真正的 POSIX 绝对路径仍走下面的
747
+ // base/relative 判定,项目外的照常丢弃。
748
+ if (looksAbsolute && !path.isAbsolute(value)) {
749
+ dropped.push(raw)
750
+ continue
751
+ }
745
752
  if (base === null && looksAbsolute) {
746
753
  dropped.push(raw)
747
754
  continue
@@ -771,16 +778,57 @@ export function storeKey(rel, platform = process.platform) {
771
778
  return platform === 'win32' || platform === 'darwin' ? rel.toLowerCase() : rel
772
779
  }
773
780
 
774
- export function memoryRootFor(indexRoot, memoryDir) {
775
- return path.join(indexRoot, memoryDir)
776
- }
777
-
778
781
  /** store 目录名(配置项 `memoryDir`;调用方可能来自工具参数,缺省时兜底成默认值)。 */
779
782
  export const DEFAULT_MEMORY_DIR = '.dsh-project-memory'
780
783
 
784
+ /** 已经告过警的 `memoryDir` 值:同一个坏值在进程里只吵一次。 */
785
+ const warnedMemoryDir = new Set()
786
+
787
+ function defaultMemoryDirWarning(value) {
788
+ if (warnedMemoryDir.has(value)) return
789
+ warnedMemoryDir.add(value)
790
+ console.warn(
791
+ `[dsh-project-memory] memoryDir ${JSON.stringify(value)} must stay inside the project root; `
792
+ + `using ${DEFAULT_MEMORY_DIR} instead.`,
793
+ )
794
+ }
795
+
796
+ /**
797
+ * `memoryDir` → 真正使用的目录名(读写两侧唯一的归一入口)。
798
+ *
799
+ * 合法值 = **项目根内的一段相对路径**。会让 store 落到根外、或落到根上(`save()` 的自我忽略
800
+ * 随后把整个仓库从 git 视角隐藏)的形态一律回落到默认目录并告警一次:空/空白、`.`、`..`、
801
+ * 含 `..` 段(`a/../b`)、绝对路径(POSIX `/x`、Windows `C:\\x`)。嵌套目录(`a/b`)仍允许——
802
+ * 它仍在根内。空串的兜底在这里收口,`memoryRootFor()` 与 `memoryDirName()` 不再各写一遍。
803
+ */
804
+ export function safeMemoryDirName(raw, warn = defaultMemoryDirWarning) {
805
+ const value = typeof raw === 'string' ? raw.trim() : ''
806
+ if (!value) return DEFAULT_MEMORY_DIR
807
+ if (
808
+ value === '.' || value === '..'
809
+ || path.isAbsolute(value)
810
+ || WINDOWS_ABSOLUTE_PATH.test(value)
811
+ || value.split(/[\\/]+/).includes('..')
812
+ ) {
813
+ warn(value)
814
+ return DEFAULT_MEMORY_DIR
815
+ }
816
+ return value
817
+ }
818
+
819
+ /**
820
+ * 项目根 → store 目录。
821
+ *
822
+ * 空串/空白必须回落到默认目录:`path.join(root, '')` 等于项目根本身,而 `save()` 的自我忽略
823
+ * 会在那里写一个内容为 `*` 的 `.gitignore`(把整个仓库从 git 的视角隐藏),`format.json` /
824
+ * `shards/` 也会污染源码树。`.`, `..` 与绝对路径同理。
825
+ */
826
+ export function memoryRootFor(indexRoot, memoryDir) {
827
+ return path.join(indexRoot, safeMemoryDirName(memoryDir))
828
+ }
829
+
781
830
  export function memoryDirName(config) {
782
- const raw = config?.memoryDir
783
- return typeof raw === 'string' && raw.trim() ? raw : DEFAULT_MEMORY_DIR
831
+ return safeMemoryDirName(config?.memoryDir)
784
832
  }
785
833
 
786
834
  /**
@@ -3,6 +3,18 @@ import { CYRILLIC_WORD_RE, RU_STOPWORDS, normalizeRuWord, stemRu } from './ru.js
3
3
  export const CJK_RANGE =
4
4
  /[\u3400-\u9fff\uf900-\ufaff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/
5
5
 
6
+ /**
7
+ * 一段连续的 CJK 字符。分词时用它一次性取出所有段,取代"逐字符 test 再累积"的状态机。
8
+ *
9
+ * 从 `CJK_RANGE` 派生而不是另抄一份字符类:「什么算 CJK」全仓库只该有一个定义,
10
+ * 改字符范围时不会有两处不同步。`u` 让字符类按码点匹配——当前字符集全在 BMP,
11
+ * 输出与逐字符判断一致;将来若要纳入增补平面(U+20000 起),段内的二元组切分
12
+ * 必须一并改成按码点,`test/tokenizer-equivalence.test.mjs` 里有一条哨兵用例会在那时失败。
13
+ *
14
+ * 输出与逐字符实现逐字节一致,由同一条差分测试守住。
15
+ */
16
+ const CJK_RUN_RE = new RegExp(`${CJK_RANGE.source}+`, 'gu')
17
+
6
18
  /**
7
19
  * 分词契约的版本号。改 tokenizeRaw 的**输出集合**(新增书写系统、词干、停用词)就要 +1:
8
20
  * 落盘的 doc `terms` 是它的产物,旧版本写的 terms 里没有新词项,必须让
@@ -64,15 +76,6 @@ export function tokenizeRaw(text, { stem = true } = {}) {
64
76
  if (!text) return []
65
77
  const lower = text.toLowerCase()
66
78
  const tokens = []
67
- let cjkRun = ''
68
- const flushCjk = () => {
69
- if (cjkRun.length === 1) {
70
- tokens.push(cjkRun)
71
- } else {
72
- for (let i = 0; i < cjkRun.length - 1; i++) tokens.push(cjkRun.slice(i, i + 2))
73
- }
74
- cjkRun = ''
75
- }
76
79
  const latin = lower.match(/[a-z0-9_]+/g) || []
77
80
  for (const tok of latin) tokens.push(tok)
78
81
  // 西里尔(只做了俄语):切词 → 去虚词 → Snowball 词干。
@@ -85,11 +88,12 @@ export function tokenizeRaw(text, { stem = true } = {}) {
85
88
  const token = word.length <= 3 || !stem ? word : stemRu(word)
86
89
  if (token.length >= 2) tokens.push(token)
87
90
  }
88
- for (const ch of lower) {
89
- if (CJK_RANGE.test(ch)) cjkRun += ch
90
- else flushCjk()
91
+ // CJK:按「连续段」结算 —— 段长 1 产单字,段长 ≥2 产全部相邻二元组。
92
+ // 旧实现是逐字符累积 + 遇非 CJK 结算,两者输出逐字节一致(差分测试见上)。
93
+ for (const run of lower.match(CJK_RUN_RE) || []) {
94
+ if (run.length === 1) tokens.push(run)
95
+ else for (let i = 0; i < run.length - 1; i++) tokens.push(run.slice(i, i + 2))
91
96
  }
92
- flushCjk()
93
97
  return tokens
94
98
  }
95
99
 
package/src/watch.js CHANGED
@@ -270,6 +270,10 @@ export class WatchManager {
270
270
  }
271
271
 
272
272
  async pollRoot(root, state) {
273
+ // 根可能在运行期被删除/rename。这里**不能**继续走到 storeFor() → save():
274
+ // save() 会把 !formatWritten 当脏并 mkdirSync,把删掉的根重新创建成一个空目录。
275
+ // 暂时读不到的挂载点同样跳过本轮;它回来后会继续按原逻辑扫描。
276
+ if (!existsSync(root)) return false
273
277
  const seen = new Set()
274
278
  const updates = []
275
279
  // rel → 本轮采集的 mtime:size。提交成功后才落进快照;CAS 失败的条目下轮重试。
@@ -356,13 +360,20 @@ export class WatchManager {
356
360
  }
357
361
  state.failures.delete(rel)
358
362
  clearIndexFailure(root, rel)
359
- // 内容未变 / 体积超限也要落快照:否则 mtime:size 快路径永远命中不了,每次 poll 都要重读全仓。
360
- if (plan.key === UNCHANGED || plan.key === OVERSIZE) {
363
+ // 内容未变也要落快照:否则 mtime:size 快路径永远命中不了,每次 poll 都要重读全仓。
364
+ if (plan.key === UNCHANGED) {
361
365
  // 内容没变、只有 mtime 变了:把新 mtime 写回条目,让下一轮(及其它入口)的快路径能命中。
362
- if (plan.key === UNCHANGED && typeof plan.mtimeMs === 'number') store.refreshMtime(rel, plan.mtimeMs)
366
+ if (typeof plan.mtimeMs === 'number') store.refreshMtime(rel, plan.mtimeMs)
363
367
  state.snapshot[rel] = sig
364
368
  continue
365
369
  }
370
+ if (plan.key === OVERSIZE) {
371
+ // 体积超限必须把旧条目摘掉(与 index_repo 同一语义):只跳过快照会让
372
+ // 查询继续命中一个按配置已经不该索引的文件。
373
+ signatures.set(rel, sig)
374
+ updates.push({ rel, drop: true })
375
+ continue
376
+ }
366
377
 
367
378
  signatures.set(rel, sig)
368
379
  updates.push(toFileUpdate(rel, plan, record))