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

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yolk_vat-y/dsh-project-memory",
3
- "version": "0.6.9",
3
+ "version": "0.6.11",
4
4
  "description": "Persistent project memory for dsh agents: index docs (PDF/Markdown/text) and code symbols into a searchable per-workspace store, recall them with cited sources, and keep experience entries (problems -> solutions) searchable on demand.",
5
5
  "author": "00080000 <3388065969@qq.com>",
6
6
  "type": "module",
@@ -20,7 +20,7 @@
20
20
  "url": "https://github.com/00080000/dsh-project-memory.git"
21
21
  },
22
22
  "scripts": {
23
- "test": "node test/run-test.mjs && node test/taskbridge.test.mjs && node test/insight-store.test.mjs && node test/reflection-pipeline.test.mjs && node test/auto-inject.test.mjs && node test/insight-actions.test.mjs && node test/insight-paging.test.mjs && node test/config-schema.test.mjs && node test/host-contract.test.mjs && node test/session-dir.test.mjs && node test/llm-route.test.mjs && node test/doc-index.test.mjs && node test/chunker.test.mjs && node test/client-hints.test.mjs && node test/client-paging.test.mjs && node test/client-task-sync.test.mjs && node test/recall.test.mjs && node test/recall-vector-fusion.test.mjs && node test/vector-index.test.mjs && node test/readiness.test.mjs && node test/insight-derive.test.mjs && node test/readiness-eval.test.mjs && node test/ops.test.mjs && node test/injection-audit.test.mjs && node test/signal-source.test.mjs && node test/skill.test.mjs && node test/injection-budget.test.mjs && node test/injection-scenarios.test.mjs && node test/bugfix-0.5.7.test.mjs && node test/client-icons.test.mjs && node test/client-slash.test.mjs && node test/client-toolview.test.mjs && node test/workflow-command.test.mjs && node test/client-session-id.test.mjs && node test/client-degraded.test.mjs && node test/settings-card.test.mjs && node test/watch-idle.test.mjs && node test/citation-paths.test.mjs && node test/task-view.test.mjs && node test/root-guards.test.mjs && node test/root-policy.test.mjs && node test/gitignore-index.test.mjs && node test/store-gitignore.test.mjs && node test/atomic-write.test.mjs && node test/store-cache.test.mjs && node test/store-concurrent.test.mjs && node test/store-lock.test.mjs && node test/windows-compat.test.mjs && node test/tool-schema-size.test.mjs && node test/enhancer.test.mjs && node test/multilingual-ru.test.mjs && node test/lazy-batch.test.mjs && node test/pdfjs-host.test.mjs && node test/index-failures.test.mjs",
23
+ "test": "node test/run-test.mjs && node test/taskbridge.test.mjs && node test/insight-store.test.mjs && node test/reflection-pipeline.test.mjs && node test/auto-inject.test.mjs && node test/insight-actions.test.mjs && node test/insight-paging.test.mjs && node test/config-schema.test.mjs && node test/host-contract.test.mjs && node test/session-dir.test.mjs && node test/llm-route.test.mjs && node test/doc-index.test.mjs && node test/chunker.test.mjs && node test/client-hints.test.mjs && node test/client-paging.test.mjs && node test/client-task-sync.test.mjs && node test/recall.test.mjs && node test/recall-vector-fusion.test.mjs && node test/vector-index.test.mjs && node test/readiness.test.mjs && node test/insight-derive.test.mjs && node test/readiness-eval.test.mjs && node test/ops.test.mjs && node test/injection-audit.test.mjs && node test/signal-source.test.mjs && node test/skill.test.mjs && node test/injection-budget.test.mjs && node test/injection-scenarios.test.mjs && node test/bugfix-0.5.7.test.mjs && node test/client-icons.test.mjs && node test/client-slash.test.mjs && node test/client-toolview.test.mjs && node test/workflow-command.test.mjs && node test/client-session-id.test.mjs && node test/client-degraded.test.mjs && node test/settings-card.test.mjs && node test/watch-idle.test.mjs && node test/citation-paths.test.mjs && node test/task-view.test.mjs && node test/root-guards.test.mjs && node test/root-policy.test.mjs && node test/gitignore-index.test.mjs && node test/store-gitignore.test.mjs && node test/atomic-write.test.mjs && node test/store-cache.test.mjs && node test/store-concurrent.test.mjs && node test/store-lock.test.mjs && node test/windows-compat.test.mjs && node test/tool-schema-size.test.mjs && node test/enhancer.test.mjs && node test/multilingual-ru.test.mjs && node test/tokenizer-equivalence.test.mjs && node test/lazy-batch.test.mjs && node test/pdfjs-host.test.mjs && node test/index-failures.test.mjs && node test/audit-2026-11-02.test.mjs && node test/memorydir-guard.test.mjs && node test/audit-2026-11-05.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",
@@ -54,13 +54,13 @@
54
54
  "pdfjs-dist": "^4.10.38"
55
55
  },
