@thincoder/core 0.11.5 → 0.12.1

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 (199) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/abort-provenance.mjs +23 -0
  3. package/advisor/citations.mjs +5 -1
  4. package/advisor/compaction.mjs +13 -10
  5. package/advisor/history.mjs +6 -1
  6. package/advisor/loop.mjs +35 -10
  7. package/advisor/messages.mjs +31 -43
  8. package/advisor/project-context.mjs +49 -45
  9. package/advisor/run.mjs +82 -26
  10. package/advisor.mjs +40 -11
  11. package/agent/assemble.mjs +5 -5
  12. package/agent/chat-call.mjs +21 -1
  13. package/agent/completion.mjs +1 -20
  14. package/agent/dispatch-gates.mjs +8 -3
  15. package/agent/dispatch-run.mjs +131 -20
  16. package/agent/dispatch.mjs +23 -22
  17. package/agent/family-tools.mjs +4 -7
  18. package/agent/goal-judge.mjs +99 -0
  19. package/agent/goal-state.mjs +96 -0
  20. package/agent/helpers.mjs +13 -4
  21. package/agent/offload.mjs +1 -1
  22. package/agent/planning-graph-guardrail.mjs +224 -0
  23. package/agent/planning-prompt.mjs +179 -0
  24. package/agent/planning-step.mjs +460 -173
  25. package/agent/post-turn.mjs +23 -33
  26. package/agent/record-results.mjs +8 -5
  27. package/agent/run-stages.mjs +18 -38
  28. package/agent/run-start.mjs +26 -19
  29. package/agent/setup-reminders.mjs +16 -14
  30. package/agent/setup.mjs +3 -2
  31. package/agent/spawn-child.mjs +17 -4
  32. package/agent/suspension.mjs +42 -21
  33. package/agent/task-lifecycle.mjs +165 -52
  34. package/agent/timers.mjs +9 -1
  35. package/agent/turn-loop.mjs +160 -69
  36. package/agent/turn-projection.mjs +26 -15
  37. package/agent/turn-task-state.mjs +4 -4
  38. package/agent/write-gate-ledger.mjs +1 -1
  39. package/agent/write-gate.mjs +14 -11
  40. package/agent-tools/advisor-async.mjs +2 -0
  41. package/agent-tools/advisor-launch.mjs +27 -13
  42. package/agent-tools/advisor-settle.mjs +19 -18
  43. package/agent-tools/advisor.mjs +90 -13
  44. package/agent-tools/bash-async.mjs +3 -3
  45. package/agent-tools/batch-ledger-bind.mjs +8 -5
  46. package/agent-tools/batch-read.mjs +42 -0
  47. package/agent-tools/batch-record-write.mjs +20 -12
  48. package/agent-tools/batch-segment-vocab.mjs +6 -4
  49. package/agent-tools/batch-skeleton.mjs +43 -12
  50. package/agent-tools/consult.mjs +5 -1
  51. package/agent-tools/context.mjs +5 -4
  52. package/agent-tools/design-slots.mjs +7 -4
  53. package/agent-tools/design-token.mjs +3 -2
  54. package/agent-tools/doc-graph.mjs +257 -95
  55. package/agent-tools/escalate-async.mjs +4 -1
  56. package/agent-tools/goal.mjs +28 -95
  57. package/agent-tools/plan.mjs +1 -1
  58. package/agent-tools/review-facts.mjs +56 -7
  59. package/agent-tools/settings.mjs +35 -1
  60. package/agent-tools/ssh-transport.mjs +23 -22
  61. package/agent-tools/step.mjs +24 -4
  62. package/agent-tools/subagent-actions.mjs +6 -2
  63. package/agent-tools/subagent-async.mjs +4 -2
  64. package/agent-tools/subagent.mjs +1 -1
  65. package/agent-tools/task.mjs +73 -65
  66. package/agent-tools.mjs +3 -3
  67. package/agent.mjs +12 -3
  68. package/auto-think.mjs +16 -3
  69. package/browser/actions.mjs +5 -1
  70. package/browser/cdp.mjs +1 -1
  71. package/browser/pool.mjs +110 -17
  72. package/compaction-work-state.mjs +103 -13
  73. package/compress-form.mjs +29 -3
  74. package/config-defaults.mjs +27 -3
  75. package/config-io.mjs +3 -14
  76. package/config-normalize.mjs +24 -4
  77. package/config-presets.mjs +40 -26
  78. package/config-warn.mjs +30 -0
  79. package/config.mjs +139 -63
  80. package/context-degrade.mjs +4 -4
  81. package/context-push.mjs +20 -9
  82. package/context.mjs +65 -20
  83. package/doc-graph/anchors.mjs +39 -40
  84. package/doc-graph/clusters.mjs +49 -0
  85. package/doc-graph/code-parsers.mjs +494 -0
  86. package/doc-graph/context-pack.mjs +392 -0
  87. package/doc-graph/dir-signals.mjs +228 -0
  88. package/doc-graph/edges.mjs +231 -0
  89. package/doc-graph/format.mjs +70 -0
  90. package/doc-graph/gc-cmd.mjs +104 -0
  91. package/doc-graph/gc.mjs +112 -0
  92. package/doc-graph/glob-work-graph.mjs +307 -0
  93. package/doc-graph/golden-set.mjs +131 -0
  94. package/doc-graph/ls-work-graph.mjs +534 -0
  95. package/doc-graph/outline.mjs +377 -0
  96. package/doc-graph/output-annotations.mjs +85 -0
  97. package/doc-graph/process-docs.mjs +68 -0
  98. package/doc-graph/read-work-graph.mjs +91 -0
  99. package/doc-graph/rebuild-cmd.mjs +75 -0
  100. package/doc-graph/resolvers.mjs +322 -0
  101. package/doc-graph/roots.mjs +86 -0
  102. package/doc-graph/schema.mjs +110 -0
  103. package/doc-graph/search-augment.mjs +418 -0
  104. package/doc-graph/store.mjs +231 -0
  105. package/doc-graph/target-resolve.mjs +352 -0
  106. package/doc-graph/walk.mjs +87 -0
  107. package/doc-graph.mjs +583 -707
  108. package/explore-distill.mjs +52 -17
  109. package/generate-title.mjs +7 -4
  110. package/ledger-close.mjs +6 -6
  111. package/ledger-cmd.mjs +3 -3
  112. package/ledger-consistency.mjs +8 -6
  113. package/ledger-db.mjs +45 -10
  114. package/ledger-migrate.mjs +25 -10
  115. package/ledger-read.mjs +1 -1
  116. package/ledger-write-ops.mjs +6 -6
  117. package/ledger.mjs +2 -2
  118. package/model-context.mjs +54 -18
  119. package/model-specs.mjs +86 -67
  120. package/package.json +1 -1
  121. package/prompt-overlays.mjs +3 -3
  122. package/prompts/advisor-round1.md +6 -5
  123. package/prompts/common.md +16 -6
  124. package/prompts/consult-base.md +2 -1
  125. package/prompts/discipline-engineering.md +1 -1
  126. package/prompts/discipline-normal.md +12 -8
  127. package/prompts/knowledge/doc-lookup.md +2 -2
  128. package/prompts/knowledge/normal-batch-discipline.md +2 -2
  129. package/prompts/knowledge/normal-delivery-collaboration.md +3 -3
  130. package/prompts/knowledge/tool-advisor.md +2 -2
  131. package/prompts/knowledge/tool-apply-patch.md +1 -1
  132. package/prompts/knowledge/tool-bash.md +2 -2
  133. package/prompts/knowledge/tool-batch.md +4 -4
  134. package/prompts/knowledge/tool-glob.md +9 -2
  135. package/prompts/knowledge/tool-goal.md +9 -6
  136. package/prompts/knowledge/tool-grep.md +7 -2
  137. package/prompts/knowledge/tool-ls.md +11 -5
  138. package/prompts/knowledge/tool-lsp.md +1 -1
  139. package/prompts/knowledge/tool-operations.md +3 -2
  140. package/prompts/knowledge/tool-plan.md +1 -1
  141. package/prompts/knowledge/tool-read.md +7 -6
  142. package/prompts/knowledge/tool-repo-graph-read.md +12 -0
  143. package/prompts/knowledge/tool-repo-graph.md +12 -0
  144. package/prompts/knowledge/tool-step.md +1 -1
  145. package/prompts/knowledge/tool-subagent.md +2 -2
  146. package/prompts/knowledge/tool-task.md +10 -9
  147. package/prompts/knowledge/tool-tree.md +7 -1
  148. package/prompts/persona-eng-coder.md +1 -1
  149. package/prompts/persona-eng-designer.md +1 -1
  150. package/prompts/persona-engineering.md +2 -1
  151. package/prompts/persona-explore.md +1 -1
  152. package/prompts/persona-normal.md +7 -6
  153. package/prompts/persona-plan.md +2 -2
  154. package/prompts/planning-next-moves.md +7 -8
  155. package/provider/anthropic.mjs +53 -51
  156. package/provider/core.mjs +85 -34
  157. package/provider/errors.mjs +33 -10
  158. package/provider/google.mjs +244 -37
  159. package/provider/list-models.mjs +28 -14
  160. package/provider/responses-request.mjs +15 -9
  161. package/provider/responses.mjs +10 -8
  162. package/provider/sse.mjs +3 -6
  163. package/proxy-transport.mjs +228 -119
  164. package/rules-file.mjs +79 -0
  165. package/rules.mjs +13 -51
  166. package/session-lifecycle.mjs +32 -20
  167. package/team-ledger.mjs +7 -7
  168. package/think-off.mjs +37 -18
  169. package/token-window.mjs +48 -31
  170. package/tool-args.mjs +8 -8
  171. package/tool-docs/bash.md +1 -1
  172. package/tool-docs/glob.md +3 -1
  173. package/tool-docs/goal.md +2 -2
  174. package/tool-docs/grep.md +3 -1
  175. package/tool-docs/ls.md +7 -1
  176. package/tool-docs/read.md +1 -1
  177. package/tool-docs/repo_graph-read.md +3 -0
  178. package/tool-docs/repo_graph.md +3 -0
  179. package/tool-docs/tree.md +1 -1
  180. package/tools/bash.mjs +53 -8
  181. package/tools/browser.mjs +4 -4
  182. package/tools/file.mjs +34 -7
  183. package/tools/glob-dialect.mjs +57 -7
  184. package/tools/index.mjs +3 -7
  185. package/tools/patch.mjs +8 -7
  186. package/tools/process-doc-mark.mjs +13 -0
  187. package/tools/search.mjs +152 -37
  188. package/tools/shared.mjs +6 -0
  189. package/tools/tree.mjs +211 -8
  190. package/window-policy.mjs +205 -126
  191. package/prompts/knowledge/tool-doc-graph-read.md +0 -20
  192. package/prompts/knowledge/tool-doc-graph.md +0 -49
  193. package/prompts/knowledge/tool-peek.md +0 -10
  194. package/prompts/knowledge/tool-repo-outline.md +0 -4
  195. package/tool-docs/doc_graph-read.md +0 -3
  196. package/tool-docs/doc_graph.md +0 -3
  197. package/tool-docs/peek.md +0 -3
  198. package/tool-docs/repo_outline.md +0 -3
  199. package/tools/peek.mjs +0 -447
