@thincoder/core 0.11.4 → 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 +33 -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 +22 -41
  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,352 @@
1
+ /**
2
+ * doc-graph/target-resolve.mjs — 「用户这句话指的是仓里哪个档」的六级解析。
3
+ *
4
+ * 级别从硬到软,命中即停,每级都带 `matchTier` 让调用面能分辨置信度(Turn 0 只采纳前三档):
5
+ * 1. 精确路径 → 2. 路径后缀 → 3. 精确导出符号 → 4. 路径/符号子串 → 5. 文档候选词(反引号标识符与点分属性路径) → 6. 文档章节标题与多词 token。
6
+ *
7
+ * 改进点 1(2026-11-30,需求 F4 契约修订):2–4 级命中多个候选时不再自动展开第 1 候选 ——
8
+ * 返回 `kind = 'ambiguous'` 并携带排序后的候选清单,由调用面拒绝展开(自动挑错候选会产出
9
+ * 看似完整、实际查错对象的影响面/必读包,比多一轮精确重查贵得多)。单候选仍直接命中;
10
+ * 5/6 级是模糊检索面,保持自动展开最优先候选。
11
+ *
12
+ * 第 5 级服务配置键 / 字段路径这一类字面量:它们既不是导出符号也不是章节标题,前面四级必然落空。
13
+ *
14
+ * 同一级里多候选一律走 `sortCandidates`:过程档垫底、源码 > 设计 > 需求 > 标准 > 测试、
15
+ * 同级取更短路径 —— 排序是确定性的,同一次查询两次跑必须给同一个答案。
16
+ */
17
+ import { basename } from "node:path"
18
+
19
+ import { isTestFilePath } from "./code-parsers.mjs"
20
+
21
+ const slash = (p) => String(p ?? "").replace(/\\/g, "/")
22
+ export const normKey = (p) => slash(p).replace(/^\.\//, "").toLowerCase()
23
+
24
+ function stripNodePrefix(raw) {
25
+ const s = String(raw ?? "").trim()
26
+ const m = /^(?:doc|file|symbol|code):(.+)$/i.exec(s)
27
+ return (m ? m[1] : s).split("#")[0].trim()
28
+ }
29
+
30
+ export function docPriorityRank(relPath) {
31
+ const low = relPath.toLowerCase()
32
+ if (/\/design\//.test(low)) return 0
33
+ if (/\/requirements\//.test(low)) return 1
34
+ if (/\/standards\//.test(low)) return 2
35
+ if (/(?:^|\/)(?:agents|claude|readme)\.md$/.test(low)) return 3
36
+ return 4
37
+ }
38
+
39
+ /** 多候选确定性排序:源码 > 设计档 > 需求档 > 标准/其他文档 > 测试 > 过程档;同级取更短路径。 */
40
+ function candidateRank(f, isProc) {
41
+ if (!f) return 99
42
+ if (isProc(f.path)) return 20
43
+ if (f.kind === "code") return 0
44
+ if (f.kind === "doc") return 1 + docPriorityRank(f.path)
45
+ if (f.kind === "test") return 8
46
+ return 10
47
+ }
48
+
49
+ function sortCandidates(list, isProc) {
50
+ return [...list].sort((a, b) => {
51
+ const r = candidateRank(a, isProc) - candidateRank(b, isProc)
52
+ if (r !== 0) return r
53
+ const segA = a.path.split("/").length
54
+ const segB = b.path.split("/").length
55
+ if (segA !== segB) return segA - segB
56
+ if (a.path.length !== b.path.length) return a.path.length - b.path.length
57
+ return a.path.localeCompare(b.path)
58
+ })
59
+ }
60
+
61
+ export function isNonAuthDocPath(p, isProc) {
62
+ return isProc(p) || isTestFilePath(p)
63
+ }
64
+
65
+ export function resolveTargetInDb(db, rawQuery, isProc) {
66
+ const q = stripNodePrefix(rawQuery)
67
+ if (!q) return { kind: "empty", candidates: [] }
68
+ const qNorm = normKey(q)
69
+
70
+ const files = db.prepare("SELECT path, kind, lang, lines, namespace FROM files").all()
71
+ const byPath = new Map(files.map((f) => [f.path, f]))
72
+
73
+ // 1. 精确路径命中
74
+ for (const f of files) {
75
+ if (normKey(f.path) === qNorm) return { kind: "file", file: f, matchTier: "exact", otherCandidates: [], byPath, files }
76
+ }
77
+ // 2. 路径后缀命中(如 `agent/planning-step.mjs`、`ENGINEERING-MODE-V2.md`)
78
+ const suffixHits = files.filter((f) => {
79
+ const low = normKey(f.path)
80
+ return low.endsWith(`/${qNorm}`) || basename(low) === qNorm
81
+ })
82
+ if (suffixHits.length > 0) {
83
+ const nonProc = suffixHits.filter((f) => !isProc(f.path))
84
+ const ranked = sortCandidates(nonProc.length > 0 ? nonProc : suffixHits, isProc)
85
+ if (ranked.length > 1) {
86
+ return { kind: "ambiguous", matchTier: "suffix", query: q, candidates: ranked.map((f) => ({ path: f.path, lines: f.lines, kind: f.kind })) }
87
+ }
88
+ return {
89
+ kind: "file",
90
+ file: ranked[0],
91
+ matchTier: "suffix",
92
+ otherCandidates: [],
93
+ byPath,
94
+ files,
95
+ }
96
+ }
97
+
98
+ // 3. 精确导出符号命中(优先非测试源码)
99
+ const exactSyms = db.prepare("SELECT file, symbol FROM exports WHERE symbol = ? OR LOWER(symbol) = ?").all(q, q.toLowerCase())
100
+ if (exactSyms.length > 0) {
101
+ const codeDefs = exactSyms.map((r) => byPath.get(r.file)).filter((f) => f && f.kind === "code")
102
+ const picked = codeDefs.length > 0 ? codeDefs : exactSyms.map((r) => byPath.get(r.file)).filter(Boolean)
103
+ const uniq = sortCandidates([...new Map(picked.map((f) => [f.path, f])).values()], isProc)
104
+ if (uniq.length > 1) {
105
+ return { kind: "ambiguous", matchTier: "symbol", query: q, candidates: uniq.map((f) => ({ path: f.path, lines: f.lines, kind: f.kind })) }
106
+ }
107
+ if (uniq.length > 0) {
108
+ return {
109
+ kind: "file",
110
+ file: uniq[0],
111
+ matchedSymbol: q,
112
+ matchTier: "symbol",
113
+ otherCandidates: [],
114
+ byPath,
115
+ files,
116
+ }
117
+ }
118
+ }
119
+
120
+ // 4. 路径或符号子串匹配(改进点 1:多候选拒绝自动展开 —— 子串命中天然多候选,是
121
+ // 「看似命中、实际查错对象」的高发区,如 `existence.mjs` 同时命中 doc-check 与 chat-compact)
122
+ const subFiles = sortCandidates(files.filter((f) => !isProc(f.path) && normKey(f.path).includes(qNorm)), isProc)
123
+ if (subFiles.length > 0) {
124
+ if (subFiles.length > 1) {
125
+ return { kind: "ambiguous", matchTier: "substring", query: q, candidates: subFiles.map((f) => ({ path: f.path, lines: f.lines, kind: f.kind })) }
126
+ }
127
+ return {
128
+ kind: "file",
129
+ file: subFiles[0],
130
+ matchTier: "substring",
131
+ otherCandidates: [],
132
+ byPath,
133
+ files,
134
+ }
135
+ }
136
+ const subSyms = db.prepare("SELECT DISTINCT file, symbol FROM exports WHERE LOWER(symbol) LIKE ? LIMIT 12").all(`%${q.toLowerCase()}%`)
137
+ const validSubSyms = subSyms.filter((r) => byPath.has(r.file))
138
+ if (validSubSyms.length > 0) {
139
+ const rankedFiles = sortCandidates([...new Map(validSubSyms.map((r) => [r.file, { ...byPath.get(r.file), _sym: r.symbol }])).values()], isProc)
140
+ // 评审修正(2026-11-30):与 3 级对齐 —— 同一符号的多个定义档同样是多候选,
141
+ // 只要 rankedFiles 多于一个就拒绝展开,不再额外要求符号名也多于一个。
142
+ if (rankedFiles.length > 1) {
143
+ return { kind: "ambiguous", matchTier: "substring", query: q, candidates: rankedFiles.map((f) => ({ path: f.path, symbol: f._sym, lines: f.lines })) }
144
+ }
145
+ return {
146
+ kind: "file",
147
+ file: rankedFiles[0],
148
+ matchedSymbol: rankedFiles[0]._sym,
149
+ matchTier: "substring",
150
+ otherCandidates: [],
151
+ byPath,
152
+ files,
153
+ }
154
+ }
155
+
156
+ // 5. 文档候选面命中(`raw_refs.kind = 'doc-sym'`):反引号里的标识符与点分属性路径
157
+ // (`planningNextMoves` / `agent.planningNextMoves.enabled` …)。配置键、字段路径、常量名
158
+ // 既不是导出符号也不是章节标题,前四级一律落空 —— 这条是它们唯一的检索面(设计 §4)。
159
+ const docTokenHit = resolveByDocTokens(db, q, byPath, isProc)
160
+ if (docTokenHit) return docTokenHit
161
+
162
+ // 6. 文档章节标题(headings)与多词 token 综合检索(支持中文功能概念与空格分隔多关键词)
163
+ const headingHit = resolveByHeadingsAndTokens(db, q, files, byPath, isProc)
164
+ if (headingHit) return headingHit
165
+
166
+ return { kind: "missing", query: q, candidates: [] }
167
+ }
168
+
169
+ const QUERY_SPLIT_RE = /[\s,,、;;::/|()()\[\]【】《》「」"'`]+/
170
+ const CJK_4PLUS_RE = /^[\u4e00-\u9fff]{4,}$/
171
+
172
+ /**
173
+ * 文档候选面(`raw_refs.kind = 'doc-sym'`)按词形命中:反引号里的标识符与点分属性路径。
174
+ *
175
+ * 它服务的正是「配置键 / 字段路径查不到」这个缺口 —— `planningNextMoves` 既不是导出符号(`exports`)
176
+ * 也不是章节标题(`headings`),前几级必然落空。候选行在构建时已由 `parseMarkdownDoc` 从反引号抽取
177
+ * 并落库(`store.mjs`),本支只负责把它变成「哪个档在谈这个词」。
178
+ *
179
+ * 只认 `.` 分段边界:`raw = q` ∥ `q.…` ∥ `….q` ∥ `….q.…`。**不做无限子串** —— 「含这个子串」会把
180
+ * `planningNextMovesXyz` 也算命中,那等于把拼写错误当成答案交付。
181
+ *
182
+ * 命中多个文档时沿用全局 `sortCandidates`(设计档 > 需求档 > 标准 > 其他,同级取更短路径),
183
+ * 不另行发明一套排序。
184
+ */
185
+ function resolveByDocTokens(db, q, byPath, isProc) {
186
+ const qLow = q.toLowerCase()
187
+ let rows = []
188
+ try {
189
+ rows = db.prepare(
190
+ "SELECT file, line, raw FROM raw_refs WHERE kind = 'doc-sym' " +
191
+ "AND (LOWER(raw) = ? OR LOWER(raw) LIKE ? || '.%' OR LOWER(raw) LIKE '%.' || ? OR LOWER(raw) LIKE '%.' || ? || '.%')",
192
+ ).all(qLow, qLow, qLow, qLow)
193
+ } catch {
194
+ return null
195
+ }
196
+ if (rows.length === 0) return null
197
+
198
+ // 同档多行取最早那行:提示里的行号要对得上人翻档第一眼看到的位置。
199
+ const byFile = new Map()
200
+ for (const r of rows) {
201
+ const f = byPath.get(r.file)
202
+ if (!f || isNonAuthDocPath(f.path, isProc)) continue
203
+ const cur = byFile.get(f.path)
204
+ if (!cur || r.line < cur.line) byFile.set(f.path, { file: f, line: r.line, raw: r.raw })
205
+ }
206
+ const ranked = sortCandidates([...byFile.values()].map((x) => x.file), isProc)
207
+ if (ranked.length === 0) return null
208
+
209
+ const top = ranked[0]
210
+ const topHit = byFile.get(top.path)
211
+ return {
212
+ kind: "file",
213
+ file: top,
214
+ matchTier: "doctoken",
215
+ matchedDocToken: topHit ? { token: topHit.raw, line: topHit.line } : undefined,
216
+ otherCandidates: ranked.slice(1, 6).map((f) => ({
217
+ path: f.path,
218
+ lines: f.lines,
219
+ symbol: byFile.get(f.path)?.raw,
220
+ })),
221
+ byPath,
222
+ files: [...byPath.values()],
223
+ }
224
+ }
225
+
226
+ function splitQueryTokens(raw) {
227
+ const seen = new Set()
228
+ const out = []
229
+ for (const part of String(raw ?? "").toLowerCase().split(QUERY_SPLIT_RE)) {
230
+ const t = part.trim()
231
+ if (t.length < 2 || seen.has(t)) continue
232
+ seen.add(t)
233
+ out.push(t)
234
+ }
235
+ return out
236
+ }
237
+
238
+ function resolveByHeadingsAndTokens(db, q, files, byPath, isProc) {
239
+ const qLow = q.toLowerCase()
240
+ const tokens = splitQueryTokens(q)
241
+ if (tokens.length === 0) return null
242
+
243
+ // filePath -> { file, score, matchedTokens: Set<string>, bestHeading: { title, line, score } | null, matchedSym: string | null }
244
+ const scored = new Map()
245
+ const ensure = (file) => {
246
+ let entry = scored.get(file.path)
247
+ if (!entry) {
248
+ entry = { file, score: 0, matchedTokens: new Set(), bestHeading: null, matchedSym: null }
249
+ scored.set(file.path, entry)
250
+ }
251
+ return entry
252
+ }
253
+
254
+ // 6a. 扫描文档标题表 headings(排除过程档与测试文档)
255
+ let headingRows = []
256
+ try {
257
+ headingRows = db.prepare("SELECT file, title, level, line FROM headings").all()
258
+ } catch {
259
+ headingRows = []
260
+ }
261
+ for (const row of headingRows) {
262
+ const f = byPath.get(row.file)
263
+ if (!f || isNonAuthDocPath(f.path, isProc)) continue
264
+ const titleLow = String(row.title ?? "").toLowerCase()
265
+ let rowScore = 0
266
+ const rowTokens = []
267
+ if (qLow.length >= 2 && titleLow.includes(qLow)) {
268
+ rowScore += 10 + (row.level === 1 ? 3 : row.level === 2 ? 2 : 0)
269
+ rowTokens.push(qLow)
270
+ } else {
271
+ for (const tok of tokens) {
272
+ if (titleLow.includes(tok)) {
273
+ rowScore += 4 + (row.level === 1 ? 2 : row.level === 2 ? 1 : 0)
274
+ rowTokens.push(tok)
275
+ } else if (CJK_4PLUS_RE.test(tok)) {
276
+ const head2 = tok.slice(0, 2)
277
+ const tail2 = tok.slice(-2)
278
+ if (titleLow.includes(head2) || titleLow.includes(tail2)) {
279
+ rowScore += 1
280
+ }
281
+ }
282
+ }
283
+ }
284
+ if (rowScore > 0) {
285
+ const entry = ensure(f)
286
+ entry.score += rowScore
287
+ for (const t of rowTokens) entry.matchedTokens.add(t)
288
+ if (!entry.bestHeading || rowScore > entry.bestHeading.score) {
289
+ entry.bestHeading = { title: row.title, line: row.line, score: rowScore }
290
+ }
291
+ }
292
+ }
293
+
294
+ // 6b. 多词查询时补查路径与导出符号(单个词已由第 4 级覆盖)
295
+ if (tokens.length >= 2) {
296
+ for (const f of files) {
297
+ if (isProc(f.path)) continue
298
+ const pLow = normKey(f.path)
299
+ let hits = 0
300
+ for (const tok of tokens) {
301
+ if (pLow.includes(tok)) {
302
+ const entry = ensure(f)
303
+ entry.score += 3
304
+ entry.matchedTokens.add(tok)
305
+ hits++
306
+ }
307
+ }
308
+ if (hits >= 2) ensure(f).score += hits * 2
309
+ }
310
+ const symRows = db.prepare("SELECT file, symbol FROM exports").all()
311
+ for (const r of symRows) {
312
+ const f = byPath.get(r.file)
313
+ if (!f || isProc(f.path)) continue
314
+ const sLow = String(r.symbol ?? "").toLowerCase()
315
+ for (const tok of tokens) {
316
+ if (tok.length >= 3 && sLow.includes(tok)) {
317
+ const entry = ensure(f)
318
+ entry.score += 2
319
+ entry.matchedTokens.add(tok)
320
+ if (!entry.matchedSym) entry.matchedSym = r.symbol
321
+ }
322
+ }
323
+ }
324
+ }
325
+
326
+ const ranked = [...scored.values()]
327
+ .filter((e) => e.score >= 3 || e.matchedTokens.size >= 1)
328
+ .sort((a, b) => {
329
+ if (b.matchedTokens.size !== a.matchedTokens.size) return b.matchedTokens.size - a.matchedTokens.size
330
+ if (b.score !== a.score) return b.score - a.score
331
+ const cr = candidateRank(a.file, isProc) - candidateRank(b.file, isProc)
332
+ if (cr !== 0) return cr
333
+ return a.file.path.length - b.file.path.length || a.file.path.localeCompare(b.file.path)
334
+ })
335
+ if (ranked.length === 0) return null
336
+
337
+ const top = ranked[0]
338
+ return {
339
+ kind: "file",
340
+ file: top.file,
341
+ matchedSymbol: top.matchedSym ?? undefined,
342
+ matchedHeading: top.bestHeading ? { title: top.bestHeading.title, line: top.bestHeading.line } : undefined,
343
+ matchTier: top.bestHeading ? "heading" : "tokens",
344
+ otherCandidates: ranked.slice(1, 6).map((e) => ({
345
+ path: e.file.path,
346
+ symbol: e.bestHeading ? `§${e.bestHeading.title}` : e.matchedSym,
347
+ lines: e.file.lines,
348
+ })),
349
+ byPath,
350
+ files,
351
+ }
352
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * doc-graph/walk.mjs — 工作树扫描:决定「哪些档入图」。
3
+ *
4
+ * 判据全部从这里出,别处不再另存一份:目录剪枝 `excludedDirPredicate`(`index.excludePaths` 前缀)、
5
+ * 档过滤 `processDocPredicate`(过程档判据单源,住 `process-docs.mjs`)、构建产物/依赖树黑名单
6
+ * (`skip-dirs.mjs` + 本档 `EXTRA_SKIP_DIRS`)、`>2MB` 大档跳过。
7
+ *
8
+ * 两把谓词分家的理由写在同一行旁边:过程档目录里可以有要入图的活测试,整棵剪掉会静默丢节点。
9
+ */
10
+ import { readdirSync, statSync } from "node:fs"
11
+ import { join, relative } from "node:path"
12
+
13
+ import { BUILD_ARTIFACT_DIRS, BUILD_ARTIFACT_DIR_PREFIXES } from "../skip-dirs.mjs"
14
+ import {
15
+ CODE_EXTENSIONS,
16
+ DOC_EXTENSIONS,
17
+ detectLang,
18
+ isTestFilePath,
19
+ } from "./code-parsers.mjs"
20
+ import { excludedDirPredicate, processDocPredicate } from "./process-docs.mjs"
21
+
22
+ const MAX_FILE_BYTES = 2 * 1024 * 1024 // 跳过 >2MB 生成物/大日志
23
+
24
+ const EXTRA_SKIP_DIRS = new Set([
25
+ ".git", ".hg", ".svn", ".idea", ".vscode", ".cursor", ".thincoder",
26
+ "node_modules", "vendor", "third_party", "bin", "obj", "target",
27
+ "dist", "build", "out", "coverage", "__pycache__", ".venv", "venv",
28
+ ".next", ".nuxt", ".turbo", ".cache", "_archive",
29
+ ])
30
+
31
+ const slash = (p) => String(p ?? "").replace(/\\/g, "/")
32
+ const relOf = (root, abs) => slash(relative(root, abs))
33
+
34
+ function isSkippedDir(name) {
35
+ if (!name || name.startsWith(".")) return true
36
+ if (EXTRA_SKIP_DIRS.has(name) || BUILD_ARTIFACT_DIRS.has(name)) return true
37
+ if (BUILD_ARTIFACT_DIR_PREFIXES.some((p) => name.startsWith(p))) return true
38
+ return false
39
+ }
40
+
41
+ /** 扫描工作树内受支持的源码与 Markdown 文档,返回 Map<relPath, { abs, kind, lang, mtimeMs, size }>。 */
42
+ export function walkRepoFiles(root) {
43
+ const out = new Map()
44
+ // 排除与过程档判据各一把,且两把都从 `declaration` 取(不另读 manifest,也不再持一份前缀比较):
45
+ // 目录剪枝只认 `index.excludePaths` 前缀(`excludedDirPredicate`),档过滤走完整过程档判据
46
+ // (`processDocPredicate`)。两把分家是因为过程档目录里可以有要入图的活测试,整棵剪掉会静默丢节点。
47
+ const isProcessDocInRepo = processDocPredicate(root)
48
+ const skipDir = excludedDirPredicate(root)
49
+ const walk = (dir) => {
50
+ let entries
51
+ try { entries = readdirSync(dir, { withFileTypes: true }) } catch { return }
52
+ for (const ent of entries) {
53
+ if (ent.isSymbolicLink()) continue
54
+ const abs = join(dir, ent.name)
55
+ const rel = relOf(root, abs)
56
+ if (!rel) continue
57
+ if (ent.isDirectory()) {
58
+ if (isSkippedDir(ent.name) || skipDir(rel)) continue
59
+ walk(abs)
60
+ continue
61
+ }
62
+ if (!ent.isFile()) continue
63
+ const dot = ent.name.lastIndexOf(".")
64
+ if (dot < 0) continue
65
+ const ext = ent.name.slice(dot).toLowerCase()
66
+ const isCode = CODE_EXTENSIONS.has(ext)
67
+ const isDoc = DOC_EXTENSIONS.has(ext)
68
+ if (!isCode && !isDoc) continue
69
+ if (isProcessDocInRepo(rel) && !isTestFilePath(rel)) continue
70
+ let st
71
+ try { st = statSync(abs) } catch { continue }
72
+ if (st.size > MAX_FILE_BYTES) continue
73
+ const lang = isDoc ? "md" : detectLang(rel)
74
+ const kind = isDoc ? "doc" : (isTestFilePath(rel) ? "test" : "code")
75
+ out.set(rel, { abs, kind, lang, mtimeMs: st.mtimeMs, size: st.size })
76
+ }
77
+ }
78
+ walk(root)
79
+ return out
80
+ }
81
+
82
+ export function countLines(text) {
83
+ if (!text) return 0
84
+ let n = 1
85
+ for (let i = 0; i < text.length; i++) if (text.charCodeAt(i) === 10) n++
86
+ return n
87
+ }