@yolk_vat-y/dsh-project-memory 0.6.4 → 0.6.5
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 +23 -1
- package/README.md +19 -4
- package/README.zh-CN.md +19 -4
- package/cordis.patch.yml +6 -1
- package/package.json +2 -2
- package/src/auto-inject.js +11 -9
- package/src/commands/insight-actions.js +1 -1
- package/src/commands/task-actions.js +1 -1
- package/src/commands/tasks.js +1 -1
- package/src/index.js +17 -11
- package/src/lazy.js +5 -3
- package/src/setup/taskbridge.js +3 -3
- package/src/tools/index-doc.js +11 -3
- package/src/tools/index-repo.js +4 -4
- package/src/tools/watch-repo.js +3 -3
- package/src/util/fs.js +375 -37
- package/src/watch.js +14 -9
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,25 @@
|
|
|
1
|
+
## 0.6.5 (2026-10-24)
|
|
2
|
+
|
|
3
|
+
**升级注意**:`allowUnsafeRoots: true` 的作用面比 0.6.4 大。此前它只放开**显式**工具调用与 `autoIndexOnFirstUse`,懒索引、会话审计与 TaskBridge 即使开着也始终不动;现在它放开内置名单的**所有**根判定入口,这三条链路会在放行的目录里建 store、写审计。只想放开某个目录时用 `roots.allow`(精确匹配,不影响 `deny` / `exclude`);家目录、系统目录如非必要仍建议保持 `false`。
|
|
4
|
+
|
|
5
|
+
### 新增:可配置的项目根名单(issue #8)
|
|
6
|
+
|
|
7
|
+
**背景**:哪些目录能当项目根此前是硬编码的——文件系统根、家目录、临时目录与系统/包管理器前缀。唯一的旋钮 `allowUnsafeRoots: true` 是整体开关:既不能只放开一个目录,也不能只多排除一个目录。
|
|
8
|
+
|
|
9
|
+
**改法**:`Config` 新增 `roots`,三组都支持 `~` / `~/...`;非绝对路径忽略并在 stderr 告警一次(相对路径会按宿主 cwd 解释,不可预测);Windows 下大小写不敏感。
|
|
10
|
+
|
|
11
|
+
- `roots.allow`:即使命中内置名单也允许作根,**精确匹配**;文件系统根不在此列。
|
|
12
|
+
- `roots.deny`:这个目录不能当根,**精确匹配**;子目录仍可各自成根。
|
|
13
|
+
- `roots.exclude`:这棵子树里的文件一律不进索引,**路径边界前缀匹配**(含子目录);也不会在子树里推出新根。
|
|
14
|
+
|
|
15
|
+
优先级 `exclude` > `deny` > `allow` > 内置名单。`allowUnsafeRoots: true` 保留为兼容开关,只作用于内置名单、`deny` / `exclude` 仍然优先——它的作用面变化见上面的升级注意。
|
|
16
|
+
|
|
17
|
+
**生效面**:判定收敛到 `util/fs.js` 的 `compileRootPolicy()` / `rootRejection()`,以下入口共用同一结论——显式工具调用(`index_repo` / `index_doc` / `remember` / `query_memory` / `stats` / 任务工具)、懒索引、watch 轮询、会话审计、TaskBridge。`listProjectFiles()` 的 walk 与 git 两条分支都应用 `roots.exclude`;父根的完整扫描会跳过被排除子树,并清掉之前索引过的条目。
|
|
18
|
+
|
|
19
|
+
**自愈**:新增 `deny` / `exclude` 后,已经登记在 `watch.json` 里的根会在下次启动时自动摘掉,不需要手删。拒绝文案会说明命中的规则,并指出要改的字段(`- id: project-memory` 的 `config:` 下)。
|
|
20
|
+
|
|
21
|
+
**测试**:新增 `test/root-policy.test.mjs`,覆盖精确/前缀语义、优先级、`~` 展开、相对路径告警、Windows 大小写、walk/git 两条扫描分支、watch 自愈与各入口的一致性。`npm test` **810 项 / 45 个文件**全绿;`npm run typecheck` 通过。
|
|
22
|
+
|
|
1
23
|
## 0.6.4 (2026-10-23)
|
|
2
24
|
|
|
3
25
|
**0.6.3 之后的收口**:11 个提交全部是修复与内部整理,没有新增工具、没有删除配置项。用户能感觉到的变化集中在三处——语料开始跟随 `.gitignore`、几个"设成 0 本该关闭"的旋钮真的关闭了、面板里改一步不再整份回写。**升级前请读第一条与「向量层」那条**。
|
|
@@ -126,7 +148,7 @@
|
|
|
126
148
|
|
|
127
149
|
### 整理:示例与文档里的专名中性化
|
|
128
150
|
|
|
129
|
-
README 双语与 CHANGELOG
|
|
151
|
+
README 双语与 CHANGELOG 里的具体框架名、硬件与机器信息、内部文件名换成中性写法;测试夹具里的内部文件名改成 `notes.md` 这类占位。零运行时行为变化。
|
|
130
152
|
|
|
131
153
|
**测试**:`npm test` 720 → **756 项 / 44 个文件**(新增 `gitignore-index` / `store-concurrent` / `tool-schema-size`;`insight-store`、`recall`、`recall-vector-fusion`、`vector-index`、`auto-inject`、`client-toolview`、`client-task-sync` 等在既有 `ok` 块内补断言);`npm run typecheck` 通过;`npm run build:client` 重建与提交产物零差异。
|
|
132
154
|
|
package/README.md
CHANGED
|
@@ -128,7 +128,8 @@ The workflow panel is collapsible, adapts to dsh and theme plugin styles, and of
|
|
|
128
128
|
| `autoIndexOnFirstUse` | false | full scan of the current working directory on plugin load (opt-in) |
|
|
129
129
|
| `watch` / `watchInterval` | true / 30 | background refresh; base poll interval in seconds (polls stay quiet while a turn is running — a 5-minute fallback keeps external edits fresh — and one merged scan runs at turn end; idle polls back off up to 2 minutes and reset on any change) |
|
|
130
130
|
| `maxScanFiles` / `maxScanDepth` | 20000 / 12 | per-scan caps on files and directory depth; a truncated pass is reported and never removes what it did not reach. Cannot be disabled: `0` or any invalid value falls back to the default |
|
|
131
|
-
| `allowUnsafeRoots` | false |
|
|
131
|
+
| `allowUnsafeRoots` | false | compatibility switch that releases the **built-in** excluded list for every root decision (including lazy indexing, session audit and TaskBridge). It only applies to the built-in list — `roots.deny` / `roots.exclude` still win; to release a single directory, prefer an exact `roots.allow` entry |
|
|
132
|
+
| `roots.allow` / `roots.deny` / `roots.exclude` | `[]` / `[]` / `[]` | custom root lists (machine/profile level, CLI and web alike). `allow` / `deny` match the directory itself exactly; `exclude` is a path-boundary prefix and covers the whole subtree (no file under it enters the index). Priority: `exclude` > `deny` > `allow` > built-in list; the filesystem root can never be a root. `~` / `~/...` expansion, non-absolute entries are ignored with a one-time stderr warning, Windows is case-insensitive |
|
|
132
133
|
| `llmQueryExpansion` / `expansionCount` | false / 6 | expand queries via the LLM before search (off by default to save tokens); max variants |
|
|
133
134
|
| `tsPath` / `enableTypeScript` | (auto) / true | optional absolute path to a specific `typescript` install; set `enableTypeScript: false` to disable the type-aware layer entirely |
|
|
134
135
|
| `tasklist.enabled` / `tasklist.syncHostOnAdopt` | true / true | TaskBridge auto-sync (task entities from the session todo list and file reads); push a bound task's steps to the host task list so dsh mirrors it |
|
|
@@ -155,7 +156,17 @@ The two most relevant switches are `lazyIndexing` (index a file the moment the m
|
|
|
155
156
|
|
|
156
157
|
When the root comes from the working directory, the model gets one notice per session naming it and how to change it; mute with `autoContext.rootNotice: false`. Starting dsh in a container directory such as `~/workspace` therefore makes that directory the root, and memory spans everything beneath it up to the scan limit — start dsh inside the project for one store per project.
|
|
157
158
|
|
|
158
|
-
**Excluded directories.**
|
|
159
|
+
**Excluded directories.** By default, these are not used as a root, matched exactly (subdirectories are unaffected): the filesystem root, the home directory, temp directories — `os.tmpdir()` and the shared ones (`/tmp`, `/var/tmp`, `%TEMP%`, `%SystemRoot%\Temp`) — and system / package-manager prefixes (`/opt/homebrew` on POSIX; `%SystemRoot%`, `%ProgramFiles%`, `%ProgramData%` on Windows). A session in one of these runs without memory, with one line on stderr.
|
|
160
|
+
|
|
161
|
+
**Custom root lists.** The `roots` block overrides that decision. All three accept `~` / `~/...`; non-absolute entries are ignored with a one-time stderr warning (relative paths would resolve against the host cwd and are unpredictable); Windows is case-insensitive:
|
|
162
|
+
|
|
163
|
+
- `roots.allow` — allow a directory even when it is on the built-in list, matched exactly. The filesystem root is not eligible.
|
|
164
|
+
- `roots.deny` — this directory cannot be a root, matched exactly; its subdirectories can still be roots of their own.
|
|
165
|
+
- `roots.exclude` — no file in this subtree enters the index, matched by path-boundary prefix (subdirectories included); no new root is inferred inside it either. A complete scan of a parent root skips it and removes previously indexed entries under it.
|
|
166
|
+
|
|
167
|
+
`deny` only decides whether the directory itself can be a root: when a parent is already a root, files under a denied child are still indexed by that parent — use `exclude` (or `.gitignore`, which the git-aware scan already honours) to drop the files too. Explicit `index_doc` also respects `exclude` and returns `Not indexed` for a file under it.
|
|
168
|
+
|
|
169
|
+
Priority is `exclude` > `deny` > `allow` > built-in list. `allowUnsafeRoots: true` remains as a compatibility switch that only releases the built-in list; `deny` / `exclude` still win. The same verdict is shared by explicit tool calls, lazy indexing, watch, the session audit trail and TaskBridge. After adding a `deny` / `exclude` entry, roots already persisted in `watch.json` are dropped on the next startup. Configure under `config:` of `- id: project-memory` (CLI and web alike); the web UI does not expose a dedicated settings page yet.
|
|
159
170
|
|
|
160
171
|
**Scan limits.** One pass covers at most `maxScanFiles` files (20000) and `maxScanDepth` directory levels (12). A truncated pass is reported in the `index_repo` result and logged once per root by the watcher, and it does not remove entries it did not reach. A directory that cannot be read (e.g. `EACCES`) counts as a truncated pass too and is named in the result: a read failure is not a deletion.
|
|
161
172
|
|
|
@@ -176,7 +187,11 @@ Settings live in the plugin's config object. To change them, add an override ent
|
|
|
176
187
|
maxScanFiles: 20000 # per-scan file cap (truncation is reported, never deletes)
|
|
177
188
|
maxScanDepth: 12 # per-scan directory-depth cap
|
|
178
189
|
enableTypeScript: true # on: type-aware enhancement when TS is installed (default)
|
|
179
|
-
# allowUnsafeRoots: false #
|
|
190
|
+
# allowUnsafeRoots: false # compatibility switch: built-in list only; prefer roots.allow below
|
|
191
|
+
# roots: # custom root lists (empty by default)
|
|
192
|
+
# allow: [/srv/projects/demo] # exact release of a built-in directory (filesystem root excluded)
|
|
193
|
+
# deny: [/srv/shared] # exact: this directory cannot be a root; children still can
|
|
194
|
+
# exclude: [/srv/monorepo/archive] # subtree prefix: no file under it enters the index
|
|
180
195
|
# tsPath: /custom/path/to/typescript # optional: force specific TS install
|
|
181
196
|
# autoContext: # note: the next two keys live under autoContext, not at the top level
|
|
182
197
|
# budgetLog: once # debugging: log budget drops to stderr (default off = silent)
|
|
@@ -266,7 +281,7 @@ These commands are for **maintaining the plugin code** — regular users do not
|
|
|
266
281
|
|
|
267
282
|
```bash
|
|
268
283
|
npm install
|
|
269
|
-
npm test #
|
|
284
|
+
npm test # 810 tests
|
|
270
285
|
npm run eval:injection # synthetic pool P/R: precision 0.93 / recall 1.00, + a 3-scenario hint-only group
|
|
271
286
|
npm run eval:injection -- --store .dsh-project-memory/insights.json # replay on YOUR store; control group is a hard gate
|
|
272
287
|
npm run selfcheck:triggers # which entries can still push, which declarations are dead (reads your local store)
|
package/README.zh-CN.md
CHANGED
|
@@ -127,7 +127,8 @@ TaskPanel (Container)
|
|
|
127
127
|
| `autoIndexOnFirstUse` | false | 插件加载时对当前工作目录做全量扫描(可选) |
|
|
128
128
|
| `watch` / `watchInterval` | true / 30 | 后台刷新;基础轮询间隔(秒);回合进行中静默(5 分钟兜底,外部改动仍会自愈),回合结束立刻合并扫一次;空闲时逐步退避到最长 2 分钟,一有变化立即回到该值 |
|
|
129
129
|
| `maxScanFiles` / `maxScanDepth` | 20000 / 12 | 单次扫描的文件数与目录深度硬上限;被截断时会在报告里说明,且不会删除没扫到的条目。**无法取消**:`0` 或任何非法值都回落到默认值 |
|
|
130
|
-
| `allowUnsafeRoots` | false |
|
|
130
|
+
| `allowUnsafeRoots` | false | 兼容开关:放开**内置**排除名单,所有根判定入口(含懒索引、会话审计、任务桥)都生效。它只作用于内置名单——`roots.deny` / `roots.exclude` 仍然优先;只想放开一个目录时用 `roots.allow` |
|
|
131
|
+
| `roots.allow` / `roots.deny` / `roots.exclude` | `[]` / `[]` / `[]` | 自定义根名单(机器/配置档级,CLI 与 web 通用)。`allow` / `deny` 精确匹配目录本身;`exclude` 按路径边界前缀匹配整棵子树(其中的文件一律不进索引)。优先级 `exclude` > `deny` > `allow` > 内置名单,文件系统根永远不能当根。支持 `~`/`~/...`;非绝对路径忽略并在 stderr 告警一次;Windows 下大小写不敏感 |
|
|
131
132
|
| `llmQueryExpansion` / `expansionCount` | false / 6 | 检索前用 LLM 扩展查询(默认关闭,节省 token);扩展变体上限 |
|
|
132
133
|
| `tsPath` / `enableTypeScript` | (自动) / true | 可选:强制指定 `typescript` 安装路径;`enableTypeScript: false` 彻底禁用类型感知层 |
|
|
133
134
|
| `tasklist.enabled` / `tasklist.syncHostOnAdopt` | true / true | TaskBridge 自动同步(由会话 todo 清单与文件读取沉淀任务实体);绑定任务时把其步骤推给宿主任务清单,使 dsh 镜像该任务 |
|
|
@@ -154,7 +155,17 @@ TaskPanel (Container)
|
|
|
154
155
|
|
|
155
156
|
根来自工作目录时,模型每个会话收到一条通告,说明根的位置与改法;`autoContext.rootNotice: false` 关闭。因此在 `~/workspace` 这类容器目录里启动 dsh,该目录就是根,记忆覆盖其下所有项目直到扫描上限——想一个项目一个 store,就在项目目录里启动。
|
|
156
157
|
|
|
157
|
-
**排除名单。** 以下目录不会作为根,精确匹配(子目录不受影响):文件系统根、家目录、临时目录(`os.tmpdir()` 与共享的 `/tmp`、`/var/tmp`、`%TEMP%`、`%SystemRoot%\Temp`),以及系统/包管理器前缀(POSIX 上的 `/opt/homebrew`,Windows 上的 `%SystemRoot%`、`%ProgramFiles%`、`%ProgramData
|
|
158
|
+
**排除名单。** 以下目录不会作为根,精确匹配(子目录不受影响):文件系统根、家目录、临时目录(`os.tmpdir()` 与共享的 `/tmp`、`/var/tmp`、`%TEMP%`、`%SystemRoot%\Temp`),以及系统/包管理器前缀(POSIX 上的 `/opt/homebrew`,Windows 上的 `%SystemRoot%`、`%ProgramFiles%`、`%ProgramData%`)。这些目录下的会话默认不启用记忆,stderr 输出一行说明。
|
|
159
|
+
|
|
160
|
+
**自定义根名单。** 在同一份配置的 `roots` 下可以覆盖上述判定;三项都支持 `~`/`~/...`,非绝对路径会被忽略并在 stderr 告警一次(相对路径按宿主 cwd 解释,不可预测),Windows 下大小写不敏感:
|
|
161
|
+
|
|
162
|
+
- `roots.allow`:即使命中了内置名单也允许作根,精确匹配;文件系统根不在此列。
|
|
163
|
+
- `roots.deny`:这个目录不能当根,精确匹配;它的子目录仍可各自成根。
|
|
164
|
+
- `roots.exclude`:这棵子树里的文件一律不进索引,按路径边界前缀匹配(含子目录);也不能在这里推出新的根。父根的完整扫描会跳过它,之前索引过的条目会在下一次完整扫描时清理。
|
|
165
|
+
|
|
166
|
+
注意 `deny` 只决定这个目录自己能不能当根:父目录已经是根时,`deny` 的子目录仍会被父根索引——要连文件一起排除请用 `exclude`(或 `.gitignore`,git 仓库里的扫描本来就尊重它)。显式 `index_doc` 也服从 `exclude`,被排除的文件会返回 `Not indexed`。
|
|
167
|
+
|
|
168
|
+
优先级是 `exclude` > `deny` > `allow` > 内置名单。`allowUnsafeRoots: true` 保留为兼容,只放开内置名单,`deny` / `exclude` 仍然优先。生效面是同一套判定:显式工具调用、懒索引、watch、会话审计、任务桥。新增 `deny` / `exclude` 后,已登记在 `watch.json` 里的根会在下次启动自动摘掉。配置写在 `- id: project-memory` 的 `config:` 下(CLI 与 web 都适用);Web 端暂未提供正式配置页。
|
|
158
169
|
|
|
159
170
|
**扫描上限。** 单次扫描最多 `maxScanFiles` 个文件(20000)、`maxScanDepth` 层目录(12)。被截断时,`index_repo` 的结果里会说明,watcher 每个根记一行,且不会删除没扫到的条目。**读不到的目录**(如 `EACCES`)同样算一次截断扫描并在结果里点名:读失败不等于被删除。
|
|
160
171
|
|
|
@@ -175,7 +186,11 @@ store 建在被索引的目录树里,并且**自我忽略**:自己目录内
|
|
|
175
186
|
maxScanFiles: 20000 # 单次扫描文件上限(截断会报告,且不会误删旧条目)
|
|
176
187
|
maxScanDepth: 12 # 单次扫描目录深度上限
|
|
177
188
|
enableTypeScript: true # 开启:装了 TS 时启用类型感知增强(默认)
|
|
178
|
-
# allowUnsafeRoots: false #
|
|
189
|
+
# allowUnsafeRoots: false # 兼容开关:只放开内置名单;优先改用下面的 roots.allow
|
|
190
|
+
# roots: # 自定义根名单(默认全空)
|
|
191
|
+
# allow: [/srv/projects/demo] # 精确放行内置名单里的目录(文件系统根不可放行)
|
|
192
|
+
# deny: [/srv/shared] # 精确拒绝这个目录本身;子目录仍可成根
|
|
193
|
+
# exclude: [/srv/monorepo/archive] # 子树前缀:里面的文件一律不进索引
|
|
179
194
|
# tsPath: /custom/path/to/typescript # 可选:强制指定 TS 安装路径
|
|
180
195
|
# autoContext: # 注意:下面两个键在 autoContext 下,不是顶层
|
|
181
196
|
# budgetLog: once # 调试用:注入被预算挤掉时在 stderr 留痕(默认 off 静默)
|
|
@@ -265,7 +280,7 @@ node scripts/bench.mjs /你的/项目路径 [--json] [--samples 100] [--no-pdf]
|
|
|
265
280
|
|
|
266
281
|
```bash
|
|
267
282
|
npm install
|
|
268
|
-
npm test #
|
|
283
|
+
npm test # 810 项测试
|
|
269
284
|
npm run eval:injection # 合成池 P/R:精确率 0.93 / 召回率 1.00,另有 3 个 hint-only 场景
|
|
270
285
|
npm run eval:injection -- --store .dsh-project-memory/insights.json # 用你自己的 store 重放;对照组是硬闸门
|
|
271
286
|
npm run selfcheck:triggers # 哪些条目还推得动、哪些声明是死的(读你本地的 store)
|
package/cordis.patch.yml
CHANGED
|
@@ -12,8 +12,13 @@
|
|
|
12
12
|
watch: true
|
|
13
13
|
watchInterval: 30
|
|
14
14
|
# 危险根护栏(家目录 / 文件系统根 / 系统与包管理器前缀整体扫描会吃满内存)。
|
|
15
|
-
#
|
|
15
|
+
# 兼容开关:只放开内置名单;roots.deny / roots.exclude 仍然优先。
|
|
16
16
|
allowUnsafeRoots: false
|
|
17
|
+
# 自定义根名单(可选;allow/deny 精确匹配目录本身,exclude 是子树前缀)。
|
|
18
|
+
# roots:
|
|
19
|
+
# allow: []
|
|
20
|
+
# deny: []
|
|
21
|
+
# exclude: []
|
|
17
22
|
# 单次扫描上限;截断会报告,且不会删除未扫到的条目。
|
|
18
23
|
maxScanFiles: 20000
|
|
19
24
|
maxScanDepth: 12
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yolk_vat-y/dsh-project-memory",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.5",
|
|
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",
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
"url": "https://github.com/00080000/dsh-project-memory.git"
|
|
20
20
|
},
|
|
21
21
|
"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/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",
|
|
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
23
|
"eval:injection": "node test/injection-scenarios.test.mjs",
|
|
24
24
|
"typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.client.json",
|
|
25
25
|
"selfcheck:triggers": "node test/injection-scenarios.test.mjs --selfcheck",
|
package/src/auto-inject.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
import { createHash } from 'node:crypto'
|
|
9
9
|
import { createUserMessage } from '@deepseek-ai/dsh-llm'
|
|
10
10
|
import { ProjectMemoryStore } from './store.js'
|
|
11
|
-
import { hasProjectMarker,
|
|
11
|
+
import { hasProjectMarker, memoryRootFor, resolveProjectMemoryRoot, rootRejection } from './util/fs.js'
|
|
12
12
|
import { textOf } from './util/text.js'
|
|
13
13
|
import { stepContent } from './util/task-view.js'
|
|
14
14
|
import { insightMatchText, normalizedTokenOverlap } from './similarity.js'
|
|
@@ -702,11 +702,12 @@ export function installAutoInject(ctx, config) {
|
|
|
702
702
|
/** 已就「会话根不安全」提示过的目录:每个进程、每个根只提示一次。 */
|
|
703
703
|
const warnedUnsafeRoots = new Set()
|
|
704
704
|
|
|
705
|
-
function warnUnsafeSessionRoot(root) {
|
|
705
|
+
function warnUnsafeSessionRoot(root, rejection) {
|
|
706
706
|
if (warnedUnsafeRoots.has(root)) return
|
|
707
707
|
warnedUnsafeRoots.add(root)
|
|
708
|
+
const field = rejection?.field ? `; adjust \`${rejection.field}\` under \`- id: project-memory\` if this is intentional` : ''
|
|
708
709
|
console.error(
|
|
709
|
-
`[dsh-project-memory] session cwd ${root} is not a project root (home / system / package-manager prefix); ` +
|
|
710
|
+
`[dsh-project-memory] session cwd ${root} is not a project root (${rejection?.reason || 'home / system / package-manager prefix'}${field}); ` +
|
|
710
711
|
'project memory and its audit logs are disabled for this session. Start dsh inside a project directory to enable them.',
|
|
711
712
|
)
|
|
712
713
|
}
|
|
@@ -722,16 +723,17 @@ async function injectForStep({ payload, decision, config, cfg, audit, shadow, se
|
|
|
722
723
|
const cwd = sessionWorkingDir(session, { agent: payload?.agent })
|
|
723
724
|
const sessionId = session && session.id
|
|
724
725
|
if (!cwd || !sessionId) return null
|
|
725
|
-
// 会话 cwd
|
|
726
|
-
// 光是 load() 就能 OOM),也不写审计——`appendShadowAudit` 里的
|
|
727
|
-
// `.dsh-project-memory` 造进家目录、进而触发"目录自标记 → 家目录被锁成项目"的那一步。
|
|
728
|
-
|
|
729
|
-
|
|
726
|
+
// 会话 cwd 命中内置名单 / roots.deny / roots.exclude 时整条链路停在这里:不读 store
|
|
727
|
+
// (历史遗留的超大 store 光是 load() 就能 OOM),也不写审计——`appendShadowAudit` 里的
|
|
728
|
+
// mkdirSync 正是把 `.dsh-project-memory` 造进家目录、进而触发"目录自标记 → 家目录被锁成项目"的那一步。
|
|
729
|
+
const rejection = rootRejection(cwd, config)
|
|
730
|
+
if (rejection) {
|
|
731
|
+
warnUnsafeSessionRoot(cwd, rejection)
|
|
730
732
|
return null
|
|
731
733
|
}
|
|
732
734
|
// 记忆根与懒索引/工具侧同一套解析:项目标记优先,其次是安全的会话工作目录。
|
|
733
735
|
// 少了这一步,同一个会话的审计日志与懒索引会落在两个不同的 store 里。
|
|
734
|
-
const root = resolveProjectMemoryRoot(cwd)
|
|
736
|
+
const root = resolveProjectMemoryRoot(cwd, config)
|
|
735
737
|
if (!root) return null
|
|
736
738
|
|
|
737
739
|
const query = lastUserText(decision.messages)
|
|
@@ -396,7 +396,7 @@ export function insightCommandDefinition(config, ctx) {
|
|
|
396
396
|
const { cwd } = invocationContext(invocation)
|
|
397
397
|
const lineRaw = (invocation?.rawInput || '').trim()
|
|
398
398
|
const raw = lineRaw.split(/\s+/).filter(Boolean)
|
|
399
|
-
const root = projectRootFor(cwd)
|
|
399
|
+
const root = projectRootFor(cwd, config)
|
|
400
400
|
if (!root) return { kind: 'error', text: NO_PROJECT_ROOT_NOTE }
|
|
401
401
|
if (!raw[0]) return { kind: 'error', text: '[insight] 用法见面板' }
|
|
402
402
|
const verb = raw[0]
|
|
@@ -36,7 +36,7 @@ function withTaskSnapshot(config, cwd, sid, store, note) {
|
|
|
36
36
|
const active = tasks.filter((t) => !t.archived)
|
|
37
37
|
const archived = tasks.length - active.length
|
|
38
38
|
const boundId = sid ? store.getBoundTaskId(sid) : null
|
|
39
|
-
const root = projectRootFor(cwd)
|
|
39
|
+
const root = projectRootFor(cwd, config)
|
|
40
40
|
const human = `项目 ${root}\n${note}\n任务: ${active.length} 套${archived ? `(归档 ${archived})` : ''}`
|
|
41
41
|
const payload = buildTaskPayload(active, boundId, archived, root)
|
|
42
42
|
return { kind: 'success', text: fencedJson(human, payload) }
|
package/src/commands/tasks.js
CHANGED
|
@@ -32,7 +32,7 @@ export function buildTaskPayload(tasks, boundId, archived, root = null) {
|
|
|
32
32
|
* 任务动作命令复用同一函数,面板只需解析尾部 JSON 即可刷新。
|
|
33
33
|
*/
|
|
34
34
|
export function renderTaskSnapshot(config, cwd, sid) {
|
|
35
|
-
const root = projectRootFor(cwd)
|
|
35
|
+
const root = projectRootFor(cwd, config)
|
|
36
36
|
if (!root) return { kind: 'error', text: NO_PROJECT_ROOT_NOTE }
|
|
37
37
|
const store = new ProjectMemoryStore(memoryRootFor(root, config.memoryDir)).load()
|
|
38
38
|
const tasks = store.getTasks()
|
package/src/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import Schema from '@deepseek-ai/schemastery'
|
|
2
|
-
import { DEFAULT_SCAN_DEPTH, DEFAULT_SCAN_FILES,
|
|
2
|
+
import { DEFAULT_SCAN_DEPTH, DEFAULT_SCAN_FILES, assertSafeRoot } from './util/fs.js'
|
|
3
3
|
import { indexDocTool } from './tools/index-doc.js'
|
|
4
4
|
import { indexRepoTool, indexRepository } from './tools/index-repo.js'
|
|
5
5
|
import { queryMemoryTool } from './tools/query-memory.js'
|
|
@@ -45,9 +45,18 @@ export const Config = Schema.object({
|
|
|
45
45
|
watch: Schema.boolean().default(true),
|
|
46
46
|
watchInterval: Schema.number().default(30),
|
|
47
47
|
// 危险根护栏(issue #5):家目录 / 文件系统根 / 系统目录 / 包管理器前缀(/opt/homebrew …)
|
|
48
|
-
//
|
|
49
|
-
// `
|
|
48
|
+
// 整体扫描会吃满内存,默认一律拒绝(懒索引、会话审计、任务桥默认零副作用)。
|
|
49
|
+
// `roots.*` 是机器/配置档级的例外表(精确匹配的 allow/deny,子树级前缀的 exclude);
|
|
50
|
+
// `allowUnsafeRoots` 保留为兼容,只放开内置名单,deny / exclude 仍然优先。
|
|
50
51
|
allowUnsafeRoots: Schema.boolean().default(false),
|
|
52
|
+
roots: Schema.object({
|
|
53
|
+
// 即使在内置名单里也允许作根。精确匹配;文件系统根不在可放行之列。
|
|
54
|
+
allow: Schema.array(Schema.string()).default([]),
|
|
55
|
+
// 这个目录不能当根。精确匹配:子目录仍可各自成根。
|
|
56
|
+
deny: Schema.array(Schema.string()).default([]),
|
|
57
|
+
// 这棵子树里的文件一律不进索引(前缀匹配,含子目录)。
|
|
58
|
+
exclude: Schema.array(Schema.string()).default([]),
|
|
59
|
+
}).default({}),
|
|
51
60
|
// 单次扫描上限。超过即截断(并跳过"删除本轮未见到条目"的清理,避免把没扫到的文件误删)。
|
|
52
61
|
// **不可取消**:0 / 负数 / 非数值一律回落默认值(见 util/fs.js 的 scanLimits)。
|
|
53
62
|
maxScanFiles: Schema.number().default(DEFAULT_SCAN_FILES),
|
|
@@ -238,14 +247,11 @@ export function apply(ctx, config) {
|
|
|
238
247
|
// 全量索引 cwd 是显式开启的行为,但"cwd 是家目录"几乎总是误用:拒绝并说明,
|
|
239
248
|
// 而不是替用户把整棵树扫一遍(旧实现直接 indexRepository(ctx, config, cwd),
|
|
240
249
|
// 没有任何护栏——这正是 issue #5 里最直接的 OOM 入口)。
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
'or set allowUnsafeRoots: true to override.',
|
|
247
|
-
)
|
|
248
|
-
}
|
|
250
|
+
// 这里走与工具调用同一个 assertSafeRoot:roots.allow / deny / exclude 全部生效。
|
|
251
|
+
try {
|
|
252
|
+
assertSafeRoot(root, { config })
|
|
253
|
+
} catch (err) {
|
|
254
|
+
if (!cancelled) console.error(`[dsh-project-memory] autoIndexOnFirstUse skipped: ${err.message}`)
|
|
249
255
|
return
|
|
250
256
|
}
|
|
251
257
|
try {
|
package/src/lazy.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import path from 'node:path'
|
|
2
2
|
import { statSync } from 'node:fs'
|
|
3
|
-
import { findProjectRoot, isGitIgnored,
|
|
3
|
+
import { excludedEntryForPath, findProjectRoot, isGitIgnored, memoryRootFor, relativePath, rootRejection, storeKey } from './util/fs.js'
|
|
4
4
|
import { DROP, OVERSIZE, UNCHANGED, commitFileUpdates, fileKind, planFileIndex, toFileUpdate } from './index-pipeline.js'
|
|
5
5
|
import { ProjectMemoryStore } from './store.js'
|
|
6
6
|
import { onFileObserved } from './enhancer.js'
|
|
@@ -12,11 +12,13 @@ export { findProjectRoot }
|
|
|
12
12
|
export async function indexFile(ctx, config, filePath, watchManager = null, sessionRoot = null) {
|
|
13
13
|
const kind = fileKind(path.extname(filePath).toLowerCase())
|
|
14
14
|
if (!kind) return false
|
|
15
|
+
// roots.exclude 是子树级否定:被排除的文件连根都不推导,直接不落任何记忆。
|
|
16
|
+
if (excludedEntryForPath(filePath, config)) return false
|
|
15
17
|
// 根来源优先级:显式 watch 过的根 → 项目标记 → 会话工作目录(安全时)。
|
|
16
18
|
// 显式登记过的根优先,是为了让"没有标记但被 watch_repo 指定过"的项目也能持续刷新。
|
|
17
19
|
const extraRoots = watchManager ? [...watchManager.roots.keys()] : []
|
|
18
|
-
const root = findProjectRoot(filePath, { extraRoots, sessionRoot })
|
|
19
|
-
if (!root ||
|
|
20
|
+
const root = findProjectRoot(filePath, { extraRoots, sessionRoot, config })
|
|
21
|
+
if (!root || rootRejection(root, config)) return false
|
|
20
22
|
// 被 .gitignore 排除的文件(构建产物 / 内部文档)不进语料;显式 index_doc 不受此限。
|
|
21
23
|
if (isGitIgnored(root, filePath)) return false
|
|
22
24
|
|
package/src/setup/taskbridge.js
CHANGED
|
@@ -44,13 +44,13 @@ export const NO_PROJECT_ROOT_NOTE =
|
|
|
44
44
|
* "会话工作目录"归属,没有标记的普通目录也要能用);cwd 是家目录/系统/包管理器前缀
|
|
45
45
|
* 且上方没有标记时返回 null。
|
|
46
46
|
*/
|
|
47
|
-
export function projectRootFor(cwd) {
|
|
48
|
-
return resolveProjectMemoryRoot(cwd || process.cwd())
|
|
47
|
+
export function projectRootFor(cwd, config) {
|
|
48
|
+
return resolveProjectMemoryRoot(cwd || process.cwd(), config)
|
|
49
49
|
}
|
|
50
50
|
|
|
51
51
|
/** 没有可用项目根时返回 `{ root: null, store: null }`,调用方据此整段跳过。 */
|
|
52
52
|
export function taskStoreFor(cwd, config) {
|
|
53
|
-
const root = projectRootFor(cwd)
|
|
53
|
+
const root = projectRootFor(cwd, config)
|
|
54
54
|
if (!root) return { root: null, store: null }
|
|
55
55
|
return { root, store: new ProjectMemoryStore(memoryRootFor(root, config.memoryDir)).load() }
|
|
56
56
|
}
|
package/src/tools/index-doc.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
2
2
|
import path from 'node:path'
|
|
3
|
-
import { assertIndexRoot, assertReadableFile, assertSafeRoot, findProjectRoot, memoryRootFor, sessionMemoryRootOrNull, sha256OfFile, storeKey } from '../util/fs.js'
|
|
3
|
+
import { assertIndexRoot, assertReadableFile, assertSafeRoot, excludedEntryForPath, findProjectRoot, memoryRootFor, sessionMemoryRootOrNull, sha256OfFile, storeKey } from '../util/fs.js'
|
|
4
4
|
import { buildDocEntries } from '../doc-pipeline.js'
|
|
5
5
|
import { docEntriesNeedBackfill } from '../doc-index.js'
|
|
6
6
|
import { ProjectMemoryStore } from '../store.js'
|
|
@@ -27,16 +27,24 @@ export function indexDocTool(ctx, config) {
|
|
|
27
27
|
},
|
|
28
28
|
async execute(args, exec) {
|
|
29
29
|
const filePath = assertReadableFile(args.file_path, config.maxFileSizeMb)
|
|
30
|
+
// roots.exclude 是"这棵子树里的文件一律不进索引":显式 index_doc 也要服从。
|
|
31
|
+
const excluded = excludedEntryForPath(filePath, config)
|
|
32
|
+
if (excluded) {
|
|
33
|
+
return (
|
|
34
|
+
`Not indexed: ${filePath} is inside the subtree excluded by \`roots.exclude\` entry ${JSON.stringify(excluded.raw)}. ` +
|
|
35
|
+
'Remove that entry from `config.roots.exclude` under `- id: project-memory` if this file should be indexed.'
|
|
36
|
+
)
|
|
37
|
+
}
|
|
30
38
|
const explicit = args.root && args.root.trim() ? args.root : null
|
|
31
39
|
let root
|
|
32
40
|
if (explicit) {
|
|
33
41
|
root = path.resolve(explicit)
|
|
34
42
|
assertIndexRoot(root, explicit)
|
|
35
|
-
assertSafeRoot(root, { requested: explicit,
|
|
43
|
+
assertSafeRoot(root, { requested: explicit, config })
|
|
36
44
|
} else {
|
|
37
45
|
// 与懒索引同序:文件自身的项目标记优先,其次才是会话记忆根(安全但无标记的 cwd)。
|
|
38
46
|
const sessionRoot = sessionMemoryRootOrNull(exec, config)
|
|
39
|
-
root = findProjectRoot(filePath, { sessionRoot })
|
|
47
|
+
root = findProjectRoot(filePath, { sessionRoot, config })
|
|
40
48
|
if (!root) {
|
|
41
49
|
return (
|
|
42
50
|
`Not indexed: ${filePath} is not inside a detected project ` +
|
package/src/tools/index-repo.js
CHANGED
|
@@ -17,7 +17,7 @@ export async function indexRepository(ctx, config, root, { reindex = false, allo
|
|
|
17
17
|
// 不存在的 root 连同 .dsh-project-memory 一起 mkdirSync 出来。
|
|
18
18
|
assertIndexRoot(root)
|
|
19
19
|
// 再校验安全:家目录 / 系统目录 / Homebrew 前缀整体索引会吃满内存(issue #5)。
|
|
20
|
-
assertSafeRoot(root, { allowUnsafe })
|
|
20
|
+
assertSafeRoot(root, { allowUnsafe, config })
|
|
21
21
|
const memoryDir = memoryRootFor(root, config.memoryDir)
|
|
22
22
|
const store = new ProjectMemoryStore(memoryDir).load()
|
|
23
23
|
|
|
@@ -41,6 +41,7 @@ export async function indexRepository(ctx, config, root, { reindex = false, allo
|
|
|
41
41
|
const { files, truncated, capped, skipped: nestedRoots, unreadable } = listProjectFiles(root, {
|
|
42
42
|
...scanLimits(config),
|
|
43
43
|
nestedStoreName: memoryDirName(config),
|
|
44
|
+
config,
|
|
44
45
|
})
|
|
45
46
|
for (const filePath of files) {
|
|
46
47
|
const rel = storeKey(relativePath(root, filePath))
|
|
@@ -153,9 +154,8 @@ export function indexRepoTool(ctx, config) {
|
|
|
153
154
|
// 透传原始入参:Windows 风格路径在 POSIX 上会被 resolve 成 <cwd>/D:\...,
|
|
154
155
|
// 报错时要点明这是路径风格问题,而不是“目录被删了”。
|
|
155
156
|
assertIndexRoot(root, args.root)
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
return indexRepository(ctx, config, root, { reindex: Boolean(args.reindex), allowUnsafe })
|
|
157
|
+
assertSafeRoot(root, { requested: args.root, config })
|
|
158
|
+
return indexRepository(ctx, config, root, { reindex: Boolean(args.reindex) })
|
|
159
159
|
},
|
|
160
160
|
})
|
|
161
161
|
}
|
package/src/tools/watch-repo.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
2
2
|
import path from 'node:path'
|
|
3
|
-
import { assertIndexRoot, assertSafeRoot,
|
|
3
|
+
import { assertIndexRoot, assertSafeRoot, memoryRootFor, rootRejection, sessionMemoryRootOrNull } from '../util/fs.js'
|
|
4
4
|
import { ProjectMemoryStore } from '../store.js'
|
|
5
5
|
|
|
6
6
|
export function watchRepoTool(watchManager, config) {
|
|
@@ -31,7 +31,7 @@ export function watchRepoTool(watchManager, config) {
|
|
|
31
31
|
if (args.watch !== false) {
|
|
32
32
|
try {
|
|
33
33
|
assertIndexRoot(root, args.root)
|
|
34
|
-
assertSafeRoot(root, { requested: args.root,
|
|
34
|
+
assertSafeRoot(root, { requested: args.root, config })
|
|
35
35
|
} catch (err) {
|
|
36
36
|
return `Not watching: ${err.message}`
|
|
37
37
|
}
|
|
@@ -58,7 +58,7 @@ export function watchRepoTool(watchManager, config) {
|
|
|
58
58
|
// (这正是要修的场景),而写它会在家目录里造出 .dsh-project-memory。那份
|
|
59
59
|
// watch.json 现在也没有任何启动路径会读取(restorePersisted 只认会话 cwd),
|
|
60
60
|
// 留着即可;会话侧的镜像条目照常摘掉。
|
|
61
|
-
if (!
|
|
61
|
+
if (!rootRejection(root, config)) {
|
|
62
62
|
new ProjectMemoryStore(memoryDir).load().commit((s) => s.removeWatch(root))
|
|
63
63
|
}
|
|
64
64
|
await mirrorSessionWatchlist(false)
|
package/src/util/fs.js
CHANGED
|
@@ -271,6 +271,12 @@ export function walkDir(root, opts = {}) {
|
|
|
271
271
|
// 扫描也该同意这一点;否则父根会把子项目的全部内容再存一份(实测一个父目录
|
|
272
272
|
// 的 store 里 9075/9081 个文件是子根 store 的重复副本)。
|
|
273
273
|
const nestedStoreName = opts.nestedStoreName || null
|
|
274
|
+
// `roots.exclude` 是子树级前缀匹配:命中的目录整棵剪掉,命中的文件直接不收。
|
|
275
|
+
const policy = isCompiledRootPolicy(opts.policy)
|
|
276
|
+
? opts.policy
|
|
277
|
+
: isCompiledRootPolicy(opts.config)
|
|
278
|
+
? opts.config
|
|
279
|
+
: opts.config ? compileRootPolicy(opts.config) : null
|
|
274
280
|
const out = []
|
|
275
281
|
const skipped = []
|
|
276
282
|
const unreadable = []
|
|
@@ -295,6 +301,7 @@ export function walkDir(root, opts = {}) {
|
|
|
295
301
|
const full = path.join(dir, entry.name)
|
|
296
302
|
if (entry.isDirectory()) {
|
|
297
303
|
if (ignoreNames.has(entry.name)) continue
|
|
304
|
+
if (policy && excludedEntryForAbs(full, policy)) continue
|
|
298
305
|
if (nestedStoreName && hasOwnStore(full, nestedStoreName)) {
|
|
299
306
|
skipped.push(full)
|
|
300
307
|
continue
|
|
@@ -306,6 +313,7 @@ export function walkDir(root, opts = {}) {
|
|
|
306
313
|
}
|
|
307
314
|
stack.push([full, depth + 1])
|
|
308
315
|
} else {
|
|
316
|
+
if (policy && excludedEntryForAbs(full, policy)) continue
|
|
309
317
|
if (out.length >= maxFiles) {
|
|
310
318
|
truncated = true
|
|
311
319
|
capped = true
|
|
@@ -350,6 +358,11 @@ function gitListedFiles(root) {
|
|
|
350
358
|
* @returns {{files: string[], truncated: boolean, capped: boolean, skipped: string[], unreadable: string[]}}
|
|
351
359
|
*/
|
|
352
360
|
export function listProjectFiles(root, opts = {}) {
|
|
361
|
+
const policy = isCompiledRootPolicy(opts.policy)
|
|
362
|
+
? opts.policy
|
|
363
|
+
: isCompiledRootPolicy(opts.config)
|
|
364
|
+
? opts.config
|
|
365
|
+
: opts.config ? compileRootPolicy(opts.config) : null
|
|
353
366
|
const listed = opts.gitAware === false ? null : gitListedFiles(root)
|
|
354
367
|
if (listed === null) return walkDir(root, opts)
|
|
355
368
|
const maxFiles = Number.isFinite(opts.maxFiles) && opts.maxFiles > 0 ? opts.maxFiles : Infinity
|
|
@@ -366,6 +379,11 @@ export function listProjectFiles(root, opts = {}) {
|
|
|
366
379
|
if (!rel) continue
|
|
367
380
|
const segs = rel.split('/')
|
|
368
381
|
if (segs.some((s) => DEFAULT_IGNORE.has(s))) continue
|
|
382
|
+
const abs = path.join(root, rel)
|
|
383
|
+
// 与 walkDir 同一判据:exclude 是子树级前缀,git 清单里的文件同样要过这一关。
|
|
384
|
+
// 这一步必须在 maxDepth 之前:被排除文件不该把扫描标成 truncated(否则本轮
|
|
385
|
+
// 不会清理"未见到的旧条目",排除规则反而让旧索引留在盘上)。
|
|
386
|
+
if (policy && excludedEntryForAbs(abs, policy)) continue
|
|
369
387
|
if (segs.length > maxDepth) {
|
|
370
388
|
capped = true
|
|
371
389
|
continue
|
|
@@ -379,7 +397,6 @@ export function listProjectFiles(root, opts = {}) {
|
|
|
379
397
|
capped = true
|
|
380
398
|
break
|
|
381
399
|
}
|
|
382
|
-
const abs = path.join(root, rel)
|
|
383
400
|
try {
|
|
384
401
|
if (!statSync(abs).isFile()) continue
|
|
385
402
|
} catch {
|
|
@@ -615,57 +632,363 @@ const UNSAFE = collectUnsafeRootSets()
|
|
|
615
632
|
const UNSAFE_DIRS = UNSAFE.unsafe
|
|
616
633
|
const SHARED_TEMP_DIRS = UNSAFE.sharedTemp
|
|
617
634
|
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
635
|
+
// ---------------------------------------------------------------------------
|
|
636
|
+
// 用户可配置的根名单(`roots.allow` / `roots.deny` / `roots.exclude`)。
|
|
637
|
+
//
|
|
638
|
+
// 三个字段的匹配口径刻意不同,别合并成一个:
|
|
639
|
+
// - allow / deny:**精确匹配**,只针对目录本身。`deny: /srv/shared` 不拒绝
|
|
640
|
+
// `/srv/shared/myproj`——它自己是一个合法项目根。
|
|
641
|
+
// - exclude:**路径边界前缀匹配**,整棵子树都算。子树里的文件一律不进索引,
|
|
642
|
+
// 也不能在这棵子树里推出新的项目根。
|
|
643
|
+
//
|
|
644
|
+
// 优先级:exclude > deny > allow > 内置名单。`allowUnsafeRoots: true` 保留为兼容,
|
|
645
|
+
// 只放开**内置名单**;deny / exclude 仍然优先。文件系统根永远不能当根(allow 也不行)。
|
|
646
|
+
// ---------------------------------------------------------------------------
|
|
647
|
+
|
|
648
|
+
const ROOT_POLICY_FIELDS = ['allow', 'deny', 'exclude']
|
|
649
|
+
|
|
650
|
+
/** 每条告警只打一次:配置在进程内是静态的,重复刷屏没有信息量。 */
|
|
651
|
+
const warnedRootPolicyEntries = new Set()
|
|
652
|
+
|
|
653
|
+
function warnRootPolicyOnce(key, message, warn) {
|
|
654
|
+
if (warnedRootPolicyEntries.has(key)) return
|
|
655
|
+
warnedRootPolicyEntries.add(key)
|
|
656
|
+
const log = typeof warn === 'function' ? warn : console.error
|
|
657
|
+
log(`[dsh-project-memory] ${message}`)
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
function expandHomeEntry(value, home, pathApi) {
|
|
661
|
+
if (value === '~') return home
|
|
662
|
+
if (value.startsWith('~/') || value.startsWith('~\\')) {
|
|
663
|
+
return home ? pathApi.resolve(home, value.slice(2)) : null
|
|
664
|
+
}
|
|
665
|
+
return value
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
function normalizeRootPolicyEntries(list, field, { platform, pathApi, home, warn }) {
|
|
669
|
+
const out = []
|
|
670
|
+
if (list === undefined || list === null) return out
|
|
671
|
+
if (!Array.isArray(list)) {
|
|
672
|
+
warnRootPolicyOnce(
|
|
673
|
+
`shape:${field}`,
|
|
674
|
+
`config.roots.${field} must be an array of absolute paths; ignoring it.`,
|
|
675
|
+
warn,
|
|
676
|
+
)
|
|
677
|
+
return out
|
|
678
|
+
}
|
|
679
|
+
for (const raw of list) {
|
|
680
|
+
if (typeof raw !== 'string') {
|
|
681
|
+
warnRootPolicyOnce(
|
|
682
|
+
`type:${field}:${typeof raw}`,
|
|
683
|
+
`config.roots.${field} contains a non-string entry; ignoring it (only absolute path strings are accepted).`,
|
|
684
|
+
warn,
|
|
685
|
+
)
|
|
686
|
+
continue
|
|
687
|
+
}
|
|
688
|
+
const value = raw.trim()
|
|
689
|
+
if (!value) continue
|
|
690
|
+
const expanded = expandHomeEntry(value, home, pathApi)
|
|
691
|
+
if (expanded === null) {
|
|
692
|
+
warnRootPolicyOnce(
|
|
693
|
+
`home:${field}:${value}`,
|
|
694
|
+
`config.roots.${field} entry ${JSON.stringify(value)} cannot be expanded: the home directory is unavailable.`,
|
|
695
|
+
warn,
|
|
696
|
+
)
|
|
697
|
+
continue
|
|
698
|
+
}
|
|
699
|
+
if (!pathApi.isAbsolute(expanded)) {
|
|
700
|
+
warnRootPolicyOnce(
|
|
701
|
+
`relative:${field}:${value}`,
|
|
702
|
+
`config.roots.${field} entry ignored (not an absolute path): ${JSON.stringify(value)}. ` +
|
|
703
|
+
'Relative paths would be resolved against the host cwd and are unpredictable; use an absolute path or ~/...',
|
|
704
|
+
warn,
|
|
705
|
+
)
|
|
706
|
+
continue
|
|
707
|
+
}
|
|
708
|
+
let abs
|
|
709
|
+
try {
|
|
710
|
+
abs = pathApi.resolve(expanded)
|
|
711
|
+
} catch {
|
|
712
|
+
warnRootPolicyOnce(
|
|
713
|
+
`resolve:${field}:${value}`,
|
|
714
|
+
`config.roots.${field} entry ignored (cannot be resolved): ${JSON.stringify(value)}.`,
|
|
715
|
+
warn,
|
|
716
|
+
)
|
|
717
|
+
continue
|
|
718
|
+
}
|
|
719
|
+
out.push({ abs, key: storeKey(abs, platform), raw: value })
|
|
720
|
+
}
|
|
721
|
+
return out
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
function isCompiledRootPolicy(value) {
|
|
725
|
+
return Boolean(value && typeof value === 'object' && value.__rootPolicy === true)
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
/**
|
|
729
|
+
* 把插件 config 编译成一份可复用的根判定策略。
|
|
730
|
+
*
|
|
731
|
+
* 参数化(platform / pathApi / home / env)是为了在任意平台上验证 Windows 语义,
|
|
732
|
+
* 与 `collectUnsafeRootSets()` 的测试惯例一致;生产路径只用无参形式。
|
|
733
|
+
*
|
|
734
|
+
* @param {object} [config] 插件 config(只读 `config.roots` 与 `config.allowUnsafeRoots`)
|
|
735
|
+
* @param {{platform?: string, pathApi?: object, home?: string|null, env?: object, warn?: Function,
|
|
736
|
+
* allowUnsafe?: boolean, unsafeDirs?: Set<string>, sharedTemp?: Set<string>}} [opts]
|
|
737
|
+
* @returns {object} 策略对象(内部结构,调用方应通过 rootRejection/isUnsafeRoot/isExcludedPath 使用)
|
|
738
|
+
*/
|
|
739
|
+
export function compileRootPolicy(config, opts = {}) {
|
|
740
|
+
const platform = opts.platform || process.platform
|
|
741
|
+
const pathApi = opts.pathApi || path
|
|
742
|
+
const home = Object.prototype.hasOwnProperty.call(opts, 'home') ? opts.home : safeHomedir()
|
|
743
|
+
const warn = opts.warn
|
|
744
|
+
const rawRoots = config && typeof config === 'object' ? config.roots : undefined
|
|
745
|
+
const roots = rawRoots && typeof rawRoots === 'object' && !Array.isArray(rawRoots) ? rawRoots : {}
|
|
746
|
+
if (rawRoots !== undefined && (typeof rawRoots !== 'object' || rawRoots === null || Array.isArray(rawRoots))) {
|
|
747
|
+
warnRootPolicyOnce(
|
|
748
|
+
'shape:roots',
|
|
749
|
+
'config.roots must be an object with `allow` / `deny` / `exclude` arrays; ignoring it.',
|
|
750
|
+
warn,
|
|
751
|
+
)
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
const entries = {}
|
|
755
|
+
for (const field of ROOT_POLICY_FIELDS) {
|
|
756
|
+
entries[field] = normalizeRootPolicyEntries(roots[field], field, { platform, pathApi, home, warn })
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
let builtin = opts.unsafeDirs || null
|
|
760
|
+
let sharedTemp = opts.sharedTemp || null
|
|
761
|
+
if (!builtin || !sharedTemp) {
|
|
762
|
+
// 只有"完全没传模拟参数"时才复用模块级集合。只要显式给了 platform / pathApi /
|
|
763
|
+
// home / tmp / env 中的任一个,就按这些参数重算——否则在 Linux 上模拟 Windows
|
|
764
|
+
// 或换一个 home 时,内置名单会悄悄沿用当前机器的那一份。
|
|
765
|
+
const simulated = ['platform', 'pathApi', 'home', 'tmp', 'env'].some((key) =>
|
|
766
|
+
Object.prototype.hasOwnProperty.call(opts, key),
|
|
767
|
+
)
|
|
768
|
+
if (!simulated && platform === process.platform) {
|
|
769
|
+
builtin = builtin || UNSAFE_DIRS
|
|
770
|
+
sharedTemp = sharedTemp || SHARED_TEMP_DIRS
|
|
771
|
+
} else {
|
|
772
|
+
const sets = collectUnsafeRootSets({
|
|
773
|
+
platform,
|
|
774
|
+
home,
|
|
775
|
+
tmp: Object.prototype.hasOwnProperty.call(opts, 'tmp') ? opts.tmp : os.tmpdir(),
|
|
776
|
+
env: opts.env || process.env,
|
|
777
|
+
pathApi,
|
|
778
|
+
})
|
|
779
|
+
builtin = builtin || sets.unsafe
|
|
780
|
+
sharedTemp = sharedTemp || sets.sharedTemp
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
const allowEntries = new Map(entries.allow.map((e) => [e.key, e.raw]))
|
|
785
|
+
const denyEntries = new Map(entries.deny.map((e) => [e.key, e.raw]))
|
|
786
|
+
return {
|
|
787
|
+
__rootPolicy: true,
|
|
788
|
+
platform,
|
|
789
|
+
pathApi,
|
|
790
|
+
home,
|
|
791
|
+
allowUnsafeRoots: config?.allowUnsafeRoots === true || opts.allowUnsafe === true,
|
|
792
|
+
allow: new Set(allowEntries.keys()),
|
|
793
|
+
deny: new Set(denyEntries.keys()),
|
|
794
|
+
exclude: entries.exclude,
|
|
795
|
+
allowEntries,
|
|
796
|
+
denyEntries,
|
|
797
|
+
builtin,
|
|
798
|
+
sharedTemp,
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
function policyFor(configOrPolicy, opts) {
|
|
803
|
+
if (isCompiledRootPolicy(configOrPolicy)) return configOrPolicy
|
|
804
|
+
return compileRootPolicy(configOrPolicy, opts)
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
/** `parent` 是否等于 `child` 或它的祖先(按路径分隔符,含子树)。 */
|
|
808
|
+
function isInsideKey(parentKey, childKey, sep) {
|
|
809
|
+
if (parentKey === childKey) return true
|
|
810
|
+
const prefix = parentKey.endsWith(sep) ? parentKey : `${parentKey}${sep}`
|
|
811
|
+
return childKey.startsWith(prefix)
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
function excludedEntryForAbs(abs, policy) {
|
|
815
|
+
if (!policy.exclude.length) return null
|
|
816
|
+
let absResolved
|
|
817
|
+
try {
|
|
818
|
+
absResolved = policy.pathApi.resolve(abs)
|
|
819
|
+
} catch {
|
|
820
|
+
return null
|
|
821
|
+
}
|
|
822
|
+
const key = storeKey(absResolved, policy.platform)
|
|
823
|
+
for (const entry of policy.exclude) {
|
|
824
|
+
if (isInsideKey(entry.key, key, policy.pathApi.sep)) return entry
|
|
825
|
+
}
|
|
826
|
+
return null
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
/**
|
|
830
|
+
* 某个文件/目录是否落在 `roots.exclude` 的子树里。
|
|
831
|
+
* @returns {{abs: string, key: string, raw: string}|null} 命中的条目(用于报告),否则 null
|
|
832
|
+
*/
|
|
833
|
+
export function excludedEntryForPath(filePath, configOrPolicy, opts) {
|
|
834
|
+
if (typeof filePath !== 'string' || !filePath) return null
|
|
835
|
+
const policy = policyFor(configOrPolicy, opts)
|
|
836
|
+
let abs
|
|
624
837
|
try {
|
|
625
|
-
|
|
838
|
+
abs = policy.pathApi.resolve(filePath)
|
|
626
839
|
} catch {
|
|
627
|
-
|
|
840
|
+
return null
|
|
628
841
|
}
|
|
629
|
-
|
|
630
|
-
|
|
842
|
+
return excludedEntryForAbs(abs, policy)
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
/** 文案用的「为什么是它」。 */
|
|
846
|
+
function unsafeReason(abs, policy = {}) {
|
|
847
|
+
const platform = policy.platform || process.platform
|
|
848
|
+
const pathApi = policy.pathApi || path
|
|
849
|
+
const key = storeKey(abs, platform)
|
|
850
|
+
const parsed = pathApi.parse(abs)
|
|
851
|
+
if (key === storeKey(parsed.root, platform)) return 'the filesystem root'
|
|
852
|
+
if (policy.home) {
|
|
853
|
+
try {
|
|
854
|
+
if (key === storeKey(pathApi.resolve(policy.home), platform)) return 'your home directory'
|
|
855
|
+
} catch {
|
|
856
|
+
// 家目录不可解析:继续按临时/系统目录归类
|
|
857
|
+
}
|
|
858
|
+
} else {
|
|
859
|
+
try {
|
|
860
|
+
if (key === storeKey(path.resolve(os.homedir()), platform)) return 'your home directory'
|
|
861
|
+
} catch {
|
|
862
|
+
// 同上
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
const shared = policy.sharedTemp || SHARED_TEMP_DIRS
|
|
866
|
+
if (shared.has(key)) return 'the shared temp directory'
|
|
631
867
|
return 'a system directory that is never a project root'
|
|
632
868
|
}
|
|
633
869
|
|
|
634
|
-
/**
|
|
635
|
-
|
|
636
|
-
|
|
870
|
+
/**
|
|
871
|
+
* 根判定的**唯一实现**:返回 null(可用)或一条命中记录。
|
|
872
|
+
*
|
|
873
|
+
* 命中记录带 `kind` / `field` / `entry` / `reason`,调用方据此生成"是哪条命中的、
|
|
874
|
+
* 该改哪个字段"的拒绝文案。优先级在这里一眼可见:exclude → deny → 内置(allow
|
|
875
|
+
* 与 allowUnsafeRoots 只作用于内置名单)→ 文件系统根永远拒绝。
|
|
876
|
+
*
|
|
877
|
+
* @param {string} root 候选根
|
|
878
|
+
* @param {object} [configOrPolicy] 插件 config,或 `compileRootPolicy()` 的返回值
|
|
879
|
+
*/
|
|
880
|
+
export function rootRejection(root, configOrPolicy, opts) {
|
|
881
|
+
const policy = policyFor(configOrPolicy, opts)
|
|
882
|
+
if (typeof root !== 'string' || !root) {
|
|
883
|
+
return { kind: 'invalid', field: null, entry: null, reason: 'not a usable directory path' }
|
|
884
|
+
}
|
|
637
885
|
let abs
|
|
638
886
|
try {
|
|
639
|
-
abs =
|
|
887
|
+
abs = policy.pathApi.resolve(root)
|
|
640
888
|
} catch {
|
|
641
|
-
return
|
|
889
|
+
return { kind: 'invalid', field: null, entry: null, reason: 'not a usable directory path' }
|
|
890
|
+
}
|
|
891
|
+
const platform = policy.platform
|
|
892
|
+
const key = storeKey(abs, platform)
|
|
893
|
+
const parsed = policy.pathApi.parse(abs)
|
|
894
|
+
if (!parsed.dir || key === storeKey(parsed.root, platform)) {
|
|
895
|
+
return { kind: 'filesystem-root', abs, field: null, entry: null, reason: 'the filesystem root' }
|
|
896
|
+
}
|
|
897
|
+
const excluded = excludedEntryForAbs(abs, policy)
|
|
898
|
+
if (excluded) {
|
|
899
|
+
return {
|
|
900
|
+
kind: 'exclude',
|
|
901
|
+
abs,
|
|
902
|
+
field: 'roots.exclude',
|
|
903
|
+
entry: excluded.raw,
|
|
904
|
+
reason: `inside the subtree excluded by ${JSON.stringify(excluded.raw)}`,
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
if (policy.deny.has(key)) {
|
|
908
|
+
return {
|
|
909
|
+
kind: 'deny',
|
|
910
|
+
abs,
|
|
911
|
+
field: 'roots.deny',
|
|
912
|
+
entry: policy.denyEntries.get(key) || null,
|
|
913
|
+
reason: 'listed in roots.deny',
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
if (policy.builtin.has(key) && !policy.allowUnsafeRoots && !policy.allow.has(key)) {
|
|
917
|
+
return { kind: 'builtin', abs, field: 'roots.allow', entry: null, reason: unsafeReason(abs, policy) }
|
|
918
|
+
}
|
|
919
|
+
return null
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
/** 这个目录能否当项目记忆根?纯判定,无副作用。 */
|
|
923
|
+
export function isUnsafeRoot(root, configOrPolicy, opts) {
|
|
924
|
+
return rootRejection(root, configOrPolicy, opts) !== null
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
const CONFIG_LOCATION = 'under `- id: project-memory` → `config:`'
|
|
928
|
+
|
|
929
|
+
/** 把命中记录变成一句可执行的拒绝文案。 */
|
|
930
|
+
function rootRejectionMessage(target, rejection) {
|
|
931
|
+
const head = `Refusing to use ${target} as a project memory root: `
|
|
932
|
+
switch (rejection.kind) {
|
|
933
|
+
case 'filesystem-root':
|
|
934
|
+
return (
|
|
935
|
+
head +
|
|
936
|
+
'it is the filesystem root. That can never be a project memory root; pass a project directory instead.'
|
|
937
|
+
)
|
|
938
|
+
case 'exclude':
|
|
939
|
+
return (
|
|
940
|
+
head +
|
|
941
|
+
`it is inside the subtree excluded by \`roots.exclude\` entry ${JSON.stringify(rejection.entry)}. ` +
|
|
942
|
+
`Remove that entry from \`config.roots.exclude\` ${CONFIG_LOCATION} if this directory should be a root.`
|
|
943
|
+
)
|
|
944
|
+
case 'deny':
|
|
945
|
+
return (
|
|
946
|
+
head +
|
|
947
|
+
`it is listed in \`roots.deny\`${rejection.entry ? ` as ${JSON.stringify(rejection.entry)}` : ''}. ` +
|
|
948
|
+
`Remove that entry from \`config.roots.deny\` ${CONFIG_LOCATION} to allow it.`
|
|
949
|
+
)
|
|
950
|
+
case 'builtin':
|
|
951
|
+
return (
|
|
952
|
+
head +
|
|
953
|
+
`it is ${rejection.reason}, a built-in protected root. Indexing or watching it would walk the whole ` +
|
|
954
|
+
'directory tree (hundreds of thousands of files) and exhaust memory. Pass a project directory instead, ' +
|
|
955
|
+
`or add this exact directory to \`config.roots.allow\` ${CONFIG_LOCATION} if you really mean it ` +
|
|
956
|
+
'(or set `allowUnsafeRoots: true` to allow every built-in protected directory).'
|
|
957
|
+
)
|
|
958
|
+
default:
|
|
959
|
+
return head + `${rejection.reason}. Pass an absolute project directory instead.`
|
|
642
960
|
}
|
|
643
|
-
const parsed = path.parse(abs)
|
|
644
|
-
if (!parsed.dir || abs === parsed.root) return true
|
|
645
|
-
return UNSAFE_DIRS.has(storeKey(abs))
|
|
646
961
|
}
|
|
647
962
|
|
|
648
963
|
export class UnsafeRootError extends Error {
|
|
649
|
-
constructor(root, requested) {
|
|
964
|
+
constructor(root, requested, options = {}) {
|
|
650
965
|
const target = requested && String(requested).trim() ? String(requested) : String(root)
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
'Indexing or watching it would walk the whole directory tree (hundreds of thousands of files) and exhaust memory. ' +
|
|
654
|
-
'Pass a project directory instead, or set allowUnsafeRoots: true if you really mean it.',
|
|
655
|
-
)
|
|
966
|
+
const rejection = options.rejection || rootRejection(root, options.config)
|
|
967
|
+
super(rootRejectionMessage(target, rejection))
|
|
656
968
|
this.name = 'UnsafeRootError'
|
|
657
969
|
this.root = root
|
|
970
|
+
this.code = rejection.kind
|
|
971
|
+
this.kind = rejection.kind
|
|
972
|
+
this.reason = rejection.reason
|
|
973
|
+
this.field = rejection.field
|
|
974
|
+
this.entry = rejection.entry
|
|
658
975
|
}
|
|
659
976
|
}
|
|
660
977
|
|
|
661
978
|
/**
|
|
662
979
|
* 校验「这个根可以当项目记忆根」。所有把目录当根写盘的入口都必须先过这一关:
|
|
663
980
|
* 写盘前拒绝,比事后清理 `.dsh-project-memory` 便宜得多。
|
|
981
|
+
*
|
|
982
|
+
* `allowUnsafe` 是旧的内部兼容参数,语义等同 `allowUnsafeRoots: true`——只放开内置
|
|
983
|
+
* 名单,绝不会越过 `roots.deny` / `roots.exclude`。
|
|
664
984
|
*/
|
|
665
|
-
export function assertSafeRoot(root, { requested = root, allowUnsafe = false } = {}) {
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
985
|
+
export function assertSafeRoot(root, { requested = root, allowUnsafe = false, config } = {}) {
|
|
986
|
+
const policy = isCompiledRootPolicy(config)
|
|
987
|
+
? (allowUnsafe && !config.allowUnsafeRoots ? { ...config, allowUnsafeRoots: true } : config)
|
|
988
|
+
: compileRootPolicy(config, { allowUnsafe })
|
|
989
|
+
const rejection = rootRejection(root, policy)
|
|
990
|
+
if (!rejection) return root
|
|
991
|
+
throw new UnsafeRootError(root, requested, { rejection })
|
|
669
992
|
}
|
|
670
993
|
|
|
671
994
|
export function resolveIndexRoot(exec, explicitRoot) {
|
|
@@ -770,11 +1093,16 @@ function nearestMarker(absPath, markers, isUnsafe) {
|
|
|
770
1093
|
/**
|
|
771
1094
|
* 项目根推导(**只认标记与显式声明,绝不从文件路径兜底**)。
|
|
772
1095
|
*
|
|
1096
|
+
* `roots.exclude` 在这条链路里是最强的否定:文件落在被排除的子树里 → 直接 null,
|
|
1097
|
+
* 不再向上找标记,也不会退回会话工作目录(那棵树本来就不该进任何索引)。
|
|
1098
|
+
*
|
|
773
1099
|
* @param {string} filePath 目标文件(也接受目录内探针文件路径)
|
|
774
|
-
* @param {{ extraRoots?: Iterable<string>, sessionRoot?: string|null, isUnsafe?: (dir: string) => boolean
|
|
1100
|
+
* @param {{ extraRoots?: Iterable<string>, sessionRoot?: string|null, isUnsafe?: (dir: string) => boolean,
|
|
1101
|
+
* config?: object, policy?: object }} [opts]
|
|
775
1102
|
* `extraRoots`:显式登记过的根(watch_repo / watchManager)。
|
|
776
1103
|
* `sessionRoot`:会话工作目录,作为**最后**一级推定——仅当文件确实在它里面、
|
|
777
1104
|
* 且它是安全目录时采用。
|
|
1105
|
+
* `config`:插件 config;`roots.deny` / `roots.exclude` / `roots.allow` 由此生效。
|
|
778
1106
|
* `isUnsafe`:危险根判定,默认 `isUnsafeRoot`。可注入是为了让"被拒前缀里有一个合法
|
|
779
1107
|
* `.git`"这条反直觉输入能在任意平台上用一个临时目录复现(`/opt/homebrew` 正是被
|
|
780
1108
|
* `.git` 主动选中的,不是兜底误判——issue #5 的现场复核结论)。
|
|
@@ -782,13 +1110,21 @@ function nearestMarker(absPath, markers, isUnsafe) {
|
|
|
782
1110
|
*/
|
|
783
1111
|
export function findProjectRoot(filePath, opts = {}) {
|
|
784
1112
|
if (typeof filePath !== 'string' || !filePath) return null
|
|
785
|
-
const
|
|
1113
|
+
const policy = isCompiledRootPolicy(opts.policy)
|
|
1114
|
+
? opts.policy
|
|
1115
|
+
: isCompiledRootPolicy(opts.config)
|
|
1116
|
+
? opts.config
|
|
1117
|
+
: compileRootPolicy(opts.config, { allowUnsafe: opts.allowUnsafe === true })
|
|
1118
|
+
const isUnsafe = typeof opts.isUnsafe === 'function'
|
|
1119
|
+
? opts.isUnsafe
|
|
1120
|
+
: (dir) => rootRejection(dir, policy) !== null
|
|
786
1121
|
let abs
|
|
787
1122
|
try {
|
|
788
1123
|
abs = path.resolve(filePath)
|
|
789
1124
|
} catch {
|
|
790
1125
|
return null
|
|
791
1126
|
}
|
|
1127
|
+
if (excludedEntryForAbs(abs, policy)) return null
|
|
792
1128
|
const explicit = longestRootContaining(opts.extraRoots || [], abs)
|
|
793
1129
|
if (explicit) return isUnsafe(explicit) ? null : explicit
|
|
794
1130
|
|
|
@@ -803,11 +1139,12 @@ export function findProjectRoot(filePath, opts = {}) {
|
|
|
803
1139
|
/**
|
|
804
1140
|
* **会话记忆根**:本插件所有"这个会话的记忆放哪"的唯一答案。
|
|
805
1141
|
* 声明优先(标记)→ 会话工作目录(安全时)→ null(家目录/系统目录,且没有标记)。
|
|
1142
|
+
* `config` 里的 `roots.*` 与 `allowUnsafeRoots` 与工具侧共用同一套判定。
|
|
806
1143
|
*/
|
|
807
|
-
export function resolveProjectMemoryRoot(cwd) {
|
|
1144
|
+
export function resolveProjectMemoryRoot(cwd, config) {
|
|
808
1145
|
const base = resolveDir(cwd) || resolveDir(process.cwd())
|
|
809
1146
|
if (!base) return null
|
|
810
|
-
return findProjectRoot(path.join(base, PROJECT_PROBE), { sessionRoot: base })
|
|
1147
|
+
return findProjectRoot(path.join(base, PROJECT_PROBE), { sessionRoot: base, config })
|
|
811
1148
|
}
|
|
812
1149
|
|
|
813
1150
|
/**
|
|
@@ -819,13 +1156,14 @@ export function resolveSafeIndexRoot(exec, explicitRoot, config) {
|
|
|
819
1156
|
const allowUnsafe = config?.allowUnsafeRoots === true
|
|
820
1157
|
const explicit = explicitRoot && String(explicitRoot).trim() ? String(explicitRoot) : null
|
|
821
1158
|
if (explicit) {
|
|
822
|
-
return assertSafeRoot(path.resolve(explicit), { requested: explicit, allowUnsafe })
|
|
1159
|
+
return assertSafeRoot(path.resolve(explicit), { requested: explicit, allowUnsafe, config })
|
|
823
1160
|
}
|
|
824
1161
|
const cwd = resolveIndexRoot(exec)
|
|
825
|
-
const root = resolveProjectMemoryRoot(cwd)
|
|
1162
|
+
const root = resolveProjectMemoryRoot(cwd, config)
|
|
826
1163
|
if (root) return root
|
|
827
|
-
|
|
828
|
-
|
|
1164
|
+
// allowUnsafeRoots 只放开内置名单;cwd 被 deny / exclude / 文件系统根命中时仍然拒绝。
|
|
1165
|
+
if (allowUnsafe && !rootRejection(cwd, config)) return cwd
|
|
1166
|
+
throw new UnsafeRootError(cwd, cwd, { config })
|
|
829
1167
|
}
|
|
830
1168
|
|
|
831
1169
|
/** 尽力而为的会话记忆根:拿不到就返回 null(用于审计镜像这类旁路,不抛错)。 */
|
package/src/watch.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { existsSync, statSync } from 'node:fs'
|
|
2
2
|
import path from 'node:path'
|
|
3
|
-
import {
|
|
3
|
+
import { listProjectFiles, memoryDirName, memoryRootFor, relativePath, rootRejection, scanLimits, storeKey } from './util/fs.js'
|
|
4
4
|
import { OVERSIZE, UNCHANGED, commitFileUpdates, fileKind, planFileIndex, toFileUpdate } from './index-pipeline.js'
|
|
5
5
|
import { ProjectMemoryStore } from './store.js'
|
|
6
6
|
import { onFileChanged, isTypeScriptFile } from './enhancer.js'
|
|
@@ -36,7 +36,10 @@ export class WatchManager {
|
|
|
36
36
|
return best
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
-
/**
|
|
39
|
+
/**
|
|
40
|
+
* 危险根是否被显式放行(兼容旧调用点;真正的判定统一走 rootRejection)。
|
|
41
|
+
* 注意:这个开关只放开内置名单,`roots.deny` / `roots.exclude` 仍然优先。
|
|
42
|
+
*/
|
|
40
43
|
unsafeAllowed() {
|
|
41
44
|
return this.config?.allowUnsafeRoots === true
|
|
42
45
|
}
|
|
@@ -45,7 +48,7 @@ export class WatchManager {
|
|
|
45
48
|
const cwd = process.cwd()
|
|
46
49
|
// cwd 是家目录/系统目录时直接跳过:旧顺序是「先 load 再判断」,而历史遗留的超大 store
|
|
47
50
|
// 光读盘就能 OOM —— 那恰恰是 issue #5 的报告者重启后会撞上的场景。
|
|
48
|
-
if (
|
|
51
|
+
if (rootRejection(cwd, this.config)) return
|
|
49
52
|
// 用 load() 的返回值:storeCache 命中时 load() 返回的是缓存实例,忽略返回值会拿到空 store
|
|
50
53
|
const store = new ProjectMemoryStore(memoryRootFor(cwd, this.config.memoryDir)).load()
|
|
51
54
|
if (existsSync(store.dir)) {
|
|
@@ -53,10 +56,10 @@ export class WatchManager {
|
|
|
53
56
|
for (const root of [...store.watchlist]) {
|
|
54
57
|
if (typeof root !== 'string' || !root) continue
|
|
55
58
|
// 自愈剔除两类条目:已不存在的根(每轮白跑,还会把目录重新 mkdir 出来),
|
|
56
|
-
//
|
|
57
|
-
//
|
|
58
|
-
//
|
|
59
|
-
if (!existsSync(root) || (
|
|
59
|
+
// 以及按当前配置不能整体监听的根(内置名单 / roots.deny / roots.exclude)。
|
|
60
|
+
// 后者同时**修复历史遗留**与"新增 deny 后 watch.json 仍留着旧根":下一次启动
|
|
61
|
+
// 就会自动摘掉,不需要用户手删 watch.json。
|
|
62
|
+
if (!existsSync(root) || rootRejection(root, this.config)) {
|
|
60
63
|
store.removeWatch(root)
|
|
61
64
|
dropped++
|
|
62
65
|
continue
|
|
@@ -71,8 +74,9 @@ export class WatchManager {
|
|
|
71
74
|
// 根目录不存在就拒绝:否则每轮 poll 都会 commit → save → mkdirSync,
|
|
72
75
|
// 把一条历史遗留、已被删除的 watchlist 条目重新「创建」出来。
|
|
73
76
|
if (!existsSync(root)) return false
|
|
74
|
-
// 文件系统根 / 家目录 /
|
|
75
|
-
|
|
77
|
+
// 文件系统根 / 家目录 / 系统前缀 / roots.deny 不整体监听(它们的子目录允许),
|
|
78
|
+
// roots.exclude 下的目录同样不监听;除非配置显式放行(仅内置名单可放行)。
|
|
79
|
+
if (rootRejection(root, this.config)) return false
|
|
76
80
|
if (!this.roots.has(root)) {
|
|
77
81
|
// **不在这里 load()**:`restorePersisted()` 会对 cwd store 的整条 watchlist 逐个 addRoot,
|
|
78
82
|
// 急切读盘等于「watch 过多少个根,启动就同步读多少个 store 的全部 shard」——一个万文件
|
|
@@ -209,6 +213,7 @@ export class WatchManager {
|
|
|
209
213
|
const { files, truncated, capped, skipped: nestedRoots, unreadable } = listProjectFiles(root, {
|
|
210
214
|
...scanLimits(this.config),
|
|
211
215
|
nestedStoreName: memoryDirName(this.config),
|
|
216
|
+
config: this.config,
|
|
212
217
|
})
|
|
213
218
|
if (nestedRoots.length && !this._nestedStoreWarned.has(root)) {
|
|
214
219
|
// 同上,只提示一次。这里同时说明"旧副本会被本轮清掉"——升级后的存量重复就是这么收敛的。
|