@yolk_vat-y/dsh-project-memory 0.6.4 → 0.6.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,138 @@
1
+ #!/usr/bin/env node
2
+ // 项目记忆的体检脚本(零依赖、不调模型、不写盘)。
3
+ //
4
+ // node pm-digest.mjs [项目根] [--json]
5
+ //
6
+ // 面向模型与人类各一半:模型拿它替代"先读三个 JSON 再数数"的多次工具往返;
7
+ // 人拿它看 store 是否异常增长、trigger 覆盖多少、任务是不是全归档了。
8
+ // 只输出计数与少量标题,不打印正文——避免把记忆内容再塞回上下文。
9
+ import { readFileSync, readdirSync, statSync } from 'node:fs'
10
+ import { homedir } from 'node:os'
11
+ import path from 'node:path'
12
+
13
+ const args = process.argv.slice(2)
14
+ const json = args.includes('--json')
15
+ const root = path.resolve(args.find((a) => !a.startsWith('--')) || process.cwd())
16
+ const memoryDir = path.join(root, '.dsh-project-memory')
17
+
18
+ const readJson = (file, fallback) => {
19
+ try {
20
+ return JSON.parse(readFileSync(file, 'utf8'))
21
+ } catch {
22
+ return fallback
23
+ }
24
+ }
25
+ const days = (iso) => {
26
+ const t = Date.parse(iso || '')
27
+ return Number.isFinite(t) ? Math.max(0, Math.round((Date.now() - t) / 86_400_000)) : null
28
+ }
29
+
30
+ function shardStats(dir) {
31
+ try {
32
+ let files = 0
33
+ let bytes = 0
34
+ for (const name of readdirSync(dir)) {
35
+ if (!name.endsWith('.json')) continue
36
+ try {
37
+ const st = statSync(path.join(dir, name))
38
+ if (!st.isFile()) continue
39
+ files++
40
+ bytes += st.size
41
+ } catch {
42
+ /* 分片在统计途中消失:跳过 */
43
+ }
44
+ }
45
+ return { files, bytes }
46
+ } catch {
47
+ return { files: 0, bytes: 0 }
48
+ }
49
+ }
50
+
51
+ function insightStats(items) {
52
+ const kinds = {}
53
+ const scopes = {}
54
+ let archived = 0
55
+ let withTrigger = 0
56
+ let withFiles = 0
57
+ let stale90 = 0
58
+ let lastAt = null
59
+ for (const it of items) {
60
+ if (!it || typeof it !== 'object') continue
61
+ kinds[it.kind || '?'] = (kinds[it.kind || '?'] || 0) + 1
62
+ scopes[it.scope || '?'] = (scopes[it.scope || '?'] || 0) + 1
63
+ if (it.archived) archived++
64
+ if (it.trigger && it.trigger.when) withTrigger++
65
+ if (Array.isArray(it.files) && it.files.length) withFiles++
66
+ const age = days(it.updatedAt || it.createdAt)
67
+ if (age !== null && age > 90) stale90++
68
+ const at = it.updatedAt || it.createdAt
69
+ if (at && (!lastAt || at > lastAt)) lastAt = at
70
+ }
71
+ return { total: items.length, kinds, scopes, archived, withTrigger, withFiles, stale90, lastAt }
72
+ }
73
+
74
+ function taskStats(tasks) {
75
+ let archived = 0
76
+ let steps = 0
77
+ let files = 0
78
+ let withInsights = 0
79
+ const active = []
80
+ for (const t of tasks) {
81
+ if (!t || typeof t !== 'object') continue
82
+ if (t.archived) archived++
83
+ else if (t.title) active.push(String(t.title))
84
+ if (Array.isArray(t.steps)) steps += t.steps.length
85
+ if (Array.isArray(t.files)) files += t.files.length
86
+ if (Array.isArray(t.insights) && t.insights.length) withInsights++
87
+ }
88
+ return { total: tasks.length, archived, active: tasks.length - archived, steps, files, withInsights, activeTitles: active.slice(0, 3) }
89
+ }
90
+
91
+ const insDoc = readJson(path.join(memoryDir, 'insights.json'), null)
92
+ const taskDoc = readJson(path.join(memoryDir, 'tasks.json'), null)
93
+ const binding = readJson(path.join(memoryDir, 'binding.json'), null)
94
+ const globalFile = path.join(homedir(), '.config', 'dsh-project-memory', 'global.json')
95
+ const globalDoc = readJson(globalFile, null)
96
+
97
+ if (!insDoc && !taskDoc) {
98
+ const msg = `no memory store at ${memoryDir} (run index_repo or index_doc first)`
99
+ if (json) process.stdout.write(JSON.stringify({ root, memoryDir, store: false }, null, 2) + '\n')
100
+ else process.stdout.write(msg + '\n')
101
+ process.exit(0)
102
+ }
103
+
104
+ const shards = shardStats(path.join(memoryDir, 'shards'))
105
+ const insights = insightStats((insDoc && insDoc.items) || [])
106
+ const tasks = taskStats((Array.isArray(taskDoc) ? taskDoc : []) || [])
107
+ const summary = {
108
+ root,
109
+ memoryDir,
110
+ store: true,
111
+ shards,
112
+ insights,
113
+ tasks,
114
+ bindings: binding && typeof binding === 'object' ? Object.keys(binding).length : 0,
115
+ global: { items: globalDoc && Array.isArray(globalDoc.items) ? globalDoc.items.length : 0 },
116
+ }
117
+
118
+ if (json) {
119
+ process.stdout.write(JSON.stringify(summary, null, 2) + '\n')
120
+ process.exit(0)
121
+ }
122
+
123
+ const kb = (n) => (n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MB` : `${Math.round(n / 102.4) / 10} KB`)
124
+ const line = (label, value) => process.stdout.write(`${label.padEnd(12)} ${value}\n`)
125
+ line('project', root)
126
+ line('store', `${shards.files} shards · ${kb(shards.bytes)} · ${insights.total} insights · ${tasks.total} tasks`)
127
+ if (insights.total) {
128
+ const kinds = Object.entries(insights.kinds).map(([k, n]) => `${k} ${n}`).join(' · ')
129
+ line('insights', `${kinds}${insights.archived ? ` · archived ${insights.archived}` : ''}`)
130
+ line('triggers', `${insights.withTrigger}/${insights.total} with when · ${insights.withFiles} with files · ${insights.stale90} older than 90d`)
131
+ }
132
+ if (tasks.total) {
133
+ line('tasks', `${tasks.active} active · ${tasks.archived} archived · ${tasks.steps} steps · ${tasks.files} file links`)
134
+ if (tasks.activeTitles.length) line('active', tasks.activeTitles.join(' | '))
135
+ if (tasks.withInsights === 0) line('task memory', 'none — task-scoped insights are not used here')
136
+ }
137
+ line('bindings', `${summary.bindings} session(s) bound`)
138
+ line('global', `${summary.global.items} entries (~/.config/dsh-project-memory/global.json)`)
package/src/audit.js CHANGED
@@ -111,7 +111,13 @@ export function shadowRecordFrom(input) {
111
111
  // **实际用于评分**的查询文本(intent + 写目标的拼合)。它和 `query` 不是一回事:
112
112
  // 写目标驱动的那些步 `query` 是空的、候选却非空。少了这一栏,判据无法离线重放。
113
113
  scoreQuery: typeof input.scoreQuery === 'string' ? input.scoreQuery.slice(0, 300) : '',
114
+ // query 是从哪来的:本步 delta(delta)/ 会话缓存的最后一条真人消息(session)/ 没有(none)。
115
+ // 离线复盘必须先分清"这一步本来就没意图"与"意图取错了来源"。
116
+ querySource: ['delta', 'session'].includes(input.querySource) ? input.querySource : 'none',
114
117
  ops: (Array.isArray(input.ops) ? input.ops : []).slice(0, 12),
118
+ // 人类消息里解析出的**全部**动作词(含被 `PRE_ACTION_OPS` 过滤掉的删除/清理/渲染…)。
119
+ // 留着才能回答"这条为什么没注入",以及"把某类散文动作放回准入后会发生什么"。
120
+ opsIntent: (Array.isArray(input.opsIntent) ? input.opsIntent : []).slice(0, 12),
115
121
  writes: (Array.isArray(input.writes) ? input.writes : []).slice(0, 12),
116
122
  injected: reasons.map((r) => ({ id: r.id, channel: r.channel, why: r.why })),
117
123
  // 查询级支持度:语料能表示查询里多少个词(`terms` 是查询词数)—— 通道级沉默判据用的就是它。
@@ -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, isUnsafeRoot, memoryRootFor, resolveProjectMemoryRoot } from './util/fs.js'
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'
@@ -161,23 +161,34 @@ export async function createWriteCosine(config, { storeDir = null, items = [] }
161
161
  }
162
162
  }
163
163
 
164
+ /**
165
+ * 从一份消息列表里取"人说的话"。
166
+ *
167
+ * 只认 `role=user` **且**(`source.kind === 'user'` 或无 source 的老宿主/测试)。
168
+ * 其它 user 角色的消息不是人说的:`agent-message`(子代理报告 relay)、`subagent-settled`、
169
+ * `tool-jobs`(后台任务完成)、`time-context`、`runtime-context` 都会出现在 claimed delta 里。
170
+ * 实测代价:子代理报告里的"发布/渲染"曾被当成用户意图,触发 `intent:release`(1050 字符)
171
+ * 与 `intent:渲染`(1200 字符)两条无关 procedure。
172
+ *
173
+ * `agent/pre-step` 的 `messages` 是 claimed **delta**,不是完整历史,所以会话中段通常
174
+ * 根本没有真人消息 —— 调用方应回退到每会话缓存(见 `InjectionSessions.humanText`)。
175
+ * @param {object[]} messages
176
+ * @returns {string} 人类消息正文;没有则空串
177
+ */
164
178
  export function lastUserText(messages) {
165
179
  if (!Array.isArray(messages)) return ''
166
- let fallback = ''
167
180
  for (let i = messages.length - 1; i >= 0; i--) {
168
181
  const m = messages[i]
169
182
  if (!m || m.role !== 'user') continue
170
183
  const t = textOf(m)
171
184
  if (!t.trim()) continue
172
- // 真人消息优先:本插件注入的块也是 role=user,若按"最后一条 user"取,
173
- // 上一步的注入块会变成这一步的就绪查询(自激:拿自己注入的内容再检索一遍)。
174
- if (m.source && m.source.kind === 'user') return t.trim()
175
- // 本插件注入的块同样是 role=user。无 source 的老宿主下若把它当兜底查询,
176
- // 就成了"拿自己上一步注入的内容再检索一遍"的自激——正是 isOwnInjection 这道闸要防的。
185
+ // 本插件注入的块也是 role=user:绝不能再拿它当查询(自激)。
177
186
  if (isOwnInjection(m.source)) continue
178
- if (!fallback) fallback = t.trim() // 无 source 的消息(老宿主 / 测试)兜底
187
+ const kind = m.source && m.source.kind
188
+ if (kind && kind !== 'user') continue
189
+ return t.trim()
179
190
  }
180
- return fallback
191
+ return ''
181
192
  }
182
193
 
183
194
  function fingerprint(text) {
@@ -495,7 +506,14 @@ export function buildInjection(opts) {
495
506
  const { query, task, globalStore, cfg } = opts
496
507
  const store = opts.store || null
497
508
  const tags = opts.projectTagsList || []
498
- const ctx = buildReadinessContext({ ...(opts.readiness || { humanText: query || '' }), tags })
509
+ // 就绪上下文可能**已经构建过**(injectForStep 先构建、再传给这里)。二次构建会把第一遍的
510
+ // `actions` 输出当成"调用方声明的动作"重新信任一遍 —— 散文里的 file-delete 会因此绕过
511
+ // PRE_ACTION_OPS 过滤(实测:"清理一下 README 的措辞"仍注入 1200 字符恢复 procedure)。
512
+ // 结构化标记:带 ops + intentOps 的上下文是构建产物,只补 tags,不再重新归一。
513
+ const built = opts.readiness && Array.isArray(opts.readiness.ops) && Array.isArray(opts.readiness.intentOps)
514
+ const ctx = built
515
+ ? { ...opts.readiness, tags: [...new Set([...(opts.readiness.tags || []), ...tags])] }
516
+ : buildReadinessContext({ ...(opts.readiness || { humanText: query || '' }), tags })
499
517
  const labels = []
500
518
  const reasons = []
501
519
  const dropped = []
@@ -637,6 +655,10 @@ class InjectionSessions {
637
655
  // 反应窗口:本会话最近观察到的 tool/call(参数里有 git commit / npm publish / 改动的路径)。
638
656
  // 宿主没有"工具执行前拦截"钩子,所以这是 pre-step 之外唯一能拿到的动作事实。
639
657
  this.observed = cache(() => [])
658
+ // 本会话最后一条**真人**消息。`agent/pre-step` 拿到的是 claimed delta,会话中段通常没有
659
+ // 真人消息,于是"本步的意图"会退化成子代理报告 / job 通知 / 时间快照里的词(实测 386 步里
660
+ // 只有 31 步有真人 query,其余全是通知)。意图必须是会话状态,不是这一步恰好收到的文本。
661
+ this.humanText = cache()
640
662
  // 本会话是否已通告"记忆根是推定的"(会话工作目录,无项目标记)。状态声明只发一次。
641
663
  this.rootNoticed = cache(() => false)
642
664
  this._all = Object.values(this)
@@ -647,13 +669,29 @@ class InjectionSessions {
647
669
  }
648
670
  }
649
671
 
650
- /** 记录会话里的 tool/call:ops.js 从这些参数解析出 op / 写目标 / 主机。 */
672
+ /**
673
+ * 记录会话里的两类事实:
674
+ * - `user/message`(**真人的**)→ 每会话最后一条人类消息。它是会话状态,不是本步增量;
675
+ * - `tool/call` → 最近 8 次调用,ops.js 从结构化参数解析 op / 写目标 / 主机。
676
+ *
677
+ * 两者都只从**事件**里来,不再把任意工具的参数拼成文本再解析(那会让 subagent 提示词里
678
+ * 的"删除/迁移"变成父会话的动作,实测存活 8 步)。
679
+ */
651
680
  function installCallObserver(ctx, sessions) {
652
681
  ctx.on('session/event', (session, event) => {
653
682
  try {
654
- if (!event || event.type !== 'tool/call') return
655
683
  const sessionId = session && session.id
656
- if (!sessionId) return
684
+ if (!sessionId || !event) return
685
+ if (event.type === 'user/message') {
686
+ const data = event.data || {}
687
+ const kind = data.source && data.source.kind
688
+ // 通知 / relay / job / 时间快照都不是人说的;无 source 的老宿主按人话处理(与 lastUserText 同口径)。
689
+ if (kind && kind !== 'user') return
690
+ const text = textOf({ content: data.content })
691
+ if (text.trim()) sessions.humanText.set(sessionId, text.trim())
692
+ return
693
+ }
694
+ if (event.type !== 'tool/call') return
657
695
  const data = event.data || {}
658
696
  const calls = sessions.observed.ensure(sessionId)
659
697
  calls.push({ name: String(data.name || ''), arguments: String(data.arguments || '') })
@@ -702,11 +740,12 @@ export function installAutoInject(ctx, config) {
702
740
  /** 已就「会话根不安全」提示过的目录:每个进程、每个根只提示一次。 */
703
741
  const warnedUnsafeRoots = new Set()
704
742
 
705
- function warnUnsafeSessionRoot(root) {
743
+ function warnUnsafeSessionRoot(root, rejection) {
706
744
  if (warnedUnsafeRoots.has(root)) return
707
745
  warnedUnsafeRoots.add(root)
746
+ const field = rejection?.field ? `; adjust \`${rejection.field}\` under \`- id: project-memory\` if this is intentional` : ''
708
747
  console.error(
709
- `[dsh-project-memory] session cwd ${root} is not a project root (home / system / package-manager prefix); ` +
748
+ `[dsh-project-memory] session cwd ${root} is not a project root (${rejection?.reason || 'home / system / package-manager prefix'}${field}); ` +
710
749
  'project memory and its audit logs are disabled for this session. Start dsh inside a project directory to enable them.',
711
750
  )
712
751
  }
