@yolk_vat-y/dsh-project-memory 0.6.7 → 0.6.8
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 +25 -0
- package/README.md +5 -6
- package/README.zh-CN.md +5 -6
- package/client/client.js +109 -132
- package/client/client.js.map +1 -1
- package/package.json +2 -2
- package/src/index-pipeline.js +26 -7
- package/src/lazy.js +193 -43
- package/src/store.js +22 -3
- package/src/tools/index-doc.js +11 -1
- package/src/tools/index-repo.js +5 -2
- package/src/util/fs.js +77 -12
- package/src/watch.js +3 -0
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.8",
|
|
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/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",
|
|
23
|
+
"test": "node test/run-test.mjs && node test/taskbridge.test.mjs && node test/insight-store.test.mjs && node test/reflection-pipeline.test.mjs && node test/auto-inject.test.mjs && node test/insight-actions.test.mjs && node test/insight-paging.test.mjs && node test/config-schema.test.mjs && node test/host-contract.test.mjs && node test/session-dir.test.mjs && node test/llm-route.test.mjs && node test/doc-index.test.mjs && node test/chunker.test.mjs && node test/client-hints.test.mjs && node test/client-paging.test.mjs && node test/client-task-sync.test.mjs && node test/recall.test.mjs && node test/recall-vector-fusion.test.mjs && node test/vector-index.test.mjs && node test/readiness.test.mjs && node test/insight-derive.test.mjs && node test/readiness-eval.test.mjs && node test/ops.test.mjs && node test/injection-audit.test.mjs && node test/signal-source.test.mjs && node test/skill.test.mjs && node test/injection-budget.test.mjs && node test/injection-scenarios.test.mjs && node test/bugfix-0.5.7.test.mjs && node test/client-icons.test.mjs && node test/client-slash.test.mjs && node test/client-toolview.test.mjs && node test/workflow-command.test.mjs && node test/client-session-id.test.mjs && node test/client-degraded.test.mjs && node test/watch-idle.test.mjs && node test/citation-paths.test.mjs && node test/task-view.test.mjs && node test/root-guards.test.mjs && node test/root-policy.test.mjs && node test/gitignore-index.test.mjs && node test/store-gitignore.test.mjs && node test/atomic-write.test.mjs && node test/store-cache.test.mjs && node test/store-concurrent.test.mjs && node test/store-lock.test.mjs && node test/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",
|
|
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",
|
package/src/index-pipeline.js
CHANGED
|
@@ -42,21 +42,39 @@ function exceedsSizeCap(size, config) {
|
|
|
42
42
|
* key 为 UNSUPPORTED / OVERSIZE / UNCHANGED / DROP / WRITE 之一。
|
|
43
43
|
* @param {object} args
|
|
44
44
|
* @param {number} [args.size] 调用方已 statSync 时传入,避免重复 stat。
|
|
45
|
+
* @param {number} [args.mtimeMs] 调用方已 statSync 时传入;与 `record.mtimeMs` 构成"未改"快路径。
|
|
45
46
|
* @param {boolean} [args.force] index_repo 的 reindex:忽略哈希跳过。
|
|
46
47
|
*/
|
|
47
|
-
export async function planFileIndex({ rel, filePath, kind, config, record, existingEntries = [], size, force = false }) {
|
|
48
|
+
export async function planFileIndex({ rel, filePath, kind, config, record, existingEntries = [], size, mtimeMs, force = false }) {
|
|
48
49
|
if (!kind) return { key: UNSUPPORTED }
|
|
49
|
-
|
|
50
|
+
let fileSize = size
|
|
51
|
+
let fileMtime = mtimeMs
|
|
52
|
+
if (typeof fileSize !== 'number' || typeof fileMtime !== 'number') {
|
|
53
|
+
const st = statSync(filePath)
|
|
54
|
+
if (typeof fileSize !== 'number') fileSize = st.size
|
|
55
|
+
if (typeof fileMtime !== 'number') fileMtime = st.mtimeMs
|
|
56
|
+
}
|
|
50
57
|
if (exceedsSizeCap(fileSize, config)) return { key: OVERSIZE }
|
|
51
58
|
|
|
52
|
-
// 单次读盘:同一 buffer 供内容哈希与正文解码使用(未变更的文件不解码)。
|
|
53
|
-
const { hash, buffer } = readFileForIndex(filePath)
|
|
54
59
|
// 旧 store 的 doc 条目缺 terms → 即使哈希未变也重抽一次(一次性回填)。
|
|
55
60
|
const backfill = kind === 'doc' && docEntriesNeedBackfill(existingEntries)
|
|
56
|
-
|
|
61
|
+
// 快路径:mtime + size 都没动就不读盘、不哈希。懒索引由 `fs/observed` 触发,重复读同一个
|
|
62
|
+
// 文件不该每次整读 + sha256。代价与 make/tsc 同一取舍(rsync -t 保留 mtime 的还原察觉不到,
|
|
63
|
+
// 需要时用 reindex: true 强制重读)。
|
|
64
|
+
if (!force && !backfill && record && typeof record.mtimeMs === 'number' && record.mtimeMs === fileMtime && record.size === fileSize) {
|
|
65
|
+
return { key: UNCHANGED }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// 单次读盘:同一 buffer 供内容哈希与正文解码使用(未变更的文件不解码)。
|
|
69
|
+
const { hash, buffer } = readFileForIndex(filePath)
|
|
70
|
+
if (!force && record && record.sha256 === hash && !backfill) {
|
|
71
|
+
// 内容没变但 mtime 变了(touch / checkout / 还原):把新 mtime 记回去,否则快路径永远命不中,
|
|
72
|
+
// 每次扫描都要重新整读这个文件。调用方负责 `refreshMtime`。
|
|
73
|
+
return record.mtimeMs === fileMtime ? { key: UNCHANGED } : { key: UNCHANGED, mtimeMs: fileMtime }
|
|
74
|
+
}
|
|
57
75
|
|
|
58
76
|
if (kind === 'code') {
|
|
59
|
-
return { key: WRITE, hash, size: fileSize, type: 'code', entries: scanSymbols(rel, filePath, buffer.toString('utf8')) }
|
|
77
|
+
return { key: WRITE, hash, size: fileSize, type: 'code', entries: scanSymbols(rel, filePath, buffer.toString('utf8')), mtimeMs: fileMtime }
|
|
60
78
|
}
|
|
61
79
|
// dump 判定在 buildDocEntries 内部(唯一真源):不可索引的文档返回 null。
|
|
62
80
|
const entries = await buildDocEntries(rel, filePath, {
|
|
@@ -65,7 +83,7 @@ export async function planFileIndex({ rel, filePath, kind, config, record, exist
|
|
|
65
83
|
maxFileSizeMb: config.maxFileSizeMb,
|
|
66
84
|
maxPdfPages: config.maxPdfPages,
|
|
67
85
|
})
|
|
68
|
-
return entries === null ? { key: DROP } : { key: WRITE, hash, size: fileSize, type: 'doc', entries }
|
|
86
|
+
return entries === null ? { key: DROP } : { key: WRITE, hash, size: fileSize, type: 'doc', entries, mtimeMs: fileMtime }
|
|
69
87
|
}
|
|
70
88
|
|
|
71
89
|
/**
|
|
@@ -84,6 +102,7 @@ export function toFileUpdate(rel, plan, record) {
|
|
|
84
102
|
size: plan.size,
|
|
85
103
|
type: plan.type,
|
|
86
104
|
entries: plan.entries,
|
|
105
|
+
mtimeMs: plan.mtimeMs,
|
|
87
106
|
}
|
|
88
107
|
}
|
|
89
108
|
|
package/src/lazy.js
CHANGED
|
@@ -1,6 +1,17 @@
|
|
|
1
1
|
import path from 'node:path'
|
|
2
2
|
import { statSync } from 'node:fs'
|
|
3
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
ROOT_SOURCES,
|
|
5
|
+
excludedEntryForPath,
|
|
6
|
+
findProjectRoot,
|
|
7
|
+
findProjectRootWithSource,
|
|
8
|
+
isGitIgnored,
|
|
9
|
+
isGitIgnoredBatch,
|
|
10
|
+
memoryRootFor,
|
|
11
|
+
relativePath,
|
|
12
|
+
rootRejection,
|
|
13
|
+
storeKey,
|
|
14
|
+
} from './util/fs.js'
|
|
4
15
|
import { DROP, OVERSIZE, UNCHANGED, commitFileUpdates, fileKind, planFileIndex, toFileUpdate } from './index-pipeline.js'
|
|
5
16
|
import { ProjectMemoryStore } from './store.js'
|
|
6
17
|
import { onFileObserved } from './enhancer.js'
|
|
@@ -9,45 +20,184 @@ import { sessionWorkingDir } from './util/session-dir.js'
|
|
|
9
20
|
// 根推导策略已收敛到 util/fs.js(唯一实现)。这里重新导出,保持既有 import 路径可用。
|
|
10
21
|
export { findProjectRoot }
|
|
11
22
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
23
|
+
/**
|
|
24
|
+
* 懒索引的成本结构(9p 代理实测,原生 NTFS 同序只是常数小):
|
|
25
|
+
* `findProjectRoot`(逐层 readdir)18–45ms、`git check-ignore`(起进程)30ms、
|
|
26
|
+
* 整读 + sha256 4ms、save 35ms。前两项**每个文件各付一次**,与文件内容变没变无关。
|
|
27
|
+
*
|
|
28
|
+
* 所以这里做三件事,且都不改变语义:
|
|
29
|
+
* ① 根按目录缓存(5s 上限):一次 flush 里的文件通常同目录,别每个文件走一遍祖先;
|
|
30
|
+
* ② mtime + size 未变 → 不读盘、不问 git(`record.mtimeMs` 由写入侧记下);
|
|
31
|
+
* ③ 一次 flush 只 commit 一次、只起一次 `git check-ignore`。
|
|
32
|
+
* 根缓存只存**由标记推出**的根:`session` 兜底是"这一带还没有标记"的推断,钉 5s 会让
|
|
33
|
+
* `git init` / `npm init` 建出来的项目先落进会话根的 store(真根出现后就是一份重复条目)。
|
|
34
|
+
* 代价只是无标记目录仍按次走一遍祖先(与加缓存之前一致),有标记的项目热路径不受影响。
|
|
35
|
+
* 已有标记的根仍缓存 5s:在它的子目录里 5s 内嵌套新建项目,文件可能先落进父根的 store,
|
|
36
|
+
* 下一次解析就换根、父 store 里的副本留给扫描清理——这是缓存换热路径的必要取舍。
|
|
37
|
+
*/
|
|
38
|
+
const ROOT_CACHE_TTL_MS = 5000
|
|
39
|
+
const ROOT_CACHE_MAX = 4096
|
|
40
|
+
const rootCaches = new WeakMap()
|
|
41
|
+
|
|
42
|
+
function rootCacheFor(config) {
|
|
43
|
+
let cache = rootCaches.get(config)
|
|
44
|
+
if (!cache) {
|
|
45
|
+
cache = new Map()
|
|
46
|
+
rootCaches.set(config, cache)
|
|
47
|
+
}
|
|
48
|
+
return cache
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** 清空根缓存(测试 / 诊断;不传 config 表示全清)。 */
|
|
52
|
+
export function clearRootCache(config) {
|
|
53
|
+
if (config) rootCaches.delete(config)
|
|
54
|
+
else rootCaches.clear()
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function cachedProjectRoot(config, filePath, watchManager, sessionRoot) {
|
|
58
|
+
const cache = rootCacheFor(config)
|
|
59
|
+
const dir = path.dirname(filePath)
|
|
19
60
|
const extraRoots = watchManager ? [...watchManager.roots.keys()] : []
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
const
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
61
|
+
// 会话工作目录 / watch 根集合变了,答案就可能变:都进 key,不做过期以外的失效。
|
|
62
|
+
const key = `${sessionRoot || ''}\u0000${extraRoots.join('\u0001')}\u0000${dir}`
|
|
63
|
+
const hit = cache.get(key)
|
|
64
|
+
const now = Date.now()
|
|
65
|
+
if (hit && now - hit.at < ROOT_CACHE_TTL_MS) return hit.root
|
|
66
|
+
const { root, source } = findProjectRootWithSource(filePath, { extraRoots, sessionRoot, config })
|
|
67
|
+
if (!root) return null
|
|
68
|
+
// 会话根兜底不进缓存:它是"没找到标记"的推断,而"后来才建出标记"正是唯一能让它失效的事件。
|
|
69
|
+
if (source === ROOT_SOURCES.SESSION) return root
|
|
70
|
+
if (cache.size >= ROOT_CACHE_MAX) cache.clear()
|
|
71
|
+
cache.set(key, { root, at: now })
|
|
72
|
+
return root
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* 一批"观察到的文件" → 每个 store 一次 commit。
|
|
77
|
+
*
|
|
78
|
+
* @param {object} config 插件配置
|
|
79
|
+
* @param {{filePath: string, sessionRoot: string|null, watchManager?: object|null}[]} items
|
|
80
|
+
* @returns {Promise<Map<string, boolean>>} filePath → 是否真的写入了条目(未变更 / 被排除 / 失败都是 false)
|
|
81
|
+
*/
|
|
82
|
+
export async function indexObservedBatch(config, items, watchManager = null) {
|
|
83
|
+
const results = new Map()
|
|
84
|
+
/** 需要进一步判定(可能真变了)的候选;未变更的文件在这一步就被排除了。 */
|
|
85
|
+
const candidates = []
|
|
86
|
+
|
|
87
|
+
for (const item of items) {
|
|
88
|
+
const { filePath, sessionRoot } = item
|
|
89
|
+
try {
|
|
90
|
+
const kind = fileKind(path.extname(filePath).toLowerCase())
|
|
91
|
+
if (!kind) {
|
|
92
|
+
results.set(filePath, false)
|
|
93
|
+
continue
|
|
94
|
+
}
|
|
95
|
+
// roots.exclude 是子树级否定:被排除的文件连根都不推导,直接不落任何记忆。
|
|
96
|
+
if (excludedEntryForPath(filePath, config)) {
|
|
97
|
+
results.set(filePath, false)
|
|
98
|
+
continue
|
|
99
|
+
}
|
|
100
|
+
const root = cachedProjectRoot(config, filePath, watchManager, sessionRoot)
|
|
101
|
+
if (!root || rootRejection(root, config)) {
|
|
102
|
+
results.set(filePath, false)
|
|
103
|
+
continue
|
|
104
|
+
}
|
|
105
|
+
const store = new ProjectMemoryStore(memoryRootFor(root, config.memoryDir)).load()
|
|
106
|
+
const rel = storeKey(relativePath(root, filePath))
|
|
107
|
+
const record = store.fileRecord(rel)
|
|
108
|
+
const st = statSync(filePath)
|
|
109
|
+
// 快路径:mtime + size 都没动 → 连 git 都不用问。这是"重复读同一个文件"的主路径。
|
|
110
|
+
// doc 不走这条捷径:旧 store 的 terms 回填条件要看 entries,交给 planFileIndex 判。
|
|
111
|
+
if (kind === 'code' && record && typeof record.mtimeMs === 'number' && record.mtimeMs === st.mtimeMs && record.size === st.size) {
|
|
112
|
+
results.set(filePath, false)
|
|
113
|
+
continue
|
|
114
|
+
}
|
|
115
|
+
candidates.push({ store, root, rel, filePath, kind, record, size: st.size, mtimeMs: st.mtimeMs, gitRel: relativePath(root, filePath) })
|
|
116
|
+
results.set(filePath, false)
|
|
117
|
+
} catch {
|
|
118
|
+
results.set(filePath, false)
|
|
119
|
+
}
|
|
37
120
|
}
|
|
38
|
-
if (plan.key === UNCHANGED || plan.key === OVERSIZE) return false
|
|
39
121
|
|
|
40
|
-
if (
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
122
|
+
if (candidates.length === 0) return results
|
|
123
|
+
|
|
124
|
+
// 按根分组:同一个 flush 里同根的文件共用一次 check-ignore 子进程。
|
|
125
|
+
const byRoot = new Map()
|
|
126
|
+
for (const cand of candidates) {
|
|
127
|
+
let list = byRoot.get(cand.root)
|
|
128
|
+
if (!list) {
|
|
129
|
+
list = []
|
|
130
|
+
byRoot.set(cand.root, list)
|
|
131
|
+
}
|
|
132
|
+
list.push(cand)
|
|
44
133
|
}
|
|
45
134
|
|
|
46
|
-
|
|
47
|
-
|
|
135
|
+
for (const [root, list] of byRoot) {
|
|
136
|
+
// gitignore 只管"**新条目**进不进语料":已经有记录的条目(这次是内容变了要刷新)
|
|
137
|
+
// 不再逐次问 git —— 那是一次进程启动(9p 30ms / 原生 Windows 15–40ms),
|
|
138
|
+
// 而"文件被加进 .gitignore"由 index_repo / watch 的清理路径负责,不该在读路径上判。
|
|
139
|
+
const fresh = list.filter((c) => !c.record)
|
|
140
|
+
let ignored = new Set()
|
|
141
|
+
if (fresh.length > 0) {
|
|
142
|
+
try {
|
|
143
|
+
ignored = isGitIgnoredBatch(root, fresh.map((c) => c.gitRel))
|
|
144
|
+
} catch {
|
|
145
|
+
ignored = new Set()
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
const kept = ignored.size === 0 ? list : list.filter((c) => !ignored.has(c.gitRel))
|
|
149
|
+
if (kept.length === 0) continue
|
|
150
|
+
|
|
151
|
+
const store = kept[0].store
|
|
152
|
+
const updates = []
|
|
153
|
+
let refreshed = false
|
|
154
|
+
for (const cand of kept) {
|
|
155
|
+
try {
|
|
156
|
+
const plan = await planFileIndex({
|
|
157
|
+
rel: cand.rel,
|
|
158
|
+
filePath: cand.filePath,
|
|
159
|
+
kind: cand.kind,
|
|
160
|
+
config,
|
|
161
|
+
record: cand.record,
|
|
162
|
+
existingEntries: store.entries[cand.rel],
|
|
163
|
+
size: cand.size,
|
|
164
|
+
mtimeMs: cand.mtimeMs,
|
|
165
|
+
})
|
|
166
|
+
if (plan.key === UNCHANGED) {
|
|
167
|
+
// 内容没变、只有 mtime 变了:把新 mtime 记回去,否则下次还要整读一遍。
|
|
168
|
+
if (typeof plan.mtimeMs === 'number' && store.refreshMtime(cand.rel, plan.mtimeMs)) refreshed = true
|
|
169
|
+
continue
|
|
170
|
+
}
|
|
171
|
+
if (plan.key === OVERSIZE) continue
|
|
172
|
+
updates.push(toFileUpdate(cand.rel, plan, cand.record))
|
|
173
|
+
if (plan.key !== DROP && plan.type === 'code') onFileObserved(store, cand.rel, cand.filePath, config, root)
|
|
174
|
+
results.set(cand.filePath, plan.key !== DROP)
|
|
175
|
+
} catch {
|
|
176
|
+
// 单文件读盘 / 解析失败不影响同批其它文件。
|
|
177
|
+
results.set(cand.filePath, false)
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
if (watchManager && watchManager.addRoot(root)) {
|
|
182
|
+
// 只有真正新登记的根才持久化:addRoot 拒绝的根(不安全/不存在)不再被无条件
|
|
183
|
+
// addWatch 记进 watch.json —— 那样会造出一个每次启动都复活的"僵尸根"。
|
|
184
|
+
store.addWatch(root)
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
try {
|
|
188
|
+
if (updates.length > 0) commitFileUpdates(store, { updates })
|
|
189
|
+
else if (refreshed) store.commit(() => {})
|
|
190
|
+
} catch (err) {
|
|
191
|
+
console.error(`[dsh-project-memory] lazy index commit failed for ${root}: ${err.message}`)
|
|
192
|
+
}
|
|
48
193
|
}
|
|
49
|
-
|
|
50
|
-
return
|
|
194
|
+
|
|
195
|
+
return results
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export async function indexFile(ctx, config, filePath, watchManager = null, sessionRoot = null) {
|
|
199
|
+
const results = await indexObservedBatch(config, [{ filePath, sessionRoot }], watchManager)
|
|
200
|
+
return results.get(filePath) === true
|
|
51
201
|
}
|
|
52
202
|
|
|
53
203
|
export function codeFirst(paths) {
|
|
@@ -64,15 +214,15 @@ export function setupLazyIndexing(ctx, config, watchManager = null) {
|
|
|
64
214
|
|
|
65
215
|
const flush = async () => {
|
|
66
216
|
timer = null
|
|
67
|
-
const batch = codeFirst([...pending.keys()])
|
|
68
|
-
|
|
217
|
+
const batch = codeFirst([...pending.keys()]).map((filePath) => ({
|
|
218
|
+
filePath,
|
|
219
|
+
sessionRoot: pending.get(filePath) || null,
|
|
220
|
+
}))
|
|
69
221
|
pending.clear()
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
console.error(`[dsh-project-memory] lazy index failed for ${filePath}: ${err.message}`)
|
|
75
|
-
}
|
|
222
|
+
try {
|
|
223
|
+
await indexObservedBatch(config, batch, watchManager)
|
|
224
|
+
} catch (err) {
|
|
225
|
+
console.error(`[dsh-project-memory] lazy index batch failed: ${err.message}`)
|
|
76
226
|
}
|
|
77
227
|
}
|
|
78
228
|
|
|
@@ -97,4 +247,4 @@ export function setupLazyIndexing(ctx, config, watchManager = null) {
|
|
|
97
247
|
ctx.effect(() => () => {
|
|
98
248
|
if (timer) clearTimeout(timer)
|
|
99
249
|
})
|
|
100
|
-
}
|
|
250
|
+
}
|
package/src/store.js
CHANGED
|
@@ -1389,17 +1389,36 @@ export class ProjectMemoryStore {
|
|
|
1389
1389
|
* (调用方让该条目保持未落快照,下一轮重试)。
|
|
1390
1390
|
* 移除条目不经过这里:调用方在 commit 里直接 removeFile(见 index-pipeline.js)。
|
|
1391
1391
|
*/
|
|
1392
|
-
applyFileUpdate(relPath, { expectedHash, hash, entries, type, size }) {
|
|
1392
|
+
applyFileUpdate(relPath, { expectedHash, hash, entries, type, size, mtimeMs }) {
|
|
1393
1393
|
if ((this.fileRecord(relPath)?.sha256 ?? null) !== (expectedHash ?? null)) return false
|
|
1394
|
-
|
|
1394
|
+
const record = {
|
|
1395
1395
|
sha256: hash,
|
|
1396
1396
|
size,
|
|
1397
1397
|
type,
|
|
1398
1398
|
indexedAt: new Date().toISOString(),
|
|
1399
|
-
}
|
|
1399
|
+
}
|
|
1400
|
+
// mtime 是**加速用的缓存**,不是事实:缺了只是退化成每次整读 + 哈希(老 store 的条目就没有)。
|
|
1401
|
+
if (typeof mtimeMs === 'number' && Number.isFinite(mtimeMs)) record.mtimeMs = mtimeMs
|
|
1402
|
+
this.markFile(relPath, record)
|
|
1400
1403
|
this.setEntries(relPath, entries)
|
|
1401
1404
|
return true
|
|
1402
1405
|
}
|
|
1406
|
+
|
|
1407
|
+
/**
|
|
1408
|
+
* 内容没变、只是 mtime 变了(touch / checkout / 还原)时把新 mtime 记回去。
|
|
1409
|
+
* 不记回去的话 `planFileIndex` 的快路径永远命不中,每次扫描都要重新整读一遍这个文件。
|
|
1410
|
+
* 只标脏、不立刻落盘:调用方本来就在一次扫描/一批里,等那一次 save 一起写。
|
|
1411
|
+
* @returns {boolean} 是否真的改了(用于测试与诊断)
|
|
1412
|
+
*/
|
|
1413
|
+
refreshMtime(relPath, mtimeMs) {
|
|
1414
|
+
const rec = this.files[relPath]
|
|
1415
|
+
if (!rec || typeof mtimeMs !== 'number' || !Number.isFinite(mtimeMs)) return false
|
|
1416
|
+
if (rec.mtimeMs === mtimeMs) return false
|
|
1417
|
+
this.files[relPath] = { ...rec, mtimeMs }
|
|
1418
|
+
this._dirtyShards.add(relPath)
|
|
1419
|
+
this._removedShards.delete(relPath)
|
|
1420
|
+
return true
|
|
1421
|
+
}
|
|
1403
1422
|
}
|
|
1404
1423
|
|
|
1405
1424
|
function existsSafe(p) {
|
package/src/tools/index-doc.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
2
2
|
import path from 'node:path'
|
|
3
|
+
import { statSync } from 'node:fs'
|
|
3
4
|
import { assertIndexRoot, assertReadableFile, assertSafeRoot, excludedEntryForPath, findProjectRoot, memoryRootFor, sessionMemoryRootOrNull, sha256OfFile, storeKey } from '../util/fs.js'
|
|
4
5
|
import { buildDocEntries } from '../doc-pipeline.js'
|
|
5
6
|
import { docEntriesNeedBackfill } from '../doc-index.js'
|
|
@@ -57,6 +58,13 @@ export function indexDocTool(ctx, config) {
|
|
|
57
58
|
const store = new ProjectMemoryStore(memoryDir).load()
|
|
58
59
|
|
|
59
60
|
const rel = storeKey(path.relative(root, filePath).split(path.sep).join('/'))
|
|
61
|
+
// mtime 必须在读正文之前取:记录里的 mtime 不能比内容新,否则懒索引的快路径会跳过之后的真实改动。
|
|
62
|
+
let mtimeMs
|
|
63
|
+
try {
|
|
64
|
+
mtimeMs = statSync(filePath).mtimeMs
|
|
65
|
+
} catch {
|
|
66
|
+
mtimeMs = undefined
|
|
67
|
+
}
|
|
60
68
|
const { hash, size } = await sha256OfFile(filePath)
|
|
61
69
|
const existing = store.fileRecord(rel)
|
|
62
70
|
// 与 index_repo/watch/lazy 同一条判据:哈希未变但旧条目缺 terms 时仍要重抽一次(一次性回填)。
|
|
@@ -84,7 +92,9 @@ export function indexDocTool(ctx, config) {
|
|
|
84
92
|
s.setEntries(rel, entries)
|
|
85
93
|
// explicit:这个文件可能是被 .gitignore 排除的(显式索引不受 gitignore 限制),
|
|
86
94
|
// 扫描清单里永远不会有它 —— 清理时靠这个标记区分"没扫到"与"被删了"。
|
|
87
|
-
|
|
95
|
+
const record = { sha256: hash, size, type: 'doc', indexedAt: new Date().toISOString(), explicit: true }
|
|
96
|
+
if (typeof mtimeMs === 'number' && Number.isFinite(mtimeMs)) record.mtimeMs = mtimeMs
|
|
97
|
+
s.markFile(rel, record)
|
|
88
98
|
const preview = entries
|
|
89
99
|
.map((e) => ` - ${e.title} @ ${rel}:${e.sourceLine}`)
|
|
90
100
|
.join('\n')
|
package/src/tools/index-repo.js
CHANGED
|
@@ -50,10 +50,13 @@ export async function indexRepository(ctx, config, root, { reindex = false, allo
|
|
|
50
50
|
if (!kind) continue
|
|
51
51
|
|
|
52
52
|
try {
|
|
53
|
-
const
|
|
53
|
+
const st = statSync(filePath)
|
|
54
|
+
const size = st.size
|
|
54
55
|
const record = store.fileRecord(rel)
|
|
55
|
-
const plan = await planFileIndex({ rel, filePath, kind, config, record, existingEntries: store.entries[rel], size, force: reindex })
|
|
56
|
+
const plan = await planFileIndex({ rel, filePath, kind, config, record, existingEntries: store.entries[rel], size, mtimeMs: st.mtimeMs, force: reindex })
|
|
56
57
|
if (plan.key === UNCHANGED) {
|
|
58
|
+
// 内容没变、mtime 变了(touch / checkout 还原):把新 mtime 记回去,下一次扫描才命得快路径。
|
|
59
|
+
if (typeof plan.mtimeMs === 'number') store.refreshMtime(rel, plan.mtimeMs)
|
|
57
60
|
skipped++
|
|
58
61
|
continue
|
|
59
62
|
}
|
package/src/util/fs.js
CHANGED
|
@@ -617,6 +617,42 @@ export function isGitIgnored(root, filePath) {
|
|
|
617
617
|
}
|
|
618
618
|
}
|
|
619
619
|
|
|
620
|
+
/**
|
|
621
|
+
* 批量版 `isGitIgnored`:一次 `git check-ignore --stdin` 判定一批相对路径。
|
|
622
|
+
* 逐个判定的成本几乎全在**起进程**上(9p 实测 30ms/次、ext4 2.7ms/次,Windows 上更高),
|
|
623
|
+
* 一次懒索引 flush 里往往十几个文件,必须并成一次。
|
|
624
|
+
*
|
|
625
|
+
* @param {string} root 项目根
|
|
626
|
+
* @param {string[]} rels 项目相对路径(`relativePath()` 的形状,`/` 分隔)
|
|
627
|
+
* @returns {Set<string>} 被忽略的那些 rel(原样返回,便于与调用方的 rel 对齐)
|
|
628
|
+
*/
|
|
629
|
+
export function isGitIgnoredBatch(root, rels) {
|
|
630
|
+
const ignored = new Set()
|
|
631
|
+
if (!root || !rels || rels.length === 0) return ignored
|
|
632
|
+
if (!existsSync(path.join(root, '.git'))) return ignored
|
|
633
|
+
if (rels.length === 1) {
|
|
634
|
+
if (isGitIgnored(root, path.join(root, rels[0]))) ignored.add(rels[0])
|
|
635
|
+
return ignored
|
|
636
|
+
}
|
|
637
|
+
try {
|
|
638
|
+
// `-z` 让输入输出都以 NUL 分隔:文件名里带换行/空格也不会错位。
|
|
639
|
+
const out = execFileSync('git', ['-C', root, 'check-ignore', '--stdin', '-z'], {
|
|
640
|
+
input: rels.join('\0') + '\0',
|
|
641
|
+
windowsHide: true,
|
|
642
|
+
stdio: ['pipe', 'pipe', 'ignore'],
|
|
643
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
644
|
+
})
|
|
645
|
+
for (const p of String(out).split('\0')) if (p) ignored.add(p)
|
|
646
|
+
return ignored
|
|
647
|
+
} catch (err) {
|
|
648
|
+
// status 1 = 正常:一条都没被忽略(check-ignore 用退出码表达"有/没有")。
|
|
649
|
+
if (err?.status === 1) return ignored
|
|
650
|
+
// 其它失败(老 git 不支持 --stdin、输入过长、非仓目录):退回逐条判定,语义不变,只是慢。
|
|
651
|
+
for (const rel of rels) if (isGitIgnored(root, path.join(root, rel))) ignored.add(rel)
|
|
652
|
+
return ignored
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
620
656
|
export function isSupportedDoc(ext) {
|
|
621
657
|
return ['.pdf', '.md', '.markdown', '.txt'].includes(ext)
|
|
622
658
|
}
|
|
@@ -1230,17 +1266,29 @@ function resolveDir(dir) {
|
|
|
1230
1266
|
}
|
|
1231
1267
|
}
|
|
1232
1268
|
|
|
1269
|
+
/**
|
|
1270
|
+
* 根来源:显式登记的根 / VCS 标记 / 项目标记 / 会话工作目录兜底。
|
|
1271
|
+
* 调用方(懒索引的根缓存)据此区分"看到的标记"与"还没有标记时的推断"——只有前者能缓存。
|
|
1272
|
+
*/
|
|
1273
|
+
export const ROOT_SOURCES = Object.freeze({
|
|
1274
|
+
EXTRA: 'extra',
|
|
1275
|
+
VCS: 'vcs',
|
|
1276
|
+
PROJECT: 'project',
|
|
1277
|
+
SESSION: 'session',
|
|
1278
|
+
})
|
|
1279
|
+
|
|
1233
1280
|
/**
|
|
1234
1281
|
* 自底向上找最近的根标记。**一次遍历同时看 VCS 与 PROJECT**,语义仍是 VCS 优先:
|
|
1235
1282
|
* 先命中的 VCS 直接返回(它一定最深的);没有 VCS 就返回最深的 PROJECT。每层只 readdir
|
|
1236
1283
|
* 一次(两组标记各走一遍祖先链、每个 marker 一次 existsSync 在 WSL/NTFS 上实测 ~119ms/次)。
|
|
1284
|
+
* @returns {{dir: string, source: 'vcs'|'project'}|null}
|
|
1237
1285
|
*/
|
|
1238
1286
|
function nearestRootByMarkers(absPath, vcsMarkers, projectMarkers, isUnsafe) {
|
|
1239
1287
|
let project = null
|
|
1240
1288
|
let dir = path.dirname(absPath)
|
|
1241
1289
|
for (;;) {
|
|
1242
1290
|
// 撞到危险根边界就停:不把边界当根,也不再向上。已记录的 PROJECT 命中仍有效(在边界下方)。
|
|
1243
|
-
if (isUnsafe(dir)) return project
|
|
1291
|
+
if (isUnsafe(dir)) return project ? { dir: project, source: ROOT_SOURCES.PROJECT } : null
|
|
1244
1292
|
let names = null
|
|
1245
1293
|
try {
|
|
1246
1294
|
names = new Set(readdirSync(dir))
|
|
@@ -1248,11 +1296,11 @@ function nearestRootByMarkers(absPath, vcsMarkers, projectMarkers, isUnsafe) {
|
|
|
1248
1296
|
names = null
|
|
1249
1297
|
}
|
|
1250
1298
|
if (names) {
|
|
1251
|
-
if (vcsMarkers.some((marker) => names.has(marker))) return dir
|
|
1299
|
+
if (vcsMarkers.some((marker) => names.has(marker))) return { dir, source: ROOT_SOURCES.VCS }
|
|
1252
1300
|
if (!project && projectMarkers.some((marker) => names.has(marker))) project = dir
|
|
1253
1301
|
}
|
|
1254
1302
|
const parent = path.dirname(dir)
|
|
1255
|
-
if (parent === dir) return project
|
|
1303
|
+
if (parent === dir) return project ? { dir: project, source: ROOT_SOURCES.PROJECT } : null
|
|
1256
1304
|
dir = parent
|
|
1257
1305
|
}
|
|
1258
1306
|
}
|
|
@@ -1260,13 +1308,17 @@ function nearestRootByMarkers(absPath, vcsMarkers, projectMarkers, isUnsafe) {
|
|
|
1260
1308
|
/**
|
|
1261
1309
|
* 项目根推导(**只认标记与显式声明,绝不从文件路径兜底**)。`roots.exclude` 是最强的否定:
|
|
1262
1310
|
* 文件落在被排除子树里 → 直接 null,不再向上找标记,也不退回会话工作目录。
|
|
1311
|
+
*
|
|
1312
|
+
* 比 `findProjectRoot` 多返回 `source`:调用方需要区分"看到的标记"和"没有标记时的会话目录兜底",
|
|
1313
|
+
* 二者不能同等缓存(见 `src/lazy.js` 的根缓存:兜底是"这一带还没有标记"的推断,项目可能刚建出来)。
|
|
1314
|
+
*
|
|
1263
1315
|
* @param {string} filePath 目标文件(也接受目录内探针文件路径)
|
|
1264
1316
|
* @param {{ extraRoots?: Iterable<string>, sessionRoot?: string|null, isUnsafe?: (dir: string) => boolean,
|
|
1265
1317
|
* config?: object, policy?: object }} [opts] `extraRoots` 显式登记的根;`sessionRoot` 作为**最后**一级推定。
|
|
1266
|
-
* @returns {string|null}
|
|
1318
|
+
* @returns {{root: string|null, source: 'extra'|'vcs'|'project'|'session'|null}}
|
|
1267
1319
|
*/
|
|
1268
|
-
export function
|
|
1269
|
-
if (typeof filePath !== 'string' || !filePath) return null
|
|
1320
|
+
export function findProjectRootWithSource(filePath, opts = {}) {
|
|
1321
|
+
if (typeof filePath !== 'string' || !filePath) return { root: null, source: null }
|
|
1270
1322
|
const policy = isCompiledRootPolicy(opts.policy)
|
|
1271
1323
|
? opts.policy
|
|
1272
1324
|
: isCompiledRootPolicy(opts.config)
|
|
@@ -1279,19 +1331,32 @@ export function findProjectRoot(filePath, opts = {}) {
|
|
|
1279
1331
|
try {
|
|
1280
1332
|
abs = path.resolve(filePath)
|
|
1281
1333
|
} catch {
|
|
1282
|
-
return null
|
|
1334
|
+
return { root: null, source: null }
|
|
1283
1335
|
}
|
|
1284
|
-
if (excludedEntryForAbs(abs, policy)) return null
|
|
1336
|
+
if (excludedEntryForAbs(abs, policy)) return { root: null, source: null }
|
|
1285
1337
|
const explicit = longestRootContaining(opts.extraRoots || [], abs)
|
|
1286
|
-
if (explicit)
|
|
1338
|
+
if (explicit) {
|
|
1339
|
+
return isUnsafe(explicit) ? { root: null, source: null } : { root: explicit, source: ROOT_SOURCES.EXTRA }
|
|
1340
|
+
}
|
|
1287
1341
|
|
|
1288
1342
|
// 标记优先于会话根兜底;VCS 优先于 PROJECT("a marker above the cwd still wins" 是既有契约)。
|
|
1289
1343
|
const byMarker = nearestRootByMarkers(abs, VCS_MARKERS, PROJECT_MARKERS, isUnsafe)
|
|
1290
|
-
if (byMarker) return byMarker
|
|
1344
|
+
if (byMarker) return { root: byMarker.dir, source: byMarker.source }
|
|
1291
1345
|
|
|
1292
1346
|
const session = resolveDir(opts.sessionRoot)
|
|
1293
|
-
if (session && !isUnsafe(session) && isInside(session, abs)) return session
|
|
1294
|
-
return null
|
|
1347
|
+
if (session && !isUnsafe(session) && isInside(session, abs)) return { root: session, source: ROOT_SOURCES.SESSION }
|
|
1348
|
+
return { root: null, source: null }
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
/**
|
|
1352
|
+
* 项目根推导:只要根,语义与 `findProjectRootWithSource` 完全一致。
|
|
1353
|
+
* @param {string} filePath 目标文件(也接受目录内探针文件路径)
|
|
1354
|
+
* @param {{ extraRoots?: Iterable<string>, sessionRoot?: string|null, isUnsafe?: (dir: string) => boolean,
|
|
1355
|
+
* config?: object, policy?: object }} [opts]
|
|
1356
|
+
* @returns {string|null}
|
|
1357
|
+
*/
|
|
1358
|
+
export function findProjectRoot(filePath, opts = {}) {
|
|
1359
|
+
return findProjectRootWithSource(filePath, opts).root
|
|
1295
1360
|
}
|
|
1296
1361
|
|
|
1297
1362
|
/**
|
package/src/watch.js
CHANGED
|
@@ -278,6 +278,7 @@ export class WatchManager {
|
|
|
278
278
|
record,
|
|
279
279
|
existingEntries: store.entries[rel],
|
|
280
280
|
size: stats.size,
|
|
281
|
+
mtimeMs: stats.mtimeMs,
|
|
281
282
|
})
|
|
282
283
|
} catch (err) {
|
|
283
284
|
// 坏文件每轮都会重试:同一个文件的同一个错误只上报一次,否则逐轮刷屏。
|
|
@@ -290,6 +291,8 @@ export class WatchManager {
|
|
|
290
291
|
state.failures.delete(rel)
|
|
291
292
|
// 内容未变 / 体积超限也要落快照:否则 mtime:size 快路径永远命中不了,每次 poll 都要重读全仓。
|
|
292
293
|
if (plan.key === UNCHANGED || plan.key === OVERSIZE) {
|
|
294
|
+
// 内容没变、只有 mtime 变了:把新 mtime 写回条目,让下一轮(及其它入口)的快路径能命中。
|
|
295
|
+
if (plan.key === UNCHANGED && typeof plan.mtimeMs === 'number') store.refreshMtime(rel, plan.mtimeMs)
|
|
293
296
|
state.snapshot[rel] = sig
|
|
294
297
|
continue
|
|
295
298
|
}
|