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

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.
Files changed (63) hide show
  1. package/CHANGELOG.md +58 -20
  2. package/README.md +14 -105
  3. package/README.zh-CN.md +14 -105
  4. package/client/client.js +228 -95
  5. package/client/client.js.map +1 -1
  6. package/package.json +2 -2
  7. package/scripts/file-peak.mjs +1 -1
  8. package/scripts/tool-schema-size.mjs +1 -1
  9. package/skills/project-memory/SKILL.md +1 -1
  10. package/skills/project-memory/scripts/pm-digest.mjs +20 -6
  11. package/src/audit.js +10 -2
  12. package/src/auto-inject.js +124 -38
  13. package/src/client/MemoryView.tsx +119 -40
  14. package/src/client/TaskCommandNode.tsx +6 -4
  15. package/src/client/TaskComponents.tsx +13 -16
  16. package/src/client/TaskPanel.tsx +41 -15
  17. package/src/client/client.ts +4 -7
  18. package/src/client/paging.js +1 -14
  19. package/src/client/settings-card.tsx +9 -0
  20. package/src/client/task-data-store.ts +57 -7
  21. package/src/client/task-hooks.ts +0 -2
  22. package/src/client/task-scope.js +16 -1
  23. package/src/client/task-ui-store.ts +1 -1
  24. package/src/commands/insight-actions.js +85 -60
  25. package/src/commands/task-actions.js +7 -5
  26. package/src/commands/tasks.js +34 -10
  27. package/src/doc-index.js +3 -1
  28. package/src/enhancer.js +0 -12
  29. package/src/index-failures.js +1 -1
  30. package/src/index-pipeline.js +11 -2
  31. package/src/index.js +60 -14
  32. package/src/inject-visible.js +282 -0
  33. package/src/insight-store.js +129 -32
  34. package/src/lazy.js +29 -23
  35. package/src/llm-route.js +1 -1
  36. package/src/ops.js +18 -5
  37. package/src/parsers/pdfjs-parser.js +3 -33
  38. package/src/project-memory-service.js +195 -0
  39. package/src/project-profile.js +0 -4
  40. package/src/setup/taskbridge.js +38 -6
  41. package/src/store.js +638 -135
  42. package/src/symbols.js +2 -4
  43. package/src/tools/forget.js +3 -6
  44. package/src/tools/index-doc.js +61 -18
  45. package/src/tools/index-repo.js +16 -12
  46. package/src/tools/lesson-tools.js +5 -5
  47. package/src/tools/output.js +28 -0
  48. package/src/tools/query-memory.js +6 -9
  49. package/src/tools/remember.js +3 -6
  50. package/src/tools/stats.js +3 -6
  51. package/src/tools/task-tools.js +15 -8
  52. package/src/tools/watch-repo.js +15 -12
  53. package/src/util/flush.js +1 -1
  54. package/src/util/fs.js +135 -20
  55. package/src/util/message-source.js +20 -0
  56. package/src/util/relative-time.js +24 -0
  57. package/src/util/search.js +0 -1
  58. package/src/util/task-view.js +8 -15
  59. package/src/vector-index.js +2 -2
  60. package/src/watch.js +25 -8
  61. package/client/client.d.ts +0 -27
  62. package/client/client.d.ts.map +0 -1
  63. package/client/style.css +0 -395
package/src/util/fs.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  accessSync, closeSync, constants, existsSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, statSync,
3
- unlinkSync, writeFileSync,
3
+ realpathSync, unlinkSync, writeFileSync,
4
4
  } from 'node:fs'
5
5
  import { execFileSync } from 'node:child_process'
6
6
  import { readFile } from 'node:fs/promises'
@@ -175,11 +175,15 @@ function lockIsStale(state, { staleMs, hardLimit, maxHoldMs = 0 }) {
175
175
  return ageMs > staleMs || ageMs > hardLimit
176
176
  }
177
177
  const boot = bootTimeMs()
