@yolk_vat-y/dsh-project-memory 0.6.10 → 0.6.12

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.10",
3
+ "version": "0.6.12",
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/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",
23
+ "test": "node test/run-test.mjs && node test/taskbridge.test.mjs && node test/insight-store.test.mjs && node test/util-value.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",
@@ -775,7 +775,14 @@ async function injectForStep({ payload, decision, config, cfg, audit, shadow, se
775
775
 
776
776
  const fp = built.text ? fingerprint(built.dedupeText ?? built.text) : fingerprint(notice || '')
777
777
  const injectedText = notice ? (built.text ? `${notice}\n${built.text}` : notice) : built.text
778
- 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
779
786
  sessions.lastText.set(sessionId, fp)
780
787
  const itemCount = built.reasons.length
781
788
  const summary = itemCount
@@ -783,7 +790,6 @@ async function injectForStep({ payload, decision, config, cfg, audit, shadow, se
783
790
  : built.entry ? 'memory inject: task card' : 'memory root notice'
784
791
 
785
792
  // 只记真的进了上下文的那几条:dropped 的没被看到,不能记账(否则以后永远不再注入)。
786
- const seen = sessions.items.ensure(sessionId)
787
793
  for (const r of built.reasons) {
788
794
  if (r && r.id && r.hash) seen.set(r.id, { hash: r.hash, step: stepNo })
789
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,17 +2,36 @@
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
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 { isoMs } from '../util/value.js'
12
+ import { pruneKindFields } from '../util/insight-fields.js'
13
+ import { forgetVectorRows } from '../vector-index.js'
10
14
 
11
15
  /** 容量旋钮的防御性取值:cfg 可能只带显式测试字段。 */
12
16
  function capOf(value, fallback) {
13
17
  return typeof value === 'number' && Number.isFinite(value) ? value : fallback
14
18
  }
15
19
 
20
+ /**
21
+ * 面板/命令删除后的向量缓存清理:与 `forget` 工具同一承诺(真删),但这里不加载模型。
22
+ * 失败只影响缓存残留,不能挡住删除本身。
23
+ */
24
+ function forgetVectorsForDeleted({ store, gs, home, ids }) {
25
+ try {
26
+ const dir = home === 'global'
27
+ ? (gs && typeof gs.file === 'string' ? path.dirname(gs.file) : null)
28
+ : (store && typeof store.dir === 'string' ? store.dir : null)
29
+ if (dir && ids.length) forgetVectorRows({ dir, ids })
30
+ } catch {
31
+ /* 缓存删除失败不影响删除承诺 */
32
+ }
33
+ }
34
+
16
35
  /**
17
36
  * 记忆列表单页上限。面板每页只请求 30 条(客户端 PAGE_SIZE),远小于它——
18
37
  * 封顶只用于挡住畸形/滥用调用,避免单个响应被抓成超大载荷。
@@ -64,16 +83,6 @@ function findTaskInsight(store, id) {
64
83
  return null
65
84
  }
66
85
 
67
- /**
68
- * 时间戳解析:非法/缺失一律 0,让排序键永远是可比较的数字。
69
- * @param {unknown} value - ISO 时间字符串。
70
- * @returns {number} 毫秒时间戳;不可解析时 0。
71
- */
72
- function tsOf(value) {
73
- const t = Date.parse(value == null ? '' : String(value))
74
- return Number.isFinite(t) ? t : 0
75
- }
76
-
77
86
  /**
78
87
  * 记忆列表的**全序**比较器:新 → 旧。
79
88
  *
@@ -86,11 +95,11 @@ function tsOf(value) {
86
95
  * @returns {number} 排序结果。
87
96
  */
88
97
  function compareInsightRecency(a, b) {
89
- const ua = tsOf(a.raw?.updatedAt) || tsOf(a.raw?.createdAt)
90
- const ub = tsOf(b.raw?.updatedAt) || tsOf(b.raw?.createdAt)
98
+ const ua = isoMs(a.raw?.updatedAt) || isoMs(a.raw?.createdAt)
99
+ const ub = isoMs(b.raw?.updatedAt) || isoMs(b.raw?.createdAt)
91
100
  if (ua !== ub) return ub - ua
92
- const ca = tsOf(a.raw?.createdAt)
93
- const cb = tsOf(b.raw?.createdAt)
101
+ const ca = isoMs(a.raw?.createdAt)
102
+ const cb = isoMs(b.raw?.createdAt)
94
103
  if (ca !== cb) return cb - ca
95
104
  return String(a.raw?.id ?? '').localeCompare(String(b.raw?.id ?? ''))
96
105
  }
@@ -159,6 +168,7 @@ export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
159
168
  recordDeleted({ store, globalStore: gs }, [{ ...insight, home: 'task', taskId: task.id }])
160
169
  task.insights = (task.insights || []).filter((i) => i.id !== id)
161
170
  store.markTasksDirty()
171
+ forgetVectorsForDeleted({ store, gs, home: 'task', ids: [id] })
162
172
  return { ok: true, text: `已删除任务级条目 ${id}` }
163
173
  }
164
174
  if (act === 'archive' || act === 'restore') {
@@ -207,6 +217,7 @@ export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
207
217
  recordDeleted({ store, globalStore: gs }, [{ ...ins, home: 'project' }])
208
218
  items.splice(idx, 1)
209
219
  store.replaceInsightItems(items)
220
+ forgetVectorsForDeleted({ store, gs, home: 'project', ids: [id] })
210
221
  return { ok: true, text: `已删除 project 条目 ${id}` }
211
222
  }
212
223
  if (act === 'promote') {
@@ -267,6 +278,7 @@ export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
267
278
  recordDeleted({ store, globalStore: gs }, [{ ...ins, home: 'global' }])
268
279
  items.splice(idx, 1)
269
280
  gs.markDirty()
281
+ forgetVectorsForDeleted({ store, gs, home: 'global', ids: [id] })
270
282
  return { ok: true, text: `已删除 global 条目 ${id}` }
271
283
  }
272
284
  if (act === 'demote') {
@@ -303,17 +315,6 @@ export function saveMemoryItem({ store, gs, cfg, scope, fields }) {
303
315
 
304
316
  const EDIT_FIELDS = new Set(['title', 'kind', 'body', 'pattern', 'fix', 'problem', 'solution', 'choice', 'reason', 'confidence', 'steps', 'trigger', 'tags', 'files', 'symbols'])
305
317
 
306
- // kind 各自的“内容字段”;切 kind 时清掉不再属于它的旧字段(否则旧经验文本会残留显示)
307
- const KIND_CONTENT = {
308
- lesson: ['pattern', 'fix'],
309
- decision: ['choice', 'reason'],
310
- procedure: ['steps', 'trigger'],
311
- experience: ['problem', 'solution'],
312
- }
313
- // 切 kind 时要清掉的内容字段。**不含 trigger**:任何 kind 都可以带 authored trigger,
314
- // 放进这里会在 lesson↔decision 之间切换时把自动注入能力一并删掉。
315
- const ALL_CONTENT = ['body', 'pattern', 'fix', 'problem', 'solution', 'choice', 'reason', 'steps']
316
-
317
318
  /** 编辑既有条目(title/kind/正文/trigger 等白名单字段)。任务级按 id 在任务池定位。 */
318
319
  export function editMemoryItem({ store, gs, scope, id, fields, root }) {
319
320
  if (!fields || typeof fields !== 'object') return { ok: false, text: 'edit 需要字段对象' }
@@ -365,16 +366,7 @@ export function editMemoryItem({ store, gs, scope, id, fields, root }) {
365
366
  item[key] = s
366
367
  changed = true
367
368
  }
368
- // 切 kind → 清理不再属于新 kind 的旧内容字段
369
- if (changed && item.kind !== oldKind && KIND_CONTENT[item.kind]) {
370
- const keep = new Set(KIND_CONTENT[item.kind])
371
- const isProcedure = item.kind === 'procedure'
372
- for (const f of ALL_CONTENT) {
373
- if (keep.has(f)) continue
374
- if (isProcedure && f === 'body') continue // procedure 保留通用 body
375
- delete item[f]
376
- }
377
- }
369
+ pruneKindFields(item, oldKind)
378
370
  if (changed) item.updatedAt = new Date().toISOString()
379
371
  return changed
380
372
  }
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) {
@@ -13,6 +13,8 @@ import { trackDirty, untrackDirty } from './util/flush.js'
13
13
  import { backfillDerivedTriggers } from './readiness.js'
14
14
  import { vectorText } from './vector-index.js'
15
15
  import { tokenize } from './util/search.js'
16
+ import { isRecord, isoMs, newerIso } from './util/value.js'
17
+ import { pruneKindFields } from './util/insight-fields.js'
16
18
 
17
19
  export const INSIGHT_KINDS = ['lesson', 'decision', 'procedure', 'experience']
18
20
  export const INSIGHT_SCOPES = ['task', 'project', 'global']
@@ -43,13 +45,6 @@ function num(v, d) {
43
45
  return typeof v === 'number' && Number.isFinite(v) ? v : d
44
46
  }
45
47
 
46
- /** 两个 ISO 时间戳的先后;缺失/非法一律 0。 */
47
- function newerIso(a, b) {
48
- const ta = Date.parse(a || '') || 0
49
- const tb = Date.parse(b || '') || 0
50
- return ta - tb
51
- }
52
-
53
48
  /** 合并配置(config.insight 之上补默认)。 */
54
49
  export function cfgInsight(config) {
55
50
  const c = (config && config.insight) || {}
@@ -228,6 +223,7 @@ const UPDATE_ARRAYS = ['steps', 'files', 'symbols', 'tags']
228
223
  export function applyUpdate(item, raw, nowIso) {
229
224
  const now = nowIso || new Date().toISOString()
230
225
  const replaced = []
226
+ const oldKind = item.kind
231
227
  for (const f of UPDATE_FIELDS) {
232
228
  const v = raw[f]
233
229
  if (v === undefined || v === null || v === '') continue
@@ -251,6 +247,9 @@ export function applyUpdate(item, raw, nowIso) {
251
247
  }
252
248
  putField(item, f, String(v), replaced)
253
249
  }
250
+ // 改 kind 时清掉旧 kind 的专属字段(procedure 保留通用 body):否则 lesson→decision 后
251
+ // `fix` 会盖在 `choice` 前面进入正文/摘要(insightBodyText 的优先级是 fix > choice > …)。
252
+ pruneKindFields(item, oldKind)
254
253
  item.updatedAt = now
255
254
  if (item.archived) item.archived = false
256
255
  // 显式编辑一条草稿 = 作者确认:reflection 产出的 draft 可被 save_lesson 带 id 直接改正文并转正。
@@ -397,13 +396,8 @@ function removeFromTask(store, insightId) {
397
396
 
398
397
  const DAY_MS = 86400000
399
398
 
400
- function tsOf(ins, field) {
401
- const v = ins[field]
402
- return v ? Date.parse(v) || 0 : 0
403
- }
404
-
405
399
  function activityOf(ins) {
406
- return tsOf(ins, 'lastHitAt') || tsOf(ins, 'updatedAt') || tsOf(ins, 'createdAt') || 0
400
+ return isoMs(ins.lastHitAt) || isoMs(ins.updatedAt) || isoMs(ins.createdAt)
407
401
  }
408
402
 
409
403
  export function applyDecay(items, cfg, nowIso) {
@@ -591,25 +585,33 @@ export class GlobalStore {
591
585
  return res
592
586
  }
593
587
  try {
594
- const disk = normalizeDoc(readJson(this.file, null))
595
- const byId = new Map()
596
- for (const it of disk.items) if (it?.id) byId.set(it.id, it)
597
- for (const it of this.doc.items) {
598
- if (!it?.id) continue
599
- if (this._deletedIds.has(it.id)) {
600
- byId.delete(it.id)
601
- continue
602
- }
603
- const prev = byId.get(it.id)
604
- if (!prev) {
605
- // 磁盘没有:本进程新建的才补写;否则是对方删了,丢掉内存里的旧副本。
606
- if (this._createdIds.has(it.id)) byId.set(it.id, it)
607
- continue
588
+ const rawDisk = readJson(this.file, null)
589
+ const disk = isRecord(rawDisk) && Array.isArray(rawDisk.items) ? rawDisk : null
590
+ if (disk) {
591
+ const byId = new Map()
592
+ for (const it of disk.items) if (it?.id) byId.set(it.id, it)
593
+ for (const it of this.doc.items) {
594
+ if (!it?.id) continue
595
+ if (this._deletedIds.has(it.id)) {
596
+ byId.delete(it.id)
597
+ continue
598
+ }
599
+ const prev = byId.get(it.id)
600
+ if (!prev) {
601
+ // 磁盘没有:本进程新建的才补写;否则是对方删了,丢掉内存里的旧副本。
602
+ if (this._createdIds.has(it.id)) byId.set(it.id, it)
603
+ continue
604
+ }
605
+ if (newerIso(it.updatedAt, prev.updatedAt) >= 0) byId.set(it.id, it)
608
606
  }
609
- if (newerIso(it.updatedAt, prev.updatedAt) >= 0) byId.set(it.id, it)
607
+ for (const id of this._deletedIds) byId.delete(id)
608
+ this.doc.items = [...byId.values()]
609
+ } else {
610
+ // 文件缺失/不可读/损坏(readJson 已把损坏件备份)时,不能把"空 doc"当成
611
+ // "对端把所有条目都删了":那会把整库旧条目静默清掉。保留内存里的完整副本重写。
612
+ // 项目 store 在同样场景也是保留内存整份写回(见 _mergeAuxFromDisk 的 isRecord 守卫)。
613
+ this.doc.items = this.doc.items.filter((it) => isRecord(it) && it.id)
610
614
  }
611
- for (const id of this._deletedIds) byId.delete(id)
612
- this.doc.items = [...byId.values()]
613
615
  writeJsonAtomic(this.file, this.doc)
614
616
  this._dirty = false
615
617
  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 {
@@ -185,7 +187,7 @@ export async function indexObservedBatch(config, items, watchManager = null) {
185
187
  continue
186
188
  }
187
189
  updates.push(toFileUpdate(cand.rel, plan, cand.record))
188
- 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])
189
191
  results.set(cand.filePath, plan.key !== DROP)
190
192
  } catch (err) {
191
193
  // 单文件读盘 / 解析失败不影响同批其它文件;但要登记,否则"读了却没索引成"
@@ -203,7 +205,16 @@ export async function indexObservedBatch(config, items, watchManager = null) {
203
205
  }
204
206
 
205
207
  try {
206
- 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
+ }
207
218
  // addedWatch 也要落盘:本轮可能没有任何条目更新(文件已是最新),但新登记的 watch 根
208
219
  // 是独立的事实;不 save 的话重启后它不在 watch.json 里,监视会静默退回启动时的根集合。
209
220
  else if (refreshed || addedWatch) store.commit(() => {})
package/src/llm.js CHANGED
@@ -2,19 +2,12 @@
2
2
  // chatText 是唯一的宿主调用出口:provider/model 必填,缺失时显式抛错,由调用方决定回退并记 degraded。
3
3
  import { BlockAssembler, createUserMessage } from '@deepseek-ai/dsh-llm'
4
4
  import { noteDegraded } from './llm-route.js'
5
+ import { textOf } from './util/text.js'
5
6
 
6
7
  function systemMessage(text) {
7
8
  return { role: 'system', content: [{ type: 'text', text }] }
8
9
  }
9
10
 
10
- function textOf(message) {
11
- const blocks = message.content || []
12
- return blocks
13
- .filter((b) => b.type === 'text' && typeof b.text === 'string')
14
- .map((b) => b.text)
15
- .join('\n')
16
- }
17
-
18
11
  export async function chatText(llm, system, user, { timeoutMs = 120000, route } = {}) {
19
12
  // provider/model 是宿主 GenerateOptions 的必填项,缺失时 LlmRuntime 抛 NO_ADAPTER。
20
13
  // 这里显式失败(由调用方决定回退并记 degraded),不让异常悄悄消失。
package/src/ops.js CHANGED
@@ -5,6 +5,7 @@
5
5
  // 路径 token 规则收在 util/path-token.js —— 它无依赖,两个模块共用。
6
6
 
7
7
  import { extractPathTokens } from './util/path-token.js'
8
+ import { patchFilePaths } from './util/patch.js'
8
9
 
9
10
  /** op 闭集。新增一个 op 必须同时想清楚:它是动作,不是话题。 */
10
11
  export const OP_IDS = [
@@ -59,7 +60,7 @@ export const LEGACY_ACTION_ALIAS = {
59
60
  'write-docs': null,
60
61
  }
61
62
 
62
- const WRITE_TOOLS = new Set(['write', 'edit', 'multi_edit', 'apply_patch', 'str_replace', 'create_file', 'notebook_edit'])
63
+ const WRITE_TOOLS = new Set(['write', 'edit', 'multi_edit', 'str_replace', 'create_file', 'notebook_edit'])
63
64
  const READ_IMAGE_TOOLS = new Set(['read_image'])
64
65
  const INDEX_TOOLS = new Set(['index_doc', 'index_repo', 'watch_repo'])
65
66
  const FETCH_TOOLS = new Set(['web_fetch', 'web_search'])
@@ -156,19 +157,51 @@ function tokenizeWords(segment) {
156
157
  return out
157
158
  }
158
159
 
159
- /** 跳过环境变量赋值与 sudo/env/time 之类包装,返回真正的命令头与参数。 */
160
+ /** shell 复合命令的关键字:它们不是可执行命令,跳过后再取真正的命令头。 */
161
+ const SHELL_KEYWORDS = new Set([
162
+ 'if', 'then', 'else', 'elif', 'fi', 'while', 'until', 'for', 'do', 'done',
163
+ 'case', 'esac', 'function', 'in', 'select', 'time',
164
+ ])
165
+ /**
166
+ * 包装器带值的选项:`nice -n 10 npm publish` / `sudo -u user rm` / `env -u NAME rm`。
167
+ * 只跳过选项本身不够——值会被当成命令头,动作与写目标一起丢。
168
+ */
169
+ const WRAPPER_VALUE_FLAGS = new Set([
170
+ '-n', '--adjustment', '-u', '--user', '-g', '--group', '-C', '--chdir', '-p', '--prompt',
171
+ '-r', '--role', '-t', '--type', '-U', '--other-user', '-f', '--format', '-o', '--output',
172
+ '-S', '--split-string', '-c', '--command', '-D', '--chdir',
173
+ ])
174
+
175
+ /** 跳过环境变量赋值、包装器(及其选项/值)与 shell 关键字,返回真正的命令头与参数。 */
160
176
  function commandHead(tokens) {
161
177
  let i = 0
178
+ /** 最近一个包装器:`time -p` 与 `sudo -p <prompt>` 的 -p 语义不同,需要知道是谁。 */
179
+ let wrapper = null
162
180
  while (i < tokens.length) {
163
181
  const t = tokens[i]
164
- if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(t) || WRAPPERS.has(t) || t === '(') { i++; continue }
182
+ if (WRAPPERS.has(t)) { wrapper = t; i++; continue }
183
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(t) || SHELL_KEYWORDS.has(t)) { i++; continue }
184
+ if (t === '(' || t === '{' || t === '}' || t === ')') { i++; continue }
185
+ if (t.startsWith('-') && t !== '-') {
186
+ // 包装器/命令的选项:带值的连值一起跳,避免把值当成可执行命令。
187
+ // `time -p` 是 POSIX 的“不打印计时”,不带值;其余同名 -p(sudo -p prompt)带值。
188
+ const takesValue = WRAPPER_VALUE_FLAGS.has(t) && !(wrapper === 'time' && t === '-p')
189
+ if (takesValue && i + 1 < tokens.length) i += 2
190
+ else i++
191
+ continue
192
+ }
165
193
  break
166
194
  }
167
- const raw = tokens[i] || ''
195
+ let raw = tokens[i] || ''
196
+ // `(rm` / `{rm` 这类紧挨着的分段:剥掉开头括号再取命令头。
197
+ raw = raw.replace(/^[({]+/, '')
168
198
  // 目录(两种分隔符)+ Windows 可执行后缀都要剥:`C:\Program Files\nodejs\npm.cmd` → `npm`。
169
199
  // 只 `split('/')` 会让 Windows 上的绝对路径命令头整个失配,`.cmd`/`.exe` 同理。
170
200
  const head = raw.split(/[\\/]/).pop().toLowerCase().replace(/\.(exe|cmd|bat|com|ps1)$/, '')
171
201
  let rest = tokens.slice(i + 1)
202
+ if (rest.length && /[)}]+$/.test(rest[rest.length - 1])) {
203
+ rest[rest.length - 1] = rest[rest.length - 1].replace(/[)}]+$/, '')
204
+ }
172
205
  if (rest.length && rest[rest.length - 1] === ')') rest = rest.slice(0, -1)
173
206
  return { head, rest }
174
207
  }
@@ -181,8 +214,31 @@ const BENCH_SCRIPT = /^(bench|benchmark)(:[\w.-]+)?$/i
181
214
  /** 包管理器里带值的全局 flag(`npm --prefix x …`)。 */
182
215
  const PM_VALUE_FLAGS = new Set(['-C', '--prefix', '--cwd', '-w', '--workspace', '--filter', '-F', '--dir'])
183
216
 
217
+ /**
218
+ * 包管理器子命令:先扫已知动词(`publish` / `version` / `run` / `exec` …),再退回第一个非选项。
219
+ * 不能直接取第一个非 `-` 参数:`npm --registry <url> publish` / `npm --otp 123456 publish`
220
+ * 会先把 flag 的值当子命令,发布动作因此识别不到(而 `npm publish --registry …` 正常)。
221
+ */
222
+ const PM_VERBS = new Set([
223
+ 'publish', 'pack', 'version', 'run', 'run-script', 'exec', 'dlx', 'x', 'test', 't', 'tst',
224
+ 'install', 'i', 'add', 'remove', 'rm', 'uninstall', 'un', 'update', 'up', 'link', 'why',
225
+ 'audit', 'config', 'init', 'create', 'start', 'stop', 'restart', 'rebuild', 'ci', 'dedupe',
226
+ 'prune', 'outdated', 'view', 'info', 'search', 'login', 'logout', 'whoami', 'owner', 'team',
227
+ 'token', 'deprecate', 'dist-tag', 'unpublish', 'workspace', 'workspaces',
228
+ ])
229
+
184
230
  /** 跳过全局 flag,返回第一个子命令及其后的参数。 */
185
231
  function packageSubcommand(args) {
232
+ for (let i = 0; i < args.length; i++) {
233
+ const a = args[i]
234
+ if (typeof a !== 'string') continue
235
+ if (a.startsWith('-')) {
236
+ if (PM_VALUE_FLAGS.has(a)) i++
237
+ continue
238
+ }
239
+ if (PM_VERBS.has(a.toLowerCase())) return { sub: a.toLowerCase(), rest: args.slice(i + 1) }
240
+ }
241
+ // 没有已知动词:退回旧行为,保留 `yarn bench` / `pnpm dlx …` 这类按脚本名直接跑的形态。
186
242
  for (let i = 0; i < args.length; i++) {
187
243
  if (args[i].startsWith('-')) {
188
244
  if (PM_VALUE_FLAGS.has(args[i])) i++
@@ -404,6 +460,20 @@ export function classifyToolCall(name, argsText) {
404
460
  const targets = [filePath, ...extractPathTokens(filePath)]
405
461
  return { ops: ['file-write'], targets: [...new Set(targets)], hosts: [] }
406
462
  }
463
+ // 0.2.2 的 `apply_patch` 没有 path/file_path:目标文件只写在补丁正文的
464
+ // `*** Add/Update/Delete File:` 与 `*** Move to:` 行里。漏掉它时跨文件补丁
465
+ // 只留下一个没有目标的 file-write,审计与热点都指不到具体文件。
466
+ // 同名工具若走 `path`/`file_path`(非 dsh 形状),退回通用路径,别把旧行为弄丢。
467
+ if (tool === 'apply_patch') {
468
+ const obj = safeJson(argsText) || {}
469
+ const files = patchFilePaths(obj.input)
470
+ const fromArgs = files.length > 0
471
+ ? files
472
+ : [obj.file_path, obj.path].filter((v) => typeof v === 'string' && v)
473
+ const targets = fromArgs.flatMap((p) => [p, ...extractPathTokens(p)])
474
+ const hosts = targets.some((t) => WSL_HINT_RE.test(t)) ? ['wsl'] : []
475
+ return { ops: ['file-write'], targets: [...new Set(targets)], hosts }
476
+ }
407
477
  if (READ_IMAGE_TOOLS.has(tool)) return { ops: ['read-image'], targets: [], hosts: [] }
408
478
  if (INDEX_TOOLS.has(tool)) return { ops: ['index-doc'], targets: [], hosts: [] }
409
479
  if (FETCH_TOOLS.has(tool)) return { ops: ['fetch-web'], targets: [], hosts: [] }
@@ -8,8 +8,10 @@ import { sessionWorkingDir } from '../util/session-dir.js'
8
8
  import { ProjectMemoryStore } from '../store.js'
9
9
  import { BoundedMap } from '../util/session-cache.js'
10
10
  import { stepContent, stepStatus } from '../util/task-view.js'
11
+ import { patchFilePaths } from '../util/patch.js'
11
12
 
12
- const FS_FILE_TOOLS = new Set(['read', 'write', 'edit', 'read_image', 'str_replace_editor'])
13
+ // apply_patch 的参数是整段补丁文本,路径在正文里(见 util/patch.js),单独分支处理。
14
+ const FS_FILE_TOOLS = new Set(['read', 'write', 'edit', 'read_image', 'str_replace_editor', 'apply_patch'])
13
15
  const WRITE_TOOLS = new Set(['write', 'edit']) // 编辑/写入 = 高热点
14
16
  const READ_TOOLS = new Set(['read', 'read_image'])
15
17
  const MAX_FILES_PER_TASK = 100
@@ -266,6 +268,34 @@ export function onSessionEvent(config, session, event, meta, ctx) {
266
268
  } catch {
267
269
  return
268
270
  }
271
+ // 文件工具调用是最高频的写口:每次 commit 都落盘会把 tasks.json 写成“每读一个文件一次”。
272
+ // 这里只改内存 + 标脏,回合结束(turn/end)或会话销毁时统一 flush。
273
+ const record = (rels, kind) => store.commit((s) => {
274
+ const task = s.getTask(taskId)
275
+ if (!task || task.archived) return
276
+ for (const rel of rels) touchTaskFile(task, rel, kind, now)
277
+ task.lastActiveAt = now
278
+ s.markTasksDirty()
279
+ }, { save: false })
280
+
281
+ // 0.2.2 的 apply_patch:路径只在补丁正文的文件头里,没有 file_path / path。
282
+ // 相对路径以会话当前工作目录为基准(= 宿主文档约定的“Session working directory”),
283
+ // 再归一到项目根;项目外的路径由 normalizeRelFile 丢掉。
284
+ // Delete/Move 也记为写:任务卡片关心“这次任务碰过哪些文件”,而不是它们是否还存在。
285
+ // 正文里一个路径都取不到时**不返回**:同名工具若走 path/file_path 参数,交给下面的通用分支。
286
+ if (data.name === 'apply_patch') {
287
+ const base = typeof cwd === 'string' && cwd ? cwd : root
288
+ const rels = []
289
+ for (const target of patchFilePaths(args?.input)) {
290
+ const rel = normalizeRelFile(root, path.isAbsolute(target) ? target : path.resolve(base, target))
291
+ if (rel) rels.push(rel)
292
+ }
293
+ if (rels.length > 0) {
294
+ record(rels, 'write')
295
+ return
296
+ }
297
+ }
298
+
269
299
  // read/write/edit/read_image 用 file_path;宿主的 str_replace_editor 用 path。
270
300
  const raw = typeof args?.file_path === 'string'
271
301
  ? args.file_path
@@ -278,19 +308,13 @@ export function onSessionEvent(config, session, event, meta, ctx) {
278
308
  const cmd = typeof args?.command === 'string' ? args.command.toLowerCase() : ''
279
309
  if (cmd === 'view') kind = 'read'
280
310
  else if (['create', 'str_replace', 'insert'].includes(cmd)) kind = 'write'
311
+ } else if (data.name === 'apply_patch') {
312
+ kind = 'write' // 补丁没解析出文件头时的 path/file_path 变体:仍是写
281
313
  } else {
282
314
  kind = WRITE_TOOLS.has(data.name) ? 'write' : READ_TOOLS.has(data.name) ? 'read' : null
283
315
  }
284
316
  if (!kind) return
285
- // 文件工具调用是最高频的写口:每次 commit 都落盘会把 tasks.json 写成“每读一个文件一次”。
286
- // 这里只改内存 + 标脏,回合结束(turn/end)或会话销毁时统一 flush。
287
- store.commit((s) => {
288
- const task = s.getTask(taskId)
289
- if (!task || task.archived) return
290
- touchTaskFile(task, rel, kind, now)
291
- task.lastActiveAt = now
292
- s.markTasksDirty()
293
- }, { save: false })
317
+ record([rel], kind)
294
318
  }
295
319
  }
296
320