@@ -0,0 +1,418 @@
1
+ /**
2
+ * search-augment.mjs — grep 命中行上的图谱注解(glob / ls 已切到各自的工作图模块)。
3
+ *
4
+ * 两件事在同一次建图里算完,且都落在**命中行自己身上**,不再另起一段「另一批文件」的清单:
5
+ * - 每个命中档的首行缀 ` · ←N`(该档被多少个源码档 import)与本结果集内最大者的 `(本结果集最多)`
6
+ * - 该档的引用方名单 `↳ 引用者:`、直接/展开的设计与配对文档及直接导入测试(写整档阅读提示),都是首行之下的缩进行
7
+ * 为什么不是另起一段:一次 grep 的命中有几十上百行,模型读完清单就到终点;「还有哪些文档像相关」
8
+ * 讲的是另一批文件,和「这个词在哪」不是一个问题,挪位置、压数字都不解决。注解挂在展开自的那个命中档下面,
9
+ * 读那一行就同时拿到了「它被几次 import」「它的设计档与测试在哪」。
10
+ *
11
+ * 只有被展开过的命中档才有 `↳` 行(每根至多 `MAX_ANCHORS_PER_ROOT` 个)。`rank 3`(上游调用方/同级/下游)
12
+ * 不回注——它回答的不是「这个档的设计档是什么」,仍留在末尾知识段里(首屏 8 条 + 剩余条数)。
13
+ *
14
+ * 只由 tools/search.mjs 动态导入:本档静态闭包经 store.mjs 达 node:sqlite,
15
+ * 不得被端壳或工具门面前置静态引用。文件系统结果由调用方先完成;这里只加注记与追加段。
16
+ */
17
+ import { existsSync } from "node:fs"
18
+ import { basename, dirname, isAbsolute, posix, relative, resolve, sep, win32 } from "node:path"
19
+
20
+ import { buildCodeContextPack, buildDocContextPack } from "./context-pack.mjs"
21
+ import { fileInboundWithRefs } from "./dir-signals.mjs"
22
+ import { processDocPredicate } from "./process-docs.mjs"
23
+ import { discoverSubProjects, resolveProjectRootForFile, resolveQueryRoot } from "./roots.mjs"
24
+ import { syncGraph } from "./store.mjs"
25
+ import { resolveTargetInDb } from "./target-resolve.mjs"
26
+
27
+ export const KNOWLEDGE_COLD_FILE_LIMIT = 2500
28
+ const MAX_QUERY_TERMS = 6
29
+ const MAX_ANCHORS_PER_ROOT = 3
30
+ /** 注解行每组最多列几个名字:超过就写 `… +N`,一行注解不得长成一段话。 */
31
+ const REC_SHOW = 2
32
+ /** `↳ 引用者:` 列前几个:`←43` 列 43 个名字与列 43 条推荐同罪,数本身已在 `←N` 里。 */
33
+ const REFS_SHOW = 3
34
+
35
+ const slash = (p) => String(p ?? "").replace(/\\/g, "/")
36
+ const absPath = (p, base) => resolve(isAbsolute(String(p)) ? String(p) : resolve(base, String(p)))
37
+ /** 文件身份不等于大小写不敏感的查询词:仅 Windows 默认折叠大小写。 */
38
+ export const pathKey = (p, platform = process.platform) => {
39
+ if (platform !== "win32") return posix.resolve(p)
40
+ return slash(win32.resolve(p)).toLowerCase()
41
+ }
42
+
43
+ /** 搜索词只提供图谱定位线索;正则运算符与 glob 通配符不进入查询。 */
44
+ export function extractKnowledgeTerms(tool, args = {}) {
45
+ let source = tool === "grep" || tool === "glob" ? String(args.pattern ?? "") : ""
46
+ if (!source.trim()) return []
47
+ if (tool === "glob") {
48
+ // `*.mjs` / `*.{js,mjs}` 只是文件过滤条件,不是“查找 mjs/js 主题”。
49
+ source = source
50
+ .replace(/(?:^|\s)!\S+/g, " ")
51
+ .replace(/\*?\.\{[^}\s]*\}/g, " ")
52
+ .replace(/\*\.[\p{L}\p{N}_]+/gu, " ")
53
+ } else if (tool === "grep" && args.literal !== true) {
54
+ source = source
55
+ .replace(/\\\./g, "\u0000")
56
+ .replace(/\\[sSdDwWbB]/g, " ")
57
+ .replace(/\[[^\]]*\]/g, " ")
58
+ .replace(/[.*+?^${}()|[\]\\]/g, " ")
59
+ .replace(/\u0000/g, ".")
60
+ }
61
+ const seen = new Set()
62
+ const out = []
63
+ for (const match of source.matchAll(/[\p{L}\p{N}_][\p{L}\p{N}_.-]*/gu)) {
64
+ const term = match[0].trim().replace(/^[.-]+|[.-]+$/g, "")
65
+ const key = term.toLowerCase()
66
+ if (term.length < 2 || seen.has(key)) continue
67
+ seen.add(key)
68
+ out.push(term)
69
+ if (out.length >= MAX_QUERY_TERMS) break
70
+ }
71
+ return out
72
+ }
73
+
74
+ function targetPaths(args, cwd, tool) {
75
+ const raw = Array.isArray(args.paths) && args.paths.length > 0
76
+ ? args.paths
77
+ : typeof args.path === "string" && args.path.trim()
78
+ ? [args.path]
79
+ : [cwd]
80
+ const cleaned = raw.map((p) => String(p).trim()).filter(Boolean)
81
+ // 与 grep 主径一致:完整现存路径优先;只有单个不存在目标才尝试逗号多目标。
82
+ if (tool === "grep" && cleaned.length === 1 && cleaned[0].includes(",") && !existsSync(absPath(cleaned[0], cwd))) {
83
+ const split = cleaned[0].split(",").map((p) => p.trim()).filter(Boolean)
84
+ if (split.length > 1) return split.map((p) => absPath(p, cwd))
85
+ }
86
+ return cleaned.map((p) => absPath(p, cwd))
87
+ }
88
+
89
+ function containsPath(target, file) {
90
+ const rel = relative(target, file)
91
+ return rel === "" || (!isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`))
92
+ }
93
+
94
+ function fallbackRootForHit(hit, targets, cwd) {
95
+ const target = targets
96
+ .filter((candidate) => containsPath(candidate, hit))
97
+ .sort((a, b) => b.length - a.length)[0]
98
+ if (!target) return dirname(hit)
99
+ const resolved = resolveQueryRoot(target)
100
+ // workspace 命中有标记时仍由 resolveProjectRootForFile 落真实子仓;无标记才回到搜索目标。
101
+ return resolved.ok ? resolved.root : target
102
+ }
103
+
104
+ /** 有真实命中时按命中落子仓;零命中时按搜索目标判根,父工作区逐直接子仓处理。 */
105
+ export function knowledgeRootsForCall(args = {}, ctx = {}, hitPaths = [], tool = "grep") {
106
+ const cwd = resolve(String(ctx.cwd ?? ctx.agent?.cwd ?? "."))
107
+ const targets = targetPaths(args, cwd, tool)
108
+ const roots = new Map()
109
+ const add = (root) => { if (root) roots.set(pathKey(root), resolve(root)) }
110
+ if (hitPaths.length > 0) {
111
+ for (const p of hitPaths) {
112
+ const abs = absPath(p, cwd)
113
+ add(resolveProjectRootForFile(abs, fallbackRootForHit(abs, targets, cwd)))
114
+ }
115
+ return [...roots.values()]
116
+ }
117
+ for (const target of targets) {
118
+ const resolved = resolveQueryRoot(target)
119
+ if (resolved.ok) add(resolved.root)
120
+ else if (resolved.reason === "workspace") {
121
+ for (const sub of discoverSubProjects(target)) add(sub.root)
122
+ }
123
+ }
124
+ return [...roots.values()]
125
+ }
126
+
127
+ /**
128
+ * 候选池。`anchor` 记「这条推荐是从哪个命中档展开出来的」——注解行靠它归位。
129
+ * 同一个候选被多个锚点展开时归 rank 最小的那个(同 rank 归先入者,锚点按命中顺序进),
130
+ * 这就是旧的跨命中去重口径,不变。
131
+ */
132
+ function makeCollector(root, isProc, excludedPaths) {
133
+ const candidates = new Map()
134
+ const add = (item, { rank, role, reason }, anchor = null) => {
135
+ if (!item?.path) return
136
+ const abs = isAbsolute(item.path) ? resolve(item.path) : resolve(root, item.path)
137
+ const key = pathKey(abs)
138
+ if (excludedPaths.has(key)) return
139
+ const rel = slash(relative(root, abs))
140
+ if (!rel || rel.startsWith("../") || rel === "..") return
141
+ if (isProc(rel)) return
142
+ const next = {
143
+ root,
144
+ abs,
145
+ path: rel,
146
+ lines: Number(item.lines) || 0,
147
+ rank,
148
+ role,
149
+ anchor,
150
+ reason: String(reason ?? "图谱关联"),
151
+ }
152
+ const prev = candidates.get(key)
153
+ if (!prev || rank < prev.rank) candidates.set(key, next)
154
+ }
155
+ return { candidates, add }
156
+ }
157
+
158
+ /** `via` 在 context-pack 里有两种形状:字符串(测试的编排者)与 Set(同级模块的编排者集合)。
159
+ * 直接模板插值 Set 会写出 `[object Set]`——一句没有任何信息量的 reason,所以统一先成文本。 */
160
+ const viaText = (v) => (v instanceof Set ? [...v].slice(0, 2).join(" / ") : String(v ?? ""))
161
+
162
+ function addPackCandidates(pack, add, anchor) {
163
+ for (const doc of pack.docs ?? []) {
164
+ add(doc, {
165
+ rank: doc.direct === false ? 1 : 0,
166
+ role: doc.direct === false ? "配对文档" : "需求/设计",
167
+ reason: doc.reason || "归属文档",
168
+ }, anchor)
169
+ }
170
+ // 这组回注只承诺直接导入;上游关联测试仍归 repo_graph(context),不在这里换名冒充直接测试。
171
+ for (const test of pack.tests ?? []) {
172
+ if (test.via) continue
173
+ add(test, { rank: 2, role: "直接导入测试", reason: "直接导入命中档" }, anchor)
174
+ }
175
+ for (const [items, label] of [[pack.callers, "上游调用方"], [pack.siblings, "同级模块"], [pack.deps, "下游依赖"]]) {
176
+ for (const item of items ?? []) add(item, { rank: 3, role: label, reason: item.via ? `经由 ${viaText(item.via)}` : "高影响关系" }, anchor)
177
+ }
178
+ // 文档向 context-pack 把对应源码/测试放在 coveredCode,而非 tests/deps。
179
+ for (const item of pack.coveredCode ?? []) {
180
+ // 文档覆盖的测试不必然 import 当前命中档;只回注对应源码,测试留给精确 context 判读。
181
+ if (item.kind === "test") continue
182
+ add(item, { rank: 3, role: "对应源码", reason: "文档路径或符号引用" }, anchor)
183
+ }
184
+ }
185
+
186
+ function expandResolved(db, resolved, term, add, expanded, isProc, anchor = null) {
187
+ // 与 repo_graph(context) 同一边界:多候选需要调用方精化,不能把排序前几名冒充相关知识。
188
+ if (resolved.kind === "ambiguous") return
189
+ if (resolved.kind !== "file" || !resolved.file) return
190
+ const file = resolved.file
191
+ if (file.kind === "doc") add(file, { rank: 0, role: "需求/设计", reason: `搜索词或章节命中:${term}` }, anchor)
192
+ else add(file, { rank: file.kind === "test" ? 2 : 3, role: file.kind === "test" ? "测试" : "命中源码", reason: `搜索词或路径命中:${term}` }, anchor)
193
+ if (expanded.has(file.path)) return
194
+ expanded.add(file.path)
195
+ const pack = file.kind === "doc"
196
+ ? buildDocContextPack(db, file, resolved.byPath, isProc)
197
+ : buildCodeContextPack(db, file, resolved.byPath, resolved.matchedSymbol, isProc)
198
+ addPackCandidates(pack, add, anchor)
199
+ }
200
+
201
+ /**
202
+ * 一根的候选与该根命中档的行注记。
203
+ * `rowNotes` 覆盖**全部**命中档(不只是展开过的那几个):`←N` 是档属性,问的是「谁 import 了它」,
204
+ * 与「有没有被展开」无关。一次 `fileInbound` 取全表,不按档逐次查库。
205
+ */
206
+ function buildRootKnowledge(root, { terms, hitPaths, excludedPaths }, sync = syncGraph) {
207
+ const { db, fileCount, skippedCold } = sync(root, { maxColdFiles: KNOWLEDGE_COLD_FILE_LIMIT })
208
+ if (skippedCold || !db) {
209
+ return {
210
+ candidates: [],
211
+ rowNotes: new Map(),
212
+ docAnchors: [],
213
+ notes: [`冷仓共 ${fileCount} 档,超过 ${KNOWLEDGE_COLD_FILE_LIMIT},已跳过自动建图;需要时显式调用 repo_graph(action="overview", target=${JSON.stringify(root)})。`],
214
+ }
215
+ }
216
+ try {
217
+ const isProc = processDocPredicate(root)
218
+ const { candidates, add } = makeCollector(root, isProc, excludedPaths)
219
+ const expanded = new Set()
220
+ const seenAnchors = new Set()
221
+ const rootHits = []
222
+ for (const p of hitPaths) {
223
+ const abs = absPath(p, root)
224
+ if (pathKey(resolveProjectRootForFile(abs, root)) !== pathKey(root)) continue
225
+ const key = pathKey(abs)
226
+ if (seenAnchors.has(key)) continue
227
+ seenAnchors.add(key)
228
+ rootHits.push(abs)
229
+ }
230
+ const byPath = new Map(db.prepare("SELECT path, kind, lines FROM files").all().map((f) => [f.path, f]))
231
+ const directRecs = new Map()
232
+ // 完整展开仍只走前三个命中档;直接权威文档、配对档与直接测试则覆盖全部命中档,且不按文档跨档去重。
233
+ for (const abs of rootHits) {
234
+ const rel = slash(relative(root, abs))
235
+ if (!byPath.has(rel) || byPath.get(rel).kind === "doc") continue
236
+ const items = []
237
+ const seen = new Set()
238
+ const addDirect = (path, rank, role, reason) => {
239
+ const f = byPath.get(path)
240
+ const key = `${rank}\0${path}`
241
+ if (!f || isProc(path) || seen.has(key)) return
242
+ seen.add(key)
243
+ items.push({ path, lines: f.lines ?? 0, rank, role, reason })
244
+ }
245
+ const docEdges = db.prepare(
246
+ "SELECT DISTINCT src FROM edges WHERE dst = ? AND kind IN ('doc-covers', 'doc-symbol') AND state = 'ok'",
247
+ ).all(rel)
248
+ for (const { src } of docEdges) {
249
+ addDirect(src, 0, "需求/设计", "直接归属")
250
+ const peer = /\/design\//i.test(src)
251
+ ? src.replace(/\/design\//i, "/requirements/")
252
+ : /\/requirements\//i.test(src) ? src.replace(/\/requirements\//i, "/design/") : null
253
+ if (peer) addDirect(peer, 0, "需求/设计", "同主题配对")
254
+ }
255
+ const testEdges = db.prepare(
256
+ "SELECT DISTINCT src FROM edges WHERE dst = ? AND kind = 'imports' AND state = 'ok'",
257
+ ).all(rel)
258
+ for (const { src } of testEdges) {
259
+ if (byPath.get(src)?.kind === "test") addDirect(src, 2, "直接导入测试", "直接导入命中档")
260
+ }
261
+ items.sort((a, b) => a.rank - b.rank || a.path.localeCompare(b.path))
262
+ directRecs.set(pathKey(abs), items)
263
+ }
264
+ for (const abs of rootHits.slice(0, MAX_ANCHORS_PER_ROOT)) {
265
+ const rel = slash(relative(root, abs))
266
+ const resolved = resolveTargetInDb(db, rel, isProc)
267
+ expandResolved(db, resolved, rel, add, expanded, isProc, pathKey(abs))
268
+ }
269
+ for (const term of terms) {
270
+ const resolved = resolveTargetInDb(db, term, isProc)
271
+ expandResolved(db, resolved, term, add, expanded, isProc, null)
272
+ }
273
+ const rowNotes = new Map()
274
+ const docAnchors = []
275
+ if (rootHits.length > 0) {
276
+ // 数与前几个引用方同一次扫描取回(同一批 `edges`,不是第二趟查库)。
277
+ const inbound = fileInboundWithRefs(db, REFS_SHOW)
278
+ for (const abs of rootHits) {
279
+ const rel = slash(relative(root, abs))
280
+ const kind = byPath.get(rel)?.kind ?? null
281
+ // 只有入图的源码档带数:文档行已有层标签,再缀一个入度会把两种语义搅在一起;
282
+ // 没入图的档不写数——「没入图」与「←0」是两件事。
283
+ rowNotes.set(pathKey(abs), kind === "code" ? (inbound.get(rel) ?? { count: 0, refs: [] }) : null)
284
+ // 文档档的 `↳` 行探的是 `doc-cites`(被谁引用/引用了谁),不是「本档的设计规格」——
285
+ // 下游要靠这个标志换标签,否则把「相关文档」说成「设计」。
286
+ if (kind === "doc") docAnchors.push(pathKey(abs))
287
+ }
288
+ }
289
+ return { candidates: [...candidates.values()], rowNotes, docAnchors, directRecs, notes: [] }
290
+ } finally {
291
+ try { db.close() } catch { /* 缓存库关闭失败不影响原始结果 */ }
292
+ }
293
+ }
294
+
295
+ /**
296
+ * 可注入 sync 的内部测试面;生产调用只传第一个参数。
297
+ * 返回的候选同时带着 `anchor`,调用方据此把 rank ≤2 的推荐散回各自命中档。
298
+ */
299
+ export function buildSearchKnowledge({ tool, args = {}, ctx = {}, hitPaths = [] }, sync = syncGraph) {
300
+ const roots = knowledgeRootsForCall(args, ctx, hitPaths, tool)
301
+ const excludedPaths = new Set(hitPaths.map((p) => pathKey(absPath(p, ctx.cwd ?? ctx.agent?.cwd ?? "."))))
302
+ const terms = extractKnowledgeTerms(tool, args)
303
+ const candidates = new Map()
304
+ const rowNotes = new Map()
305
+ const docAnchors = new Set()
306
+ const directRecs = new Map()
307
+ const notes = []
308
+ for (const root of roots) {
309
+ try {
310
+ const result = buildRootKnowledge(root, { terms, hitPaths, excludedPaths }, sync)
311
+ for (const item of result.candidates) {
312
+ const key = pathKey(item.abs)
313
+ const prev = candidates.get(key)
314
+ if (!prev || item.rank < prev.rank) candidates.set(key, item)
315
+ }
316
+ for (const [key, value] of result.rowNotes) if (!rowNotes.has(key)) rowNotes.set(key, value)
317
+ for (const key of result.docAnchors) docAnchors.add(key)
318
+ for (const [key, value] of result.directRecs ?? []) if (!directRecs.has(key)) directRecs.set(key, value)
319
+ notes.push(...result.notes)
320
+ } catch (error) {
321
+ notes.push(`项目 ${root} 自动增强失败:${error?.message || String(error)};原始文件系统结果不受影响。`)
322
+ }
323
+ }
324
+ return { candidates: [...candidates.values()], rowNotes, docAnchors, directRecs, notes, rootCount: roots.length }
325
+ }
326
+
327
+ /** 挂在某个命中档下的推荐;`rank ≤ 2` 才回注(rank 3 归 `repo_graph(context)`,不回注也不另列)。 */
328
+ function recsByAnchor(candidates) {
329
+ const map = new Map()
330
+ for (const item of candidates) {
331
+ if (!item.anchor || item.rank > 2) continue
332
+ if (!map.has(item.anchor)) map.set(item.anchor, [])
333
+ map.get(item.anchor).push(item)
334
+ }
335
+ for (const list of map.values()) list.sort((a, b) => a.rank - b.rank || a.path.localeCompare(b.path))
336
+ return map
337
+ }
338
+
339
+ /** 名字用基名;同组里基名撞车时改用仓内相对路径(两行同名只能被读成重复,与 `ls` 的 hub 同一条理由)。 */
340
+ function shortLabels(items, { keepPaths = false } = {}) {
341
+ if (keepPaths) return items.map((item) => item.path)
342
+ const count = new Map()
343
+ for (const item of items) {
344
+ const base = basename(item.path)
345
+ count.set(base, (count.get(base) ?? 0) + 1)
346
+ }
347
+ return items.map((item) => (count.get(basename(item.path)) > 1 ? item.path : basename(item.path)))
348
+ }
349
+
350
+ /** 引用方名单:只列文件名。`↳ 引用者:` 回答的是「这个位置要不要去读?」,目录聚合回答的是
351
+ * 「这个仓怎么分层」——那是另一个问题,另一个位置。 */
352
+ function renderRefs(refs, count) {
353
+ const shown = shortLabels(refs.slice(0, REFS_SHOW).map((path) => ({ path })))
354
+ const rest = count - shown.length
355
+ return `${shown.join(" · ")}${rest > 0 ? ` … +${rest}` : ""}`
356
+ }
357
+
358
+ function renderRecLine(items, docAnchor = false) {
359
+ const group = (list, label, { keepPaths = false } = {}) => {
360
+ if (list.length === 0) return ""
361
+ const shown = shortLabels(list.slice(0, REC_SHOW), { keepPaths }).join(" · ")
362
+ const rest = list.length - REC_SHOW
363
+ return `${label}: ${shown}${rest > 0 ? ` … +${rest}` : ""}`
364
+ }
365
+ return [
366
+ // 文档档上这组是 `doc-cites` 的邻档(被本档引用),不是它的设计规格。
367
+ group(items.filter((item) => item.rank <= 1), docAnchor ? "相关文档" : "设计(修改前整档 read)", { keepPaths: true }),
368
+ group(items.filter((item) => item.rank === 2), "直接导入测试", { keepPaths: true }),
369
+ ].filter(Boolean).join(" | ")
370
+ }
371
+
372
+ /**
373
+ * grep 的注解入口:输入原始命中行(`{ file, text }`,输出顺序),返回加了注记的行与末尾知识段。
374
+ * 行文本的 `path:line: text` 不动,注记只缀行尾;同一档只在**首条**命中行上标一次。
375
+ * 任何异常都退回原行 + 一行降级说明,绝不改写或丢行。
376
+ */
377
+ export async function annotateGrepRows({ args = {}, ctx = {}, hitPaths = [], rows = [] }, sync = syncGraph) {
378
+ const plain = rows.map((row) => row.text)
379
+ try {
380
+ const built = buildSearchKnowledge({ tool: "grep", args, ctx, hitPaths }, sync)
381
+ const recs = recsByAnchor(built.candidates)
382
+ // 末尾不再列推荐:`rank 3` 上下游与按词展开的候选是半个 `repo_graph(context)`,比它差一档却撑出第二段。
383
+ // 只剩降级事项——那必须说:图谱没加载成,得让人知道注记为什么不在。
384
+ const section = built.notes.map((note) => `[Knowledge · repo_graph] ${note}`).join("\n")
385
+ const lines = []
386
+ const seen = new Set()
387
+ // 「本结果集最多」跨**全部命中档**算一次(不只是被展开的那 3 个锚点):`←N` 是档属性,
388
+ // 比大小也在这批档之间比。并列第一全部标注——同一张表两个副本同是 `←43` 时挑一个是编的;
389
+ // 全批都是 0 时谁也不是「最多」,`←0` 已把「没人用」说完了。
390
+ let maxInbound = 0
391
+ for (const note of built.rowNotes.values()) {
392
+ if (typeof note?.count === "number" && note.count > maxInbound) maxInbound = note.count
393
+ }
394
+ for (const row of rows) {
395
+ const key = pathKey(row.file)
396
+ const first = !seen.has(key)
397
+ if (first) seen.add(key)
398
+ const note = first ? built.rowNotes.get(key) : undefined
399
+ const inbound = typeof note?.count === "number" ? note.count : null
400
+ const top = inbound !== null && inbound > 0 && inbound === maxInbound ? "(本结果集最多)" : ""
401
+ lines.push(inbound === null ? row.text : `${row.text} · ←${inbound}${top}`)
402
+ // `←0` 不出名单行:没有引用者这件事 `←0` 已经说完了,再写一行是噪声。
403
+ if (inbound !== null && inbound > 0 && note.refs?.length) {
404
+ lines.push(` ↳ 引用者: ${renderRefs(note.refs, inbound)}`)
405
+ }
406
+ const list = first ? [...(built.directRecs.get(key) ?? []), ...(recs.get(key) ?? [])] : []
407
+ if (list.length > 0) {
408
+ const unique = [...new Map(list.map((item) => [`${item.rank}\0${item.path}`, item])).values()]
409
+ .sort((a, b) => a.rank - b.rank || a.path.localeCompare(b.path))
410
+ const text = renderRecLine(unique, built.docAnchors.has(key))
411
+ if (text) lines.push(` ↳ ${text}`)
412
+ }
413
+ }
414
+ return { lines, section }
415
+ } catch (error) {
416
+ return { lines: plain, section: `[Knowledge · repo_graph] 自动增强失败:${error?.message || String(error)};原始文件系统结果不受影响。` }
417
+ }
418
+ }
@@ -0,0 +1,231 @@
1
+ /**
2
+ * doc-graph/store.mjs — 图谱库同步门面:按 `(mtime_ms, size)` 懒增量同步 + 只重建边表的轻路径。
3
+ *
4
+ * 拆分后的职责边界(本档只留「什么时候重算」这一件事,其余各归其档):
5
+ * - `schema.mjs`:库结构、迁移顺序、图库路径与 `openGraphDb`;
6
+ * - `walk.mjs`:哪些档入图(目录剪枝与过程档判据);
7
+ * - `resolvers.mjs`:一条 raw 引用落到仓内哪个真实路径(五语言 + 文档路径);
8
+ * - `edges.mjs`:从 `files`/`exports`/`raw_refs` 重算 `edges`。
9
+ *
10
+ * 对外签名不变:`openGraphDb` / `graphDbPath` / `graphKey` / `graphDirPath` / `_setGraphDirForTest` /
11
+ * `_resetGraphDirForTest` 由本档原样再导出,既有消费方(`golden-set.mjs`、`gc-cmd.mjs`、
12
+ * `rebuild-cmd.mjs`、两份集成档)一行不改照样 import 得动。
13
+ *
14
+ * 静态链路不暴露给端壳静态闭包:消费方动态 import 本模块(遵 W8 契约②)。
15
+ */
16
+ import { createHash } from "node:crypto"
17
+ import { existsSync, readFileSync } from "node:fs"
18
+ import { dirname, join, resolve } from "node:path"
19
+ import { fileURLToPath } from "node:url"
20
+
21
+ import { parseCodeFile, parseMarkdownDoc } from "./code-parsers.mjs"
22
+ import { rebuildEdgesInTx } from "./edges.mjs"
23
+ import { PRUNE_INTERVAL_MS, STALE_GRAPH_MS, graphGc } from "./gc.mjs"
24
+ import { graphDbPath, graphDirPath, graphKey, openGraphDb } from "./schema.mjs"
25
+ import { countLines, walkRepoFiles } from "./walk.mjs"
26
+
27
+ export {
28
+ _resetGraphDirForTest,
29
+ _setGraphDirForTest,
30
+ graphDbPath,
31
+ graphDirPath,
32
+ graphKey,
33
+ openGraphDb,
34
+ } from "./schema.mjs"
35
+
36
+ // P2-9 增量:解析器签名 = 参与解析/扫档/落边的模块档的**内容**摘要。
37
+ // 早先用 `(mtime_ms, size)`:同尺寸同 mtime 的改写(复制保时、构建还原)判不出变化。
38
+ // 内容哈希补上这一层;拆分后凡影响「什么档入图 / 边怎么落」的子档一律在列 —— 漏掉一档就等于
39
+ // 改了判据却复用旧图(`#65-2` 的原始病灶)。
40
+ const PARSER_SOURCES = [
41
+ "code-parsers.mjs",
42
+ "process-docs.mjs",
43
+ "walk.mjs",
44
+ "resolvers.mjs",
45
+ "edges.mjs",
46
+ "store.mjs",
47
+ ]
48
+
49
+ /**
50
+ * 一组源档的内容摘要。仓内两个消费面:`parserSignature`(签名接线)与常驻集成用例
51
+ * `test/integration/doc-anchor-graph.test.mjs` 的 43-7(判摘要本身对同尺寸同 mtime 改写敏感)。
52
+ * @param {string} dir 目录绝对路径
53
+ * @param {string[]} names 目录内的档名
54
+ * @returns {string} 16 位 hex
55
+ */
56
+ export function hashSourceFiles(dir, names) {
57
+ const h = createHash("sha1")
58
+ for (const name of names) {
59
+ let body = null
60
+ try { body = readFileSync(join(dir, name)) } catch { body = null }
61
+ h.update(`${name}:`)
62
+ h.update(body ?? "absent")
63
+ h.update("|")
64
+ }
65
+ return h.digest("hex").slice(0, 16)
66
+ }
67
+
68
+ function parserSignature() {
69
+ return hashSourceFiles(dirname(fileURLToPath(import.meta.url)), PARSER_SOURCES)
70
+ }
71
+
72
+ /**
73
+ * 按 `mtime_ms` + `size` 自动懒增量同步知识图谱,并重建受影响边。
74
+ * 未改动项目仅做目录 stat 对比,~5–15ms 返回;改动后只重解析变更文件并原子重建边表。
75
+ * **对外建议入口**:内部经 `openGraphDb`(裸库面,`schema.mjs`)开库——不解析只开库的直调请走那边;
76
+ * 返回形 `{ db, changedCount, deletedCount, fileCount }`(冷仓限额命中 ⇒ `{ db: null, skippedCold: true, … }`)。
77
+ */
78
+ export function syncGraph(root, { maxColdFiles = 0, forceRebuild = false } = {}) {
79
+ const absRoot = resolve(root)
80
+ const hadDb = existsSync(graphDbPath(absRoot))
81
+ if (!hadDb && maxColdFiles > 0) {
82
+ const diskFiles = walkRepoFiles(absRoot)
83
+ if (diskFiles.size > maxColdFiles) {
84
+ return { db: null, skippedCold: true, changedCount: 0, deletedCount: 0, fileCount: diskFiles.size }
85
+ }
86
+ }
87
+ const db = openGraphDb(absRoot)
88
+ try {
89
+ // P2-9:解析器签名变了(含首次建库 / 升级后首跑)⇒ 本次按全量重抽走一次,然后把新签名写回。
90
+ const parserSig = parserSignature()
91
+ const prevSig = db.prepare("SELECT value FROM meta WHERE key = 'parser_sig'").get()?.value ?? null
92
+ const rebuildAll = forceRebuild || prevSig !== parserSig
93
+ const diskFiles = walkRepoFiles(absRoot)
94
+ const dbRows = db.prepare("SELECT path, kind, lang, mtime_ms, size, lines, namespace FROM files").all()
95
+ const dbMap = new Map(dbRows.map((r) => [r.path, r]))
96
+
97
+ const changed = []
98
+ const deleted = []
99
+ for (const [rel, info] of diskFiles) {
100
+ const prev = dbMap.get(rel)
101
+ // forceRebuild 语义 = 全量重抽:解析器 / store 改了但源档 mtime 未变时,增量检测看不到这层变化,只能强制重抽(P0-2 的边源在这里;下一次真改源码时自动落)。
102
+ if (rebuildAll || !prev || prev.mtime_ms !== info.mtimeMs || prev.size !== info.size) {
103
+ changed.push({ rel, info })
104
+ }
105
+ }
106
+ for (const rel of dbMap.keys()) {
107
+ if (!diskFiles.has(rel)) deleted.push(rel)
108
+ }
109
+
110
+ if (changed.length === 0 && deleted.length === 0 && !rebuildAll) {
111
+ return { db, changedCount: 0, deletedCount: 0, fileCount: dbRows.length }
112
+ }
113
+
114
+ db.exec("BEGIN")
115
+ try {
116
+ const delFile = db.prepare("DELETE FROM files WHERE path = ?")
117
+ const delExp = db.prepare("DELETE FROM exports WHERE file = ?")
118
+ const delRef = db.prepare("DELETE FROM raw_refs WHERE file = ?")
119
+ const delHeading = db.prepare("DELETE FROM headings WHERE file = ?")
120
+ const upsertFile = db.prepare(
121
+ "INSERT OR REPLACE INTO files (path, kind, lang, mtime_ms, size, lines, namespace) VALUES (?, ?, ?, ?, ?, ?, ?)",
122
+ )
123
+ const insExp = db.prepare("INSERT OR IGNORE INTO exports (file, symbol) VALUES (?, ?)")
124
+ const insRef = db.prepare("INSERT INTO raw_refs (file, kind, raw, detail, line) VALUES (?, ?, ?, ?, ?)")
125
+ const insHeading = db.prepare("INSERT INTO headings (file, title, level, line) VALUES (?, ?, ?, ?)")
126
+
127
+ for (const rel of deleted) {
128
+ delFile.run(rel)
129
+ delExp.run(rel)
130
+ delRef.run(rel)
131
+ delHeading.run(rel)
132
+ }
133
+
134
+ for (const { rel, info } of changed) {
135
+ let text = ""
136
+ try { text = readFileSync(info.abs, "utf8") } catch { continue }
137
+ const lines = countLines(text)
138
+ delExp.run(rel)
139
+ delRef.run(rel)
140
+ delHeading.run(rel)
141
+
142
+ if (info.kind === "doc") {
143
+ upsertFile.run(rel, info.kind, info.lang, info.mtimeMs, info.size, lines, null)
144
+ const parsed = parseMarkdownDoc(text)
145
+ for (const pr of parsed.pathRefs) insRef.run(rel, "doc-path", pr.raw, "", pr.line)
146
+ for (const sc of parsed.symbolCandidates) insRef.run(rel, "doc-sym", sc.symbol, "", sc.line)
147
+ for (const h of parsed.headings) insHeading.run(rel, h.title, h.level, h.line)
148
+ } else {
149
+ const parsed = parseCodeFile(info.lang, text)
150
+ upsertFile.run(rel, info.kind, info.lang, info.mtimeMs, info.size, lines, parsed.namespace ?? null)
151
+ for (const sym of parsed.exports) insExp.run(rel, sym)
152
+ for (const imp of parsed.imports) {
153
+ insRef.run(rel, imp.global ? "cs-global-using" : "code-imp", imp.raw, imp.detail ?? imp.symbols.join(","), imp.line)
154
+ }
155
+ // 定义面(SQL 专用):裸名引用 `FROM t` / `CALL p` 在落边时要知道「谁声明了这个名字」。
156
+ // 表与视图是 `FROM` 的两个合法目标,而它们的定义档名不一定是对象名(`bms/tables/sys/chart/sys_chart_of_account.sql`
157
+ // 是视图、不是表),所以按 **声明** 记名,不按文件名猜。
158
+ for (const t of parsed.tables ?? []) insRef.run(rel, "sql-table", t, "", 0)
159
+ for (const v of parsed.views ?? []) insRef.run(rel, "sql-view", v, "", 0)
160
+ // P0-2 源面(落边面见 edges.mjs):代码头注 / 行注释引 `docs/**/*.md` 的设计档指路,落成 `code-cite` raw_ref。
161
+ for (const dc of parsed.docCites ?? []) {
162
+ insRef.run(rel, "code-cite", dc.raw, "", dc.line)
163
+ }
164
+ if (info.lang === "cs" && parsed.refs.length > 0) {
165
+ insRef.run(rel, "cs-refs", "", parsed.refs.join(","), 1)
166
+ }
167
+ }
168
+ }
169
+
170
+ // 全量轻量重算 edges(基于内存中的 files + exports + raw_refs,几百个文件 < 15ms,保证跨文件引用零漂移)
171
+ rebuildEdgesInTx(db, absRoot)
172
+ db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES ('parser_sig', ?)").run(parserSig)
173
+ db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES ('updated_at', ?)").run(new Date().toISOString())
174
+ db.exec("COMMIT")
175
+ } catch (err) {
176
+ try { db.exec("ROLLBACK") } catch { /* ignore */ }
177
+ throw err
178
+ }
179
+
180
+ const total = db.prepare("SELECT COUNT(*) AS n FROM files").get().n
181
+ pruneStaleGraphsIfDue(db, absRoot)
182
+ return { db, changedCount: changed.length, deletedCount: deleted.length, fileCount: total }
183
+ } catch (err) {
184
+ try { db.close() } catch { /* ignore */ }
185
+ throw err
186
+ }
187
+ }
188
+
189
+ /**
190
+ * 只重建边表(`#65-4` 轻路径):从**已落库的** `files` / `exports` / `raw_refs` 重算 `edges`,不重读源档。
191
+ * 用途 = 边语义改动后、或 `edges` 与 raw 面漂了的时候;源档改了仍要 `syncGraph`(只有它会重解析)。
192
+ * @param {string} root 项目根
193
+ * @returns {{ok: boolean, edges: number, files: number, ms: number}}
194
+ */
195
+ export function rebuildEdgesOnly(root) {
196
+ const absRoot = resolve(String(root ?? "."))
197
+ const started = Date.now()
198
+ const db = openGraphDb(absRoot)
199
+ try {
200
+ db.exec("BEGIN")
201
+ try {
202
+ rebuildEdgesInTx(db, absRoot)
203
+ db.exec("COMMIT")
204
+ } catch (err) {
205
+ try { db.exec("ROLLBACK") } catch { /* ignore */ }
206
+ throw err
207
+ }
208
+ const edges = db.prepare("SELECT COUNT(*) AS n FROM edges").get().n
209
+ const files = db.prepare("SELECT COUNT(*) AS n FROM files").get().n
210
+ db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES ('updated_at', ?)").run(new Date().toISOString())
211
+
212
+ return { ok: true, edges, files, ms: Date.now() - started }
213
+ } finally {
214
+ try { db.close() } catch { /* ignore */ }
215
+ }
216
+ }
217
+
218
+ /**
219
+ * P2-8 保守清理:每 `PRUNE_INTERVAL_MS` 最多跑一次,只删长期未用的图库档,不做 VACUUM。
220
+ * 该不该跑由这里决定,判据(多久算旧、删谁)单源在 `gc.mjs`;`keepKeys` 永远含当前项目,绝不删正在用的库。
221
+ * 失败绝不打断查询 —— 图库是纯缓存,清理出错下次再说。
222
+ */
223
+ function pruneStaleGraphsIfDue(db, absRoot) {
224
+ try {
225
+ const now = Date.now()
226
+ const last = Number(db.prepare("SELECT value FROM meta WHERE key = 'last_prune'").get()?.value ?? 0)
227
+ if (last > 0 && now - last < PRUNE_INTERVAL_MS) return
228
+ graphGc({ dir: graphDirPath(), keepKeys: [graphKey(absRoot)], staleAfterMs: STALE_GRAPH_MS, apply: true })
229
+ db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES ('last_prune', ?)").run(String(now))
230
+ } catch { /* 清理失败不影响查询 */ }
231
+ }