@@ -722,19 +761,26 @@ async function injectForStep({ payload, decision, config, cfg, audit, shadow, se
722
761
  const cwd = sessionWorkingDir(session, { agent: payload?.agent })
723
762
  const sessionId = session && session.id
724
763
  if (!cwd || !sessionId) return null
725
- // 会话 cwd 是家目录/系统目录时整条链路停在这里:不读 store(历史遗留的超大 store
726
- // 光是 load() 就能 OOM),也不写审计——`appendShadowAudit` 里的 mkdirSync 正是把
727
- // `.dsh-project-memory` 造进家目录、进而触发"目录自标记 → 家目录被锁成项目"的那一步。
728
- if (isUnsafeRoot(cwd)) {
729
- warnUnsafeSessionRoot(cwd)
764
+ // 会话 cwd 命中内置名单 / roots.deny / roots.exclude 时整条链路停在这里:不读 store
765
+ // (历史遗留的超大 store 光是 load() 就能 OOM),也不写审计——`appendShadowAudit` 里的
766
+ // mkdirSync 正是把 `.dsh-project-memory` 造进家目录、进而触发"目录自标记 → 家目录被锁成项目"的那一步。
767
+ const rejection = rootRejection(cwd, config)
768
+ if (rejection) {
769
+ warnUnsafeSessionRoot(cwd, rejection)
730
770
  return null
731
771
  }
732
772
  // 记忆根与懒索引/工具侧同一套解析:项目标记优先,其次是安全的会话工作目录。
733
773
  // 少了这一步,同一个会话的审计日志与懒索引会落在两个不同的 store 里。
734
- const root = resolveProjectMemoryRoot(cwd)
774
+ const root = resolveProjectMemoryRoot(cwd, config)
735
775
  if (!root) return null
736
776
 
737
- const query = lastUserText(decision.messages)
777
+ // 意图是**会话状态**:先看本步 delta 里有没有新的人类消息,没有则回退到本会话最后一条。
778
+ // `agent/pre-step` 拿到的是 claimed delta(宿主 agent-loop 的 inbox.claim),会话中段通常
779
+ // 只有 tool result / 子代理报告 / job 通知,拿它们当查询就是"这步在做什么"用错了来源。
780
+ const deltaHuman = lastUserText(decision.messages)
781
+ const rememberedHuman = sessions.humanText.peek(sessionId) || ''
782
+ const query = deltaHuman || rememberedHuman
783
+ const querySource = deltaHuman ? 'delta' : rememberedHuman ? 'session' : 'none'
738
784
  const memoryRoot = memoryRootFor(root, config.memoryDir)
739
785
  const store = new ProjectMemoryStore(memoryRoot).load()
740
786
  const globalStore = new GlobalStore(cfg.globalFile || defaultGlobalFile()).load()
@@ -742,12 +788,12 @@ async function injectForStep({ payload, decision, config, cfg, audit, shadow, se
742
788
  const task = boundTaskId ? store.getTask(boundTaskId) : null
743
789
 
744
790
  // 两个窗口合并进同一个就绪上下文:人类消息(先发)+ 已观察动作(反应)。
745
- // 动作平面(S1):把"最近做过什么"解析成 op / 写目标 / 主机——不再把原始参数当文本搜。
791
+ // 动作平面(S1):**只**从结构化 tool/call 归一(activityFromCalls),不再把全部参数拼成
792
+ // actionText —— 那会把 subagent 提示词 / remember 正文 / 任意脚本里的词当成动作(实测 8 步)。
746
793
  const observed = sessions.observed.ensure(sessionId)
747
794
  const activity = activityFromCalls(observed)
748
795
  const readiness = buildReadinessContext({
749
796
  humanText: query || '',
750
- actionText: observed.map((c) => `${c.name} ${c.arguments}`).join('\n'),
751
797
  ops: activity.ops,
752
798
  targets: activity.targets,
753
799
  hosts: activity.hosts,
@@ -798,7 +844,9 @@ async function injectForStep({ payload, decision, config, cfg, audit, shadow, se
798
844
  root,
799
845
  step: stepNo,
800
846
  query: query || '',
847
+ querySource,
801
848
  ops: readiness.ops,
849
+ opsIntent: readiness.intentOps,
802
850
  writes: readiness.targets,
803
851
  reasons: built.reasons,
804
852
  candidates: built.candidates,
@@ -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) }
@@ -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/doc-index.js CHANGED
@@ -4,8 +4,8 @@
4
4
  // 而 summary 为了注入预算被压到 300 字符 —— 一个 3000 字符的 chunk 有九成内容检索不到。
5
5
  // 这里把「注入用的短摘要」和「检索用的词项」拆开:summary 仍然短,terms 覆盖整个 chunk。
6
6
  //
7
- // 纯规则、确定性、可重放:tokenizeRaw(拉丁词 + CJK bigram)→ 去停用词/纯数字 → 词频排序 → 截断。
8
- import { tokenizeRaw } from './util/search.js'
7
+ // 纯规则、确定性、可重放:tokenizeRaw(拉丁词 + CJK bigram + 俄语词干)→ 去停用词/纯数字 → 词频排序 → 截断。
8
+ import { TOKENIZER_VERSION, tokenizeRaw } from './util/search.js'
9
9
 
10
10
  export const MAX_TERMS = 160
11
11
  export const MAX_KEYWORDS = 8
@@ -62,10 +62,12 @@ export function extractKeywords(title, text, { max = MAX_KEYWORDS } = {}) {
62
62
  }
63
63
 
64
64
  /**
65
- * 旧 store 的 doc 条目没有 `terms`:需要一次定向回填,否则内容哈希未变的文件会被跳过,
66
- * 新的检索覆盖不会生效。只对 doc 条目判断,code 条目(符号表)不需要 terms。
65
+ * 旧 store 的 doc 条目没有 `terms`、或 `termsVersion` 落后于当前分词契约:需要一次定向回填,
66
+ * 否则内容哈希未变的文件会被跳过,新的检索覆盖(新增书写系统 / 词干 / 停用词)不会生效。
67
+ * 只对 doc 条目判断,code 条目(符号表)不需要 terms。
67
68
  */
68
69
  export function docEntriesNeedBackfill(entries) {
69
70
  if (!Array.isArray(entries) || entries.length === 0) return true
70
- return entries.some((e) => e && e.type === 'doc' && typeof e.terms !== 'string')
71
+ return entries.some((e) => e && e.type === 'doc' &&
72
+ (typeof e.terms !== 'string' || e.termsVersion !== TOKENIZER_VERSION))
71
73
  }
@@ -6,6 +6,7 @@ import { summarizeText } from './util/text.js'
6
6
  import { parsePdf } from './parsers/pdfjs-parser.js'
7
7
  import { chunkText } from './chunker.js'
8
8
  import { extractKeywords, extractTermText } from './doc-index.js'
9
+ import { TOKENIZER_VERSION } from './util/search.js'
9
10
  import { entryIdPrefix } from './util/entry-id.js'
10
11
 
11
12
  export async function extractTextFromFile(filePath, { maxFileSizeMb = 10, maxPdfPages = 1000 } = {}) {
@@ -49,6 +50,7 @@ export async function buildDocEntries(relPath, filePath, opts = {}) {
49
50
  summary: summarizeText(chunk.text),
50
51
  keywords: extractKeywords(chunk.title, chunk.text),
51
52
  terms: extractTermText(chunk.text),
53
+ termsVersion: TOKENIZER_VERSION,
52
54
  hash,
53
55
  }))
54
56
  }
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, isUnsafeRoot } from './util/fs.js'
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'
@@ -16,6 +16,8 @@ import { lessonTool } from './tools/lesson-tools.js'
16
16
  import { installAutoInject } from './auto-inject.js'
17
17
  import { rememberRoute } from './llm-route.js'
18
18
  import { workflowCommandDefinition } from './commands/workflow.js'
19
+ import { setupSkill } from './skill.js'
20
+ import { flushDirtyStores } from './util/flush.js'
19
21
 
20
22
  export const name = 'dsh-project-memory'
21
23
  export const inject = ['llm', 'tools']
@@ -45,9 +47,18 @@ export const Config = Schema.object({
45
47
  watch: Schema.boolean().default(true),
46
48
  watchInterval: Schema.number().default(30),
47
49
  // 危险根护栏(issue #5):家目录 / 文件系统根 / 系统目录 / 包管理器前缀(/opt/homebrew …)
48
- // 整体扫描会吃满内存,默认一律拒绝。懒索引、会话审计、任务桥在这类目录里始终零副作用;
49
- // `autoIndexOnFirstUse` 不在此列——本开关同样放行它。其余只放开**显式**带 root 的工具调用。
50
+ // 整体扫描会吃满内存,默认一律拒绝(懒索引、会话审计、任务桥默认零副作用)。
51
+ // `roots.*` 是机器/配置档级的例外表(精确匹配的 allow/deny,子树级前缀的 exclude);
52
+ // `allowUnsafeRoots` 保留为兼容,只放开内置名单,deny / exclude 仍然优先。
50
53
  allowUnsafeRoots: Schema.boolean().default(false),
54
+ roots: Schema.object({
55
+ // 即使在内置名单里也允许作根。精确匹配;文件系统根不在可放行之列。
56
+ allow: Schema.array(Schema.string()).default([]),
57
+ // 这个目录不能当根。精确匹配:子目录仍可各自成根。
58
+ deny: Schema.array(Schema.string()).default([]),
59
+ // 这棵子树里的文件一律不进索引(前缀匹配,含子目录)。
60
+ exclude: Schema.array(Schema.string()).default([]),
61
+ }).default({}),
51
62
  // 单次扫描上限。超过即截断(并跳过"删除本轮未见到条目"的清理,避免把没扫到的文件误删)。
52
63
  // **不可取消**:0 / 负数 / 非数值一律回落默认值(见 util/fs.js 的 scanLimits)。
53
64
  maxScanFiles: Schema.number().default(DEFAULT_SCAN_FILES),
@@ -184,8 +195,14 @@ export function apply(ctx, config) {
184
195
  setupLazyIndexing(ctx, config, watchManager)
185
196
  }
186
197
 
198
+ // 卸载/退出前把还脏着的 store 同步写一次(后台重试只是兜底,不能当正确性保证)。
199
+ if (typeof ctx.effect === 'function') {
200
+ ctx.effect(() => () => flushDirtyStores({ timeoutMs: 1500 }))
201
+ }
187
202
  // TaskBridge:任务实体 + 宿主 todo 同步
188
203
  setupTaskbridge(ctx, config)
204
+ // 用法本身也是记忆的一部分:注册成宿主 skill(可选依赖,没有 skills 服务就静默跳过)。
205
+ setupSkill(ctx)
189
206
  // 跟踪会话路由(request/header 事件),为无会话上下文的召回期可选 LLM(查询扩展 / 反思)兜底
190
207
  ctx.on('session/event', (session, event) => {
191
208
  if (event?.type === 'request/header') rememberRoute(session)
@@ -238,14 +255,11 @@ export function apply(ctx, config) {
238
255
  // 全量索引 cwd 是显式开启的行为,但"cwd 是家目录"几乎总是误用:拒绝并说明,
239
256
  // 而不是替用户把整棵树扫一遍(旧实现直接 indexRepository(ctx, config, cwd),
240
257
  // 没有任何护栏——这正是 issue #5 里最直接的 OOM 入口)。
241
- if (isUnsafeRoot(root) && config.allowUnsafeRoots !== true) {
242
- if (!cancelled) {
243
- console.error(
244
- `[dsh-project-memory] autoIndexOnFirstUse skipped: cwd ${root} is not a project root ` +
245
- '(home / system / package-manager prefix). Start dsh inside a project directory, ' +
246
- 'or set allowUnsafeRoots: true to override.',
247
- )
248
- }
258
+ // 这里走与工具调用同一个 assertSafeRoot:roots.allow / deny / exclude 全部生效。
259
+ try {
260
+ assertSafeRoot(root, { config })
261
+ } catch (err) {
262
+ if (!cancelled) console.error(`[dsh-project-memory] autoIndexOnFirstUse skipped: ${err.message}`)
249
263
  return
250
264
  }
251
265
  try {
@@ -11,6 +11,8 @@ import path from 'node:path'
11
11
  import os from 'node:os'
12
12
  import { normalizedTokenOverlap, findBestOverlapMatch, insightMatchText } from './similarity.js'
13
13
  import { acquireDirLock, writeJsonAtomic } from './util/fs.js'
14
+ import { debugPersistence } from './util/persist.js'
15
+ import { trackDirty, untrackDirty } from './util/flush.js'
14
16
  import { backfillDerivedTriggers } from './readiness.js'
15
17
  import { vectorText } from './vector-index.js'
16
18
  import { tokenize } from './util/search.js'
@@ -534,7 +536,14 @@ export class GlobalStore {
534
536
  this._dirty = false
535
537
  this._baseIds = new Set()
536
538
  this._deletedIds = new Set()
539
+ /** 本进程新建的 id:磁盘缺失时只有它们该补写,否则会把对方删掉的条目复活。 */
540
+ this._createdIds = new Set()
541
+ /** 上一次 commit 是否真的落盘(锁竞争时 false);调用方据此如实回报。 */
542
+ this.lastCommitOk = true
537
543
  this._lockWarned = false
544
+ /** 锁竞争后的有限次延迟重试(与 ProjectMemoryStore.save 同一套节拍)。 */
545
+ this._retryTimer = null
546
+ this._retryAttempts = 0
538
547
  }
539
548
 
540
549
  load() {
@@ -563,20 +572,52 @@ export class GlobalStore {
563
572
  this._dirty = true
564
573
  }
565
574
 
566
- /** 变更提交:fn(this.doc) 后加锁、合并另一进程的磁盘状态、原子落盘。 */
567
- commit(fn) {
575
+ /** 退出/卸载路径的同步兜底(见 util/flush.js)。 */
576
+ flushPending(timeoutMs = 1500) {
577
+ return this.commit(undefined, { timeoutMs })
578
+ }
579
+
580
+ /** 锁竞争失败后的延迟重试:旧实现完全没有重试,一次竞争就永久丢这次写入。 */
581
+ _scheduleRetry() {
582
+ const delays = [100, 500, 2000, 6000, 12000]
583
+ if (this._retryTimer || this._retryAttempts >= delays.length) return
584
+ const delay = delays[this._retryAttempts++]
585
+ this._retryTimer = setTimeout(() => {
586
+ this._retryTimer = null
587
+ try {
588
+ this.commit(undefined, { timeoutMs: 2000 })
589
+ } catch (err) {
590
+ console.error(`[dsh-project-memory] deferred global save failed: ${err?.message || err}`)
591
+ }
592
+ }, delay)
593
+ this._retryTimer.unref?.()
594
+ }
595
+
596
+ /**
597
+ * 变更提交:fn(this.doc) 后加锁、合并另一进程的磁盘状态、原子落盘。
598
+ * @param {(doc: object, store: GlobalStore) => any} [fn]
599
+ * @param {{ timeoutMs?: number }} [options] 等锁上限(默认 15s:正确性靠同步等待,不靠重试)
600
+ */
601
+ commit(fn, options = {}) {
568
602
  const res = fn ? fn(this.doc, this) : undefined
569
603
  if (!this._dirty && res === undefined) return res
570
604
  // 本进程从基线里删掉的 id(removeMemory 直接 splice,没有单独的删除 API)。
571
605
  const current = new Set(this.doc.items.map((it) => it?.id).filter(Boolean))
572
606
  for (const id of this._baseIds) if (!current.has(id)) this._deletedIds.add(id)
573
- for (const id of current) this._deletedIds.delete(id)
574
- const release = acquireDirLock(path.dirname(this.file))
607
+ for (const id of current) {
608
+ this._deletedIds.delete(id)
609
+ if (!this._baseIds.has(id)) this._createdIds.add(id)
610
+ }
611
+ const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : 15000
612
+ const release = acquireDirLock(path.dirname(this.file), { timeoutMs })
575
613
  if (!release) {
614
+ this.lastCommitOk = false
615
+ trackDirty(this)
576
616
  if (!this._lockWarned) {
577
617
  this._lockWarned = true
578
- console.error(`[dsh-project-memory] global store ${this.file} is busy (another dsh process is writing); this save was skipped and will retry on the next write.`)
618
+ debugPersistence(`[dsh-project-memory] global store ${this.file} is busy (another dsh process is writing); this write is pending.`)
579
619
  }
620
+ this._scheduleRetry()
580
621
  return res
581
622
  }
582
623
  try {
@@ -590,13 +631,22 @@ export class GlobalStore {
590
631
  continue
591
632
  }
592
633
  const prev = byId.get(it.id)
593
- if (!prev || newerIso(it.updatedAt, prev.updatedAt) >= 0) byId.set(it.id, it)
634
+ if (!prev) {
635
+ // 磁盘没有:本进程新建的才补写;否则是对方删了,丢掉内存里的旧副本。
636
+ if (this._createdIds.has(it.id)) byId.set(it.id, it)
637
+ continue
638
+ }
639
+ if (newerIso(it.updatedAt, prev.updatedAt) >= 0) byId.set(it.id, it)
594
640
  }
595
641
  for (const id of this._deletedIds) byId.delete(id)
596
642
  this.doc.items = [...byId.values()]
597
643
  writeJsonAtomic(this.file, this.doc)
598
644
  this._dirty = false
599
645
  this._baseIds = new Set(this.doc.items.map((it) => it?.id).filter(Boolean))
646
+ this._createdIds.clear()
647
+ this.lastCommitOk = true
648
+ this._retryAttempts = 0
649
+ untrackDirty(this)
600
650
  } finally {
601
651
  release()
602
652
  }
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, isUnsafeRoot, memoryRootFor, relativePath, storeKey } from './util/fs.js'
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 || isUnsafeRoot(root)) return false
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