56
56
  "devDependencies": {
57
- "@deepseek-ai/cordis": "^4.0.4",
58
- "@deepseek-ai/dsh-client-locale": "0.2.1-rc.2",
59
- "@deepseek-ai/dsh-client-store": "0.2.1-rc.2",
60
- "@deepseek-ai/dsh-client-ui-primitives": "0.2.1-rc.2",
61
- "@deepseek-ai/dsh-client-ui-slots": "0.2.1-rc.2",
62
- "@deepseek-ai/dsh-llm": "0.2.1-rc.2",
63
- "@deepseek-ai/dsh-tools": "0.2.1-rc.2",
57
+ "@deepseek-ai/cordis": "^4.1.0",
58
+ "@deepseek-ai/dsh-client-locale": "0.2.2-rc.1",
59
+ "@deepseek-ai/dsh-client-store": "0.2.2-rc.1",
60
+ "@deepseek-ai/dsh-client-ui-primitives": "0.2.2-rc.1",
61
+ "@deepseek-ai/dsh-client-ui-slots": "0.2.2-rc.1",
62
+ "@deepseek-ai/dsh-llm": "0.2.2-rc.1",
63
+ "@deepseek-ai/dsh-tools": "0.2.2-rc.1",
64
64
  "@deepseek-ai/schemastery": "^3.18.3",
65
65
  "@tsdown/css": "0.22.14",
66
66
  "@types/react": "^18.3.31",
@@ -66,7 +66,11 @@ Run from a shell (no dsh required):
66
66
  ```bash
67
67
  node <this-skill-dir>/scripts/pm-digest.mjs <project-root>
68
68
  node <this-skill-dir>/scripts/pm-digest.mjs <project-root> --json
69
+ node <this-skill-dir>/scripts/pm-digest.mjs <project-root> --memory-dir <name>
69
70
  ```
70
71
 
71
72
  It prints store size, insight/task counts, trigger coverage, and staleness. Use it when memory looks
72
- empty, suspiciously large, or when you need to explain what is stored.
73
+ empty, suspiciously large, or when you need to explain what is stored. The store directory is usually
74
+ `.dsh-project-memory`; if the project configures another `memoryDir`, pass it with `--memory-dir`
75
+ (or `DSH_PROJECT_MEMORY_DIR`) — without either, a single store-shaped directory directly under the
76
+ root is picked up and reported as `auto-detected`, and the "no memory store" message says how to pass it.
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  // 项目记忆的体检脚本(零依赖、不调模型、不写盘)。
3
3
  //
4
- // node pm-digest.mjs [项目根] [--json]
4
+ // node pm-digest.mjs [项目根] [--json] [--memory-dir <name>]
5
5
  //
6
6
  // 面向模型与人类各一半:模型拿它替代"先读三个 JSON 再数数"的多次工具往返;
7
7
  // 人拿它看 store 是否异常增长、trigger 覆盖多少、任务是不是全归档了。
@@ -10,10 +10,61 @@ import { readFileSync, readdirSync, statSync } from 'node:fs'
10
10
  import { homedir } from 'node:os'
11
11
  import path from 'node:path'
12
12
 
13
+ const DEFAULT_MEMORY_DIR = '.dsh-project-memory'
14
+ const STORE_MARKER = 'format.json'
15
+
13
16
  const args = process.argv.slice(2)
14
17
  const json = args.includes('--json')
15
- const root = path.resolve(args.find((a) => !a.startsWith('--')) || process.cwd())
16
- const memoryDir = path.join(root, '.dsh-project-memory')
18
+ // store 目录名 = config 的 memoryDir;显式 --memory-dir / 环境变量优先。
19
+ let memoryDirName = process.env.DSH_PROJECT_MEMORY_DIR || ''
20
+ const positional = []
21
+ for (let i = 0; i < args.length; i++) {
22
+ const arg = args[i]
23
+ if (arg === '--json') continue
24
+ if (arg === '--memory-dir') {
25
+ memoryDirName = args[++i] || ''
26
+ continue
27
+ }
28
+ if (arg.startsWith('--memory-dir=')) {
29
+ memoryDirName = arg.slice('--memory-dir='.length)
30
+ continue
31
+ }
32
+ if (arg.startsWith('--')) continue
33
+ positional.push(arg)
34
+ }
35
+ const root = path.resolve(positional[0] || process.cwd())
36
+
37
+ const isFile = (file) => {
38
+ try {
39
+ return statSync(file).isFile()
40
+ } catch {
41
+ return false
42
+ }
43
+ }
44
+
45
+ /**
46
+ * store 目录。写死默认名在自定义 `memoryDir` 的项目上会报"没有 store",
47
+ * 而脚本读不到宿主 profile,所以:显式名 → 默认名 → 根下一层按 `format.json` 标记找**唯一**候选。
48
+ * 0 个或多个候选都不猜,沿用默认名并在报错里点名怎么传。
49
+ */
50
+ function resolveMemoryDir(root, name) {
51
+ if (name) return { dir: path.join(root, name), name }
52
+ const fallback = path.join(root, DEFAULT_MEMORY_DIR)
53
+ if (isFile(path.join(fallback, STORE_MARKER))) return { dir: fallback, name: DEFAULT_MEMORY_DIR }
54
+ let candidates = []
55
+ try {
56
+ candidates = readdirSync(root, { withFileTypes: true })
57
+ .filter((entry) => entry.isDirectory() && isFile(path.join(root, entry.name, STORE_MARKER)))
58
+ .map((entry) => entry.name)
59
+ } catch {
60
+ candidates = []
61
+ }
62
+ if (candidates.length === 1) return { dir: path.join(root, candidates[0]), name: candidates[0], detected: true }
63
+ return { dir: fallback, name: DEFAULT_MEMORY_DIR }
64
+ }
65
+
66
+ const resolved = resolveMemoryDir(root, memoryDirName)
67
+ const memoryDir = resolved.dir
17
68
 
18
69
  const readJson = (file, fallback) => {
19
70
  try {
@@ -94,8 +145,15 @@ const binding = readJson(path.join(memoryDir, 'binding.json'), null)
94
145
  const globalFile = path.join(homedir(), '.config', 'dsh-project-memory', 'global.json')
95
146
  const globalDoc = readJson(globalFile, null)
96
147
 
97
- if (!insDoc && !taskDoc) {
98
- const msg = `no memory store at ${memoryDir} (run index_repo or index_doc first)`
148
+ // 有没有 store:`format.json` 标记(走过一次 save)或已有的 insights/tasks 都算。
149
+ // 只看后两者会把"只索引了文档、还没写洞察/任务"的项目误报成没有 store。
150
+ const hasStore = isFile(path.join(memoryDir, STORE_MARKER)) || Boolean(insDoc || taskDoc)
151
+
152
+ if (!hasStore) {
153
+ const hint = resolved.detected || memoryDirName
154
+ ? ''
155
+ : '; if `memoryDir` is customized, pass --memory-dir <name>'
156
+ const msg = `no memory store at ${memoryDir} (run index_repo or index_doc first)${hint}`
99
157
  if (json) process.stdout.write(JSON.stringify({ root, memoryDir, store: false }, null, 2) + '\n')
100
158
  else process.stdout.write(msg + '\n')
101
159
  process.exit(0)
@@ -107,6 +165,7 @@ const tasks = taskStats((Array.isArray(taskDoc) ? taskDoc : []) || [])
107
165
  const summary = {
108
166
  root,
109
167
  memoryDir,
168
+ ...(resolved.detected ? { detected: true } : {}),
110
169
  store: true,
111
170
  shards,
112
171
  insights,
@@ -123,6 +182,9 @@ if (json) {
123
182
  const kb = (n) => (n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MB` : `${Math.round(n / 102.4) / 10} KB`)
124
183
  const line = (label, value) => process.stdout.write(`${label.padEnd(12)} ${value}\n`)
125
184
  line('project', root)
185
+ if (resolved.name !== DEFAULT_MEMORY_DIR || resolved.detected) {
186
+ line('location', `${resolved.name}${resolved.detected ? ' (auto-detected)' : ''}`)
187
+ }
126
188
  line('store', `${shards.files} shards · ${kb(shards.bytes)} · ${insights.total} insights · ${tasks.total} tasks`)
127
189
  if (insights.total) {
128
190
  const kinds = Object.entries(insights.kinds).map(([k, n]) => `${k} ${n}`).join(' · ')
@@ -426,7 +426,9 @@ function scoreHints({ cands, query, humanText, hintQuery, cfg, dropped, rerank =
426
426
  * @returns {{ text: string, labels: string[], reasons: object[], dropped: object[] }}
427
427
  */
428
428
  export function buildInjection(opts) {
429
- const { query, task, globalStore, cfg } = opts
429
+ const { query, globalStore, cfg } = opts
430
+ // 归档任务不是“当前任务”:即使调用方还拿着旧绑定,也不能回声任务卡或任务级 insights。
431
+ const task = opts.task && !opts.task.archived ? opts.task : null
430
432
  const store = opts.store || null
431
433
  const tags = opts.projectTagsList || []
432
434
  // 就绪上下文可能**已经构建过**(injectForStep 先构建、再传给这里)。二次构建会把第一遍的
@@ -767,12 +769,20 @@ async function injectForStep({ payload, decision, config, cfg, audit, shadow, se
767
769
  }), shadow, root)
768
770
 
769
771
  // 记忆根通告:根是**推定**的(会话工作目录且无任何项目标记)时,第一次注入前告诉模型"记忆存在哪、
770
- // 怎么改"。它是状态声明(与常驻任务卡同类),只发一次、不占条目额度。
771
- const notice = rootNotice({ root, sessionId, sessions, config })
772
+ // 怎么改"。它是状态声明(与常驻任务卡同类),只发一次、不占条目额度;但 maxTokens: 0
773
+ // 的契约是"完全不注入",状态声明也不能绕过。
774
+ const notice = cfg.maxTokens > 0 ? rootNotice({ root, sessionId, sessions, config }) : null
772
775
 
773
776
  const fp = built.text ? fingerprint(built.dedupeText ?? built.text) : fingerprint(notice || '')
774
777
  const injectedText = notice ? (built.text ? `${notice}\n${built.text}` : notice) : built.text
775
- if (!injectedText || fp === sessions.lastText.peek(sessionId)) return null
778
+ // 条目级冷却(reinjectItemsAfter>0)与块级指纹必须对齐:条目级已放行、块正文没变时,
779
+ // 块级 fp 会把“该重发”判成“没变化”。宿主外部裁剪历史时,这个开关本来就是为了重发。
780
+ const seen = sessions.items.ensure(sessionId)
781
+ const reinjectDue = cfg.reinjectItemsAfter > 0 && built.reasons.some((r) => {
782
+ const rec = seen.get(r.id)
783
+ return rec && Number.isFinite(rec.step) && stepNo - rec.step >= cfg.reinjectItemsAfter
784
+ })
785
+ if (!injectedText || (!reinjectDue && fp === sessions.lastText.peek(sessionId))) return null
776
786
  sessions.lastText.set(sessionId, fp)
777
787
  const itemCount = built.reasons.length
778
788
  const summary = itemCount
@@ -780,7 +790,6 @@ async function injectForStep({ payload, decision, config, cfg, audit, shadow, se
780
790
  : built.entry ? 'memory inject: task card' : 'memory root notice'
781
791
 
782
792
  // 只记真的进了上下文的那几条:dropped 的没被看到,不能记账(否则以后永远不再注入)。
783
- const seen = sessions.items.ensure(sessionId)
784
793
  for (const r of built.reasons) {
785
794
  if (r && r.id && r.hash) seen.set(r.id, { hash: r.hash, step: stepNo })
786
795
  }
@@ -285,7 +285,7 @@ export function MemoryView({
285
285
  return
286
286
  }
287
287
  void loadRef.current(0, PAGE_SIZE, false)
288
- }, [scope, sessionId])
288
+ }, [scope, sessionId, root, boundTaskId])
289
289
 
290
290
  // 滚到底之前就取下一页(rootMargin 600px)。哨兵消失(nextOffset=null)即停止。
291
291
  useEffect(() => {
@@ -326,12 +326,15 @@ export function MemoryView({
326
326
  }
327
327
 
328
328
  const rowToForm = (row: InsightRow) => {
329
- // 正文按 kind 取专属字段(fix/solution/reason),避免把与标题相同的 pattern/problem 当正文
329
+ // 正文按 kind 取专属字段(fix/solution/reason),避免把与标题相同的 pattern/problem 当正文。
330
+ // procedure 的 row.body 是服务端 insSummary 合成的“步骤 N 条:…”——它不是正文,
331
+ // 表单里也没有对应输入框;预填后提交会把合成摘要写进真实 body,所以这里不预填。
330
332
  const main =
331
333
  row.kind === 'lesson' ? row.fix
332
334
  : row.kind === 'experience' ? row.solution
333
335
  : row.kind === 'decision' ? row.reason
334
- : row.body
336
+ : row.kind === 'procedure' ? ''
337
+ : row.body
335
338
  const body = main && main !== row.title ? main : ''
336
339
  return {
337
340
  title: row.title || '',
@@ -381,7 +384,8 @@ export function MemoryView({
381
384
  if (form.kind === 'lesson') fields.pattern = title
382
385
  if (form.kind === 'decision') fields.choice = title
383
386
  if (form.kind === 'experience') fields.problem = title
384
- if (form.body.trim()) {
387
+ // procedure 的正文由 steps 表达;不要把 body 一起提交(它只可能是合成摘要)。
388
+ if (form.kind !== 'procedure' && form.body.trim()) {
385
389
  if (form.kind === 'lesson') fields.fix = form.body.trim()
386
390
  else if (form.kind === 'decision') fields.reason = form.body.trim()
387
391
  else if (form.kind === 'experience') fields.solution = form.body.trim()
@@ -2,11 +2,33 @@
2
2
  // 动作:list / confirm / promote / demote / archive / restore / delete
3
3
  // 纯函数 actInsight / listInsights 操作传入的 store/gs 内存对象,持久化由调用方
4
4
  // (命令 handler:store.commit + gs.commit)统一负责,便于单测。
5
+ import path from 'node:path'
5
6
  import { ProjectMemoryStore } from '../store.js'
6
7
  import { memoryRootFor, normalizeCitationFiles } from '../util/fs.js'
7
- import { cfgInsight, GlobalStore, normalizeInsight, defaultGlobalFile, saveInsight, recordDeleted, INSIGHT_KINDS } from '../insight-store.js'
8
+ import { cfgInsight, GlobalStore, normalizeInsight, defaultGlobalFile, saveInsight, recordDeleted, carryUsageFields, pruneItems, INSIGHT_KINDS } from '../insight-store.js'
8
9
  import { NO_PROJECT_ROOT_NOTE, projectRootFor } from '../setup/taskbridge.js'
9
10
  import { fencedJson, invocationContext } from './invocation.js'
11
+ import { forgetVectorRows } from '../vector-index.js'
12
+
13
+ /** 容量旋钮的防御性取值:cfg 可能只带显式测试字段。 */
14
+ function capOf(value, fallback) {
15
+ return typeof value === 'number' && Number.isFinite(value) ? value : fallback
16
+ }
17
+
18
+ /**
19
+ * 面板/命令删除后的向量缓存清理:与 `forget` 工具同一承诺(真删),但这里不加载模型。
20
+ * 失败只影响缓存残留,不能挡住删除本身。
21
+ */
22
+ function forgetVectorsForDeleted({ store, gs, home, ids }) {
23
+ try {
24
+ const dir = home === 'global'
25
+ ? (gs && typeof gs.file === 'string' ? path.dirname(gs.file) : null)
26
+ : (store && typeof store.dir === 'string' ? store.dir : null)
27
+ if (dir && ids.length) forgetVectorRows({ dir, ids })
28
+ } catch {
29
+ /* 缓存删除失败不影响删除承诺 */
30
+ }
31
+ }
10
32
 
11
33
  /**
12
34
  * 记忆列表单页上限。面板每页只请求 30 条(客户端 PAGE_SIZE),远小于它——
@@ -154,6 +176,7 @@ export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
154
176
  recordDeleted({ store, globalStore: gs }, [{ ...insight, home: 'task', taskId: task.id }])
155
177
  task.insights = (task.insights || []).filter((i) => i.id !== id)
156
178
  store.markTasksDirty()
179
+ forgetVectorsForDeleted({ store, gs, home: 'task', ids: [id] })
157
180
  return { ok: true, text: `已删除任务级条目 ${id}` }
158
181
  }
159
182
  if (act === 'archive' || act === 'restore') {
@@ -163,16 +186,22 @@ export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
163
186
  return { ok: true, text: `已${act === 'archive' ? '归档' : '恢复'}` }
164
187
  }
165
188
  if (act === 'promote') {
166
- // task → project(手动提升,无视自动阈值)
189
+ // task → project(手动提升,无视自动阈值)。必须和自动提升一样保留使用痕迹:
190
+ // normalizeInsight 只复制白名单字段,triggerDerived/prev/lastHitAt 要显式带回。
191
+ const now = new Date().toISOString()
167
192
  const items = store.insightItems()
168
- const copy = normalizeInsight(insight, { scope: 'project', source: insight.source, nowIso: new Date().toISOString() })
193
+ const copy = carryUsageFields(
194
+ normalizeInsight(insight, { scope: 'project', source: insight.source, nowIso: now }),
195
+ insight,
196
+ )
169
197
  copy.id = id
170
198
  copy.draft = false
171
199
  copy.confidence = Math.max(insight.confidence || 0, (cfg && cfg.promoteConfidence) || 0.7)
172
- copy.movedFrom = { scope: 'task', id, at: new Date().toISOString() }
200
+ copy.movedFrom = { scope: 'task', id, at: now }
173
201
  copy.createdAt = insight.createdAt || copy.createdAt
174
202
  copy.hitCount = insight.hitCount || 0
175
203
  items.push(copy)
204
+ pruneItems(items, capOf(cfg?.maxProject, 100), now)
176
205
  store.replaceInsightItems(items)
177
206
  task.insights = (task.insights || []).filter((i) => i.id !== id)
178
207
  store.markTasksDirty()
@@ -196,19 +225,24 @@ export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
196
225
  recordDeleted({ store, globalStore: gs }, [{ ...ins, home: 'project' }])
197
226
  items.splice(idx, 1)
198
227
  store.replaceInsightItems(items)
228
+ forgetVectorsForDeleted({ store, gs, home: 'project', ids: [id] })
199
229
  return { ok: true, text: `已删除 project 条目 ${id}` }
200
230
  }
201
231
  if (act === 'promote') {
202
232
  // project → global
203
233
  if (!gs) return { ok: false, text: 'global 存储不可用' }
204
234
  const now = new Date().toISOString()
205
- const copy = normalizeInsight(ins, { scope: 'global', source: ins.source, nowIso: now })
235
+ const copy = carryUsageFields(
236
+ normalizeInsight(ins, { scope: 'global', source: ins.source, nowIso: now }),
237
+ ins,
238
+ )
206
239
  copy.id = id
207
240
  copy.draft = false
208
241
  copy.movedFrom = { scope: 'project', id, at: now }
209
242
  copy.createdAt = ins.createdAt || copy.createdAt
210
243
  copy.hitCount = ins.hitCount || 0
211
244
  gs.items().push(copy)
245
+ pruneItems(gs.items(), capOf(cfg?.maxGlobalProcedures, 200), now)
212
246
  gs.markDirty()
213
247
  items.splice(idx, 1)
214
248
  store.replaceInsightItems(items)
@@ -219,7 +253,10 @@ export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
219
253
  const task = store.getTask(taskId)
220
254
  if (!task) return { ok: false, text: '降级到任务需要 taskId' }
221
255
  const now = new Date().toISOString()
222
- const copy = normalizeInsight(ins, { scope: 'task', source: ins.source, nowIso: now })
256
+ const copy = carryUsageFields(
257
+ normalizeInsight(ins, { scope: 'task', source: ins.source, nowIso: now }),
258
+ ins,
259
+ )
223
260
  copy.id = `${id}_d${Date.now().toString(36)}`
224
261
  copy.movedFrom = { scope: 'project', id, at: now }
225
262
  copy.createdAt = ins.createdAt || copy.createdAt
@@ -249,17 +286,22 @@ export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
249
286
  recordDeleted({ store, globalStore: gs }, [{ ...ins, home: 'global' }])
250
287
  items.splice(idx, 1)
251
288
  gs.markDirty()
289
+ forgetVectorsForDeleted({ store, gs, home: 'global', ids: [id] })
252
290
  return { ok: true, text: `已删除 global 条目 ${id}` }
253
291
  }
254
292
  if (act === 'demote') {
255
293
  // global → project
256
294
  const now = new Date().toISOString()
257
295
  const pjItems = store.insightItems()
258
- const copy = normalizeInsight(ins, { scope: 'project', source: ins.source, nowIso: now })
296
+ const copy = carryUsageFields(
297
+ normalizeInsight(ins, { scope: 'project', source: ins.source, nowIso: now }),
298
+ ins,
299
+ )
259
300
  copy.id = `${id}_d${Date.now().toString(36)}`
260
301
  copy.movedFrom = { scope: 'global', id, at: now }
261
302
  copy.createdAt = ins.createdAt || copy.createdAt
262
303
  pjItems.push(copy)
304
+ pruneItems(pjItems, capOf(cfg?.maxProject, 100), now)
263
305
  store.replaceInsightItems(pjItems)
264
306
  items.splice(idx, 1)
265
307
  gs.markDirty()
@@ -42,7 +42,7 @@ export function renderTaskSnapshot(config, cwd, sid) {
42
42
  const bound = boundId ? tasks.find((t) => t.id === boundId) : null
43
43
 
44
44
  if (!active.length) {
45
- const payload = buildTaskPayload([], boundId, archived)
45
+ const payload = buildTaskPayload([], boundId, archived, root)
46
46
  const note = `项目 ${root}\n任务记录: 0 套${archived ? `(归档 ${archived})` : ''}。让模型开始干活并维护 todo 清单后会自动建档。`
47
47
  return { kind: 'success', text: fencedJson(note, payload) }
48
48
  }
package/src/enhancer.js CHANGED
@@ -343,8 +343,10 @@ export function enqueueEnhance(store, relPath, filePath, priority = PRIORITY.BAT
343
343
  }
344
344
  const cacheKey = getCacheKey(content)
345
345
 
346
- // 去重:同 relPath 同内容 → 复用队列里那条 promise。
347
- const existingIdx = enhanceQueue.findIndex(q => q.relPath === relPath)
346
+ // 去重:同一 store + 同 relPath + 同内容 → 复用队列里那条 promise。
347
+ // **必须带 store 身份**:web 进程同时服务多个项目时,两个项目都有 `src/api.ts` 很正常;
348
+ // 只比 relPath 会让后入队的顶掉前一个(promise 被 resolve、任务却从未增强)。
349
+ const existingIdx = enhanceQueue.findIndex(q => q.store === store && q.relPath === relPath)
348
350
  if (existingIdx >= 0) {
349
351
  const existing = enhanceQueue[existingIdx]
350
352
  if (existing.cacheKey === cacheKey) {
@@ -7,7 +7,7 @@ import { readFileSync, renameSync } from 'node:fs'
7
7
  import path from 'node:path'
8
8
  import os from 'node:os'
9
9
  import { normalizedTokenOverlap, findBestOverlapMatch, insightMatchText } from './similarity.js'
10
- import { acquireDirLock, writeJsonAtomic } from './util/fs.js'
10
+ import { acquireDirLock, storeKey, writeJsonAtomic } from './util/fs.js'
11
11
  import { debugPersistence } from './util/persist.js'
12
12
  import { trackDirty, untrackDirty } from './util/flush.js'
13
13
  import { backfillDerivedTriggers } from './readiness.js'
@@ -39,6 +39,10 @@ export function containsSecretFields(ins, fields = ['title', 'body', 'pattern',
39
39
  return null
40
40
  }
41
41
 
42
+ function isRecord(value) {
43
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
44
+ }
45
+
42
46
  function num(v, d) {
43
47
  return typeof v === 'number' && Number.isFinite(v) ? v : d
44
48
  }
@@ -224,10 +228,21 @@ export function mergeInto(existing, base, cfg, nowIso) {
224
228
  const UPDATE_FIELDS = ['title', 'kind', 'body', 'pattern', 'fix', 'problem', 'solution', 'choice', 'reason', 'steps', 'trigger', 'files', 'symbols', 'tags', 'confidence']
225
229
  const UPDATE_ARRAYS = ['steps', 'files', 'symbols', 'tags']
226
230
 
231
+ // 切 kind 时要保留的专属字段;其余内容字段清掉(与 commands/insight-actions 的 editMemoryItem 同语义)。
232
+ // 两条写入路径必须一致:同一次“改 kind”,面板会清、save_lesson 不清就是两套数据形状。
233
+ const KIND_CONTENT = {
234
+ lesson: ['pattern', 'fix'],
235
+ decision: ['choice', 'reason'],
236
+ procedure: ['steps', 'trigger'],
237
+ experience: ['problem', 'solution'],
238
+ }
239
+ const ALL_CONTENT = ['body', 'pattern', 'fix', 'problem', 'solution', 'choice', 'reason', 'steps']
240
+
227
241
  /** 显式就地更新(`save_lesson` 带 id):只动调用方给的字段,其余原样,旧值进 `prev`。 */
228
242
  export function applyUpdate(item, raw, nowIso) {
229
243
  const now = nowIso || new Date().toISOString()
230
244
  const replaced = []
245
+ const oldKind = item.kind
231
246
  for (const f of UPDATE_FIELDS) {
232
247
  const v = raw[f]
233
248
  if (v === undefined || v === null || v === '') continue
@@ -251,6 +266,17 @@ export function applyUpdate(item, raw, nowIso) {
251
266
  }
252
267
  putField(item, f, String(v), replaced)
253
268
  }
269
+ // 改 kind 时清掉旧 kind 的专属字段(procedure 保留通用 body):否则 lesson→decision 后
270
+ // `fix` 会盖在 `choice` 前面进入正文/摘要(insightBodyText 的优先级是 fix > choice > …)。
271
+ if (item.kind !== oldKind && KIND_CONTENT[item.kind]) {
272
+ const keep = new Set(KIND_CONTENT[item.kind])
273
+ const isProcedure = item.kind === 'procedure'
274
+ for (const f of ALL_CONTENT) {
275
+ if (keep.has(f)) continue
276
+ if (isProcedure && f === 'body') continue
277
+ delete item[f]
278
+ }
279
+ }
254
280
  item.updatedAt = now
255
281
  if (item.archived) item.archived = false
256
282
  // 显式编辑一条草稿 = 作者确认:reflection 产出的 draft 可被 save_lesson 带 id 直接改正文并转正。
@@ -509,7 +535,9 @@ export class GlobalStore {
509
535
  load() {
510
536
  // 整份文档读改写:同一路径必须共用实例,否则两个工具/会话交错时后写覆盖先写。
511
537
  // 与 ProjectMemoryStore 的 storeCache 同语义,这里只按路径缓存。
512
- const key = path.resolve(this.file)
538
+ // Windows/macOS 大小写不敏感:同一个 global.json 的两种写法不能并存两个实例。
539
+ // 项目 store 已有同名归一(storeCacheAlias),这里此前漏了。
540
+ const key = storeKey(path.resolve(this.file))
513
541
  const hot = globalStoreCache.get(key)
514
542
  if (hot) {
515
543
  this.doc = hot.doc
@@ -589,25 +617,33 @@ export class GlobalStore {
589
617
  return res
590
618
  }
591
619
  try {
592
- const disk = normalizeDoc(readJson(this.file, null))
593
- const byId = new Map()
594
- for (const it of disk.items) if (it?.id) byId.set(it.id, it)
595
- for (const it of this.doc.items) {
596
- if (!it?.id) continue
597
- if (this._deletedIds.has(it.id)) {
598
- byId.delete(it.id)
599
- continue
600
- }
601
- const prev = byId.get(it.id)
602
- if (!prev) {
603
- // 磁盘没有:本进程新建的才补写;否则是对方删了,丢掉内存里的旧副本。
604
- if (this._createdIds.has(it.id)) byId.set(it.id, it)
605
- continue
620
+ const rawDisk = readJson(this.file, null)
621
+ const disk = isRecord(rawDisk) && Array.isArray(rawDisk.items) ? rawDisk : null
622
+ if (disk) {
623
+ const byId = new Map()
624
+ for (const it of disk.items) if (it?.id) byId.set(it.id, it)
625
+ for (const it of this.doc.items) {
626
+ if (!it?.id) continue
627
+ if (this._deletedIds.has(it.id)) {
628
+ byId.delete(it.id)
629
+ continue
630
+ }
631
+ const prev = byId.get(it.id)
632
+ if (!prev) {
633
+ // 磁盘没有:本进程新建的才补写;否则是对方删了,丢掉内存里的旧副本。
634
+ if (this._createdIds.has(it.id)) byId.set(it.id, it)
635
+ continue
636
+ }
637
+ if (newerIso(it.updatedAt, prev.updatedAt) >= 0) byId.set(it.id, it)
606
638
  }
607
- if (newerIso(it.updatedAt, prev.updatedAt) >= 0) byId.set(it.id, it)
639
+ for (const id of this._deletedIds) byId.delete(id)
640
+ this.doc.items = [...byId.values()]
641
+ } else {
642
+ // 文件缺失/不可读/损坏(readJson 已把损坏件备份)时,不能把"空 doc"当成
643
+ // "对端把所有条目都删了":那会把整库旧条目静默清掉。保留内存里的完整副本重写。
644
+ // 项目 store 在同样场景也是保留内存整份写回(见 _mergeAuxFromDisk 的 isRecord 守卫)。
645
+ this.doc.items = this.doc.items.filter((it) => isRecord(it) && it.id)
608
646
  }
609
- for (const id of this._deletedIds) byId.delete(id)
610
- this.doc.items = [...byId.values()]
611
647
  writeJsonAtomic(this.file, this.doc)
612
648
  this._dirty = false
613
649
  this._baseIds = new Set(this.doc.items.map((it) => it?.id).filter(Boolean))
package/src/lazy.js CHANGED
@@ -158,6 +158,8 @@ export async function indexObservedBatch(config, items, watchManager = null) {
158
158
 
159
159
  const store = kept[0].store
160
160
  const updates = []
161
+ /** 基础条目落盘成功后才入增强队列(顺序与 index_repo / watch 一致)。 */
162
+ const codeToEnhance = []
161
163
  let refreshed = false
162
164
  for (const cand of kept) {
163
165
  try {
@@ -178,9 +180,14 @@ export async function indexObservedBatch(config, items, watchManager = null) {
178
180
  continue
179
181
  }
180
182
  clearIndexFailure(cand.root, cand.rel)
181
- if (plan.key === OVERSIZE) continue
183
+ if (plan.key === OVERSIZE) {
184
+ // 与 index_repo 同一语义:文件涨过阈值后,旧条目必须摘掉,而不是只跳过本轮。
185
+ updates.push({ rel: cand.rel, drop: true })
186
+ results.set(cand.filePath, false)
187
+ continue
188
+ }
182
189
  updates.push(toFileUpdate(cand.rel, plan, cand.record))
183
- if (plan.key !== DROP && plan.type === 'code') onFileObserved(store, cand.rel, cand.filePath, config, root)
190
+ if (plan.key !== DROP && plan.type === 'code') codeToEnhance.push([cand.rel, cand.filePath])
184
191
  results.set(cand.filePath, plan.key !== DROP)
185
192
  } catch (err) {
186
193
  // 单文件读盘 / 解析失败不影响同批其它文件;但要登记,否则"读了却没索引成"
@@ -198,7 +205,16 @@ export async function indexObservedBatch(config, items, watchManager = null) {
198
205
  }
199
206
 
200
207
  try {
201
- if (updates.length > 0) commitFileUpdates(store, { updates })
208
+ if (updates.length > 0) {
209
+ const { stale } = commitFileUpdates(store, { updates })
210
+ // 增强是「合并进已有条目」:必须在基础条目落盘**之后**入队。先入队时 enhancer 的
211
+ // commit 会同步跑完、随后被本次 applyFileUpdate 的 setEntries 整段覆盖(实测 lazy
212
+ // 单文件读取会因此丢 L2 符号,甚至 0 条目)。
213
+ const staleSet = new Set(stale || [])
214
+ for (const [rel, filePath] of codeToEnhance) {
215
+ if (!staleSet.has(rel)) onFileObserved(store, rel, filePath, config, root)
216
+ }
217
+ }
202
218
  // addedWatch 也要落盘:本轮可能没有任何条目更新(文件已是最新),但新登记的 watch 根
203
219
  // 是独立的事实;不 save 的话重启后它不在 watch.json 里,监视会静默退回启动时的根集合。
204
220
  else if (refreshed || addedWatch) store.commit(() => {})