@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
package/tools/search.mjs CHANGED
@@ -12,7 +12,7 @@ import {
12
12
  import { SKIP_DIRS } from "../skip-dirs.mjs";
13
13
  // 过程档标记 + 文档层标识(机制 = `docs/core/design/TOOLS.md` §7.1):命中行的**档**在索引排除集内 ⇒ 行首逐字前缀;
14
14
  // 每行再带它自己的层标识。只加可读信息,不改命中集。
15
- import { PROCESS_DOC_MARK, isProcessDocPath, docLayerName, processDocsReport } from "./process-doc-mark.mjs";
15
+ import { PROCESS_DOC_MARK, isProcessDocPath, layerLabel, processDocsReport } from "./process-doc-mark.mjs";
16
16
  import { readFile, readdir, stat, lstat } from "node:fs/promises";
17
17
  import { join } from "node:path";
18
18
 
@@ -26,6 +26,39 @@ function escapeRegExp(s) {
26
26
  * `description` 的最短语义是 tiny 档唯一的参数面(那里看不见知识主题)。 */
27
27
  const INCLUDE_PROCESS_DOCS_DESC = "Include process-layer docs (batch records, archived material) — omitted = excluded by default; true = include them"
28
28
 
29
+ /** grep 的注解:命中行加 ` · ←N`(及 `↳ 引用者:` / `↳ 设计/测试` 缩进行),其余推荐仍以知识段追加在后。
30
+ * **没有开关**:注记是清单的一部分,不是模型选不选的功能——`ls` / `tree` / `glob` 也都没有开关。
31
+ * 任何失败都退回原行 + 一行降级说明——注记不得让清单少一行、换一行。 */
32
+ async function withGrepAnnotations(args, ctx, rows, hitPaths) {
33
+ const plain = rows.map((row) => row.text)
34
+ try {
35
+ const { annotateGrepRows } = await import("../doc-graph/search-augment.mjs")
36
+ return await annotateGrepRows({ args, ctx, hitPaths, rows })
37
+ } catch (error) {
38
+ return { lines: plain, section: `[Knowledge · repo_graph] 自动增强加载失败:${error?.message || String(error)};原始文件系统结果不受影响。` }
39
+ }
40
+ }
41
+
42
+ async function withGlobWorkGraph(args, ctx, rawResult, hitPaths) {
43
+ if (hitPaths.length === 0) return rawResult
44
+ try {
45
+ const { appendGlobWorkGraph } = await import("../doc-graph/glob-work-graph.mjs")
46
+ return await appendGlobWorkGraph({ args, ctx, rawResult, hitPaths })
47
+ } catch (error) {
48
+ return `${rawResult}\n[graph] ${error?.message || String(error)}; match list unchanged.`
49
+ }
50
+ }
51
+
52
+ async function withLsWorkGraph(args, ctx, rawResult, targetDir, hitFiles, hitDirs, rowPaths = []) {
53
+ if (hitFiles.length === 0 && hitDirs.length === 0) return rawResult
54
+ try {
55
+ const { appendLsWorkGraph } = await import("../doc-graph/ls-work-graph.mjs")
56
+ return await appendLsWorkGraph({ args, ctx, rawResult, targetDir, hitFiles, hitDirs, rowPaths })
57
+ } catch (error) {
58
+ return `${rawResult}\nRelations: ${error?.message || String(error)}; entry list unchanged.`
59
+ }
60
+ }
61
+
29
62
  // ---------------------------------------------------------------- glob
30
63
 
31
64
  export const globTool = {
@@ -34,8 +67,9 @@ export const globTool = {
34
67
  parameters: {
35
68
  type: "object",
36
69
  properties: {
37
- pattern: { type: "string", description: "Glob pattern — supports **, *, ?, [..], {a,b} braces, and space-separated exclusion (\"**/*.js !test/**\")" },
70
+ pattern: { type: "string", description: "Glob pattern — supports **, *, ?, [..], {a,b} braces, and space-separated exclusion (\"**/*.js !test/**\"). A single word with no wildcard (e.g. case_field_acl) matches any file whose name contains it" },
38
71
  path: { type: "string", description: "Directory to search in (default cwd)" },
72
+ ignoreCase: { type: "boolean", description: "Case-insensitive pattern match (default false)" },
39
73
  includeProcessDocs: { type: "boolean", description: INCLUDE_PROCESS_DOCS_DESC },
40
74
  },
41
75
  required: ["pattern"],
@@ -46,11 +80,13 @@ export const globTool = {
46
80
  const includeProcessDocs = args.includeProcessDocs === true
47
81
  // TOOLS.md §6.7 调用侧拆分(评审 #5 职责分层):空格分隔 include !exclude 多模式在这里拆;
48
82
  // globToRegex 只收单个模式(数组由 compileGlobMatchers 收)。
83
+ // 本工具开启裸词便捷匹配(无通配符的词 = `**/*word*`)与 ignoreCase;grep/`repo_graph(outline)` 的
84
+ // glob 过滤参数不开启,保持纯 glob 语义。
49
85
  let match
50
86
  try {
51
87
  const parts = splitGlobPatterns(args.pattern)
52
88
  if (parts.length === 0) return "Error: pattern is required"
53
- match = compileGlobMatchers(parts).test
89
+ match = compileGlobMatchers(parts, { ignoreCase: args.ignoreCase === true, bareWord: true }).test
54
90
  } catch (e) {
55
91
  return `glob error: invalid pattern "${args.pattern}": ${e.message}`
56
92
  }
@@ -74,8 +110,12 @@ export const globTool = {
74
110
  const n = includeProcessDocs ? results.filter((p) => isProcessDocPath(join(base, p), procCache)).length : excluded
75
111
  const body = results.length === 0
76
112
  ? "(no matches)"
77
- : truncate(results.sort().map((p) => `[${docLayerName(join(base, p), layerCache)}] ${p}`).join("\n"))
78
- return n > 0 ? `${body}\n${processDocsReport(n, includeProcessDocs)}` : body
113
+ : results.sort().map((p) => { const lab = layerLabel(join(base, p), layerCache); return lab ? `${lab} ${p}` : p }).join("\n")
114
+ const withProcessReport = n > 0 ? `${body}\n${processDocsReport(n, includeProcessDocs)}` : body
115
+ const rawResult = results.length >= 1000
116
+ ? `${withProcessReport}\n[glob: result limit 1000 reached; additional matches may be omitted]`
117
+ : withProcessReport
118
+ return withGlobWorkGraph(args, ctx, rawResult, results.map((p) => join(base, p)))
79
119
  },
80
120
  }
81
121
 
@@ -110,18 +150,22 @@ export const grepTool = {
110
150
  properties: {
111
151
  pattern: { type: "string", description: "Regular expression, or a literal string when literal=true" },
112
152
  path: { type: "string", description: "Directory or file to search (default cwd)" },
153
+ paths: { type: "array", items: { type: "string" }, description: "Multiple files or directories to search in one call (overrides path when non-empty)" },
113
154
  glob: { type: "string", description: "Only search files matching this glob — supports **, *, ?, [..], {a,b} braces and space-separated exclusion (\"**/*.js !test/**\")" },
114
155
  ignoreCase: { type: "boolean", description: "Case-insensitive match (default false)" },
115
156
  literal: { type: "boolean", description: "Literal string match — no regex interpretation (default false)" },
116
157
  before: { type: "integer", description: "Lines of context to show before each match (grep -B). Default 0" },
117
158
  after: { type: "integer", description: "Lines of context to show after each match (grep -A). Default 0" },
159
+ limit: { type: "integer", description: "Max matching lines to return (default 200, capped at 200)" },
118
160
  includeProcessDocs: { type: "boolean", description: INCLUDE_PROCESS_DOCS_DESC },
119
161
  },
120
162
  required: ["pattern"],
121
163
  },
122
164
  readonly: true,
123
165
  async execute(args, ctx) {
124
- const base = resolveInCwd(ctx, args.path ?? ".")
166
+ let rawTargets = Array.isArray(args.paths) && args.paths.length > 0
167
+ ? args.paths.map((p) => String(p ?? "").trim()).filter(Boolean)
168
+ : [args.path ?? "."]
125
169
  let regex
126
170
  try {
127
171
  const pat = args.literal ? escapeRegExp(String(args.pattern)) : args.pattern
@@ -129,11 +173,24 @@ export const grepTool = {
129
173
  } catch (e) {
130
174
  throw new Error(`grep pattern /${args.pattern}/ is not a valid regex: ${e.message}`, { cause: e })
131
175
  }
132
- // §2.5 #65 并入(VSC「路径不存在明确报错」):目标路径缺失不再静默 "(no matches)"。
133
- try {
134
- await lstat(base)
135
- } catch {
136
- return `grep error: path not found: ${base}`
176
+ // 兼容单字符串内逗号分隔多目标(仅当原串本身不是现存路径时才按逗号拆)
177
+ if (rawTargets.length === 1 && typeof rawTargets[0] === "string" && rawTargets[0].includes(",")) {
178
+ const whole = resolveInCwd(ctx, rawTargets[0])
179
+ let existsWhole = false
180
+ try { await lstat(whole); existsWhole = true } catch { existsWhole = false }
181
+ if (!existsWhole) {
182
+ const split = rawTargets[0].split(",").map((s) => s.trim()).filter(Boolean)
183
+ if (split.length > 1) rawTargets = split
184
+ }
185
+ }
186
+ const bases = rawTargets.map((t) => resolveInCwd(ctx, t))
187
+ // §2.5 #65 并入(VSC「路径不存在明确报错」):任一目标路径缺失不再静默 "(no matches)"。
188
+ for (const base of bases) {
189
+ try {
190
+ await lstat(base)
191
+ } catch {
192
+ return `grep error: path not found: ${base}`
193
+ }
137
194
  }
138
195
  // TOOLS.md §6.7 调用侧拆分:glob 参数支持空格分隔 include !exclude 多模式(include/exclude 求交)。
139
196
  let fileTest = null
@@ -147,6 +204,7 @@ export const grepTool = {
147
204
  }
148
205
  const before = Math.max(0, Math.floor(args.before ?? 0))
149
206
  const after = Math.max(0, Math.floor(args.after ?? 0))
207
+ const maxHits = Number.isFinite(args.limit) && args.limit > 0 ? Math.min(200, Math.floor(args.limit)) : 200
150
208
  const wantCtx = before > 0 || after > 0
151
209
  const includeProcessDocs = args.includeProcessDocs === true
152
210
  const hits = [] // { file, line(1-based), text }
@@ -164,7 +222,7 @@ export const grepTool = {
164
222
  } catch {
165
223
  return // Skip unreadable files; binary files will be read as UTF-8 and searched (may produce garbled matches)
166
224
  }
167
- // 默认排除在**命中处**生效:被排除的档不占 200 条配额,也不进上下文区。
225
+ // 默认排除在**命中处**生效:被排除的档不占配额,也不进上下文区。
168
226
  // 首次命中时才判定(整仓 grep 不必为每个扫到的档付一次属辖声明探测)。
169
227
  let skipProcess = null
170
228
  const lines = content.split("\n")
@@ -174,12 +232,12 @@ export const grepTool = {
174
232
  if (skipProcess === null) skipProcess = !includeProcessDocs && isProcessDocPath(file, procCache)
175
233
  if (skipProcess) { excludedRows += 1; continue }
176
234
  hits.push({ file, line: i + 1, text: lines[i] })
177
- if (hits.length >= 200) break
235
+ if (hits.length >= maxHits) break
178
236
  }
179
237
  }
180
238
 
181
239
  async function walk(target, rel) {
182
- if (hits.length >= 200) return
240
+ if (hits.length >= maxHits) return
183
241
  // Use lstat to avoid following symlinks — prevents ./evil → /etc from making grep scan the entire system
184
242
  let s
185
243
  try { s = await lstat(target) } catch { return }
@@ -201,7 +259,10 @@ export const grepTool = {
201
259
  }
202
260
  }
203
261
 
204
- await walk(base, "")
262
+ for (const base of bases) {
263
+ if (hits.length >= maxHits) break
264
+ await walk(base, "")
265
+ }
205
266
 
206
267
  // §7.1:一次调用一个档记忆表;命中行与上下文行都在原有文案前镀前缀(判据是**档**不是行——
207
268
  // 不标则同一档的上下文行读起来像普通档的内容)。层标识紧随既有过程档前缀之后:
@@ -209,15 +270,23 @@ export const grepTool = {
209
270
  const markCache = new Map()
210
271
  const layerCache = new Map()
211
272
  const mark = (f) => (isProcessDocPath(f, markCache) ? `${PROCESS_DOC_MARK} ` : "")
212
- const lead = (f) => `${mark(f)}[${docLayerName(f, layerCache)}] `
273
+ const lead = (f) => { const lab = layerLabel(f, layerCache); return `${mark(f)}${lab ? `${lab} ` : ""}` }
213
274
  // 报数 N = 本次输出里被判为过程档的行(排除模式 = 被排掉的行;取回模式 = 进来的行)。
214
275
  const reported = includeProcessDocs ? hits.filter((h) => isProcessDocPath(h.file, markCache)).length : excludedRows
215
276
  const withReport = (body) => (reported > 0 ? `${body}\n${processDocsReport(reported, includeProcessDocs)}` : body)
216
- if (hits.length === 0) return withReport("(no matches)")
277
+ // 命中行先按 { file, text } 收起来:注解要缀在**每个档的首行**上,得知道哪行属于哪个档。
278
+ // 顺序不变:注解只是在首行后插入一行缩进行,路径、行号、文本、次序一字未动,也不删行。
279
+ const finish = async (rows) => {
280
+ const { lines, section } = await withGrepAnnotations(args, ctx, rows, hits.map((h) => h.file))
281
+ const body = rows.length === 0 ? "(no matches)" : truncate(lines.join("\n"))
282
+ const reported = withReport(body)
283
+ return section ? `${reported}\n${section}` : reported
284
+ }
285
+ if (hits.length === 0) return finish([])
217
286
 
218
287
  // No context: one line per hit — layer label first, then the original path:line: content shape.
219
288
  if (!wantCtx) {
220
- return withReport(truncate(hits.map((h) => `${lead(h.file)}${h.file}:${h.line}: ${h.text}`).join("\n")))
289
+ return finish(hits.map((h) => ({ file: h.file, text: `${lead(h.file)}${h.file}:${h.line}: ${h.text}` })))
221
290
  }
222
291
 
223
292
  // With context: matching lines use ':', context lines use '-' (like ripgrep); overlapping ranges in same file are merged and de-duplicated
@@ -235,10 +304,10 @@ export const grepTool = {
235
304
  }
236
305
  for (const l of [...lineSet].sort((a, b) => a - b)) {
237
306
  const sep = matchedLines.has(l) ? ":" : "-"
238
- out.push(`${lead(file)}${file}${sep}${l}${sep} ${lines[l - 1]}`)
307
+ out.push({ file, text: `${lead(file)}${file}${sep}${l}${sep} ${lines[l - 1]}` })
239
308
  }
240
309
  }
241
- return withReport(truncate(out.join("\n")))
310
+ return finish(out)
242
311
  },
243
312
  }
244
313
 
@@ -249,7 +318,9 @@ export const lsTool = {
249
318
  type: "object",
250
319
  properties: {
251
320
  path: { type: "string", description: "Directory path (default cwd)" },
252
- filter: { type: "string", description: "Only list entries matching this glob (e.g. '*.mjs', '*test*')" },
321
+ filter: { type: "string", description: "Only list entries matching this glob (e.g. '*.mjs', '*test*') — applied at every listed level" },
322
+ recursive: { type: "integer", minimum: 1, maximum: 3, description: "Descend this many directory levels (1-3). Only directories are expanded — file rows stay at the top level, because recursing into files would blow the entry limit on a real repo. Omit for a flat one-level listing" },
323
+ byDirectory: { type: "boolean", description: "Drop file rows and put the recursive code/doc/test counts on each directory row — the per-directory summary of what a tree holds. Directory rows carry the size summary, cross-directory inbound edges (←), internal edges (⟳), top hubs with inbound counts and, where process docs were excluded, how many. Omit to list files as usual" },
253
324
  includeProcessDocs: { type: "boolean", description: INCLUDE_PROCESS_DOCS_DESC },
254
325
  },
255
326
  },
@@ -257,6 +328,10 @@ export const lsTool = {
257
328
  async execute(args, ctx) {
258
329
  const abs = resolveInCwd(ctx, args.path ?? ".")
259
330
  const filterRe = args.filter ? globToRegex(args.filter) : null
331
+ // `recursive` 只下钻**目录**:递归列文件在真实仓里(1500+ 档一个目录)立刻撞 500 条上限,
332
+ // 列文件是 glob 的路,计数是 `tree count` 的路。两个参数都不改上限与图谱形态。
333
+ const recursive = Number.isInteger(args.recursive) && args.recursive > 0 ? Math.min(args.recursive, 3) : 0
334
+ const byDirectory = args.byDirectory === true
260
335
  let entries
261
336
  try {
262
337
  entries = await readdir(abs, { withFileTypes: true })
@@ -271,35 +346,75 @@ export const lsTool = {
271
346
  const procCache = new Map()
272
347
  const layerCache = new Map()
273
348
  let excluded = 0
274
- const kept = []
349
+ let limitReached = false
350
+ const kept = [] // { entry, absPath, depth } —— 顺序即输出的前序顺序
351
+ const firstLevel = []
275
352
  for (const e of entries) {
276
353
  if (filterRe && !filterRe.test(e.name)) continue
277
- if (kept.length >= 500) break
278
- if (!includeProcessDocs && !e.isDirectory() && isProcessDocPath(join(abs, e.name), procCache)) { excluded += 1; continue }
279
- kept.push(e)
354
+ if (!includeProcessDocs && !e.isDirectory() && isProcessDocPath(join(abs, e.name), procCache)) {
355
+ if (kept.length < 500) excluded += 1
356
+ continue
357
+ }
358
+ firstLevel.push(e)
280
359
  }
360
+ // 前序遍历:每个目录行后面紧跟它的子层(缩进两格),文件仍**只**在第 0 层、且排在目录之后——
361
+ // 逐层排序仍是「目录在前、文件在后」,既有单层输出一个字不变(depth 恒为 0)。
362
+ async function collect(list, dir, depth) {
363
+ const dirs = list.filter((e) => e.isDirectory()).sort((a, b) => a.name.localeCompare(b.name))
364
+ const files = byDirectory || depth > 0 ? [] : list.filter((e) => !e.isDirectory()).sort((a, b) => a.name.localeCompare(b.name))
365
+ for (const e of dirs) {
366
+ if (kept.length >= 500) { limitReached = true; return }
367
+ kept.push({ entry: e, absPath: join(dir, e.name), depth })
368
+ // 递归不展开点目录与 SKIP_DIRS:`.git/objects/…` 这类子层不是「这个仓长什么样」,
369
+ // 一层几十上百条子目录会把要看的形状挤出窗口。行照留(单层清单历来就列它们),只是不下钻。
370
+ const opaque = e.name.startsWith(".") || SKIP_DIRS.has(e.name)
371
+ if (!opaque && depth + 1 <= recursive) {
372
+ let sub = null
373
+ try { sub = await readdir(join(dir, e.name), { withFileTypes: true }) } catch { sub = null }
374
+ if (sub) await collect(filterRe ? sub.filter((s) => filterRe.test(s.name)) : sub, join(dir, e.name), depth + 1)
375
+ }
376
+ }
377
+ for (const e of files) {
378
+ if (kept.length >= 500) { limitReached = true; return }
379
+ kept.push({ entry: e, absPath: join(dir, e.name), depth })
380
+ }
381
+ }
382
+ await collect(firstLevel, abs, 0)
281
383
  const rows = await Promise.all(
282
- kept.map(async (e) => {
283
- const s = await stat(join(abs, e.name)).catch(() => null)
284
- const isDir = e.isDirectory()
285
- const proc = isDir ? false : isProcessDocPath(join(abs, e.name), procCache)
384
+ kept.map(async ({ entry, absPath, depth }) => {
385
+ const s = await stat(absPath).catch(() => null)
386
+ const isDir = entry.isDirectory()
387
+ const proc = isDir ? false : isProcessDocPath(absPath, procCache)
286
388
  // 层标识跟在条目名之后——本行的字形与列宽本身是结构,行首留给 `d`/`-` 与尺寸列。
287
- const label = isDir ? "" : ` [${docLayerName(join(abs, e.name), layerCache)}]`
389
+ const lab = isDir ? "" : layerLabel(absPath, layerCache)
390
+ const label = lab ? ` ${lab}` : ""
288
391
  return {
289
392
  dir: isDir,
290
393
  proc,
291
- name: e.name + (isDir ? "/" : "") + label,
394
+ name: " ".repeat(depth) + entry.name + (isDir ? "/" : "") + label,
292
395
  size: s?.size ?? 0,
293
396
  mtime: s ? s.mtime.toISOString().slice(0, 16).replace("T", " ") : "?",
294
397
  }
295
398
  }),
296
399
  )
297
- rows.sort((a, b) => (a.dir === b.dir ? a.name.localeCompare(b.name) : a.dir ? -1 : 1))
298
400
  // 报数 N = 本次输出里被判为过程档的条目(排除模式 = 被排掉的条目;取回模式 = 进来的条目)。
299
- const reported = includeProcessDocs ? rows.filter((r) => r.proc).length : excluded
300
- if (rows.length === 0) return reported > 0 ? `(no entries)\n${processDocsReport(reported, includeProcessDocs)}` : "(no entries)"
301
- const out = rows.map((r) => `${r.dir ? "d" : "-"} ${r.name.padEnd(40)} ${String(r.size).padStart(10)} ${r.mtime}`)
302
- const body = truncate(out.join("\n"))
303
- return reported > 0 ? `${body}\n${processDocsReport(reported, includeProcessDocs)}` : body
401
+ // 摘要模式没有档行,报数行会指称不存在的条目 ⇒ 不加行(摘要里的计数本身已按入图档算,过程档不计入)。
402
+ const reported = byDirectory ? 0 : includeProcessDocs ? rows.filter((r) => r.proc).length : excluded
403
+ if (rows.length === 0) {
404
+ return reported > 0 ? `(no entries)\n${processDocsReport(reported, includeProcessDocs)}` : "(no entries)"
405
+ }
406
+ // 目录没有字节大小:目录行尺寸格写 `-`。写 `0` 会与「空目录」撞车(同一个 `0` 两种意思),
407
+ // 也不该因尺寸列恒定而让人以为目录被算成了 0 字节。宽度不变,列不漂。
408
+ const sizeCell = (r) => (r.dir ? "-" : String(r.size)).padStart(10)
409
+ const out = rows.map((r) => `${r.dir ? "d" : "-"} ${r.name.padEnd(40)} ${sizeCell(r)} ${r.mtime}`)
410
+ const body = out.join("\n")
411
+ const withProcessReport = reported > 0 ? `${body}\n${processDocsReport(reported, includeProcessDocs)}` : body
412
+ const rawResult = limitReached
413
+ ? `${withProcessReport}\n[ls: result limit 500 reached; additional entries may be omitted]`
414
+ : withProcessReport
415
+ const hitFiles = kept.filter((k) => !k.entry.isDirectory()).map((k) => k.absPath)
416
+ const hitDirs = kept.filter((k) => k.entry.isDirectory()).map((k) => k.absPath)
417
+ // 递归行的名字前面带缩进,不能再靠名字还原绝对路径:按输出顺序交出每条行的路径。
418
+ return withLsWorkGraph(args, ctx, rawResult, abs, hitFiles, hitDirs, kept.map((k) => k.absPath))
304
419
  },
305
420
  }
package/tools/shared.mjs CHANGED
@@ -322,6 +322,9 @@ export function resolveInCwd(ctx, p) {
322
322
 
323
323
  /** Resolve a path relative to cwd without boundary check — kept for compatibility (≡ resolveInCwd) */
324
324
  export function resolveExternal(ctx, p) {
325
+ if (typeof p !== "string" || !p.trim()) {
326
+ throw new Error("path is required (pass a non-empty file or directory path string)")
327
+ }
325
328
  const cwd = realCwd(ctx.cwd)
326
329
  return resolve(cwd, p)
327
330
  }
@@ -406,6 +409,9 @@ export function detectDanger(command) {
406
409
  * (system.mjs tools, ls filter, tests) keep their import paths unchanged. */
407
410
  export {
408
411
  globToRegex,
412
+ firstAbsoluteGlobPattern,
413
+ absoluteGlobRejection,
414
+ looksLikeGlob,
409
415
  splitGlobPatterns,
410
416
  compileGlobMatchers,
411
417
  GLOB_EXTGLOB_ERROR,
package/tools/tree.mjs CHANGED
@@ -3,16 +3,20 @@
3
3
  * Renders a repo's directory tree (default depth 3), skipping dotfiles,
4
4
  * build/vendor dirs and binary files, so the model can see which modules
5
5
  * exist without shelling out to `tree`/`find`.
6
+ *
7
+ * `count: true` 是摘要模式:只出目录行,右列是该目录的**递归**文件数,不列文件名。
8
+ * 深度只限制列出的目录层级,计数始终全递归——目录行远少于文件行,同一 200 条上限
9
+ * 不再把「一个目录几千个档」截成一屏问号(2026-12-01 实测反馈)。
6
10
  */
7
11
  import { DESC, truncate, resolveInCwd } from "./shared.mjs"
8
12
  import { readdir, stat } from "node:fs/promises"
9
- import { join, basename, extname } from "node:path"
13
+ import { join, basename, extname, relative } from "node:path"
10
14
  // 排除名单单源(零依赖叶档 `skip-dirs.mjs`——2026-10-27 四份名单合一):本档不再持本地副本。
11
15
  // 两项旧值随之退场:`turbo`(无点,笔误——另三份都是 `.turbo`)、`bin`(`thincoder-cli/bin/**`
12
16
  // 是 CLI 入口、产品代码,不该从任何面上被剪掉)。
13
17
  import { SKIP_DIRS } from "../skip-dirs.mjs"
14
18
  // 过程档默认排除 + 层标识(机制 = `docs/core/design/TOOLS.md` §7.1):只对**档结果**判,目录节点照留。
15
- import { isProcessDocPath, docLayerName, processDocsReport } from "./process-doc-mark.mjs"
19
+ import { isProcessDocPath, layerLabel, processDocsReport } from "./process-doc-mark.mjs"
16
20
 
17
21
  const MAX_ENTRIES = 200
18
22
  const DEFAULT_DEPTH = 3
@@ -40,6 +44,7 @@ export const treeTool = {
40
44
  properties: {
41
45
  path: { type: "string", description: "Root directory (default cwd)" },
42
46
  depth: { type: "integer", description: `Tree depth (default ${DEFAULT_DEPTH}, max 6)` },
47
+ count: { type: "boolean", description: "Summary mode: one row per directory (up to `depth`), right column = that directory's recursive file count — no file names are listed. A row also says how many of its own files it contains and how many process docs were excluded from its count. Counts ignore `depth`; only the listed directory levels do. Each row also carries graph signals when the graph is available: `←N` cross-directory inbound import edges, `hub <file>(N)` the most-imported file in that subtree, `⚠cycle a↔b` directory-level cycles, and `entry N` files with no in-repo importer. When the graph is unavailable all four say `n/a` (never `0`) and the output starts with a line saying why. Omit for the normal tree" },
43
48
  includeProcessDocs: { type: "boolean", description: "Include process-layer docs (batch records, archived material) — omitted = excluded by default; true = include them" },
44
49
  },
45
50
  required: [],
@@ -53,7 +58,6 @@ export const treeTool = {
53
58
  if (!st.isDirectory()) return `Error: not a directory: ${args.path ?? "."}`
54
59
  const d = Number(args.depth)
55
60
  const maxDepth = Number.isInteger(d) && d > 0 ? Math.min(d, 6) : DEFAULT_DEPTH
56
- const lines = [basename(root) + "/"]
57
61
  // 被排除的档先移出 `items`,再算 `├──` ∥ `└──` 与 `state.count`:末项字形不落在被排除的条目上,
58
62
  // 「…(更多项已省略)」也落在存活条目之后。`MAX_ENTRIES` 与 `truncate` 都不变。
59
63
  const opts = {
@@ -61,11 +65,33 @@ export const treeTool = {
61
65
  procCache: new Map(),
62
66
  layerCache: new Map(),
63
67
  }
64
- const state = { count: 1, capped: false, excluded: 0, included: 0 }
65
- await walk(root, 0, maxDepth, "", lines, state, opts)
66
- const body = truncate(lines.join("\n"))
68
+ const state = { count: args.count === true ? 0 : 1, capped: false, excluded: 0, included: 0 }
69
+ let body
70
+ if (args.count === true) {
71
+ // 摘要模式:根行也占一条配额。计数在子目录遍历完才齐,行先占位、末尾回填。
72
+ const rows = []
73
+ await countWalk(root, basename(root), 0, maxDepth, "", true, true, rows, state, opts)
74
+ // 图列是**附加**的:磁盘计数不参与它,它也不可能改它(两套数据各出一半)。
75
+ const signals = await loadDirSignals(root)
76
+ const head = signals.available
77
+ ? ""
78
+ : `[graph n/a] ${signals.reason} —— 图列四段(← / hub / 环 / 入口)标 n/a,不是 0。\n`
79
+ body = truncate(head + renderCount(rows, state, signals))
80
+ } else {
81
+ const lines = [basename(root) + "/"]
82
+ await walk(root, 0, maxDepth, "", lines, state, opts)
83
+ body = truncate(lines.join("\n"))
84
+ }
67
85
  const n = opts.includeProcessDocs ? state.included : state.excluded
68
- return n > 0 ? `${body}\n${processDocsReport(n, opts.includeProcessDocs)}` : body
86
+ if (n === 0) return body
87
+ // 摘要模式没有档行:N 说的是「这些计数里没算进去的档」,不是输出行——沿用 `of this output's rows`
88
+ // 那句会在一个只有目录行的输出里指称不存在的行(2026-12-01 实测踩到)。
89
+ if (args.count === true) {
90
+ return `${body}\n${opts.includeProcessDocs
91
+ ? `[process docs: ${n} files in these counts come from process docs — included by request]`
92
+ : `[process docs: ${n} files in these counts come from process docs — excluded from these counts; pass includeProcessDocs=true to include them]`}`
93
+ }
94
+ return `${body}\n${processDocsReport(n, opts.includeProcessDocs)}`
69
95
  },
70
96
  }
71
97
 
@@ -96,11 +122,188 @@ async function walk(dir, depth, maxDepth, prefix, lines, state, opts) {
96
122
  const { name, isDir } = kept[i]
97
123
  const isLast = i === kept.length - 1
98
124
  // 层标识跟在条目名之后(本行字形是结构);目录行不带——目录不是档。
99
- const text = isDir ? name + "/" : `${name} [${docLayerName(join(dir, name), opts.layerCache)}]`
125
+ const lab = isDir ? "" : layerLabel(join(dir, name), opts.layerCache)
126
+ const text = isDir ? name + "/" : (lab ? `${name} ${lab}` : name)
100
127
  lines.push(prefix + (isLast ? "└── " : "├── ") + text)
101
128
  state.count++
102
129
  if (isDir && depth + 1 < maxDepth) {
103
130
  await walk(join(dir, name), depth + 1, maxDepth, prefix + (isLast ? " " : "│ "), lines, state, opts)
104
131
  }
105
132
  }
133
+ }
134
+
135
+ // ─── 摘要模式(count: true)────────────────────────────────────────────────
136
+ // 同一套过滤(点条目、SKIP_DIRS、二进制扩展名、过程档按 includeProcessDocs)在这里复用,
137
+ // 所以两模式的「这个目录里有多少档」是同一个数,不是另建一套口径。
138
+ const COUNT_SEP = " "
139
+
140
+ /** 占一条配额并落一行;配额满 ⇒ 置 capped 并拒收(计数照旧跑完,根行总数才不会谎报)。 */
141
+ function pushCountRow(rows, state, row) {
142
+ if (state.capped) return null
143
+ if (state.count >= MAX_ENTRIES) { state.capped = true; return null }
144
+ rows.push(row)
145
+ state.count += 1
146
+ return row
147
+ }
148
+
149
+ /**
150
+ * 目录行 + 递归档数。返回 `{ total, excluded }`:该目录下的递归文件数与其中被排除的过程档数。
151
+ * `depth` 只决定**是否列出**这一层目录;计数永远递归到最底层。
152
+ */
153
+ async function countWalk(dir, name, depth, maxDepth, prefix, isLast, isRoot, rows, state, opts) {
154
+ let files = 0
155
+ let ownExcluded = 0
156
+ const dirs = []
157
+ let entries = null
158
+ try { entries = await readdir(dir, { withFileTypes: true }) } catch { /* unreadable — 空目录处理 */ }
159
+ for (const e of entries ?? []) {
160
+ if (e.name.startsWith(".")) continue
161
+ if (e.isDirectory()) { if (!SKIP_DIRS.has(e.name)) dirs.push(e.name); continue }
162
+ if (BINARY_EXTS.has(extname(e.name).toLowerCase())) continue
163
+ const proc = isProcessDocPath(join(dir, e.name), opts.procCache)
164
+ if (proc && !opts.includeProcessDocs) { state.excluded += 1; ownExcluded += 1; continue }
165
+ if (proc) state.included += 1
166
+ files += 1
167
+ }
168
+ dirs.sort((a, b) => a.localeCompare(b))
169
+
170
+ // 过程档被排除数按**子树**累加,与 `total` 同一遍前序遍历、同一个过滤点——不是另建一套口径。
171
+ // 没有这个数,`0` 就有两种含义(真空 ∥ 全是过程档),三个目录在输出里长得一模一样(2026-12-01 实测反馈)。
172
+ const row = pushCountRow(rows, state, { prefix, name, isLast, isRoot, total: files, own: files, excluded: ownExcluded, dir })
173
+ let total = files
174
+ let excluded = ownExcluded
175
+ const childPrefix = prefix + (isRoot ? "" : isLast ? " " : "│ ")
176
+ for (let i = 0; i < dirs.length; i++) {
177
+ const childDir = join(dir, dirs[i])
178
+ // 超出列出层级 ⇒ 只数不列(这正是「要形状、不要清单」的那一半)。
179
+ const sub = depth + 1 <= maxDepth
180
+ ? await countWalk(childDir, dirs[i], depth + 1, maxDepth, childPrefix, i === dirs.length - 1, false, rows, state, opts)
181
+ : await countOnly(childDir, opts, state)
182
+ total += sub.total
183
+ excluded += sub.excluded
184
+ }
185
+ if (row) { row.total = total; row.excluded = excluded }
186
+ return { total, excluded }
187
+ }
188
+
189
+ /** 只递归计数、不落行(超出列出层级的子树走这里)。*/
190
+ async function countOnly(dir, opts, state) {
191
+ let entries = null
192
+ try { entries = await readdir(dir, { withFileTypes: true }) } catch { return { total: 0, excluded: 0 } }
193
+ let total = 0
194
+ let excluded = 0
195
+ for (const e of entries) {
196
+ if (e.name.startsWith(".")) continue
197
+ if (e.isDirectory()) {
198
+ if (!SKIP_DIRS.has(e.name)) {
199
+ const sub = await countOnly(join(dir, e.name), opts, state)
200
+ total += sub.total
201
+ excluded += sub.excluded
202
+ }
203
+ continue
204
+ }
205
+ if (BINARY_EXTS.has(extname(e.name).toLowerCase())) continue
206
+ const proc = isProcessDocPath(join(dir, e.name), opts.procCache)
207
+ if (proc && !opts.includeProcessDocs) { state.excluded += 1; excluded += 1; continue }
208
+ if (proc) state.included += 1
209
+ total += 1
210
+ }
211
+ return { total, excluded }
212
+ }
213
+
214
+ function renderCount(rows, state, signals) {
215
+ const out = rows.map((r) => {
216
+ // 目录行的数**含**它自己这一层的档,所以父行 ≠ 子行加总(2026-12-01 实测反馈:
217
+ // 根行 3323 vs 六个子目录 3319,差的正是根级 4 个非点档)。本级有档就附一句,
218
+ // 否则读者会为差的那几个数去翻根目。没有就不加,不给空行添噪音。
219
+ // 第二段说明这个数里**没算进去**多少过程档:`0` 因此不再有两种含义(真空 ∥ 全是过程档)。
220
+ const parts = []
221
+ if (r.own > 0) parts.push(`含${r.isRoot ? "根" : "本"}级 ${r.own} 个档`)
222
+ if (r.excluded > 0) parts.push(`另有 ${r.excluded} 个过程档被排除`)
223
+ const note = parts.length ? `(${parts.join(";")})` : ""
224
+ return `${r.prefix}${r.isRoot ? "" : r.isLast ? "└── " : "├── "}${r.name}/${COUNT_SEP}${r.total}${note}${graphColumns(r, signals)}`
225
+ })
226
+ if (state.capped) out.push(`${rows.length ? rows[rows.length - 1].prefix : ""}…(更多项已省略)`)
227
+ return out.join("\n")
228
+ }
229
+
230
+ // ─── 图列(← / hub / ⚠环 / 入口)──────────────────────────────────────────
231
+ // 判据与 `repo_graph(overview)` 同源(聚合住 `doc-graph/dir-signals.mjs`,本档只排版)。
232
+ // **图不可用绝不写成 0**:四列齐标 n/a,并在输出顶部说明原因——「不知道」长得像「零」
233
+ // 比没有这一列更坏(2026-12-01 实测反馈:889 档的 `ddd/` 零入边、40 档的 `case/` 才是全仓核心,
234
+ // 只给规模会让人把「最大」读成「最要紧」)。
235
+ const GRAPH_NA = " · ←n/a · hub n/a · 环n/a · 入口 n/a"
236
+
237
+ function graphColumns(r, signals) {
238
+ if (!signals.available) return GRAPH_NA
239
+ const relDir = signals.relDirOf(r.dir)
240
+ if (relDir === null) return GRAPH_NA
241
+ const parts = []
242
+ // 根本身没有「目录之外」可数:`←—` 而不是 `←0`(零会被读成「没人依赖它」)。
243
+ if (relDir === "") {
244
+ parts.push("←—")
245
+ } else {
246
+ const inbound = signals.crossInbound.get(relDir) ?? 0
247
+ parts.push(`←${inbound}`)
248
+ if (inbound > 0) {
249
+ const h = signals.hub.get(relDir)
250
+ if (h) parts.push(`hub ${basename(h.file)}(${h.count})`)
251
+ } else {
252
+ parts.push("无入边")
253
+ }
254
+ }
255
+ const cycles = signals.cycles.filter((c) => c.lca === relDir)
256
+ if (cycles.length > 0) {
257
+ const shown = cycles.slice(0, 2).map((c) => c.label).join(",")
258
+ parts.push(`⚠环 ${shown}${cycles.length > 2 ? ` +${cycles.length - 2}` : ""}`)
259
+ }
260
+ parts.push(`入口 ${signals.entries.get(relDir) ?? 0}`)
261
+ return ` · ${parts.join(" · ")}`
262
+ }
263
+
264
+ /**
265
+ * 建图并聚合图列。**永不抛**:任何一步不成 ⇒ `{available:false, reason}`,由调用方标 n/a。
266
+ * `syncGraph` 走动态 import——`store.mjs` 的静态闭包达 `node:sqlite`,本档被端壳静态引用(W8 契约②)。
267
+ */
268
+ async function loadDirSignals(root) {
269
+ let resolved
270
+ try {
271
+ const { resolveQueryRoot } = await import("../doc-graph/roots.mjs")
272
+ resolved = resolveQueryRoot(root)
273
+ } catch (error) {
274
+ return { available: false, reason: `判根失败:${error?.message || String(error)}` }
275
+ }
276
+ if (!resolved.ok) {
277
+ return {
278
+ available: false,
279
+ reason: resolved.reason === "workspace"
280
+ ? "父工作区(多仓),这棵树不是单一项目根"
281
+ : "未找到 PROJECT-MANIFEST.json,判不了属辖仓",
282
+ }
283
+ }
284
+ try {
285
+ // 无属辖声明 ⇒ 不建图:没声明就没法判「这个目录属于哪个项目」,算出来的入口/入边会以
286
+ // 一棵非项目树为界,那个数看着完整、实际不是任何人要的口径。标 n/a 比给一个假边界好。
287
+ const { declarationForTarget } = await import("../declaration.mjs")
288
+ if (!declarationForTarget(resolved.root)) {
289
+ return { available: false, reason: "未找到 PROJECT-MANIFEST.json,判不了属辖仓" }
290
+ }
291
+ const { syncGraph } = await import("../doc-graph/store.mjs")
292
+ const { db, fileCount, skippedCold } = syncGraph(resolved.root, { maxColdFiles: 2500 })
293
+ if (skippedCold || !db) {
294
+ return { available: false, reason: `仓内 ${fileCount} 档超过 2500 的自动建图阈值` }
295
+ }
296
+ try {
297
+ const { buildDirSignals, relDirOf } = await import("../doc-graph/dir-signals.mjs")
298
+ return {
299
+ available: true,
300
+ relDirOf: (abs) => relDirOf(resolved.root, abs),
301
+ ...buildDirSignals(db),
302
+ }
303
+ } finally {
304
+ try { db.close() } catch { /* 库关不掉不影响已取出的数 */ }
305
+ }
306
+ } catch (error) {
307
+ return { available: false, reason: `建图失败:${error?.message || String(error)}` }
308
+ }
106
309
  }