178
- // 写于本机上一次开机之前:持有者早已随重启消失,无论 pid 是否存活都是残留。Windows 上没有
179
- // /proc,`processStartMs()` 恒为 null,这是"重启后 pid 被复用"唯一能识破的证据。
180
- if (Number.isFinite(at) && at < boot - BOOT_SLACK_MS) return true
181
- // 锁自带的开机标记与本次不符:系统时钟被改过时 `at` 不可信,`boot` 仍可判。
182
- if (Number.isFinite(meta.boot) && Math.abs(boot - meta.boot) > BOOT_MATCH_TOLERANCE_MS) return true
178
+ // 新锁带 uptime:重启后当前 uptime 会小于锁里记录的 uptime。这个判据不受墙钟步进影响。
179
+ if (Number.isFinite(meta.up)) {
180
+ if (meta.up > os.uptime() + 5) return true
181
+ } else {
182
+ // 旧锁没有 up:保留原来的墙钟判断(时钟被改时会误判,但旧格式本来就没有更强的证据)。
183
+ // 写于本机上一次开机之前:持有者早已随重启消失,无论 pid 是否存活都是残留。
184
+ if (Number.isFinite(at) && at < boot - BOOT_SLACK_MS) return true
185
+ if (Number.isFinite(meta.boot) && Math.abs(boot - meta.boot) > BOOT_MATCH_TOLERANCE_MS) return true
186
+ }
183
187
  if (!pidAlive(meta.pid)) return true
184
188
  // 活着:正常绝不回收;例外是 pid 被复用(新进程启动晚于旧锁)。
185
189
  // 没有 `at` 的旧锁无法判断 → 信任存活,宁可等也不能双写。
@@ -220,6 +224,8 @@ export function acquireDirLock(dir, { timeoutMs = 2000, staleMs = 10000, hardSta
220
224
  at: new Date().toISOString(),
221
225
  // 本次开机时刻:跨重启的残留锁靠它识破(Windows 没有 /proc,pid 存活不足以证明持有者还在)。
222
226
  boot: bootTimeMs(),
227
+ // 开机至今的秒数:墙钟被改也不变,比 `boot` 更可靠;新锁用它判重启。
228
+ up: os.uptime(),
223
229
  })
224
230
  const deadline = Date.now() + timeoutMs
225
231
  const sleeper = new Int32Array(new SharedArrayBuffer(4))
@@ -431,6 +437,21 @@ const DEFAULT_IGNORE = new Set([
431
437
  'Pods', 'bower_components', 'jspm_packages', 'logs',
432
438
  ])
433
439
 
440
+ /** 项目相对路径是否落在默认忽略目录下;只查目录段(根下的 `build` 文件仍收)。 */
441
+ export function isDefaultIgnoredRel(rel) {
442
+ const segs = String(rel || '').split(/[\\/]/)
443
+ return segs.slice(0, -1).some((seg) => DEFAULT_IGNORE.has(seg))
444
+ }
445
+
446
+ /** git 清单可疑为空 / git 不可用:每个根只告警一次。 */
447
+ const warnedGitListing = new Set()
448
+
449
+ function warnGitListing(root, message) {
450
+ if (warnedGitListing.has(root)) return
451
+ warnedGitListing.add(root)
452
+ console.error(`[dsh-project-memory] ${message}`)
453
+ }
454
+
434
455
  /** 单次扫描的默认上限。0 / 负数 / 非数字 = 不限制。 */
435
456
  export const DEFAULT_SCAN_FILES = 20000
436
457
  export const DEFAULT_SCAN_DEPTH = 12
@@ -581,6 +602,27 @@ function gitListedFiles(root) {
581
602
  }
582
603
  }
583
604
 
