@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,231 @@
1
+ /**
2
+ * doc-graph/edges.mjs — 落边:从 `files` + `exports` + `raw_refs` 重算 `edges` 表。
3
+ *
4
+ * 一条边只用确定性的静态依据落成:真实路径解析(`resolvers.mjs`)、导出符号表、C# 命名空间。
5
+ * 零向量猜测、零反引号统计。`rebuildEdgesInTx` 只吃一个已打开的 db,事务由调用方持有 ——
6
+ * 增量同步与「只重建边表」两条路径共用它,谁的边界谁负责 COMMIT。
7
+ */
8
+ import { existsSync } from "node:fs"
9
+ import { basename, resolve } from "node:path"
10
+
11
+ import {
12
+ buildFileLookup,
13
+ buildJsResolver,
14
+ readGoModulePrefix,
15
+ resolveDocPath,
16
+ resolveGoImport,
17
+ resolveJsImport,
18
+ resolvePyImport,
19
+ resolveRustImport,
20
+ } from "./resolvers.mjs"
21
+
22
+ const MAX_SYMBOL_AMBIGUITY = 3 // 仅当导出符号在全仓 <=3 处定义时才建 doc-symbol 边(彻底消除噪音)
23
+
24
+ const slash = (p) => String(p ?? "").replace(/\\/g, "/")
25
+ /** 仓里的「库」= 路径首段(`bms/procedures/...` → `bms`);仓根档没有库目录,返回 `""`。 */
26
+ const sqlDbDir = (p) => { const i = String(p ?? "").indexOf("/"); return i > 0 ? String(p).slice(0, i) : "" }
27
+
28
+ export function rebuildEdgesInTx(db, root) {
29
+ db.exec("DELETE FROM edges")
30
+ const files = db.prepare("SELECT path, kind, lang, lines, namespace FROM files").all()
31
+ const lookup = buildFileLookup(files)
32
+ const fileByPath = new Map(files.map((f) => [f.path, f]))
33
+
34
+ // 导出符号 → 定义文件列表(仅统计非测试源码文件,供 doc-symbol 去噪求交集)
35
+ const symbolToFiles = new Map()
36
+ const expRows = db.prepare("SELECT file, symbol FROM exports").all()
37
+ for (const { file, symbol } of expRows) {
38
+ if (!lookup.fileExports.has(file)) lookup.fileExports.set(file, new Set())
39
+ lookup.fileExports.get(file).add(symbol)
40
+ const info = fileByPath.get(file)
41
+ if (info?.kind === "code") {
42
+ if (!symbolToFiles.has(symbol)) symbolToFiles.set(symbol, [])
43
+ symbolToFiles.get(symbol).push(file)
44
+ }
45
+ }
46
+
47
+ const goMod = readGoModulePrefix(root)
48
+ const jsResolver = buildJsResolver(root, files)
49
+ const rawRefs = db.prepare("SELECT file, kind, raw, detail, line FROM raw_refs").all()
50
+
51
+ // SQL 裸名索引(`CALL p_x` / `FROM t_y` 不带 schema 时用):可执行对象名 → 定义档(来自 exports),
52
+ // 表 / 视图名 → 定义档(来自 `sql-table` / `sql-view` 声明行)。两者分开算,因为 SQL 里可执行对象
53
+ // 与表是两个命名空间(`bms` 库里 `sns_post` 既是函数又是表);表名也不能拿文件名当:
54
+ // `bms_v2/tables/sys/chart/sys_chart_of_account.sql` 是视图、不是表,按 stem 猜会把 `FROM` 连到函数档上。
55
+ const sqlExec = new Map()
56
+ const sqlTable = new Map()
57
+ for (const f of files) {
58
+ if (f.lang !== "sql") continue
59
+ for (const symbol of lookup.fileExports.get(f.path) ?? []) {
60
+ const key = symbol.toLowerCase()
61
+ if (!sqlExec.has(key)) sqlExec.set(key, [])
62
+ sqlExec.get(key).push(f.path)
63
+ }
64
+ }
65
+ for (const r of rawRefs) {
66
+ if (r.kind !== "sql-table" && r.kind !== "sql-view") continue
67
+ const key = String(r.raw).toLowerCase()
68
+ if (!sqlTable.has(key)) sqlTable.set(key, [])
69
+ sqlTable.get(key).push(r.file)
70
+ }
71
+
72
+ // 预收集 C# 文件引用的类型标识与 global using 命名空间(按顶层项目目录作用域归集)
73
+ const csRefMap = new Map()
74
+ const csGlobalUsings = new Map() // projectScope -> Set<namespace>
75
+ const csScopeOf = (relPath) => {
76
+ const idx = relPath.indexOf("/")
77
+ return idx > 0 ? relPath.slice(0, idx).toLowerCase() : ""
78
+ }
79
+ for (const r of rawRefs) {
80
+ if (r.kind === "cs-refs") csRefMap.set(r.file, new Set(r.detail.split(",").filter(Boolean)))
81
+ else if (r.kind === "cs-global-using") {
82
+ const sc = csScopeOf(r.file)
83
+ if (!csGlobalUsings.has(sc)) csGlobalUsings.set(sc, new Set())
84
+ csGlobalUsings.get(sc).add(r.raw)
85
+ }
86
+ }
87
+
88
+ const insEdge = db.prepare(
89
+ "INSERT OR IGNORE INTO edges (src, dst, kind, detail, line, state, symbol) VALUES (?, ?, ?, ?, ?, ?, ?)",
90
+ )
91
+
92
+ for (const r of rawRefs) {
93
+ const srcFile = fileByPath.get(r.file)
94
+ if (!srcFile) continue
95
+
96
+ if (r.kind === "code-imp") {
97
+ // P0-1 符号级边:具名导入按被引符号各落一行(`symbol` 列可反查「本档的哪个符号被谁用」);
98
+ // 无具名符号(副作用 import / 命名空间导入)落一行 `symbol = ''` 的档级边,行为与旧版一致。
99
+ const emitImport = (dst, symbols) => {
100
+ if (!dst || dst === r.file) return
101
+ const rows = symbols.length > 0 ? symbols : [""]
102
+ for (const sym of rows) insEdge.run(r.file, dst, "imports", sym || r.detail, r.line, "ok", sym)
103
+ }
104
+ const namedSymbols = String(r.detail ?? "").split(",").map((s) => s.trim()).filter(Boolean)
105
+ if (srcFile.lang === "js" || srcFile.lang === "ts") {
106
+ emitImport(resolveJsImport(r.file, r.raw, lookup, jsResolver), namedSymbols)
107
+ } else if (srcFile.lang === "py") {
108
+ emitImport(resolvePyImport(r.file, r.raw, lookup), namedSymbols)
109
+ } else if (srcFile.lang === "go") {
110
+ for (const dst of resolveGoImport(r.raw, goMod, lookup)) emitImport(dst, namedSymbols)
111
+ } else if (srcFile.lang === "rs") {
112
+ emitImport(resolveRustImport(r.file, r.raw, lookup), namedSymbols)
113
+ } else if (srcFile.lang === "cs") {
114
+ const candidates = lookup.byNamespace.get(r.raw) ?? []
115
+ const usedIdents = csRefMap.get(r.file) ?? new Set()
116
+ for (const dst of candidates) {
117
+ if (dst === r.file) continue
118
+ const exps = lookup.fileExports.get(dst)
119
+ const matched = exps ? [...exps].filter((s) => usedIdents.has(s)) : []
120
+ if (matched.length > 0 || candidates.length <= 3) emitImport(dst, matched)
121
+ }
122
+ } else if (srcFile.lang === "sql") {
123
+ // SQL:可执行对象(过程 / 函数 / 触发器 / 视图)按 exports 名命中;
124
+ // 表按定义文件名回查(表不进 exports,它的文件通常就叫 `<table>.sql`)。
125
+ const dot = r.raw.lastIndexOf(".")
126
+ if (dot > 0) {
127
+ // 两段式 `schema.object`:两者都限定在同一 schema 的 namespace 候选内,不同库的同名表不互连。
128
+ const schema = r.raw.slice(0, dot)
129
+ const object = r.raw.slice(dot + 1)
130
+ const candidates = lookup.byNamespace.get(schema) ?? []
131
+ for (const dst of candidates) {
132
+ if (dst === r.file) continue
133
+ const exps = lookup.fileExports.get(dst)
134
+ if (exps?.has(object)) {
135
+ emitImport(dst, [object])
136
+ continue
137
+ }
138
+ const base = basename(dst)
139
+ const stem = base.slice(0, Math.max(0, base.lastIndexOf(".")))
140
+ if (stem === object || stem.endsWith(`.${object}`)) emitImport(dst, [object])
141
+ }
142
+ } else {
143
+ // 裸名:MySQL 里不带 schema 的名字就指**同一个库**,不是猜。库在仓里是路径首段,
144
+ // 所以候选只在那一个目录里找;仓根档没有库目录,判不了就不落边。
145
+ // 同库里同名定义不止一份时同落多条边(与两段式口径一致:引用只带名字,两份都是真实定义)。
146
+ const dbDir = sqlDbDir(r.file)
147
+ const defs = (r.detail === "call" ? sqlExec : sqlTable).get(String(r.raw).toLowerCase()) ?? []
148
+ if (dbDir) {
149
+ for (const dst of defs) {
150
+ if (dst === r.file || sqlDbDir(dst) !== dbDir) continue
151
+ emitImport(dst, [r.raw])
152
+ }
153
+ }
154
+ }
155
+ }
156
+ continue
157
+ }
158
+
159
+ if (r.kind === "code-cite") {
160
+ // P0-2 落边:代码头注引 `docs/**/*.md` → `code-cites`(src = 源码档,dst = 设计档)。
161
+ // `doc-path` 是「文档 → 代码 / 文档」,本分支是「代码 → 文档」,两向不同族。
162
+ // 断链与 `doc-path` 同判据(#65-5):含目录分隔符、不越根、盘上真没有 ⇒ 落 `missing`,
163
+ // 否则 `refs` 查不到「头注里的设计档名写错了」。示意路径(含 `...`)在抽取层已过滤,不进这里。
164
+ const resolved = resolveDocPath(r.file, r.raw, lookup)
165
+ if (resolved && resolved !== r.file) {
166
+ const dstInfo = fileByPath.get(resolved)
167
+ if (dstInfo?.kind === "doc") insEdge.run(r.file, resolved, "code-cites", r.raw, r.line, "ok", "")
168
+ } else if (r.raw.includes("/")) {
169
+ const rawDst = slash(r.raw)
170
+ const escapes = rawDst.startsWith("/") || rawDst === ".." || rawDst.startsWith("../")
171
+ if (!escapes && !existsSync(resolve(root, rawDst))) {
172
+ insEdge.run(r.file, rawDst, "code-cites", r.raw, r.line, "missing", "")
173
+ }
174
+ }
175
+ continue
176
+ }
177
+
178
+ if (r.kind === "doc-path") {
179
+ const resolved = resolveDocPath(r.file, r.raw, lookup)
180
+ if (resolved) {
181
+ if (resolved === r.file) continue
182
+ const dstInfo = fileByPath.get(resolved)
183
+ const edgeKind = dstInfo?.kind === "doc" ? "doc-cites" : "doc-covers"
184
+ insEdge.run(r.file, resolved, edgeKind, "", r.line, "ok", "")
185
+ } else if (r.raw.includes("/")) {
186
+ // P1-4 断链判别:只有「盘上真没有这个档」才算断链。被过程档排除 ∥ 被扩展名过滤出图的档
187
+ // 仍在盘上,把它们记成 missing 会把「已排除」误报成「断链」(实测 61 条里 8 条如此)。
188
+ // 越根 dst(`../x`、`/x`)不落:它指不到本图的任何真实位置,`refs` 也反查不到。
189
+ const rawDst = slash(r.raw)
190
+ const escapes = rawDst.startsWith("/") || rawDst === ".." || rawDst.startsWith("../")
191
+ if (!escapes && !existsSync(resolve(root, rawDst))) {
192
+ const edgeKind = r.raw.toLowerCase().endsWith(".md") ? "doc-cites" : "doc-covers"
193
+ insEdge.run(r.file, rawDst, edgeKind, "", r.line, "missing", "")
194
+ }
195
+ }
196
+ continue
197
+ }
198
+
199
+ if (r.kind === "doc-sym") {
200
+ // 只对「仓内真实导出且低歧义(<=3 处定义)」的符号建边,彻底过滤 v2/docs/open 等噪音
201
+ const defs = symbolToFiles.get(r.raw)
202
+ if (!defs || defs.length === 0 || defs.length > MAX_SYMBOL_AMBIGUITY) continue
203
+ for (const dst of defs) {
204
+ if (dst !== r.file) insEdge.run(r.file, dst, "doc-symbol", r.raw, r.line, "ok", r.raw)
205
+ }
206
+ }
207
+ }
208
+
209
+ // C# 同命名空间互引 + 同项目 global using 命名空间互引
210
+ for (const f of files) {
211
+ if (f.lang !== "cs") continue
212
+ const usedIdents = csRefMap.get(f.path)
213
+ if (!usedIdents || usedIdents.size === 0) continue
214
+ const nsSet = new Set()
215
+ if (f.namespace) nsSet.add(f.namespace)
216
+ const globals = csGlobalUsings.get(csScopeOf(f.path))
217
+ if (globals) for (const g of globals) nsSet.add(g)
218
+ for (const ns of nsSet) {
219
+ const peers = lookup.byNamespace.get(ns) ?? []
220
+ for (const dst of peers) {
221
+ if (dst === f.path) continue
222
+ const exps = lookup.fileExports.get(dst)
223
+ if (!exps) continue
224
+ const matched = [...exps].filter((s) => usedIdents.has(s))
225
+ // 与 `emitImport` 同形:`imports` 边的 `detail` 与 `symbol` 同取该符号,一个符号一行 ——
226
+ // 否则 `repo_graph(symbol)` 查不到第二个被用的 C# 符号(设计 §1 的边形状)。
227
+ for (const s of matched) insEdge.run(f.path, dst, "imports", s, 1, "ok", s)
228
+ }
229
+ }
230
+ }
231
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * doc-graph/format.mjs — 输出面的纯格式化函数(零 db、零 fs)。数量不写进注释:加一个函数就漂,交给导出面看。
3
+ *
4
+ * 为什么单独一档:`fmtItem` / `truncNote` 被必读包、影响面、总览、符号面四处共用,
5
+ * 原先与解析、库查询混在一档里;`truncNote` 还带一条产品口径 —— 列表截断必须显式说出
6
+ * 「还有 N 条没列」,绝不静默丢弃(P1-5 输出诚实性)。这条口径集中在这里,改一次到处生效。
7
+ */
8
+
9
+ /** P0-1 符号级边:输出优先用 `symbol` 列,非符号边退回 `detail`(`doc-cites` 的原文路径等)。 */
10
+ export function edgeLabel(e) {
11
+ const label = String(e?.symbol ?? "").trim() || String(e?.detail ?? "").trim()
12
+ return label ? ` [${label}]` : ""
13
+ }
14
+
15
+ export function formatOtherCandidatesNote(otherCandidates) {
16
+ if (!Array.isArray(otherCandidates) || otherCandidates.length === 0) return ""
17
+ const items = otherCandidates.slice(0, 5).map((c) => `${c.path}${c.symbol ? ` [${c.symbol}]` : ""}${c.lines ? ` (${c.lines}行)` : ""}`)
18
+ return `> 已自动展开最优先候选;其他同名候选(如需查其他项请传精确路径):${items.join(" · ")}`
19
+ }
20
+
21
+ /**
22
+ * 改进点 1(2026-11-30):多候选拒绝展开时列出候选清单(已按确定性排序)。与
23
+ * `formatOtherCandidatesNote` 同款排版但语义相反 —— 这里是「没替你挑」,不是「已挑了第 1 个」。
24
+ */
25
+ export function formatAmbiguousNote(candidates) {
26
+ if (!Array.isArray(candidates) || candidates.length === 0) return ""
27
+ const items = candidates.slice(0, 8).map((c) => `${c.path}${c.symbol ? ` [${c.symbol}]` : ""}${c.lines ? ` (${c.lines}行)` : ""}${c.kind ? ` · ${c.kind}` : ""}`)
28
+ return `> 命中 ${candidates.length} 个候选:${items.join(" · ")}`
29
+ }
30
+
31
+ /**
32
+ * 改进点 2(2026-11-30):翻页版报数 —— 与 `truncNote` 同一「截断必报数」口径(P1-5 输出诚实性),
33
+ * 但尾行给出续读 offset,让长列表逐页取全而不是「报了数却拿不到」。
34
+ */
35
+ export function pageNote(total, shown, label = "其余", nextPageHint = "") {
36
+ const rest = Math.max(0, Number(total) - Number(shown))
37
+ if (rest <= 0) return []
38
+ return [` - …(${label} ${rest} 条未列出,共 ${total} 条${nextPageHint ? `;${nextPageHint}` : ""})`]
39
+ }
40
+
41
+ export function fmtItem(item, extra = "") {
42
+ const ln = item.lines ? ` (${item.lines} 行)` : ""
43
+ return ` - ${item.path}${ln}${extra ? ` — ${extra}` : ""}`
44
+ }
45
+
46
+ /**
47
+ * P1-5 输出诚实性:列表按上限截断时返回「其余 N 条未列出」标记行,绝不静默丢弃超限条目。
48
+ * 调用点按 `...(truncNote(total, shown, label))` 展开;无超限时返回空数组。
49
+ */
50
+ export function truncNote(total, shown, label = "其余") {
51
+ const rest = Math.max(0, Number(total) - Number(shown))
52
+ if (rest <= 0) return []
53
+ return [` - …(${label} ${rest} 条未列出,共 ${total} 条;可收窄 query 或对该档调 read 取全文)`]
54
+ }
55
+
56
+ /**
57
+ * 未读包的行渲染器(`{missingDocs, missingTargets, missingCallers, missingSiblings}` → 几行文本)。
58
+ * 消费面共用这一个实现(§5 的 `[图谱被动上下文]` 注入、规划步的「图谱必读核对」、`read` 返回值里的
59
+ * 图谱头)—— 同一件事有几个实现就会漂几次,所以这里只说「共用」、不数个数。
60
+ */
61
+ export function graphMissingRows(graphMissing) {
62
+ if (!graphMissing) return []
63
+ const fmt = (arr) => arr.map((item) => `${item.path}${item.lines ? ` (${item.lines}行)` : ""}`).join("、")
64
+ const rows = []
65
+ if (graphMissing.missingDocs?.length) rows.push(` - 所属需求/设计:${fmt(graphMissing.missingDocs)}`)
66
+ if (graphMissing.missingTargets?.length) rows.push(` - 目标源码:${fmt(graphMissing.missingTargets)}`)
67
+ if (graphMissing.missingCallers?.length) rows.push(` - 上游调用方:${fmt(graphMissing.missingCallers)}`)
68
+ if (graphMissing.missingSiblings?.length) rows.push(` - 同级编排模块:${fmt(graphMissing.missingSiblings)}`)
69
+ return rows
70
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * doc-graph/gc-cmd.mjs — `thincoder graph gc` 的命令面(P2-8 的显式入口,2026-11-29 挂账收尾)。
3
+ *
4
+ * 为什么需要它:`graphGc` 原本只在 `syncGraph` 里按 7 天节流自动跑一次,且 **`vacuum: false`**
5
+ * ——自动路径只删陈旧库,从不压实。于是「删掉旧库」有入口,「把正在用的库压回去」没有入口,
6
+ * 用户唯一的办法是改代码。本档只做壳:判据与落盘全在 `gc.mjs`(`graphGc`),不另写一份清理逻辑。
7
+ *
8
+ * 两档语义照既有先例(`session gc` / `ledger migrate`):
9
+ * - 缺省 = 只报告(`apply:false`),一行都不删;
10
+ * - `--confirm` 才落盘,`--vacuum` 只在 `--confirm` 下执行(SQLite 的 VACUUM 是写操作,
11
+ * 且需要约两倍库大小的空闲磁盘,`https://sqlite.org/lang_vacuum.html`)。
12
+ */
13
+ import { resolve } from "node:path"
14
+ import { graphGc, STALE_GRAPH_MS } from "./gc.mjs"
15
+ import { graphDirPath, graphKey } from "./store.mjs"
16
+
17
+ const USAGE = "Usage: thincoder graph gc [--dry-run | --confirm] [--vacuum] [--stale-days <N>] [--keep <key>] [--dir <path>]"
18
+
19
+ const days = (ms) => `${(ms / 86400000).toFixed(1)}d`
20
+ const mb = (bytes) => `${(bytes / 1048576).toFixed(1)}MB`
21
+
22
+ /**
23
+ * 跑一次清理。
24
+ * @param {string[]} args `graph gc` 之后的参数
25
+ * @returns {Promise<number>} 进程退出码(0 成 ∥ 1 参数错)
26
+ */
27
+ export async function runGraphGc(args = []) {
28
+ const argv = Array.isArray(args) ? args.slice() : []
29
+ let apply = false
30
+ let vacuum = false
31
+ let staleAfterMs = STALE_GRAPH_MS
32
+ let dir = null
33
+ const keepKeys = []
34
+
35
+ for (let i = 0; i < argv.length; i++) {
36
+ const a = argv[i]
37
+ if (a === "--confirm") { apply = true; continue }
38
+ if (a === "--dry-run") { apply = false; continue }
39
+ if (a === "--vacuum") { vacuum = true; continue }
40
+ if (a === "--stale-days") {
41
+ const n = Number(argv[++i])
42
+ if (!Number.isFinite(n) || n < 0) {
43
+ console.error(`[graph gc] --stale-days 需要一个非负数字,收到 ${JSON.stringify(argv[i] ?? null)}\n${USAGE}`)
44
+ return 1
45
+ }
46
+ staleAfterMs = n * 86400000
47
+ continue
48
+ }
49
+ if (a === "--keep") {
50
+ const k = argv[++i]
51
+ if (!k) {
52
+ console.error(`[graph gc] --keep 需要一个库 key\n${USAGE}`)
53
+ return 1
54
+ }
55
+ keepKeys.push(k)
56
+ continue
57
+ }
58
+ if (a === "--dir") {
59
+ const d = argv[++i]
60
+ if (!d) {
61
+ console.error(`[graph gc] --dir 需要一个路径\n${USAGE}`)
62
+ return 1
63
+ }
64
+ dir = resolve(d)
65
+ continue
66
+ }
67
+ console.error(`[graph gc] 未知参数 ${JSON.stringify(a)}\n${USAGE}`)
68
+ return 1
69
+ }
70
+
71
+ // 当前项目库永不删:key 从项目根算(cwd 可能是子目录,子目录的 key 不是这份库的 key)。
72
+ if (keepKeys.length === 0) {
73
+ try {
74
+ const mod = await import("../doc-graph.mjs")
75
+ const r = mod.resolveQueryRoot(process.cwd())
76
+ keepKeys.push(graphKey(r.ok ? r.root : process.cwd()))
77
+ } catch {
78
+ // 判根失败就不保任何库 —— 但那意味着可能删掉正在用的库,故降级为只报告。
79
+ console.error("[graph gc] 判不出当前项目根,无法保证不删正在用的库 —— 本次只报告不落盘(传 --keep <key> 后可 --confirm)")
80
+ apply = false
81
+ }
82
+ }
83
+
84
+ const report = graphGc({ dir: dir ?? graphDirPath(), keepKeys, staleAfterMs, vacuum, apply })
85
+
86
+ console.log(`[graph gc] 目录 ${report.dir ?? "(无)"} · 扫描 ${report.scanned} 个库 · 判旧阈值 ${days(staleAfterMs)} · 保留 ${keepKeys.join(", ") || "(无)"}`)
87
+ if (report.stale.length === 0) {
88
+ console.log("[graph gc] 没有超过阈值的库")
89
+ } else {
90
+ for (const s of report.stale) console.log(` - ${s.key} · 闲置 ${days(s.ageMs)} · ${mb(s.bytes)}${report.applied ? " · 已删" : "(待删)"}`)
91
+ console.log(`[graph gc] ${report.applied ? "已释放" : "可释放"} ${mb(report.freedBytes)}`)
92
+ }
93
+ if (report.vacuumed.length > 0) {
94
+ for (const v of report.vacuumed) {
95
+ if (v.error) console.log(` ! ${v.key} 压实失败:${v.error}`)
96
+ else if (v.skipped) console.log(` - ${v.key} 跳过压实:${v.skipped}`)
97
+ else console.log(` - ${v.key} 压实 ${mb(v.beforeBytes)} → ${mb(v.afterBytes)}`)
98
+ }
99
+ } else if (vacuum && !apply) {
100
+ console.log("[graph gc] --vacuum 只在 --confirm 下执行(VACUUM 是写操作,需约两倍库大小的空闲磁盘)")
101
+ }
102
+ if (!apply) console.log("[graph gc] 只报告:加 --confirm 才落盘")
103
+ return 0
104
+ }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * doc-graph/gc.mjs — 图谱缓存库的保守清理与可选 VACUUM(P2-8)。
3
+ *
4
+ * 清理判据只有一条:库档 mtime 超过 `staleAfterMs` 未被用过(图库是纯缓存,删了下次查询自动重建),
5
+ * 且其 key 不在 `keepKeys`(调用面用当前项目 key 指名,永不删正在用的库)。
6
+ *
7
+ * VACUUM 与删档分开,且只在 `apply: true` 时执行 —— 按 SQLite 官方语义:
8
+ * 「A VACUUM will fail if there is an open transaction on the database connection that is attempting
9
+ * to run the VACUUM... VACUUM (but not VACUUM INTO) is a write operation and so if another database
10
+ * connection is holding a lock that prevents writes, then the VACUUM will fail」,且需要约两倍原库
11
+ * 大小的空闲磁盘(`https://sqlite.org/lang_vacuum.html`)。因此它不适合挂在查询路径上。
12
+ */
13
+ import { existsSync, readdirSync, rmSync, statSync } from "node:fs"
14
+ import { join } from "node:path"
15
+ import { DatabaseSync } from "node:sqlite"
16
+
17
+ export const STALE_GRAPH_MS = 30 * 24 * 60 * 60 * 1000
18
+ export const PRUNE_INTERVAL_MS = 7 * 24 * 60 * 60 * 1000
19
+
20
+ const WAL_SUFFIXES = ["-wal", "-shm"]
21
+ const DB_SUFFIX = ".db"
22
+
23
+ function sizeOf(path) {
24
+ try { return statSync(path).size } catch { return 0 }
25
+ }
26
+
27
+ function totalSize(dbPath) {
28
+ return sizeOf(dbPath) + WAL_SUFFIXES.reduce((n, s) => n + sizeOf(dbPath + s), 0)
29
+ }
30
+
31
+ /**
32
+ * 清理 / 压实 `~/.thincoder/graphs` 下的图库缓存。
33
+ * @param {object} opts
34
+ * @param {string} opts.dir 图库目录(由调用面传入,测试可用 `_setGraphDirForTest` 的同一目录)
35
+ * @param {string[]} [opts.keepKeys] 永不清理的库 key(当前项目)
36
+ * @param {number} [opts.staleAfterMs] 判旧的空闲阈值,默认 30 天
37
+ * @param {boolean} [opts.vacuum] 是否对保留库跑 `wal_checkpoint(TRUNCATE)` + `VACUUM`(只在 apply 时执行)
38
+ * @param {boolean} [opts.apply] false = 只报告不落盘(默认)
39
+ * @param {number} [opts.now] 当前时间戳(测试注入)
40
+ */
41
+ export function graphGc({
42
+ dir,
43
+ keepKeys = [],
44
+ staleAfterMs = STALE_GRAPH_MS,
45
+ vacuum = false,
46
+ apply = false,
47
+ now = Date.now(),
48
+ } = {}) {
49
+ const report = { dir: dir ?? null, scanned: 0, stale: [], vacuumed: [], freedBytes: 0, applied: Boolean(apply) }
50
+ if (!dir || !existsSync(dir)) return report
51
+ let names = []
52
+ try { names = readdirSync(dir) } catch { return report }
53
+ const dbNames = names.filter((n) => n.endsWith(DB_SUFFIX))
54
+ const keep = new Set(keepKeys.filter(Boolean))
55
+
56
+ for (const name of dbNames) {
57
+ report.scanned++
58
+ const key = name.slice(0, -DB_SUFFIX.length)
59
+ if (keep.has(key)) continue
60
+ const dbPath = join(dir, name)
61
+ let st
62
+ try { st = statSync(dbPath) } catch { continue }
63
+ const ageMs = Math.max(0, now - st.mtimeMs)
64
+ if (ageMs < staleAfterMs) continue
65
+ report.stale.push({ key, path: dbPath, ageMs, bytes: totalSize(dbPath) })
66
+ }
67
+
68
+ for (const item of report.stale) report.freedBytes += item.bytes
69
+
70
+ if (apply) {
71
+ for (const item of report.stale) {
72
+ let removedBytes = 0
73
+ for (const suffix of ["", ...WAL_SUFFIXES]) {
74
+ const target = item.path + suffix
75
+ const bytes = sizeOf(target)
76
+ try {
77
+ rmSync(target, { force: true })
78
+ removedBytes += bytes
79
+ } catch { /* 单档失败不掩整批;freedBytes 只记真删掉的字节 */ }
80
+ }
81
+ item.freedBytes = removedBytes
82
+ }
83
+ report.freedBytes = report.stale.reduce((n, i) => n + (i.freedBytes ?? 0), 0)
84
+ }
85
+
86
+ if (vacuum && apply) {
87
+ for (const name of dbNames) {
88
+ const key = name.slice(0, -DB_SUFFIX.length)
89
+ // `keepKeys` 只约束「不删」,不约束「不压实」—— 当前项目库恰恰是最该压实的那个。
90
+ if (report.stale.some((s) => s.key === key)) continue
91
+ const dbPath = join(dir, name)
92
+ const beforeBytes = totalSize(dbPath)
93
+ let db = null
94
+ try {
95
+ db = new DatabaseSync(dbPath)
96
+ if (db.isTransaction) {
97
+ report.vacuumed.push({ key, path: dbPath, beforeBytes, afterBytes: beforeBytes, skipped: "open-transaction" })
98
+ continue
99
+ }
100
+ db.exec("PRAGMA wal_checkpoint(TRUNCATE)")
101
+ db.exec("VACUUM")
102
+ report.vacuumed.push({ key, path: dbPath, beforeBytes, afterBytes: totalSize(dbPath) })
103
+ } catch (err) {
104
+ report.vacuumed.push({ key, path: dbPath, beforeBytes, afterBytes: beforeBytes, error: String(err?.message ?? err) })
105
+ } finally {
106
+ try { db?.close() } catch { /* ignore */ }
107
+ }
108
+ }
109
+ }
110
+
111
+ return report
112
+ }