@yolk_vat-y/dsh-project-memory 0.6.8 → 0.6.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +59 -0
- package/README.md +11 -9
- package/README.zh-CN.md +11 -9
- package/client/client.js +411 -14
- package/client/client.js.map +1 -1
- package/cordis.patch.yml +4 -0
- package/package.json +4 -4
- package/skills/project-memory/SKILL.md +5 -1
- package/skills/project-memory/scripts/pm-digest.mjs +67 -5
- package/src/auto-inject.js +10 -5
- package/src/client/SettingsCard.module.css +185 -0
- package/src/client/client.ts +4 -1
- package/src/client/locales.ts +31 -0
- package/src/client/settings-card.tsx +346 -0
- package/src/commands/insight-actions.js +29 -7
- package/src/commands/tasks.js +1 -1
- package/src/enhancer.js +7 -3
- package/src/index-failures.js +46 -0
- package/src/index.js +36 -11
- package/src/insight-store.js +10 -3
- package/src/lazy.js +25 -5
- package/src/ops.js +13 -0
- package/src/parsers/pdfjs-parser.js +33 -4
- package/src/recall.js +2 -1
- package/src/setup/taskbridge.js +18 -5
- package/src/store.js +190 -78
- package/src/tools/index-doc.js +13 -3
- package/src/tools/index-repo.js +13 -4
- package/src/tools/lesson-tools.js +4 -2
- package/src/tools/query-memory.js +20 -8
- package/src/tools/stats.js +8 -0
- package/src/tools/task-tools.js +4 -0
- package/src/tools/watch-repo.js +14 -8
- package/src/util/config.js +65 -0
- package/src/util/fs.js +121 -17
- package/src/util/search.js +17 -13
- package/src/watch.js +92 -10
package/src/tools/index-repo.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
2
2
|
import path from 'node:path'
|
|
3
3
|
import { statSync } from 'node:fs'
|
|
4
|
-
import { assertIndexRoot, assertSafeRoot, listProjectFiles, memoryDirName, memoryRootFor, relativePath, scanLimits, storeKey } from '../util/fs.js'
|
|
4
|
+
import { assertIndexRoot, assertSafeRoot, listProjectFiles, memoryDirName, memoryRootFor, relativePath, resolveIndexRoot, scanLimits, storeKey } from '../util/fs.js'
|
|
5
5
|
import { DROP, OVERSIZE, UNCHANGED, commitFileUpdates, fileKind, planFileIndex, toFileUpdate } from '../index-pipeline.js'
|
|
6
6
|
import { ProjectMemoryStore } from '../store.js'
|
|
7
7
|
import { onFileIndexed, isTypeScriptFile, enhanceQueueStats } from '../enhancer.js'
|
|
8
|
+
import { listIndexFailures } from '../index-failures.js'
|
|
8
9
|
|
|
9
10
|
/**
|
|
10
11
|
* 每批提交的文件数。旧实现把整棵树的 updates 攒到最后一次性 commit:一次全量扫描的
|
|
@@ -116,6 +117,13 @@ export async function indexRepository(ctx, config, root, { reindex = false, allo
|
|
|
116
117
|
if (failures.length) {
|
|
117
118
|
report += `\nfailed to index ${failures.length} file(s): ${failures.join(', ')}`
|
|
118
119
|
}
|
|
120
|
+
// 后台(watch / 懒索引)的失败不在本次扫描里,但它们同样意味着"这些文件没进语料"。
|
|
121
|
+
// 过去只写日志,用户看不到;这里跟随本次结果一起报出来。
|
|
122
|
+
const background = listIndexFailures(root, 5)
|
|
123
|
+
if (background.count) {
|
|
124
|
+
const detail = background.items.map((i) => `${i.rel} — ${i.message.slice(0, 100)}`).join('; ')
|
|
125
|
+
report += `\n${background.count} file(s) failing in background indexing (watch / lazy): ${detail}`
|
|
126
|
+
}
|
|
119
127
|
|
|
120
128
|
// Trigger TS enhancement for code files (TS/JS only), now that the base entries are on disk.
|
|
121
129
|
const dropsBefore = enhanceQueueStats().dropped
|
|
@@ -142,7 +150,7 @@ export function indexRepoTool(ctx, config) {
|
|
|
142
150
|
root: {
|
|
143
151
|
type: 'string',
|
|
144
152
|
required: true,
|
|
145
|
-
description: '
|
|
153
|
+
description: '项目根(相对路径按会话当前工作目录解析)',
|
|
146
154
|
},
|
|
147
155
|
reindex: {
|
|
148
156
|
type: 'boolean',
|
|
@@ -153,8 +161,9 @@ export function indexRepoTool(ctx, config) {
|
|
|
153
161
|
schema: { type: 'string' },
|
|
154
162
|
render: (_args, value) => [{ type: 'text', text: value }],
|
|
155
163
|
},
|
|
156
|
-
async execute(args) {
|
|
157
|
-
|
|
164
|
+
async execute(args, exec) {
|
|
165
|
+
// 相对 root 按会话当前工作目录解析(不是宿主进程 cwd)——见 util/fs.js 的 resolveIndexRoot。
|
|
166
|
+
const root = resolveIndexRoot(exec, args.root)
|
|
158
167
|
// 透传原始入参:Windows 风格路径在 POSIX 上会被 resolve 成 <cwd>/D:\...,
|
|
159
168
|
// 报错时要点明这是路径风格问题,而不是“目录被删了”。
|
|
160
169
|
assertIndexRoot(root, args.root)
|
|
@@ -12,7 +12,7 @@ import { createWriteCosine } from '../auto-inject.js'
|
|
|
12
12
|
export function lessonTool(config) {
|
|
13
13
|
const kindDesc = 'lesson(坑→改法) | decision(选择+理由) | procedure(步骤) | experience(问题→解法);默认 lesson。'
|
|
14
14
|
const scopeDesc =
|
|
15
|
-
'task(任务私有) | project(项目资产) | global(跨项目)
|
|
15
|
+
'task(任务私有) | project(项目资产) | global(跨项目);默认:绑定任务时 task,否则 project;给 id 时就地更新。'
|
|
16
16
|
return defineTool({
|
|
17
17
|
name: 'save_lesson',
|
|
18
18
|
description:
|
|
@@ -100,7 +100,9 @@ export function lessonTool(config) {
|
|
|
100
100
|
if (!args.id && !raw.title && !raw.pattern && !raw.choice) {
|
|
101
101
|
return truncate(JSON.stringify({ success: false, error: '需要 title / pattern / choice 之一(或给 id 做就地更新)' }), config.maxOutputChars || 8000)
|
|
102
102
|
}
|
|
103
|
-
|
|
103
|
+
// 只有新建才补默认 kind;带 id 的就地更新必须“只覆盖传了的字段”,
|
|
104
|
+
// 否则一次改 fix/reason 会把 decision/procedure 静默降级成 lesson。
|
|
105
|
+
if (!args.id && !INSIGHT_KINDS.includes(raw.kind)) raw.kind = 'lesson'
|
|
104
106
|
|
|
105
107
|
let scope = args.scope
|
|
106
108
|
if (!scope) scope = taskId ? 'task' : 'project'
|
|
@@ -11,6 +11,7 @@ import { createVectorRerank, vectorItemsFrom } from '../vector-index.js'
|
|
|
11
11
|
import { resolveLinkedSymbols } from '../link.js'
|
|
12
12
|
import { truncate } from '../util/text.js'
|
|
13
13
|
import { stepContent, stepStatus } from '../util/task-view.js'
|
|
14
|
+
import { cfgValue } from '../util/config.js'
|
|
14
15
|
function toAbs(root, rel) {
|
|
15
16
|
return path.isAbsolute(rel) ? rel : path.join(root, rel)
|
|
16
17
|
}
|
|
@@ -101,7 +102,7 @@ export function queryMemoryTool(ctx, config) {
|
|
|
101
102
|
const type = args.type || 'all'
|
|
102
103
|
const limit = Math.max(1, Math.min(Number(args.limit) || 8, 20))
|
|
103
104
|
|
|
104
|
-
const queries = config
|
|
105
|
+
const queries = cfgValue(config, 'llmQueryExpansion')
|
|
105
106
|
? await expandQuery(ctx.llm, args.query, config.expansionCount, { route: resolveRoute(exec, config) })
|
|
106
107
|
: [args.query]
|
|
107
108
|
|
|
@@ -247,19 +248,30 @@ export function queryMemoryTool(ctx, config) {
|
|
|
247
248
|
if (type === 'task') {
|
|
248
249
|
const q = (queries[0] || '').toLowerCase()
|
|
249
250
|
const matched = tasks
|
|
250
|
-
.filter((t) =>
|
|
251
|
+
.filter((t) => {
|
|
252
|
+
const title = String(t.title || '').toLowerCase()
|
|
253
|
+
const steps = Array.isArray(t.steps) ? t.steps : []
|
|
254
|
+
const files = Array.isArray(t.files) ? t.files : []
|
|
255
|
+
return !t.archived && (
|
|
256
|
+
title.includes(q)
|
|
257
|
+
|| steps.some((s) => stepContent(s).toLowerCase().includes(q))
|
|
258
|
+
|| files.some((f) => String(f).toLowerCase().includes(q))
|
|
259
|
+
)
|
|
260
|
+
})
|
|
251
261
|
.slice(0, limit)
|
|
252
262
|
if (!matched.length) {
|
|
253
263
|
return `任务记录: 0 套匹配 "${args.query}"(list_tasks 查看全部,select_task 续做)`
|
|
254
264
|
}
|
|
255
265
|
for (const t of matched) {
|
|
256
|
-
const
|
|
257
|
-
const
|
|
258
|
-
const
|
|
259
|
-
|
|
266
|
+
const steps = Array.isArray(t.steps) ? t.steps : []
|
|
267
|
+
const files = Array.isArray(t.files) ? t.files : []
|
|
268
|
+
const done = steps.filter((s) => stepStatus(s) === 'completed').length
|
|
269
|
+
const total = steps.length
|
|
270
|
+
const stepsText = steps.length
|
|
271
|
+
? steps.map((s) => `- [${stepStatus(s) === 'completed' ? 'x' : stepStatus(s) === 'in_progress' ? '*' : ' '}] ${stepContent(s)}`).join('\n')
|
|
260
272
|
: '(无步骤)'
|
|
261
|
-
const
|
|
262
|
-
lines.push(`### ${t.title} (${done}/${total} 完成)\n${stepsText}\n- 文件: ${
|
|
273
|
+
const filesText = files.slice(0, 8).join(', ')
|
|
274
|
+
lines.push(`### ${t.title} (${done}/${total} 完成)\n${stepsText}\n- 文件: ${filesText || '无'}`)
|
|
263
275
|
}
|
|
264
276
|
return truncate(lines.join('\n\n'), config.maxOutputChars)
|
|
265
277
|
}
|
package/src/tools/stats.js
CHANGED
|
@@ -5,6 +5,7 @@ import { cfgInsight, defaultGlobalFile, GlobalStore } from '../insight-store.js'
|
|
|
5
5
|
import { cfgEngine } from '../auto-inject.js'
|
|
6
6
|
import { resolveVectorLayer, vectorIndexSummary, vectorItemsFrom } from '../vector-index.js'
|
|
7
7
|
import { truncate } from '../util/text.js'
|
|
8
|
+
import { listIndexFailures } from '../index-failures.js'
|
|
8
9
|
|
|
9
10
|
const TOP_N = 30
|
|
10
11
|
|
|
@@ -37,6 +38,13 @@ export function statsTool(config) {
|
|
|
37
38
|
`Files indexed: ${overview.files} | Entries: ${overview.entries} | Experience notes: ${overview.experience}`,
|
|
38
39
|
overview.latest ? `Last index: ${overview.latest}` : 'Last index: never',
|
|
39
40
|
]
|
|
41
|
+
// 后台索引失败(watch / 懒索引)过去只写日志:这里跟 store 状态一起报,避免
|
|
42
|
+
// "看着一切正常、实际有文件从没进过语料"。
|
|
43
|
+
const background = listIndexFailures(root, 3)
|
|
44
|
+
if (background.count) {
|
|
45
|
+
const detail = background.items.map((i) => `${i.rel} (${truncate(i.message, 60)})`).join('; ')
|
|
46
|
+
lines.push(`Index failures: ${background.count} file(s) — ${detail}`)
|
|
47
|
+
}
|
|
40
48
|
if (files.length) {
|
|
41
49
|
lines.push('')
|
|
42
50
|
for (const [rel, rec] of files.slice(0, TOP_N)) {
|
package/src/tools/task-tools.js
CHANGED
|
@@ -182,6 +182,10 @@ export function archiveTaskTool(config, host) {
|
|
|
182
182
|
if (task.archived) return truncate(JSON.stringify({ success: false, error: 'Already archived' }), config.maxOutputChars)
|
|
183
183
|
task.archived = true
|
|
184
184
|
task.updatedAt = new Date().toISOString()
|
|
185
|
+
// 归档 = 停止续做:绑定必须在同一事务里清掉,否则本会话(以及别的会话)下一次
|
|
186
|
+
// 注入仍会拿到这张归档任务卡,task 级 insights 也继续可见;下一次 load 的
|
|
187
|
+
// _pruneBindings() 会自愈,但用户已经在中间几步看到了错误状态。
|
|
188
|
+
store.removeBindingsForTask(task.id)
|
|
185
189
|
store.markTasksDirty()
|
|
186
190
|
store.save()
|
|
187
191
|
// 反思钩子:归档即收割最终教训(默认关)
|
package/src/tools/watch-repo.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
2
|
+
import { existsSync } from 'node:fs'
|
|
2
3
|
import path from 'node:path'
|
|
3
|
-
import { assertIndexRoot, assertSafeRoot, memoryRootFor, rootRejection, sessionMemoryRootOrNull } from '../util/fs.js'
|
|
4
|
+
import { assertIndexRoot, assertSafeRoot, memoryRootFor, resolveIndexRoot, rootRejection, sessionMemoryRootOrNull, storeKey } from '../util/fs.js'
|
|
4
5
|
import { ProjectMemoryStore } from '../store.js'
|
|
6
|
+
import { cfgValue } from '../util/config.js'
|
|
5
7
|
|
|
6
8
|
export function watchRepoTool(watchManager, config) {
|
|
7
9
|
return defineTool({
|
|
@@ -12,7 +14,7 @@ export function watchRepoTool(watchManager, config) {
|
|
|
12
14
|
root: {
|
|
13
15
|
type: 'string',
|
|
14
16
|
required: true,
|
|
15
|
-
description: '
|
|
17
|
+
description: '项目根(相对路径按会话当前工作目录解析)',
|
|
16
18
|
},
|
|
17
19
|
watch: {
|
|
18
20
|
type: 'boolean',
|
|
@@ -24,7 +26,7 @@ export function watchRepoTool(watchManager, config) {
|
|
|
24
26
|
render: (_args, value) => [{ type: 'text', text: value }],
|
|
25
27
|
},
|
|
26
28
|
async execute(args, exec) {
|
|
27
|
-
const root =
|
|
29
|
+
const root = resolveIndexRoot(exec, args.root)
|
|
28
30
|
// 不存在的根不写进 watchlist:watch 每轮会 commit → save → mkdirSync,把它重新造出来。
|
|
29
31
|
// 根是**文件**时同样要拦:否则 save() 的 mkdirSync 会抛裸 ENOTDIR。
|
|
30
32
|
// 家目录 / 系统目录 / Homebrew 前缀也不监听:整体轮询扫描会吃满内存(issue #5)。
|
|
@@ -45,7 +47,8 @@ export function watchRepoTool(watchManager, config) {
|
|
|
45
47
|
// 会话根不可用(家目录/系统目录且无标记)时跳过镜像:那会在不该有项目记忆的目录里
|
|
46
48
|
// 造出 watch.json,而 watch.json 一旦落在那里,下次以该目录为 cwd 启动又会把它读回来。
|
|
47
49
|
if (!sessionRoot || !sessionMemoryDir) return
|
|
48
|
-
|
|
50
|
+
// Windows/macOS 大小写不敏感:同一目录的两种写法不能当成两个 store 互相镜像。
|
|
51
|
+
if (storeKey(path.resolve(sessionMemoryDir)) === storeKey(path.resolve(memoryDir))) return
|
|
49
52
|
const sessionStore = new ProjectMemoryStore(sessionMemoryDir).load()
|
|
50
53
|
const removed = sessionStore.removeWatch(root)
|
|
51
54
|
const added = present ? sessionStore.addWatch(root) : false
|
|
@@ -58,7 +61,9 @@ export function watchRepoTool(watchManager, config) {
|
|
|
58
61
|
// (这正是要修的场景),而写它会在家目录里造出 .dsh-project-memory。那份
|
|
59
62
|
// watch.json 现在也没有任何启动路径会读取(restorePersisted 只认会话 cwd),
|
|
60
63
|
// 留着即可;会话侧的镜像条目照常摘掉。
|
|
61
|
-
|
|
64
|
+
// 根可能早已被删除:这时**不能** load/commit,否则 save() 的 mkdirSync 会把
|
|
65
|
+
// watch_repo 刚停掉的路径重新创建出来。watch.json 的清理只对仍存在的根有意义。
|
|
66
|
+
if (existsSync(root) && !rootRejection(root, config)) {
|
|
62
67
|
new ProjectMemoryStore(memoryDir).load().commit((s) => s.removeWatch(root))
|
|
63
68
|
}
|
|
64
69
|
await mirrorSessionWatchlist(false)
|
|
@@ -67,8 +72,9 @@ export function watchRepoTool(watchManager, config) {
|
|
|
67
72
|
new ProjectMemoryStore(memoryDir).load().commit((s) => s.addWatch(root))
|
|
68
73
|
await mirrorSessionWatchlist(true)
|
|
69
74
|
watchManager.addRoot(root)
|
|
70
|
-
|
|
71
|
-
|
|
75
|
+
const interval = Number(cfgValue(config, 'watchInterval'))
|
|
76
|
+
watchManager.start(interval * 1000)
|
|
77
|
+
return `Watching ${root} (interval ${interval}s). Docs/code changes will be re-indexed silently.`
|
|
72
78
|
},
|
|
73
79
|
})
|
|
74
|
-
}
|
|
80
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 配置读取的唯一入口。
|
|
3
|
+
*
|
|
4
|
+
* Config 里标了 `.volatile()` 的字段由宿主注入成 **ref**(`{ get() }`)——这是设置页
|
|
5
|
+
* 「改完立即生效、不重启插件」的代价:同一个 `config` 对象上,volatile 字段是 ref、
|
|
6
|
+
* 其余字段仍是普通值。直接写 `if (config.watch)` 会把 ref 对象当成永远为真(watch 关不掉),
|
|
7
|
+
* 所以所有读取点都走 {@link cfg}。
|
|
8
|
+
*
|
|
9
|
+
* 为什么不用顶层 `inject` 或每次读 `config.x.get()`:ref 与值混在一行会让「这个键是活的吗」
|
|
10
|
+
* 变成隐式知识;`cfgValue()` 两种形状都给同一个答案,改字段的 volatile 属性不需要连带改读取点。
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* 读一个顶层配置字段的**当前值**。
|
|
15
|
+
* @param {object | undefined} config 插件 Config
|
|
16
|
+
* @param {string} key 顶层字段名
|
|
17
|
+
* @returns {*} 字段值;volatile 字段取 `ref.get()`
|
|
18
|
+
*/
|
|
19
|
+
export function cfgValue(config, key) {
|
|
20
|
+
const value = config?.[key]
|
|
21
|
+
return value && typeof value.get === 'function' ? value.get() : value
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
let warnedNoVolatile = false
|
|
25
|
+
/**
|
|
26
|
+
* 把 schema 标成 volatile;宿主 schemastery < 3.18.3 时降级为普通值。
|
|
27
|
+
*
|
|
28
|
+
* `.volatile()` 是 3.18.3 才有的方法,而 peer 范围曾经写成 `^3.18.1`:旧宿主在
|
|
29
|
+
* **模块加载期**执行 `Schema.boolean().default(false).volatile()` 会直接抛 TypeError,插件
|
|
30
|
+
* 整个起不来。这里做一次特性探测:方法不在就原样返回(设置页不可用,但 cfgValue 仍能读值,
|
|
31
|
+
* 插件其余功能正常),并只告警一次。
|
|
32
|
+
* @template T
|
|
33
|
+
* @param {T} schema 任意 schemastery schema
|
|
34
|
+
* @returns {T}
|
|
35
|
+
*/
|
|
36
|
+
export function asVolatile(schema) {
|
|
37
|
+
const method = schema?.volatile
|
|
38
|
+
if (typeof method === 'function') return method.call(schema)
|
|
39
|
+
if (!warnedNoVolatile) {
|
|
40
|
+
warnedNoVolatile = true
|
|
41
|
+
console.warn(
|
|
42
|
+
'[dsh-project-memory] host schemastery has no .volatile() (needs >= 3.18.3); ' +
|
|
43
|
+
'visual settings are unavailable, config values stay static',
|
|
44
|
+
)
|
|
45
|
+
}
|
|
46
|
+
return schema
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 把 `loader/volatile-update` 的路径列表归成顶层字段名集合。
|
|
51
|
+
*
|
|
52
|
+
* 空路径 `[]` 表示整份 Config 都可能变了:返回 `null`(调用方按「全部重读」处理),
|
|
53
|
+
* 而不是一个空集合——空集合会被读成「什么都没变」,正好是相反的结论。
|
|
54
|
+
* @param {readonly (readonly string[])[] | undefined} paths 变更路径
|
|
55
|
+
* @returns {Set<string> | null} 顶层字段名;`null` = 全部
|
|
56
|
+
*/
|
|
57
|
+
export function changedConfigKeys(paths) {
|
|
58
|
+
if (!Array.isArray(paths) || paths.length === 0) return null
|
|
59
|
+
const keys = new Set()
|
|
60
|
+
for (const path of paths) {
|
|
61
|
+
if (!Array.isArray(path) || path.length === 0) return null
|
|
62
|
+
keys.add(path[0])
|
|
63
|
+
}
|
|
64
|
+
return keys
|
|
65
|
+
}
|
package/src/util/fs.js
CHANGED
|
@@ -70,6 +70,18 @@ export function writeJsonAtomic(file, data, { ensureDir = true } = {}) {
|
|
|
70
70
|
}
|
|
71
71
|
}
|
|
72
72
|
|
|
73
|
+
/**
|
|
74
|
+
* 删除文件并对 Windows 的瞬时占用(EPERM/EBUSY/EACCES)重试。
|
|
75
|
+
*
|
|
76
|
+
* 为什么需要:`unlinkSync` 和 `renameSync` 一样会被杀毒/索引器短暂占用。删除失败若被当成
|
|
77
|
+
* "已经没了",删除意图(`forget` / 索引清理)会被静默丢掉,下一次 load 时旧 shard 又会复活。
|
|
78
|
+
* @param {string} file - 目标文件。
|
|
79
|
+
* @throws 真实失败(ENOENT 之外且重试仍失败)时原样抛出。
|
|
80
|
+
*/
|
|
81
|
+
export function unlinkWithRetry(file) {
|
|
82
|
+
return retryTransient(() => unlinkSync(file))
|
|
83
|
+
}
|
|
84
|
+
|
|
73
85
|
/** 本机标识:锁的存活判定只在同机可信(跨机只能退回 mtime)。 */
|
|
74
86
|
const LOCK_HOST = os.hostname()
|
|
75
87
|
const LOCK_FILE = '.write.lock'
|
|
@@ -243,9 +255,9 @@ export function acquireDirLock(dir, { timeoutMs = 2000, staleMs = 10000, hardSta
|
|
|
243
255
|
if (lockIsStale(state, { staleMs, hardLimit, maxHoldMs })) {
|
|
244
256
|
// 只删"刚刚读到的那个内容":两次读之间锁可能已被别人抢到并重写。
|
|
245
257
|
try {
|
|
246
|
-
if (readFileSync(file, 'utf8') === state.text)
|
|
258
|
+
if (readFileSync(file, 'utf8') === state.text) unlinkWithRetry(file)
|
|
247
259
|
} catch {
|
|
248
|
-
//
|
|
260
|
+
// 已被别处回收,或杀毒瞬时占用;下一轮继续判定
|
|
249
261
|
}
|
|
250
262
|
continue
|
|
251
263
|
}
|
|
@@ -275,7 +287,24 @@ function releaseDirLock(file, token) {
|
|
|
275
287
|
} else if (text.trim() !== String(process.pid)) {
|
|
276
288
|
return
|
|
277
289
|
}
|
|
278
|
-
|
|
290
|
+
// 释放失败不能静默:锁文件还在、pid 又是自己,下一次 acquire 会把自己当成活锁
|
|
291
|
+
// (同机 pid 存活默认不回收,save 的 maxHoldMs 是 10 分钟),后续写入会被堵住。
|
|
292
|
+
// 先对 Windows 的 EPERM/EBUSY 做瞬时重试;仍删不掉就把内容改成 pid 0(死进程),
|
|
293
|
+
// 下一次 acquire 能立即判 stale,而不是等 10 分钟。
|
|
294
|
+
try {
|
|
295
|
+
unlinkWithRetry(file)
|
|
296
|
+
} catch {
|
|
297
|
+
try {
|
|
298
|
+
writeFileSync(file, JSON.stringify({
|
|
299
|
+
pid: 0,
|
|
300
|
+
host: LOCK_HOST,
|
|
301
|
+
token: 'released',
|
|
302
|
+
at: new Date().toISOString(),
|
|
303
|
+
}))
|
|
304
|
+
} catch {
|
|
305
|
+
// 连覆盖也失败:只能等 staleMs 兜底,不能因此抛给调用方
|
|
306
|
+
}
|
|
307
|
+
}
|
|
279
308
|
} catch {
|
|
280
309
|
// 已被回收或目录不可写:不影响调用方
|
|
281
310
|
}
|
|
@@ -491,6 +520,8 @@ export function walkDir(root, opts = {}) {
|
|
|
491
520
|
continue
|
|
492
521
|
}
|
|
493
522
|
for (const entry of entries) {
|
|
523
|
+
// 隐藏路径一律不进语料(与 listProjectFiles 的 git 分支同一口径):配置/状态/密钥
|
|
524
|
+
// (`.env`、`.ssh`)默认落在点文件里;作者真要索引就显式 `index_doc`。
|
|
494
525
|
if (entry.name.startsWith('.')) continue
|
|
495
526
|
const full = path.join(dir, entry.name)
|
|
496
527
|
if (entry.isDirectory()) {
|
|
@@ -574,6 +605,11 @@ export function listProjectFiles(root, opts = {}) {
|
|
|
574
605
|
const rel = String(raw).split(path.sep).join('/')
|
|
575
606
|
if (!rel) continue
|
|
576
607
|
const segs = rel.split('/')
|
|
608
|
+
// 与 walkDir 同一口径:隐藏路径(任一段以 `.` 开头)与内置忽略名单都不进语料。
|
|
609
|
+
// 两份清单必须一致,否则同一棵树在 `git init` 前后索引内容会变;隐藏路径默认是
|
|
610
|
+
// 配置/状态/密钥(`.env`、`.ssh`),非 git 目录没有"被跟踪=作者同意"这层信号。
|
|
611
|
+
// 真要索引某个隐藏文件,走显式 `index_doc`(它不受扫描清单限制)。
|
|
612
|
+
if (segs.some((s) => s.startsWith('.'))) continue
|
|
577
613
|
if (segs.some((s) => DEFAULT_IGNORE.has(s))) continue
|
|
578
614
|
const abs = path.join(root, rel)
|
|
579
615
|
// 与 walkDir 同一判据:exclude 是子树级前缀。必须在 maxDepth 之前——被排除文件不该把
|
|
@@ -678,6 +714,17 @@ export function relativePath(root, filePath) {
|
|
|
678
714
|
return path.relative(root, filePath).split(path.sep).join('/')
|
|
679
715
|
}
|
|
680
716
|
|
|
717
|
+
/**
|
|
718
|
+
* 路径里是否有以 `.` 开头的段(与扫描口径一致):隐藏路径默认是配置/状态/密钥,
|
|
719
|
+
* 不进入自动索引面(显式 `index_doc` 仍可索引)。按 `/` 切分后逐段判断,
|
|
720
|
+
* 因此 `.env`、`.github/x.md`、`src/.cache/y.js` 都算隐藏。
|
|
721
|
+
* @param {string} relOrAbs 项目相对或绝对路径
|
|
722
|
+
* @returns {boolean}
|
|
723
|
+
*/
|
|
724
|
+
export function isHiddenPath(relOrAbs) {
|
|
725
|
+
return String(relOrAbs || '').split(/[\\/]/).some((seg) => seg.startsWith('.'))
|
|
726
|
+
}
|
|
727
|
+
|
|
681
728
|
/**
|
|
682
729
|
* `insight.files` 的写入期归一:schema 承诺「项目相对路径」,不校验就会让项目外绝对路径原样落盘。
|
|
683
730
|
* 规则:反斜杠 → `/`、去掉 `./`、去重;项目内绝对路径转相对;其余(项目外绝对、
|
|
@@ -695,6 +742,13 @@ export function normalizeCitationFiles(files, root) {
|
|
|
695
742
|
const value = raw.trim().replace(/\\/g, '/')
|
|
696
743
|
if (!value) continue
|
|
697
744
|
const looksAbsolute = value.startsWith('/') || /^[A-Za-z]:\//.test(value)
|
|
745
|
+
// Windows 盘符路径在 POSIX 上 `path.isAbsolute()` 是 false:不能把它当项目内相对路径
|
|
746
|
+
// 落成 `C:/...`(那会生成一个永远不存在的引用)。真正的 POSIX 绝对路径仍走下面的
|
|
747
|
+
// base/relative 判定,项目外的照常丢弃。
|
|
748
|
+
if (looksAbsolute && !path.isAbsolute(value)) {
|
|
749
|
+
dropped.push(raw)
|
|
750
|
+
continue
|
|
751
|
+
}
|
|
698
752
|
if (base === null && looksAbsolute) {
|
|
699
753
|
dropped.push(raw)
|
|
700
754
|
continue
|
|
@@ -703,13 +757,13 @@ export function normalizeCitationFiles(files, root) {
|
|
|
703
757
|
let rel = value.replace(/^\.\//, '')
|
|
704
758
|
if (abs !== null) {
|
|
705
759
|
const inside = path.relative(base, abs)
|
|
706
|
-
if (inside === '' || inside.startsWith(
|
|
760
|
+
if (inside === '' || inside === '..' || inside.startsWith(`..${path.sep}`) || path.isAbsolute(inside)) {
|
|
707
761
|
dropped.push(raw)
|
|
708
762
|
continue
|
|
709
763
|
}
|
|
710
764
|
rel = inside.split(path.sep).join('/')
|
|
711
765
|
}
|
|
712
|
-
if (!rel || rel.startsWith('
|
|
766
|
+
if (!rel || rel === '..' || rel.startsWith('../')) {
|
|
713
767
|
dropped.push(raw)
|
|
714
768
|
continue
|
|
715
769
|
}
|
|
@@ -724,16 +778,57 @@ export function storeKey(rel, platform = process.platform) {
|
|
|
724
778
|
return platform === 'win32' || platform === 'darwin' ? rel.toLowerCase() : rel
|
|
725
779
|
}
|
|
726
780
|
|
|
727
|
-
export function memoryRootFor(indexRoot, memoryDir) {
|
|
728
|
-
return path.join(indexRoot, memoryDir)
|
|
729
|
-
}
|
|
730
|
-
|
|
731
781
|
/** store 目录名(配置项 `memoryDir`;调用方可能来自工具参数,缺省时兜底成默认值)。 */
|
|
732
782
|
export const DEFAULT_MEMORY_DIR = '.dsh-project-memory'
|
|
733
783
|
|
|
784
|
+
/** 已经告过警的 `memoryDir` 值:同一个坏值在进程里只吵一次。 */
|
|
785
|
+
const warnedMemoryDir = new Set()
|
|
786
|
+
|
|
787
|
+
function defaultMemoryDirWarning(value) {
|
|
788
|
+
if (warnedMemoryDir.has(value)) return
|
|
789
|
+
warnedMemoryDir.add(value)
|
|
790
|
+
console.warn(
|
|
791
|
+
`[dsh-project-memory] memoryDir ${JSON.stringify(value)} must stay inside the project root; `
|
|
792
|
+
+ `using ${DEFAULT_MEMORY_DIR} instead.`,
|
|
793
|
+
)
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
/**
|
|
797
|
+
* `memoryDir` → 真正使用的目录名(读写两侧唯一的归一入口)。
|
|
798
|
+
*
|
|
799
|
+
* 合法值 = **项目根内的一段相对路径**。会让 store 落到根外、或落到根上(`save()` 的自我忽略
|
|
800
|
+
* 随后把整个仓库从 git 视角隐藏)的形态一律回落到默认目录并告警一次:空/空白、`.`、`..`、
|
|
801
|
+
* 含 `..` 段(`a/../b`)、绝对路径(POSIX `/x`、Windows `C:\\x`)。嵌套目录(`a/b`)仍允许——
|
|
802
|
+
* 它仍在根内。空串的兜底在这里收口,`memoryRootFor()` 与 `memoryDirName()` 不再各写一遍。
|
|
803
|
+
*/
|
|
804
|
+
export function safeMemoryDirName(raw, warn = defaultMemoryDirWarning) {
|
|
805
|
+
const value = typeof raw === 'string' ? raw.trim() : ''
|
|
806
|
+
if (!value) return DEFAULT_MEMORY_DIR
|
|
807
|
+
if (
|
|
808
|
+
value === '.' || value === '..'
|
|
809
|
+
|| path.isAbsolute(value)
|
|
810
|
+
|| WINDOWS_ABSOLUTE_PATH.test(value)
|
|
811
|
+
|| value.split(/[\\/]+/).includes('..')
|
|
812
|
+
) {
|
|
813
|
+
warn(value)
|
|
814
|
+
return DEFAULT_MEMORY_DIR
|
|
815
|
+
}
|
|
816
|
+
return value
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
/**
|
|
820
|
+
* 项目根 → store 目录。
|
|
821
|
+
*
|
|
822
|
+
* 空串/空白必须回落到默认目录:`path.join(root, '')` 等于项目根本身,而 `save()` 的自我忽略
|
|
823
|
+
* 会在那里写一个内容为 `*` 的 `.gitignore`(把整个仓库从 git 的视角隐藏),`format.json` /
|
|
824
|
+
* `shards/` 也会污染源码树。`.`, `..` 与绝对路径同理。
|
|
825
|
+
*/
|
|
826
|
+
export function memoryRootFor(indexRoot, memoryDir) {
|
|
827
|
+
return path.join(indexRoot, safeMemoryDirName(memoryDir))
|
|
828
|
+
}
|
|
829
|
+
|
|
734
830
|
export function memoryDirName(config) {
|
|
735
|
-
|
|
736
|
-
return typeof raw === 'string' && raw.trim() ? raw : DEFAULT_MEMORY_DIR
|
|
831
|
+
return safeMemoryDirName(config?.memoryDir)
|
|
737
832
|
}
|
|
738
833
|
|
|
739
834
|
/**
|
|
@@ -1190,12 +1285,20 @@ export function assertSafeRoot(root, { requested = root, allowUnsafe = false, co
|
|
|
1190
1285
|
throw new UnsafeRootError(root, requested, { rejection })
|
|
1191
1286
|
}
|
|
1192
1287
|
|
|
1288
|
+
/**
|
|
1289
|
+
* 解析「当前工作目录」:显式 root 优先,但**相对路径按会话工作目录解析**,而不是宿主的
|
|
1290
|
+
* `process.cwd()`——web profile 里一个进程会服务多个会话,cd 之后两者的 cwd 不是一回事。
|
|
1291
|
+
* 没有显式 root 时返回会话工作目录本身;会话信息缺失(测试 / 老宿主)才退回进程 cwd。
|
|
1292
|
+
* @param {object|null} exec 宿主工具执行上下文(`exec.agent.session`)
|
|
1293
|
+
* @param {string|null} [explicitRoot] 工具参数里的 root,可为绝对或相对路径
|
|
1294
|
+
* @returns {string} 绝对路径
|
|
1295
|
+
*/
|
|
1193
1296
|
export function resolveIndexRoot(exec, explicitRoot) {
|
|
1194
|
-
if (explicitRoot && explicitRoot.trim()) return path.resolve(explicitRoot)
|
|
1195
1297
|
// 会话当前工作目录:0.2.1+ 读 workingDirectory 投影(cd 后会变),老宿主回退 header.cwd。
|
|
1196
1298
|
const sessionCwd = sessionWorkingDir(exec?.agent?.session, { agent: exec?.agent })
|
|
1197
|
-
|
|
1198
|
-
return path.resolve(
|
|
1299
|
+
const base = sessionCwd ? path.resolve(sessionCwd) : path.resolve(process.cwd())
|
|
1300
|
+
if (explicitRoot && String(explicitRoot).trim()) return path.resolve(base, String(explicitRoot))
|
|
1301
|
+
return base
|
|
1199
1302
|
}
|
|
1200
1303
|
|
|
1201
1304
|
// ---------------------------------------------------------------------------
|
|
@@ -1238,7 +1341,7 @@ export function hasProjectMarker(dir) {
|
|
|
1238
1341
|
|
|
1239
1342
|
function isInside(parent, child) {
|
|
1240
1343
|
const rel = path.relative(parent, child)
|
|
1241
|
-
return rel === '' || (!rel.startsWith(
|
|
1344
|
+
return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel))
|
|
1242
1345
|
}
|
|
1243
1346
|
|
|
1244
1347
|
/** 显式登记的根里,包含该文件的**最深**那一个(最长前缀匹配)。 */
|
|
@@ -1375,10 +1478,11 @@ export function resolveProjectMemoryRoot(cwd, config) {
|
|
|
1375
1478
|
export function resolveSafeIndexRoot(exec, explicitRoot, config) {
|
|
1376
1479
|
const allowUnsafe = config?.allowUnsafeRoots === true
|
|
1377
1480
|
const explicit = explicitRoot && String(explicitRoot).trim() ? String(explicitRoot) : null
|
|
1481
|
+
// 显式 root 也走 resolveIndexRoot:相对路径必须按**会话**工作目录解析(见该函数注释)。
|
|
1482
|
+
const cwd = resolveIndexRoot(exec, explicit)
|
|
1378
1483
|
if (explicit) {
|
|
1379
|
-
return assertSafeRoot(
|
|
1484
|
+
return assertSafeRoot(cwd, { requested: explicit, allowUnsafe, config })
|
|
1380
1485
|
}
|
|
1381
|
-
const cwd = resolveIndexRoot(exec)
|
|
1382
1486
|
const root = resolveProjectMemoryRoot(cwd, config)
|
|
1383
1487
|
if (root) return root
|
|
1384
1488
|
// allowUnsafeRoots 只放开内置名单;cwd 被 deny / exclude / 文件系统根命中时仍然拒绝。
|
package/src/util/search.js
CHANGED
|
@@ -3,6 +3,18 @@ import { CYRILLIC_WORD_RE, RU_STOPWORDS, normalizeRuWord, stemRu } from './ru.js
|
|
|
3
3
|
export const CJK_RANGE =
|
|
4
4
|
/[\u3400-\u9fff\uf900-\ufaff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/
|
|
5
5
|
|
|
6
|
+
/**
|
|
7
|
+
* 一段连续的 CJK 字符。分词时用它一次性取出所有段,取代"逐字符 test 再累积"的状态机。
|
|
8
|
+
*
|
|
9
|
+
* 从 `CJK_RANGE` 派生而不是另抄一份字符类:「什么算 CJK」全仓库只该有一个定义,
|
|
10
|
+
* 改字符范围时不会有两处不同步。`u` 让字符类按码点匹配——当前字符集全在 BMP,
|
|
11
|
+
* 输出与逐字符判断一致;将来若要纳入增补平面(U+20000 起),段内的二元组切分
|
|
12
|
+
* 必须一并改成按码点,`test/tokenizer-equivalence.test.mjs` 里有一条哨兵用例会在那时失败。
|
|
13
|
+
*
|
|
14
|
+
* 输出与逐字符实现逐字节一致,由同一条差分测试守住。
|
|
15
|
+
*/
|
|
16
|
+
const CJK_RUN_RE = new RegExp(`${CJK_RANGE.source}+`, 'gu')
|
|
17
|
+
|
|
6
18
|
/**
|
|
7
19
|
* 分词契约的版本号。改 tokenizeRaw 的**输出集合**(新增书写系统、词干、停用词)就要 +1:
|
|
8
20
|
* 落盘的 doc `terms` 是它的产物,旧版本写的 terms 里没有新词项,必须让
|
|
@@ -64,15 +76,6 @@ export function tokenizeRaw(text, { stem = true } = {}) {
|
|
|
64
76
|
if (!text) return []
|
|
65
77
|
const lower = text.toLowerCase()
|
|
66
78
|
const tokens = []
|
|
67
|
-
let cjkRun = ''
|
|
68
|
-
const flushCjk = () => {
|
|
69
|
-
if (cjkRun.length === 1) {
|
|
70
|
-
tokens.push(cjkRun)
|
|
71
|
-
} else {
|
|
72
|
-
for (let i = 0; i < cjkRun.length - 1; i++) tokens.push(cjkRun.slice(i, i + 2))
|
|
73
|
-
}
|
|
74
|
-
cjkRun = ''
|
|
75
|
-
}
|
|
76
79
|
const latin = lower.match(/[a-z0-9_]+/g) || []
|
|
77
80
|
for (const tok of latin) tokens.push(tok)
|
|
78
81
|
// 西里尔(只做了俄语):切词 → 去虚词 → Snowball 词干。
|
|
@@ -85,11 +88,12 @@ export function tokenizeRaw(text, { stem = true } = {}) {
|
|
|
85
88
|
const token = word.length <= 3 || !stem ? word : stemRu(word)
|
|
86
89
|
if (token.length >= 2) tokens.push(token)
|
|
87
90
|
}
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
+
// CJK:按「连续段」结算 —— 段长 1 产单字,段长 ≥2 产全部相邻二元组。
|
|
92
|
+
// 旧实现是逐字符累积 + 遇非 CJK 结算,两者输出逐字节一致(差分测试见上)。
|
|
93
|
+
for (const run of lower.match(CJK_RUN_RE) || []) {
|
|
94
|
+
if (run.length === 1) tokens.push(run)
|
|
95
|
+
else for (let i = 0; i < run.length - 1; i++) tokens.push(run.slice(i, i + 2))
|
|
91
96
|
}
|
|
92
|
-
flushCjk()
|
|
93
97
|
return tokens
|
|
94
98
|
}
|
|
95
99
|
|