605
+ /** git 清单里所有“自带 store 的祖先目录”(相对路径);不再受 nestedStoreRoots 的深度/300 目录预算限制。 */
606
+ function nestedStoreDirsFor(root, rels, memoryDirName) {
607
+ const found = new Set()
608
+ const checked = new Map()
609
+ const isStore = (dir) => {
610
+ if (!checked.has(dir)) checked.set(dir, hasOwnStore(path.join(root, dir), memoryDirName))
611
+ return checked.get(dir)
612
+ }
613
+ for (const rel of rels) {
614
+ let dir = path.posix.dirname(String(rel).split(path.sep).join('/'))
615
+ while (dir && dir !== '.' && dir !== '/') {
616
+ if (isStore(dir)) {
617
+ found.add(dir)
618
+ break
619
+ }
620
+ dir = path.posix.dirname(dir)
621
+ }
622
+ }
623
+ return found
624
+ }
625
+
584
626
  /**
585
627
  * 项目文件清单:git 仓库走 `git ls-files`(尊重 `.gitignore`),非 git 目录回退 {@link walkDir};
586
628
  * 返回形状与 walkDir 一致,调用方无需分支。
@@ -595,13 +637,23 @@ export function listProjectFiles(root, opts = {}) {
595
637
  ? opts.config
596
638
  : opts.config ? compileRootPolicy(opts.config) : null
597
639
  const listed = opts.gitAware === false ? null : gitListedFiles(root)
598
- if (listed === null) return walkDir(root, opts)
640
+ const workTree = findGitWorkTree(root)
641
+ if (listed === null) {
642
+ if (workTree) {
643
+ warnGitListing(root, `${root}: git could not list the work tree (${workTree}); .gitignore is not applied this pass and deletions are suppressed`)
644
+ return { ...walkDir(root, opts), truncated: true }
645
+ }
646
+ return walkDir(root, opts)
647
+ }
648
+ // 祖先仓的 .gitignore 可能把整棵子树全忽略:空清单不等于“文件都被删了”,不能触发 unseen 清理。
649
+ if (listed.length === 0 && workTree && path.resolve(workTree) !== path.resolve(root) && opts.maxFiles !== 0) {
650
+ warnGitListing(root, `${root}: git listed no files but a parent work tree exists (${workTree}); .gitignore may hide everything — deletions suppressed`)
651
+ return { files: [], truncated: true, capped: false, skipped: [], unreadable: [] }
652
+ }
599
653
  const maxFiles = Number.isFinite(opts.maxFiles) && opts.maxFiles > 0 ? opts.maxFiles : Infinity
600
654
  const maxDepth = Number.isFinite(opts.maxDepth) && opts.maxDepth > 0 ? opts.maxDepth : Infinity
601
655
  const nestedName = opts.nestedStoreName || null
602
- const nested = nestedName
603
- ? nestedStoreRoots(root, nestedName).map((p) => relativePath(root, p))
604
- : []
656
+ const nested = nestedName ? nestedStoreDirsFor(root, listed, nestedName) : new Set()
605
657
  const files = []
606
658
  const skipped = new Set()
607
659
  let capped = false
@@ -616,7 +668,7 @@ export function listProjectFiles(root, opts = {}) {
616
668
  if (segs.some((s) => s.startsWith('.'))) continue
617
669
  // 与 walkDir 同口径:`DEFAULT_IGNORE` 只作用于**目录段**,根目录下一个叫 `build`
618
670
  // 的普通文件仍然要收(此前对文件名也判,`git init` 前后语料会变)。
619
- if (segs.slice(0, -1).some((s) => DEFAULT_IGNORE.has(s))) continue
671
+ if (isDefaultIgnoredRel(rel)) continue
620
672
  const abs = path.join(root, rel)
621
673
  // 与 walkDir 同一判据:exclude 是子树级前缀。必须在 maxDepth 之前——被排除文件不该把
622
674
  // 扫描标成 truncated(否则本轮不清理"未见到的旧条目")。
@@ -627,7 +679,13 @@ export function listProjectFiles(root, opts = {}) {
627
679
  capped = true
628
680
  continue
629
681
  }
630
- const under = nested.find((n) => rel === n || rel.startsWith(`${n}/`))
682
+ let under
683
+ for (const n of nested) {
684
+ if (rel === n || rel.startsWith(`${n}/`)) {
685
+ under = n
686
+ break
687
+ }
688
+ }
631
689
  if (under) {
632
690
  skipped.add(path.join(root, under))
633
691
  continue
@@ -647,9 +705,26 @@ export function listProjectFiles(root, opts = {}) {
647
705
  return { files, truncated: capped, capped, skipped: [...skipped].sort(), unreadable: [] }
648
706
  }
649
707
 
708
+ /** 向上找最近的 .git(目录或 worktree 文件);纯 fs,非 git 根不 spawn。 */
709
+ function findGitWorkTree(dir) {
710
+ if (typeof dir !== 'string' || !dir) return null
711
+ let cur
712
+ try {
713
+ cur = path.resolve(dir)
714
+ } catch {
715
+ return null
716
+ }
717
+ for (;;) {
718
+ if (existsSync(path.join(cur, '.git'))) return cur
719
+ const parent = path.dirname(cur)
720
+ if (parent === cur) return null
721
+ cur = parent
722
+ }
723
+ }
724
+
650
725
  /** 单个文件是否被 git 忽略(仅 git 仓库;非 git 目录返回 false)。 */
