@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,534 @@
1
+ /**
2
+ * ls-work-graph.mjs — fuse ls's exact directory entries (files + subdirs) with their graph relations.
3
+ * Returns per-entry notes (appended to the entry's own row) plus one `Relations:` block that follows
4
+ * the entry list inside the same section — there is no separate "[Work graph]" section.
5
+ * Dynamically imported by tools/search.mjs: this module reaches node:sqlite through store.mjs.
6
+ */
7
+ import { readdirSync } from "node:fs"
8
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path"
9
+
10
+ import {
11
+ GLOB_WORK_GRAPH_BUDGET,
12
+ addKnowledgeLines,
13
+ directDocuments,
14
+ directTests,
15
+ edgeText,
16
+ importEdges,
17
+ pathKey,
18
+ sectionIndex,
19
+ selectConnectors,
20
+ slash,
21
+ } from "./glob-work-graph.mjs"
22
+ import { buildDirSignals, topInbound } from "./dir-signals.mjs"
23
+ import { processDocPredicate } from "./process-docs.mjs"
24
+ import { resolveQueryRoot } from "./roots.mjs"
25
+ import { syncGraph } from "./store.mjs"
26
+ // 过程档计数与 `tree` 同一把判据 + 同一份目录抑制名单:同一个目录在两个工具里不能一个说 40、一个说 0。
27
+ import { SKIP_DIRS } from "../skip-dirs.mjs"
28
+ import { isProcessDocPath } from "../tools/process-doc-mark.mjs"
29
+
30
+ export const LS_WORK_GRAPH_BUDGET = GLOB_WORK_GRAPH_BUDGET
31
+ /** Per-row note ceiling: a single row must not grow into a paragraph. */
32
+ const ROW_NOTE_MAX = 160
33
+
34
+ /**
35
+ * 子树过程档计数:`Map<relDir, n>`(`relDir` = 仓内相对目录,本目录与其各级子目录都有条目)。
36
+ * 为什么得回磁盘数:图谱库里**根本没有**这些档——`walk.mjs` 入图前就把过程档剪掉了,
37
+ * 所以 `files` 表查不到它们,`docs/batches/` 会只剩一句 `no indexed files`,被读成空目录。
38
+ * 判据与 `tree` 同一把(`isProcessDocPath` + `SKIP_DIRS` + 点条目),同一个目录在两处才能报同一个数。
39
+ */
40
+ function processDocCounts(relDir, absDir) {
41
+ const counts = new Map()
42
+ const cache = new Map()
43
+ const walk = (abs, rel) => {
44
+ let entries
45
+ try { entries = readdirSync(abs, { withFileTypes: true }) } catch { entries = [] }
46
+ let n = 0
47
+ for (const ent of entries) {
48
+ if (ent.name.startsWith(".")) continue
49
+ const childAbs = join(abs, ent.name)
50
+ const childRel = rel ? `${rel}/${ent.name}` : ent.name
51
+ if (ent.isDirectory()) {
52
+ if (SKIP_DIRS.has(ent.name)) continue
53
+ n += walk(childAbs, childRel)
54
+ continue
55
+ }
56
+ if (ent.isFile() && isProcessDocPath(childAbs, cache)) n += 1
57
+ }
58
+ counts.set(rel, n)
59
+ return n
60
+ }
61
+ walk(absDir, relDir)
62
+ return counts
63
+ }
64
+
65
+ const kindSummary = (paths, byPath) => {
66
+ const counts = { code: 0, doc: 0, test: 0 }
67
+ for (const p of paths) {
68
+ const k = byPath.get(p)?.kind
69
+ if (k in counts) counts[k] += 1
70
+ }
71
+ const parts = []
72
+ if (counts.code > 0) parts.push(`${counts.code} code`)
73
+ if (counts.doc > 0) parts.push(`${counts.doc} doc`)
74
+ if (counts.test > 0) parts.push(`${counts.test} test`)
75
+ return parts.join(", ") || "no indexed files"
76
+ }
77
+
78
+ const moduleBucket = (path) => {
79
+ const parts = path.split("/")
80
+ if (parts.length <= 1) return path
81
+ return parts.length === 2 ? parts[0] : parts.slice(0, 2).join("/")
82
+ }
83
+
84
+ function docCoveredTargets(db, scopeSeeds, byPath, isProc) {
85
+ const rows = db.prepare("SELECT src, dst FROM edges WHERE kind = 'doc-covers' AND state = 'ok'").all()
86
+ const buckets = new Map()
87
+ for (const row of rows) {
88
+ if (!scopeSeeds.has(row.src) || scopeSeeds.has(row.dst)) continue
89
+ if (byPath.get(row.src)?.kind !== "doc" || isProc(row.src) || isProc(row.dst)) continue
90
+ const bucket = moduleBucket(row.dst)
91
+ if (!buckets.has(bucket)) buckets.set(bucket, { bucket, docs: new Set(), targets: new Set() })
92
+ buckets.get(bucket).docs.add(row.src)
93
+ buckets.get(bucket).targets.add(row.dst)
94
+ }
95
+ return [...buckets.values()].sort((a, b) =>
96
+ b.targets.size - a.targets.size || b.docs.size - a.docs.size || a.bucket.localeCompare(b.bucket))
97
+ }
98
+
99
+ function addCoveredLines(lines, covered) {
100
+ if (covered.length === 0) return
101
+ lines.push("Covers:")
102
+ for (const item of covered.slice(0, 4)) {
103
+ const label = item.targets.size === 1 ? [...item.targets][0] : `${item.bucket}/`
104
+ lines.push(` - ${label} · ${item.targets.size} file${item.targets.size === 1 ? "" : "s"} covered by ${item.docs.size} doc${item.docs.size === 1 ? "" : "s"}`)
105
+ }
106
+ if (covered.length > 4) lines.push(` … ${covered.length - 4} covered modules omitted`)
107
+ }
108
+
109
+ /** 本级档数:只数直接落在这个目录下的(不进子目录)——与 `tree` 的「含本级 N 个档」同一个意思。 */
110
+ function ownLevelCount(dir) {
111
+ const prefix = `${dir.relDir}/`
112
+ let n = 0
113
+ for (const file of dir.files) {
114
+ if (!file.slice(prefix.length).includes("/")) n += 1
115
+ }
116
+ return n
117
+ }
118
+
119
+ /**
120
+ * 目录行注记(`byDirectory` 的目录行与 `Relations` 的 `Subdirectories` 共用一处拼装):
121
+ * `1640 code, 75 test (2 at this level) · ←11 · ⟳291 · hubs: a(492), b(323)`。
122
+ *
123
+ * 四段全部无条件给:目录行的「这层多大」与图读数不是同一件事,两处(条目行∥ Subdirectories)
124
+ * 也不能只在一处有——2026-12-01 复测:`qhse/` 的子目录有 13 档,普通模式却只剩 `←36 · hubs:`,
125
+ * 规模信息在那个视图里整个消失。
126
+ *
127
+ * `←N` = 跨目录入边,与 `tree` 的 `←N` **是同一个数**(`dir-signals` 的 `crossInbound`:一条边只当
128
+ * 源不在该目录子树内才计数)。`⟳M` = 该目录**内部**边数(原 `M internal import edges`)。两个数必须分开写:
129
+ * 2026-12-01 实测,`bms_op` 内部边 291、跨目录入边只有 11,而 `bms_accounting` 内部 49、入边 60——
130
+ * 只拿内部边排序,会把「大而自循环的钩子层」排到「小而外部重用的库」前面,结论整个反过来。
131
+ */
132
+ function dirNote(dir, { byPath, imports, signals }) {
133
+ // 一档都没入图的目录:报 `no indexed files`,不再给 `←0`(那种目录上量不出入边,写 0 会被读成量过)。
134
+ // 但「空目录」与「全被排除」必须两种话:`docs/batches/` 有 40 个过程档,只说 `no indexed files`
135
+ // 会把它读成空目录;`tree` 早在同一处写「另有 N 个过程档被排除」,两个工具不能一个说真一个说假。
136
+ if (dir.files.size === 0) {
137
+ if (!dir.excluded) return " · no indexed files"
138
+ return ` · no indexed files · ${dir.excluded} process doc${dir.excluded === 1 ? "" : "s"} excluded`
139
+ }
140
+ const parts = []
141
+ const summary = kindSummary(dir.files, byPath)
142
+ const own = ownLevelCount(dir)
143
+ parts.push(own > 0 ? `${summary} (${own} at this level)` : summary)
144
+ if (dir.excluded) parts.push(`${dir.excluded} process doc${dir.excluded === 1 ? "" : "s"} excluded`)
145
+ parts.push(`←${signals.crossInbound.get(dir.relDir) ?? 0}`)
146
+ const internal = imports.filter((e) => dir.files.has(e.src) && dir.files.has(e.dst)).length
147
+ if (internal > 0) parts.push(`⟳${internal}`)
148
+ const hubs = topInbound(dir.files, signals.inboundOfFile, 2)
149
+ if (hubs.length > 0) parts.push(`hubs: ${hubLabels(hubs, dir.relDir)}`)
150
+ return ` · ${parts.join(" · ")}`
151
+ }
152
+
153
+ /**
154
+ * hub 标签:默认只给基名;**同一个目录里出现同名档时**改用相对该目录的路径。
155
+ * 2026-12-01 复测:`manifest/` 下 `manifest_outbound_batch.sql` 在两处子目录各一份、入度又相等,
156
+ * 只给基名就变成 `hubs: x.sql(5), x.sql(5)`——同一行两个一模一样的条目,只能被读成重复计数。
157
+ * 反过来默认全给相对路径会把最常见的单 hub 行(`case_main.sql(492)`)白白拉长。
158
+ */
159
+ function hubLabels(hubs, relDir) {
160
+ const seen = new Map()
161
+ for (const h of hubs) {
162
+ const name = basename(h.file)
163
+ seen.set(name, (seen.get(name) ?? 0) + 1)
164
+ }
165
+ return hubs.map((h) => {
166
+ const name = basename(h.file)
167
+ if ((seen.get(name) ?? 0) < 2) return `${name}(${h.count})`
168
+ return `${relDir === "" ? h.file : h.file.slice(relDir.length + 1)}(${h.count})`
169
+ }).join(", ")
170
+ }
171
+
172
+ function collectOwnerConnections(imports, ownerOf) {
173
+ const grouped = new Map()
174
+ for (const edge of imports) {
175
+ const srcOwner = ownerOf.get(edge.src)
176
+ const dstOwner = ownerOf.get(edge.dst)
177
+ if (!srcOwner || !dstOwner || srcOwner.key === dstOwner.key) continue
178
+ const key = `${srcOwner.key}\u0000${dstOwner.key}`
179
+ if (!grouped.has(key)) {
180
+ grouped.set(key, { src: srcOwner, dst: dstOwner, count: 0, symbols: new Set() })
181
+ }
182
+ const item = grouped.get(key)
183
+ item.count += 1
184
+ for (const sym of edge.symbols) item.symbols.add(sym)
185
+ }
186
+ return [...grouped.values()].sort((a, b) =>
187
+ b.count - a.count ||
188
+ Number(a.src.kind !== "dir" && a.dst.kind !== "dir") - Number(b.src.kind !== "dir" && b.dst.kind !== "dir") ||
189
+ a.src.key.localeCompare(b.src.key) || a.dst.key.localeCompare(b.dst.key))
190
+ }
191
+
192
+ function collectExternalOrchestrators(imports, scopeSeeds, ownerOf, byPath) {
193
+ const callers = new Map()
194
+ for (const edge of imports) {
195
+ if (!scopeSeeds.has(edge.dst) || scopeSeeds.has(edge.src) || byPath.get(edge.src)?.kind !== "code") continue
196
+ if (!callers.has(edge.src)) callers.set(edge.src, { path: edge.src, files: new Set(), owners: new Set() })
197
+ const item = callers.get(edge.src)
198
+ item.files.add(edge.dst)
199
+ const owner = ownerOf.get(edge.dst)
200
+ if (owner) item.owners.add(owner.short)
201
+ }
202
+ const ranked = [...callers.values()].sort((a, b) =>
203
+ b.files.size - a.files.size || b.owners.size - a.owners.size || a.path.localeCompare(b.path))
204
+ return { items: ranked.slice(0, 4), omitted: Math.max(0, ranked.length - 4) }
205
+ }
206
+
207
+ /** Same-directory neighbours show as bare names; only cross-directory paths keep their relative form. */
208
+ function neighbourLabel(target, self) {
209
+ if (dirname(target) === dirname(self)) return basename(target)
210
+ return target
211
+ }
212
+
213
+ /** `a, b +N` — compact joined list with an exact overflow count. */
214
+ const joinLimited = (items, max) => {
215
+ const shown = items.slice(0, max).join(", ")
216
+ return items.length > max ? `${shown} +${items.length - max}` : shown
217
+ }
218
+
219
+ /** Row note: one compact line fragment ` · → deps · ← orchestrators · direct tests: tests`, capped at ROW_NOTE_MAX. */
220
+ function rowNoteFor(path, { imports, byPath, testsOf, isDir = false }) {
221
+ if (isDir) return ""
222
+ const label = (p) => neighbourLabel(p, path)
223
+ const outs = imports.filter((e) => e.src === path).map((e) => label(e.dst))
224
+ const ins = imports.filter((e) => e.dst === path && byPath.get(e.src)?.kind === "code").map((e) => label(e.src))
225
+ const tests = (testsOf.get(path) ?? []).map(label)
226
+ // Build with shrinking per-list caps until the whole note fits; never leave a bare ellipsis.
227
+ let note = ""
228
+ for (const cap of [3, 2, 1]) {
229
+ const parts = []
230
+ if (outs.length > 0) parts.push(`→ ${joinLimited(outs, cap)}`)
231
+ if (ins.length > 0) parts.push(`← ${joinLimited(ins, cap)}`)
232
+ if (tests.length > 0) parts.push(`direct tests: ${joinLimited(tests, Math.min(cap, 2))}`)
233
+ if (parts.length === 0) return ""
234
+ note = ` · ${parts.join(" · ")}`
235
+ if (note.length <= ROW_NOTE_MAX) break
236
+ }
237
+ return note.length <= ROW_NOTE_MAX ? note : ` · ${joinLimited([...outs, ...ins], 1)}`
238
+ }
239
+
240
+ /** Inverse of the test list used by `directTests`: seed path → test paths importing it. */
241
+ function testsBySeed(imports, byPath, isProc) {
242
+ const map = new Map()
243
+ for (const edge of imports) {
244
+ if (byPath.get(edge.src)?.kind !== "test" || isProc(edge.src)) continue
245
+ if (!map.has(edge.dst)) map.set(edge.dst, [])
246
+ map.get(edge.dst).push(edge.src)
247
+ }
248
+ return map
249
+ }
250
+
251
+ function renderRelations({ fileSeeds, indexedDirs, scopeSeeds, imports, docs, tests, sections, covered, byPath, signals }) {
252
+ const ownerOf = new Map()
253
+ for (const file of fileSeeds) {
254
+ ownerOf.set(file, { key: file, label: file, short: basename(file), kind: "file" })
255
+ }
256
+ for (const dir of indexedDirs) {
257
+ const owner = { key: `${dir.relDir}/`, label: `${dir.relDir}/`, short: `${dir.name}/`, kind: "dir" }
258
+ for (const file of dir.files) ownerOf.set(file, owner)
259
+ }
260
+ const lines = []
261
+ const sortedDirs = [...indexedDirs].sort((a, b) => b.files.size - a.files.size || a.relDir.localeCompare(b.relDir))
262
+ if (sortedDirs.length > 0) {
263
+ lines.push("Subdirectories:")
264
+ for (const dir of sortedDirs.slice(0, 12)) {
265
+ lines.push(` - ${dir.relDir}/${dirNote(dir, { byPath, imports, signals })}`)
266
+ }
267
+ if (sortedDirs.length > 12) lines.push(` … ${sortedDirs.length - 12} subdirectories omitted`)
268
+ }
269
+
270
+ const connections = collectOwnerConnections(imports, ownerOf)
271
+ if (connections.length > 0) {
272
+ lines.push("Connections:")
273
+ const shown = connections.slice(0, 24)
274
+ const bySrc = new Map()
275
+ for (const conn of shown) {
276
+ if (!bySrc.has(conn.src.label)) bySrc.set(conn.src.label, [])
277
+ bySrc.get(conn.src.label).push(conn)
278
+ }
279
+ for (const [srcLabel, edges] of bySrc) {
280
+ lines.push(` ${srcLabel}`)
281
+ for (const conn of edges) {
282
+ const syms = [...conn.symbols].sort()
283
+ const detail = conn.count === 1
284
+ ? edgeText(syms)
285
+ : `${conn.count} edges${syms.length > 0 ? ` · ${syms.slice(0, 5).join(", ")}` : ""}`
286
+ lines.push(` → ${conn.dst.label} · ${detail}`)
287
+ }
288
+ }
289
+ if (connections.length > 24) lines.push(` … ${connections.length - 24} connections omitted`)
290
+ }
291
+
292
+ const external = collectExternalOrchestrators(imports, scopeSeeds, ownerOf, byPath)
293
+ if (external.items.length > 0) {
294
+ lines.push("External orchestrators:")
295
+ for (const item of external.items) {
296
+ const targetList = [...item.owners].sort().slice(0, 4).join(", ")
297
+ lines.push(` - ${item.path} · imports ${item.files.size} file${item.files.size === 1 ? "" : "s"} in ${targetList}`)
298
+ }
299
+ if (external.omitted > 0) lines.push(` … ${external.omitted} orchestrator${external.omitted === 1 ? "" : "s"} omitted`)
300
+ }
301
+
302
+ const hasDirSection = sortedDirs.length > 0
303
+ if (!hasDirSection && connections.length === 0 && external.items.length === 0 && covered.length === 0 && docs.length === 0 && tests.length === 0) {
304
+ return ""
305
+ }
306
+ const knowledge = []
307
+ addKnowledgeLines(knowledge, { docs, tests, sections, byPath }, scopeSeeds.size > 100)
308
+ let docCount = 0
309
+ for (const p of scopeSeeds) if (byPath.get(p)?.kind === "doc") docCount += 1
310
+ if (docCount * 2 >= scopeSeeds.size) addCoveredLines(knowledge, covered)
311
+ if (lines.length === 0 && knowledge.length === 0) return ""
312
+ lines.push(...knowledge)
313
+ return ["Relations:", ...lines.map((l) => ` ${l}`)].join("\n")
314
+ }
315
+
316
+ function buildSingleRootLsGraph(root, hitFiles, hitDirs, sync, byDirectory = false) {
317
+ const { db, fileCount, skippedCold } = sync(root, { maxColdFiles: 2500 })
318
+ if (skippedCold || !db) {
319
+ return { notes: new Map(), relations: `Relations: cold graph skipped — ${fileCount} files exceed 2500. Run repo_graph(action="overview", target=${JSON.stringify(root)}) to build it explicitly.` }
320
+ }
321
+ try {
322
+ const files = db.prepare("SELECT path, kind FROM files").all()
323
+ const byPath = new Map(files.map((file) => [file.path, file]))
324
+ const dbKeys = new Map(files.map((file) => [pathKey(file.path), file.path]))
325
+ const isProc = processDocPredicate(root)
326
+ const relOfHit = new Map()
327
+ const fileSeeds = new Set()
328
+ for (const abs of hitFiles) {
329
+ const rel = slash(relative(root, abs))
330
+ const matched = dbKeys.get(pathKey(rel))
331
+ if (matched && !isProc(matched)) {
332
+ fileSeeds.add(matched)
333
+ relOfHit.set(pathKey(abs), matched)
334
+ }
335
+ }
336
+ const indexedDirs = []
337
+ // 过程档排除数只在摘要模式算:它要回磁盘递归一遍,而普通 `ls` 的 Relations 只列前 12 个目录,
338
+ // 为一行附加信息把整棵树走一遍不划算(摘要模式反正已经走了一次图)。
339
+ const procCounts = new Map()
340
+ if (byDirectory) {
341
+ for (const abs of hitDirs) {
342
+ const relDir = slash(relative(root, abs)).replace(/\/+$/, "")
343
+ if (!relDir || relDir === "." || relDir.startsWith("../")) continue
344
+ for (const [key, n] of processDocCounts(relDir, abs)) procCounts.set(key, n)
345
+ }
346
+ }
347
+ for (const abs of hitDirs) {
348
+ const relDir = slash(relative(root, abs)).replace(/\/+$/, "")
349
+ if (!relDir || relDir === "." || relDir.startsWith("../") || relDir === "..") continue
350
+ const prefix = `${relDir}/`
351
+ const memberFiles = new Set()
352
+ for (const file of files) {
353
+ if (file.path.startsWith(prefix) && !isProc(file.path)) memberFiles.add(file.path)
354
+ }
355
+ // 摘要模式每个目录行都要有数,包括「一档都没入图」的目录——那里报 `no indexed files` 是真话,
356
+ // 空行则会被读成「没算过」,而 `0 indexed` 会被读成「索引还没跑完」。`excluded` 让「空」
357
+ // 与「全被过程档默认排除」分成两句话(与 `tree` 的「另有 N 个过程档被排除」同一个事实)。
358
+ if (memberFiles.size > 0 || byDirectory) indexedDirs.push({ name: basename(abs), relDir, files: memberFiles, excluded: procCounts.get(relDir) ?? 0 })
359
+ }
360
+ if (fileSeeds.size === 0 && indexedDirs.length === 0) {
361
+ return { notes: new Map(), relations: `Relations: none of the listed entries are indexed in ${root}.` }
362
+ }
363
+ const imports = importEdges(db)
364
+ // 目录级图信号与 `tree` 同源(`dir-signals`):跨目录入边 / hub 入度都只算一次,不另建口径。
365
+ const signals = buildDirSignals(db)
366
+ const sections = sectionIndex(db)
367
+ const testsOf = testsBySeed(imports, byPath, isProc)
368
+ const notes = new Map()
369
+ for (const [hitKey, seedPath] of relOfHit) {
370
+ const note = rowNoteFor(seedPath, { imports, byPath, testsOf })
371
+ if (note) notes.set(hitKey, note)
372
+ }
373
+ for (const dir of indexedDirs) {
374
+ notes.set(pathKey(resolve(root, dir.relDir)), dirNote(dir, { byPath, imports, signals }))
375
+ }
376
+ // 目录摘要只保留目录行自己的递归规模与图信号;文件级连接/编排者/文档/测试归 context。
377
+ if (byDirectory) return { notes, relations: "" }
378
+ if (indexedDirs.length === 0) {
379
+ const docOnly = [...fileSeeds].every((p) => byPath.get(p)?.kind === "doc")
380
+ if (docOnly) {
381
+ const covered = docCoveredTargets(db, fileSeeds, byPath, isProc)
382
+ const lines = []
383
+ if (covered.length > 0) addCoveredLines(lines, covered)
384
+ if (lines.length === 0) return { notes, relations: "" }
385
+ return { notes, relations: ["Relations:", ...lines.map((l) => ` ${l}`)].join("\n") }
386
+ }
387
+ const internal = imports.filter((edge) => fileSeeds.has(edge.src) && fileSeeds.has(edge.dst))
388
+ const connectorSelection = selectConnectors(fileSeeds, internal, imports, byPath)
389
+ const connectors = connectorSelection.items
390
+ const connectorPaths = new Set(connectors.map(([path]) => path))
391
+ const docs = directDocuments(db, fileSeeds, byPath, isProc).filter((doc) => !fileSeeds.has(doc.path))
392
+ const tests = directTests(imports, fileSeeds, byPath, isProc).filter((test) => !fileSeeds.has(test.path))
393
+ const extra = []
394
+ addKnowledgeLines(extra, { docs, tests, sections, byPath })
395
+ if (extra.length === 0) return { notes, relations: "" }
396
+ return { notes, relations: ["Relations:", ...extra.map((l) => ` ${l}`)].join("\n") }
397
+ }
398
+ const scopeSeeds = new Set(fileSeeds)
399
+ for (const dir of indexedDirs) for (const file of dir.files) scopeSeeds.add(file)
400
+ const docs = directDocuments(db, scopeSeeds, byPath, isProc).filter((doc) => !scopeSeeds.has(doc.path))
401
+ const tests = directTests(imports, scopeSeeds, byPath, isProc).filter((test) => !scopeSeeds.has(test.path))
402
+ const covered = docCoveredTargets(db, scopeSeeds, byPath, isProc)
403
+ return { notes, relations: renderRelations({ fileSeeds, indexedDirs, scopeSeeds, imports, docs, tests, sections, covered, byPath, signals }) }
404
+ } finally {
405
+ try { db.close() } catch { /* graph cleanup cannot affect entries */ }
406
+ }
407
+ }
408
+
409
+ function buildWorkspaceProjectSummary(sub, sync) {
410
+ const { db, fileCount, skippedCold } = sync(sub.root, { maxColdFiles: 2500 })
411
+ if (skippedCold || !db) {
412
+ return `Project: ${sub.name}/ — cold graph skipped: ${fileCount} files exceed 2500. Run repo_graph(action="overview", target=${JSON.stringify(sub.root)}) to build it explicitly.`
413
+ }
414
+ try {
415
+ const isProc = processDocPredicate(sub.root)
416
+ const files = db.prepare("SELECT path, kind FROM files").all().filter((f) => !isProc(f.path))
417
+ const byPath = new Map(files.map((f) => [f.path, f]))
418
+ const dirs = new Map()
419
+ for (const file of files) {
420
+ const top = file.path.includes("/") ? `${file.path.split("/")[0]}/` : "(root)"
421
+ dirs.set(top, (dirs.get(top) ?? 0) + 1)
422
+ }
423
+ const rankedDirs = [...dirs.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
424
+ const lines = [`Project: ${sub.name}/ · ${kindSummary(new Set(files.map((f) => f.path)), byPath)} (${files.length} indexed)`]
425
+ for (const [dir, count] of rankedDirs.slice(0, 4)) lines.push(` - ${dir} · ${count} indexed`)
426
+ if (rankedDirs.length > 4) lines.push(` … ${rankedDirs.length - 4} top directories omitted`)
427
+ return lines.join("\n")
428
+ } finally {
429
+ try { db.close() } catch { /* graph cleanup cannot affect entries */ }
430
+ }
431
+ }
432
+
433
+ function buildWorkspaceGraph(hitDirs, candidates, sync) {
434
+ const dirKeys = new Set(hitDirs.map((dir) => pathKey(dir)))
435
+ const matched = candidates.filter((sub) => dirKeys.has(pathKey(sub.root)))
436
+ if (matched.length === 0) return { notes: new Map(), relations: "" }
437
+ const notes = new Map()
438
+ const lines = [`Relations: workspace · ${matched.length} project${matched.length === 1 ? "" : "s"}`]
439
+ for (const sub of matched.slice(0, 12)) {
440
+ try {
441
+ const summary = buildWorkspaceProjectSummary(sub, sync)
442
+ lines.push(` ${summary.split("\n").join("\n ")}`)
443
+ const head = summary.split("\n")[0]
444
+ const kinds = /· (.*?) \(\d+ indexed\)/.exec(head)?.[1]
445
+ if (kinds) notes.set(pathKey(sub.root), ` · ${kinds}`)
446
+ } catch (error) {
447
+ lines.push(` Project: ${sub.name}/ — ${error?.message || String(error)}; entry list unchanged.`)
448
+ }
449
+ }
450
+ if (matched.length > 12) lines.push(` … ${matched.length - 12} projects omitted`)
451
+ return { notes, relations: lines.join("\n") }
452
+ }
453
+
454
+ /** Whole-line cap; the entry list is outside this string. Exported for the batch test only. */
455
+ export function capRelationsForTest(text, maxChars = LS_WORK_GRAPH_BUDGET) {
456
+ return capRelations(text, maxChars)
457
+ }
458
+
459
+ function capRelations(text, maxChars = LS_WORK_GRAPH_BUDGET) {
460
+ const source = String(text)
461
+ if (source.length <= maxChars) return source
462
+ const lines = source.split("\n")
463
+ const kept = []
464
+ let used = 0
465
+ for (const line of lines) {
466
+ if (used + line.length + 1 > maxChars - 140) break
467
+ kept.push(line)
468
+ used += line.length + 1
469
+ }
470
+ let note = ""
471
+ while (true) {
472
+ const omitted = lines.length - kept.length
473
+ note = ` … ${omitted} relation lines omitted by the ${maxChars}-character budget; entry list unchanged.`
474
+ if (used + note.length <= maxChars || kept.length === 0) break
475
+ used -= kept.pop().length + 1
476
+ }
477
+ return [...kept, note].join("\n")
478
+ }
479
+
480
+ export function buildLsWorkGraph({ args = {}, ctx = {}, targetDir, hitFiles = [], hitDirs = [] }, sync = syncGraph) {
481
+ const cwd = resolve(String(ctx.cwd ?? ctx.agent?.cwd ?? "."))
482
+ const absTarget = targetDir ? resolve(targetDir) : resolve(cwd, String(args.path ?? "."))
483
+ const resolved = resolveQueryRoot(absTarget)
484
+ let built
485
+ if (!resolved.ok && resolved.reason === "workspace") {
486
+ built = buildWorkspaceGraph(hitDirs, resolved.candidates ?? [], sync)
487
+ } else if (resolved.ok) {
488
+ const absFiles = hitFiles.map((p) => (isAbsolute(p) ? resolve(p) : resolve(cwd, p)))
489
+ const absDirs = hitDirs.map((p) => (isAbsolute(p) ? resolve(p) : resolve(cwd, p)))
490
+ built = buildSingleRootLsGraph(resolved.root, absFiles, absDirs, sync, args.byDirectory === true)
491
+ } else {
492
+ built = { notes: new Map(), relations: "Relations: no project root resolved for the listed entries." }
493
+ }
494
+ return { notes: built.notes, relations: built.relations ? capRelations(built.relations) : "" }
495
+ }
496
+
497
+ /** Fuse: append each entry's own note to its row, then the Relations block — one section, entries untouched otherwise. */
498
+ export async function appendLsWorkGraph({ args = {}, ctx = {}, rawResult = "", targetDir, hitFiles = [], hitDirs = [], rowPaths = [] }, sync = syncGraph) {
499
+ const raw = String(rawResult)
500
+ if (hitFiles.length === 0 && hitDirs.length === 0) return raw
501
+ try {
502
+ const { notes, relations } = buildLsWorkGraph({ args, ctx, targetDir, hitFiles, hitDirs }, sync)
503
+ return fuseLsOutput(raw, targetDir, notes, relations, rowPaths)
504
+ } catch (error) {
505
+ return `${raw}\nRelations: ${error?.message || String(error)}; entry list unchanged.`
506
+ }
507
+ }
508
+
509
+ /**
510
+ * Fuse the complete entry list with its graph relations into ONE section.
511
+ * `rawResult` = entry rows (+ process-doc report + limit notice); rows keep every original column and only
512
+ * gain a trailing ` · …` note. Non-row lines (report / limit notice) pass through untouched.
513
+ */
514
+ export function fuseLsOutput(rawResult, targetDir, notes, relations, rowPaths = []) {
515
+ const base = resolve(targetDir)
516
+ const noteOf = (abs) => notes.get(pathKey(abs)) ?? ""
517
+ // Row shape: `d|- <name padded to ≥40> <size right-aligned 10> <mtime>` — the name column may overflow
518
+ // 40 for long names, so anchor on the fixed ` <10-wide size> <16-char mtime>` tail instead.
519
+ // 前导缩进属于 `recursive` 展开的子层;它不进名字,路径改由 `rowPaths` 按输出顺序给。
520
+ const ROW_TAIL = /^(\s*)([d-]) (.*?)( \[[^\]]+\])?(\s{2,}(?:\d{1,10}|-)\s{2,}\d{4}-\d{2}-\d{2} \d{2}:\d{2})$/
521
+ let cursor = 0
522
+ const rows = String(rawResult).split("\n").map((line) => {
523
+ const m = ROW_TAIL.exec(line)
524
+ if (!m) return line
525
+ const isDir = m[2] === "d"
526
+ const name = m[3].trimEnd()
527
+ // 递归行不能靠名字还原路径(不同层会出现同名目录),按输出顺序取调用方交来的路径。
528
+ const abs = rowPaths.length > cursor ? rowPaths[cursor] : resolve(base, isDir ? name.replace(/\/$/, "") : name)
529
+ cursor += 1
530
+ const note = noteOf(abs)
531
+ return note ? `${line}${note}` : line
532
+ })
533
+ return relations ? [...rows, relations].join("\n") : rows.join("\n")
534
+ }