651
726
  export function isGitIgnored(root, filePath) {
652
- if (!root || !filePath || !existsSync(path.join(root, '.git'))) return false
727
+ if (!root || !filePath || !findGitWorkTree(root)) return false
653
728
  try {
654
729
  execFileSync('git', ['-C', root, 'check-ignore', '-q', '--', relativePath(root, filePath)], {
655
730
  stdio: 'ignore',
@@ -673,7 +748,9 @@ export function isGitIgnored(root, filePath) {
673
748
  export function isGitIgnoredBatch(root, rels) {
674
749
  const ignored = new Set()
675
750
  if (!root || !rels || rels.length === 0) return ignored
676
- if (!existsSync(path.join(root, '.git'))) return ignored
751
+ // 只判 `.git` 在不在:项目根可能是仓库的子目录(`.gitignore` 在父仓),此时
752
+ // `git -C root` 会向上找仓库;先做纯 fs 的向上查找,避免非 git 目录每批起一个进程。
753
+ if (!findGitWorkTree(root)) return ignored
677
754
  if (rels.length === 1) {
678
755
  if (isGitIgnored(root, path.join(root, rels[0]))) ignored.add(rels[0])
679
756
  return ignored
@@ -780,8 +857,6 @@ export function normalizeCitationFiles(files, root) {
780
857
  return { files: kept, dropped }
781
858
  }
782
859
 
783
- export const CASE_INSENSITIVE_FS = process.platform === 'win32' || process.platform === 'darwin'
784
-
785
860
  export function storeKey(rel, platform = process.platform) {
786
861
  return platform === 'win32' || platform === 'darwin' ? rel.toLowerCase() : rel
787
862
  }
@@ -824,6 +899,26 @@ export function safeMemoryDirName(raw, warn = defaultMemoryDirWarning) {
824
899
  return value
825
900
  }
826
901
 
902
+ /**
903
+ * store 目录的自我忽略。目录不存在时不创建(是否建目录由调用方决定),存在则保证 `.gitignore` 在。
904
+ * 审计日志会先建目录再写盘,若不在这里补自我忽略,全新项目里 `git add -A` 会把含人类消息原文的
905
+ * 影子日志一起提交。
906
+ * @param {string} dir store 目录
907
+ * @returns {boolean} 本次是否新写了 `.gitignore`
908
+ */
909
+ export function ensureSelfIgnoreDir(dir) {
910
+ if (!dir || !existsSync(dir)) return false
911
+ const file = path.join(dir, '.gitignore')
912
+ if (existsSync(file)) return false
913
+ try {
914
+ writeFileSync(file, '# dsh-project-memory: local by default. `git add -f` to commit it.\n*\n')
915
+ return true
916
+ } catch {
917
+ // 旁路:写不进去不影响存储本身
918
+ return false
919
+ }
920
+ }
921
+
827
922
  /**
828
923
  * 项目根 → store 目录。
829
924
  *
@@ -1042,7 +1137,7 @@ function isCompiledRootPolicy(value) {
1042
1137
  * @param {object} [config] 插件 config(只读 `config.roots` 与 `config.allowUnsafeRoots`)
1043
1138
  * @param {{platform?: string, pathApi?: object, home?: string|null, env?: object, warn?: Function,
1044
1139
  * allowUnsafe?: boolean, unsafeDirs?: Set<string>, sharedTemp?: Set<string>}} [opts]
1045
- * @returns {object} 策略对象(内部结构,调用方应通过 rootRejection/isUnsafeRoot/isExcludedPath 使用)
1140
+ * @returns {object} 策略对象(内部结构,调用方应通过 rootRejection/isUnsafeRoot/excludedEntryForPath 使用)
1046
1141
  */
1047
1142
  export function compileRootPolicy(config, opts = {}) {
1048
1143
  const platform = opts.platform || process.platform
@@ -1111,6 +1206,19 @@ function policyFor(configOrPolicy, opts) {
1111
1206
  return compileRootPolicy(configOrPolicy, opts)
1112
1207
  }
1113
1208
 
1209
+ /**
1210
+ * 根判定的物理键:符号链接别名必须和被 deny/exclude 的目录同键,否则 `ln -s denied safe` 就能绕过。
1211
+ * 只在真实平台 + 真实 path 模块上做 realpath;参数化模拟(Windows 语义测试)没有真实文件系统。
1212
+ */
1213
+ function physicalKey(abs, policy) {
1214
+ if (policy.platform !== process.platform || policy.pathApi !== path) return null
1215
+ try {
1216
+ return storeKey(realpathSync(abs), policy.platform)
1217
+ } catch {
1218
+ return null
1219
+ }
1220
+ }
1221
+
1114
1222
  /** `parent` 是否等于 `child` 或它的祖先(按路径分隔符,含子树)。 */
1115
1223
  function isInsideKey(parentKey, childKey, sep) {
1116
1224
  if (parentKey === childKey) return true
@@ -1194,11 +1302,14 @@ export function rootRejection(root, configOrPolicy, opts) {
1194
1302
  }
1195
1303
  const platform = policy.platform
1196
1304
  const key = storeKey(abs, platform)
1305
+ const physical = physicalKey(abs, policy)
1306
+ const keys = physical && physical !== key ? new Set([key, physical]) : new Set([key])
1197
1307
  const parsed = policy.pathApi.parse(abs)
1198
1308
  if (!parsed.dir || key === storeKey(parsed.root, platform)) {
1199
1309
  return { kind: 'filesystem-root', abs, field: null, entry: null, reason: 'the filesystem root' }
1200
1310
  }
1201
1311
  const excluded = excludedEntryForAbs(abs, policy)
1312
+ || (physical ? excludedEntryForAbs(physical, policy) : null)
1202
1313
  if (excluded) {
1203
1314
  return {
1204
1315
  kind: 'exclude',
@@ -1208,16 +1319,17 @@ export function rootRejection(root, configOrPolicy, opts) {
1208
1319
  reason: `inside the subtree excluded by ${JSON.stringify(excluded.raw)}`,
1209
1320
  }
1210
1321
  }
1211
- if (policy.deny.has(key)) {
1322
+ const denied = [...keys].find((k) => policy.deny.has(k))
1323
+ if (denied) {
1212
1324
  return {
1213
1325
  kind: 'deny',
1214
1326
  abs,
1215
1327
  field: 'roots.deny',
1216
- entry: policy.denyEntries.get(key) || null,
1328
+ entry: policy.denyEntries.get(denied) || null,
1217
1329
  reason: 'listed in roots.deny',
1218
1330
  }
1219
1331
  }
1220
- if (policy.builtin.has(key) && !policy.allowUnsafeRoots && !policy.allow.has(key)) {
1332
+ if ([...keys].some((k) => policy.builtin.has(k)) && !policy.allowUnsafeRoots && ![...keys].some((k) => policy.allow.has(k))) {
1221
1333
  return { kind: 'builtin', abs, field: 'roots.allow', entry: null, reason: unsafeReason(abs, policy) }
1222
1334
  }
1223
1335
  return null
@@ -1500,6 +1612,9 @@ export function resolveSafeIndexRoot(exec, explicitRoot, config) {
1500
1612
 
1501
1613
  /** 尽力而为的会话记忆根:拿不到就返回 null(用于审计镜像这类旁路,不抛错)。 */
1502
1614
  export function sessionMemoryRootOrNull(exec, config) {
1615
+ // 没有会话信息时不要退回进程 cwd:那会把「没有会话」的工具调用(测试 / 脚本)
1616
+ // 当成以 cwd 为根的会话,在仓库里镜像 watchlist、甚至改写开发者的真实 store。
1617
+ if (!sessionWorkingDir(exec?.agent?.session, { agent: exec?.agent })) return null
1503
1618
  try {
1504
1619
  return resolveSafeIndexRoot(exec, null, config)
1505
1620
  } catch {
@@ -0,0 +1,20 @@
1
+ /**
2
+ * 本插件注入消息的生产者判据。放在 util 里:注入对账(inject-visible)与注入引擎
3
+ * (auto-inject)都要用,但前者被后者 import,反向依赖会成环。
4
+ */
5
+
6
+ export const SOURCE_KIND = 'plugin:dsh-project-memory'
7
+
8
+ /**
9
+ * 三种写法都要认,因为同一条历史消息在不同阶段形状不同:
10
+ * `plugin:dsh-project-memory`(现在写的,也是迁移结果)、`project-memory`(保留的别名)、
11
+ * `plugin: 'dsh-project-memory'`(迁移前尚未落盘的旧形状)。
12
+ * @param {object|undefined|null} source - message.source
13
+ * @returns {boolean}
14
+ */
15
+ export function isOwnInjection(source) {
16
+ if (!source || typeof source !== 'object') return false
17
+ return source.kind === SOURCE_KIND
18
+ || source.kind === 'project-memory'
19
+ || source.plugin === 'dsh-project-memory'
20
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * 相对时间(中文)的唯一实现:面板、`list_tasks`、`/tasks` 共用。
3
+ *
4
+ * 两处调用方对"时间坏掉"的期待不同,所以 fallback 是参数而不是第二份实现:
5
+ * - 服务端把条目交给模型,省略时间会像"没有时间信息",默认 `'未知'`;
6
+ * - 面板是给人看的,时间坏了就留空,不显示脏字。
7
+ *
8
+ * 客户端旧副本用 `new Date(iso).getTime()` 直接算 diff:非法 ISO 得到 NaN,一路比较都不成立,
9
+ * 最后渲染成 "NaN天前"。收敛到这一份后,非法/缺失时间一律走 fallback(而不是各写一套判据)。
10
+ * @param {string} [iso] ISO 时间戳
11
+ * @param {string} [fallback] 解析失败时的文案
12
+ * @returns {string}
13
+ */
14
+ export function timeAgo(iso, fallback = '未知') {
15
+ const t = Date.parse(iso ?? '')
16
+ if (!Number.isFinite(t)) return fallback
17
+ const diff = Date.now() - t
18
+ const m = Math.floor(diff / 60000)
19
+ if (m < 1) return '刚刚'
20
+ if (m < 60) return `${m}分钟前`
21
+ const h = Math.floor(m / 60)
22
+ if (h < 24) return `${h}小时前`
23
+ return `${Math.floor(h / 24)}天前`
24
+ }
@@ -103,7 +103,6 @@ export function tokenize(text) {
103
103
 
104
104
  const K1 = 1.5
105
105
  const B = 0.75
106
- const DELTA = 1
107
106
 
108
107
  function avgDocLen(docs) {
109
108
  if (!docs.length) return 1
@@ -2,7 +2,7 @@
2
2
  * 任务步骤的读取与展示(纯函数,零依赖,commands/ 与 tools/ 共用)。
3
3
  *
4
4
  * 步骤在数据里出现过三种形状:早期裸字符串、`{ text }` 时代、现在的 `{ content, status }`。
5
- * 「取文本 / 归一状态 / 数完成度 / 相对时间 / 取 exec 会话 id」这几件事原本在
5
+ * 「取文本 / 归一状态 / 数完成度 / 取 exec 会话 id」这几件事原本在
6
6
  * commands/tasks.js、commands/task-actions.js、tools/query-memory.js、tools/task-tools.js、
7
7
  * tools/lesson-tools.js、setup/taskbridge.js、auto-inject.js、reflection-pipeline.js 里各抄了一份,
8
8
  * 并且已经漂移成两种取文本语义(`??` 与 `||`)和三种状态归一(无校验 / Set 白名单 / 数组白名单)。
@@ -17,11 +17,13 @@ export const STEP_STATUSES = new Set(['pending', 'in_progress', 'completed'])
17
17
  /**
18
18
  * 步骤文本。字符串步骤原样返回;对象步骤按 `content ?? text ?? ''` 读。
19
19
  * @param {string | { content?: unknown, text?: unknown } | null | undefined} step
20
- * @returns {string}
20
+ * @returns {string} 非字符串的 content/text(手改 tasks.json 的脏数据)也转成字符串
21
21
  */
22
22
  export function stepContent(step) {
23
23
  if (typeof step === 'string') return step
24
- return step?.content ?? step?.text ?? ''
24
+ const value = step?.content ?? step?.text
25
+ if (typeof value === 'string') return value
26
+ return value == null ? '' : String(value)
25
27
  }
26
28
 
27
29
  /**
@@ -49,18 +51,9 @@ export function stepProgress(task) {
49
51
  return { done, total: steps.length }
50
52
  }
51
53
 
52
- /** 相对时间(中文):面板、list_tasks、/tasks 三处文案共用同一套阈值。 */
53
- export function timeAgo(iso) {
54
- const t = Date.parse(iso ?? '')
55
- if (!Number.isFinite(t)) return '未知'
56
- const diff = Date.now() - t
57
- const m = Math.floor(diff / 60000)
58
- if (m < 1) return '刚刚'
59
- if (m < 60) return `${m}分钟前`
60
- const h = Math.floor(m / 60)
61
- if (h < 24) return `${h}小时前`
62
- return `${Math.floor(h / 24)}天前`
63
- }
54
+ // 相对时间已移到 ./relative-time.js:客户端面板也要用同一份实现(原先是第二份副本,
55
+ // 非法时间在面板渲染成 "NaN天前")。这里转出以保持 commands/ 与 tools/ 的既有导入不变。
56
+ export { timeAgo } from './relative-time.js'
64
57
 
65
58
  /** 工具执行上下文里的会话 id:agent.session 优先,退化到 ctx.session。 */
66
59
  export function sessionIdOf(exec) {
@@ -243,7 +243,7 @@ async function resolveLeanvecDir(explicit) {
243
243
 
244
244
  /**
245
245
  * 解析当前可用的 leanvec 目录(不加载模型,只做 memo 过的解析 + 指纹)。
246
- * 给 `memory_stats` 这类"只想知道开没开"的调用方用。
246
+ * 给 `pm_stats` 这类"只想知道开没开"的调用方用。
247
247
  * @returns {Promise<{dir: string|null, fingerprint: string|null}>}
248
248
  */
249
249
  export async function resolveVectorLayer(vectorDir = null) {
@@ -398,7 +398,7 @@ export function forgetVectorRows({ dir = null, ids = [] } = {}) {
398
398
  }
399
399
 
400
400
  /**
401
- * 索引状态摘要(不加载模型):给 `memory_stats` 用的可观测量——行数、陈旧行
401
+ * 索引状态摘要(不加载模型):给 `pm_stats` 用的可观测量——行数、陈旧行
402
402
  * (文件里有、store 里已没有)、体积、模型指纹与落盘时间。
403
403
  */
404
404
  export function vectorIndexSummary({ dir = null, items = [] } = {}) {
package/src/watch.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { existsSync, statSync } from 'node:fs'
2
2
  import { stat } from 'node:fs/promises'
3
3
  import path from 'node:path'
4
- import { listProjectFiles, memoryDirName, memoryRootFor, relativePath, rootRejection, scanLimits, storeKey } from './util/fs.js'
4
+ import { excludedEntryForPath, listProjectFiles, memoryDirName, memoryRootFor, relativePath, rootRejection, scanLimits, storeKey } from './util/fs.js'
5
5
  import { OVERSIZE, UNCHANGED, commitFileUpdates, fileKind, planFileIndex, toFileUpdate } from './index-pipeline.js'
6
6
  import { ProjectMemoryStore } from './store.js'
7
7
  import { onFileChanged, isTypeScriptFile } from './enhancer.js'
@@ -55,8 +55,7 @@ async function mapLimit(items, limit, fn) {
55
55
  }
56
56
 
57
57
  export class WatchManager {
58
- constructor(ctx, config) {
59
- this.ctx = ctx
58
+ constructor(_ctx, config) {
60
59
  this.config = config
61
60
  this.roots = new Map()
62
61
  /**
@@ -72,6 +71,11 @@ export class WatchManager {
72
71
  this._unreadableWarned = new Set()
73
72
  /** 已就「跳过了嵌套项目根」告警过的根,只提示一次。 */
74
73
  this._nestedStoreWarned = new Set()
74
+ /**
75
+ * 已就「根在运行期消失」告警过的根,只提示一次。根回来时从这里删掉,
76
+ * 这样它**下一次**再消失还会再告警一次(长期挂着的根不该每轮刷屏)。
77
+ */
78
+ this._missingWarned = new Set()
75
79
  /** 正在跑回合的会话 id 集合:**多会话**下任一在跑就算活跃(见 setSessionActive)。 */
76
80
  this._activeSessions = new Set()
77
81
  this._active = false
@@ -278,10 +282,22 @@ export class WatchManager {
278
282
  }
279
283
 
280
284
  async pollRoot(root, state) {
281
- // 根可能在运行期被删除/rename。这里**不能**继续走到 storeFor() → save():
282
- // save() 会把 !formatWritten 当脏并 mkdirSync,把删掉的根重新创建成一个空目录。
283
- // 暂时读不到的挂载点同样跳过本轮;它回来后会继续按原逻辑扫描。
284
- if (!existsSync(root)) return false
285
+ // 根可能被删除/rename:不能走到 storeFor()→save(),否则会把删掉的根重建出来。
286
+ // 保留索引等待恢复;首次消失告警一次。
287
+ if (!existsSync(root)) {
288
+ // 只告警、不清理:snapshot / store entries / watch.json 全部保留(根回来即恢复)。
289
+ // 同一根只提示一次,避免长期挂着的根每轮刷屏;它回来时(见下方)会从集合里移除。
290
+ if (!this._missingWarned.has(root)) {
291
+ this._missingWarned.add(root)
292
+ console.warn(
293
+ `[dsh-project-memory] watch root ${root} does not exist; keeping its existing index and waiting for it to come back. ` +
294
+ 'The directory and its store are not recreated; polling continues.',
295
+ )
296
+ }
297
+ return false
298
+ }
299
+ // 根回来了:清掉「已告警」标记,下一次再消失会重新提示一次。
300
+ this._missingWarned.delete(root)
285
301
  const seen = new Set()
286
302
  const updates = []
287
303
  // rel → 本轮采集的 mtime:size。提交成功后才落进快照;CAS 失败的条目下轮重试。
@@ -361,7 +377,7 @@ export class WatchManager {
361
377
  state.failures.set(rel, err.message)
362
378
  console.error(`[dsh-project-memory] re-index failed for ${rel}: ${err.message}`)
363
379
  }
364
- // 日志只打一次是防刷屏;账本每轮都刷新时间,index_repo / memory_stats 才看得见
380
+ // 日志只打一次是防刷屏;账本每轮都刷新时间,index_repo / pm_stats 才看得见
365
381
  // "这个文件现在仍然没进语料",而不是一条陈年记录。
366
382
  recordIndexFailure(root, rel, err.message)
367
383
  continue
@@ -394,6 +410,7 @@ export class WatchManager {
394
410
  updates,
395
411
  unseen: truncated ? null : seen,
396
412
  root,
413
+ isExcludedRel: (rel) => Boolean(excludedEntryForPath(path.join(root, rel), this.config)),
397
414
  })
398
415
  // 扫全了才剪快照:删掉的文件不能留着,否则它以同样的 mtime:size 回来会被当成未变。
399
416
  if (!truncated) {
@@ -1,27 +0,0 @@
1
- //#region src/client/client.d.ts
2
- /**
3
- * Required primitives that may not exist on older hosts.
4
- * If missing, we skip registration gracefully.
5
- */
6
- declare const REQUIRED_PRIMITIVES: readonly ["Button", "IconChevronDownOutline14", "IconChevronUpOutline14", "IconCloseOutline16", "IconMinimizeOutline14", "IconCheckCircleOutline14", "IconCircleOutline14", "IconPlayCircleOutline14", "IconFolderOutline14", "IconFileOutline14"];
7
- declare function missingPrimitives(mod: Record<string, unknown>, required?: readonly string[]): string[];
8
- /**
9
- * Minimal host context shape we need (structural typing, no internal deps)
10
- */
11
- interface TaskPanelHostContext {
12
- effect(callback: () => unknown, label?: string): void;
13
- on(event: string, callback: () => void): () => void;
14
- off(event: string, callback: () => void): void;
15
- commands: {
16
- execute(name: string, args: unknown): Promise<unknown>;
17
- };
18
- slots: {
19
- inject(name: string, register: () => unknown): void;
20
- register(options: Record<string, unknown>, render: () => unknown): unknown;
21
- };
22
- }
23
- declare const name = "dsh-project-memory";
24
- declare function apply(ctx: TaskPanelHostContext): void;
25
- //#endregion
26
- export { REQUIRED_PRIMITIVES, apply, missingPrimitives, name };
27
- //# sourceMappingURL=client.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"client.d.ts","names":[],"sources":["../src/client/client.ts"],"mappings":";;;;;cAea;iBAaG,kBACd,KAAK,yBACL;;;;UAQQ;EACR,OAAO,yBAAyB;EAChC,GAAG,eAAe;EAClB,IAAI,eAAe;EACnB;IACE,QAAQ,cAAc,gBAAgB;;EAExC;IACE,OAAO,cAAc;IACrB,SAAS,SAAS,yBAAyB;;;cAIlC;iBAEG,MAAM,KAAK"}