@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,377 @@
1
+ /**
2
+ * doc-graph/outline.mjs — 批量文档章节大纲 / 按标题抽节 / 文件顶层结构大纲(收编自原 `peek` 精华)。
3
+ *
4
+ * 定位:
5
+ * - Markdown 文档:毫秒级批量输出 H1–H4 目录树 + 表格头 + 导语,或带 `query` 时按节标题抽取原文(不烧整档 read token);
6
+ * - 源码文件:输出文件头注 + 顶层声明/导出签名清单(附总行数,明确不切函数体碎片——看实现请用 `read` 整档读入)。
7
+ *
8
+ * 零 `node:sqlite`、零第三方依赖,可被 `repo_graph(action="outline")` 直接调用。
9
+ */
10
+ import { readFile, readdir, stat } from "node:fs/promises"
11
+ import { extname, isAbsolute, join, relative, resolve, sep } from "node:path"
12
+ import {
13
+ truncate,
14
+ firstAbsoluteGlobPattern,
15
+ absoluteGlobRejection,
16
+ looksLikeGlob,
17
+ splitGlobPatterns,
18
+ compileGlobMatchers,
19
+ normalizeEOL,
20
+ } from "../tools/shared.mjs"
21
+ import { SKIP_DIRS } from "../skip-dirs.mjs"
22
+ import { isProcessDocPath, docLayerName, processDocsReport } from "../tools/process-doc-mark.mjs"
23
+
24
+ const MAX_FILE_BYTES = 2_000_000
25
+ const DEFAULT_PER_FILE_CHARS = 4500
26
+
27
+ const MARKDOWN_EXTS = new Set([".md", ".mdx", ".markdown"])
28
+ const CODE_EXTS = new Set([
29
+ ".mjs", ".cjs", ".js", ".jsx", ".ts", ".tsx", ".mts", ".cts",
30
+ ".py", ".pyi", ".cs", ".java", ".kt", ".go", ".rs", ".c", ".h", ".cpp", ".hpp",
31
+ ".rb", ".php", ".sh", ".ps1",
32
+ ])
33
+
34
+ async function* walkFiles(dir, rel = "") {
35
+ let entries
36
+ try {
37
+ entries = await readdir(dir, { withFileTypes: true })
38
+ } catch {
39
+ return
40
+ }
41
+ for (const e of entries) {
42
+ if (e.isSymbolicLink()) continue
43
+ if (e.isDirectory() && SKIP_DIRS.has(e.name)) continue
44
+ const relPath = rel ? `${rel}/${e.name}` : e.name
45
+ if (e.isDirectory()) yield* walkFiles(join(dir, e.name), relPath)
46
+ else yield relPath
47
+ }
48
+ }
49
+
50
+ function parseMarkdownSections(lines) {
51
+ const sections = []
52
+ let fence = null
53
+ for (let i = 0; i < lines.length; i++) {
54
+ const line = lines[i]
55
+ const fm = line.match(/^\s*(`{3,}|~{3,})/)
56
+ if (fm) {
57
+ if (!fence) fence = fm[1][0]
58
+ else if (line.trimStart().startsWith(fence.repeat(3))) fence = null
59
+ continue
60
+ }
61
+ if (fence) continue
62
+ const hm = line.match(/^(#{1,4})\s+(.+?)\s*#*\s*$/)
63
+ if (!hm) continue
64
+ sections.push({ level: hm[1].length, title: hm[2].trim(), startIdx: i, endIdx: lines.length })
65
+ }
66
+ for (let i = 0; i < sections.length; i++) {
67
+ sections[i].nextHeadingIdx = i + 1 < sections.length ? sections[i + 1].startIdx : lines.length
68
+ let end = lines.length
69
+ for (let j = i + 1; j < sections.length; j++) {
70
+ if (sections[j].level <= sections[i].level) {
71
+ end = sections[j].startIdx
72
+ break
73
+ }
74
+ }
75
+ sections[i].endIdx = end
76
+ }
77
+ return sections
78
+ }
79
+
80
+ /** 提取 Markdown 紧凑大纲(支持 `maxLevel` 1–4 与批量紧凑模式 `compact`)。 */
81
+ export function outlineMarkdown(content, { maxHeadings = 45, maxLevel = 4, compact = false } = {}) {
82
+ const lines = normalizeEOL(content).split("\n")
83
+ const allSections = parseMarkdownSections(lines)
84
+ const sections = allSections.filter((s) => s.level <= maxLevel)
85
+ const out = []
86
+
87
+ if (!compact) {
88
+ const metaLimit = allSections.length > 0 ? Math.min(allSections[0].startIdx, 8) : Math.min(lines.length, 8)
89
+ for (let i = 0; i < metaLimit; i++) {
90
+ const t = lines[i].trim()
91
+ if (t && (t.startsWith(">") || /^(status|状态|版本|aliases|owner|权威)/i.test(t))) {
92
+ out.push(` ${t.slice(0, 140)}`)
93
+ }
94
+ }
95
+ }
96
+
97
+ if (sections.length === 0) {
98
+ const preview = lines.map((l) => l.trim()).filter(Boolean).slice(0, compact ? 2 : 4).join(" / ").slice(0, compact ? 100 : 220)
99
+ out.push(` (${lines.length} lines, no headings)${preview ? ` — ${preview}` : ""}`)
100
+ return out.join("\n")
101
+ }
102
+
103
+ const shown = sections.slice(0, maxHeadings)
104
+ for (const s of shown) {
105
+ const spanLines = s.endIdx - s.startIdx
106
+ const indent = " ".repeat(s.level - 1)
107
+ if (compact) {
108
+ out.push(`${indent}${"#".repeat(s.level)} ${s.title} (${spanLines}L)`)
109
+ continue
110
+ }
111
+ const bodyStart = s.startIdx + 1
112
+ const bodyEnd = s.nextHeadingIdx
113
+ let lead = ""
114
+ let tableHeader = ""
115
+ let inCode = false
116
+ for (let i = bodyStart; i < bodyEnd; i++) {
117
+ const t = lines[i].trim()
118
+ if (!t) continue
119
+ if (t.startsWith("```") || t.startsWith("~~~")) { inCode = !inCode; continue }
120
+ if (inCode) continue
121
+ if (!tableHeader && t.startsWith("|") && t.endsWith("|") && !/^\|[\s:-]+\|$/.test(t)) {
122
+ tableHeader = t.replace(/^\||\|$/g, "").split("|").map((c) => c.trim()).filter(Boolean).slice(0, 6).join(" | ")
123
+ continue
124
+ }
125
+ if (!lead && !t.startsWith("|") && !t.startsWith("---")) {
126
+ lead = t.replace(/^[-*>\s]+/, "").slice(0, 100)
127
+ }
128
+ if (lead && tableHeader) break
129
+ }
130
+ const meta = [`${spanLines}L`]
131
+ if (tableHeader) meta.push(`table: ${tableHeader}`)
132
+ const suffix = lead ? ` — ${lead}` : ""
133
+ out.push(`${indent}${"#".repeat(s.level)} ${s.title} (${meta.join("; ")})${suffix}`)
134
+ }
135
+ if (sections.length > maxHeadings) {
136
+ out.push(` ... (+${sections.length - maxHeadings} more headings)`)
137
+ }
138
+ return out.join("\n")
139
+ }
140
+
141
+ /** 按标题关键词从 Markdown 中精准抽取匹配章节原文(不重抽子节)。 */
142
+ export function extractMarkdownSections(content, query, { maxChars = DEFAULT_PER_FILE_CHARS } = {}) {
143
+ const terms = String(query ?? "").split(/[,|]/).map((s) => s.trim().toLowerCase()).filter(Boolean)
144
+ if (terms.length === 0) return null
145
+ const lines = normalizeEOL(content).split("\n")
146
+ const sections = parseMarkdownSections(lines)
147
+ const matched = []
148
+ let coveredEnd = -1
149
+ for (const s of sections) {
150
+ const titleLc = s.title.toLowerCase()
151
+ if (!terms.some((t) => titleLc.includes(t))) continue
152
+ if (s.startIdx < coveredEnd) continue
153
+ coveredEnd = s.endIdx
154
+ const block = lines.slice(s.startIdx, s.endIdx).join("\n").trimEnd()
155
+ matched.push(block)
156
+ }
157
+ if (matched.length === 0) return null
158
+ const joined = matched.join("\n\n")
159
+ return joined.length > maxChars ? `${joined.slice(0, maxChars)}\n... (truncated, ${joined.length} chars total)` : joined
160
+ }
161
+
162
+ const CODE_SYMBOL_PATTERNS = [
163
+ { re: /^(export\s+(?:default\s+)?(?:async\s+)?(?:function\*?|class|const|let|var|interface|type|enum)\s+([A-Za-z_$][\w$]*).*)/, nameIdx: 2 },
164
+ { re: /^((?:async\s+)?function\*?\s+([A-Za-z_$][\w$]*)\s*\(.*)/, nameIdx: 2 },
165
+ { re: /^(class\s+([A-Za-z_$][\w$]*).*)/, nameIdx: 2 },
166
+ { re: /^((?:async\s+)?def\s+([A-Za-z_]\w*)\s*\(.*)/, nameIdx: 2 },
167
+ { re: /^(func\s+(?:\([^)]+\)\s*)?([A-Za-z_]\w*)\s*\(.*)/, nameIdx: 2 },
168
+ { re: /^(type\s+([A-Za-z_]\w*)\s+(?:struct|interface)\b.*)/, nameIdx: 2 },
169
+ { re: /^((?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?(?:fn|struct|enum|trait|type)\s+([A-Za-z_]\w*).*)/, nameIdx: 2 },
170
+ { re: /^(\s*(?:public|internal|protected|private)\s+(?:static\s+|abstract\s+|sealed\s+|partial\s+|async\s+|virtual\s+|override\s+)*(?:class|interface|record|struct|enum|delegate\s+[\w.<>,[\]\s?]+|[\w<>[\]?.,\s]+)\s+([A-Za-z_]\w*)\s*(?:\(|[:{<]|$).*)/, nameIdx: 2 },
171
+ ]
172
+
173
+ /** 提取源码文件顶层声明签名大纲(仅大纲不切函数体,引导用 `read` 整档读实现)。 */
174
+ export function outlineCode(content, { maxSymbols = 50 } = {}) {
175
+ const lines = normalizeEOL(content).split("\n")
176
+ const out = []
177
+ for (let i = 0; i < Math.min(lines.length, 12); i++) {
178
+ const t = lines[i].trim()
179
+ if (!t || t === "/**" || t === "/*" || t === "*/") continue
180
+ if (t.startsWith("//") || t.startsWith("*") || t.startsWith("#!")) {
181
+ const cleaned = t.replace(/^(\/\/|\*|#!)\s*/, "").trim()
182
+ if (cleaned && !cleaned.startsWith("/usr/bin/env")) {
183
+ out.push(` // ${cleaned.slice(0, 140)}`)
184
+ break
185
+ }
186
+ } else {
187
+ break
188
+ }
189
+ }
190
+ const found = []
191
+ for (let i = 0; i < lines.length; i++) {
192
+ const line = lines[i]
193
+ if (!line.trim() || /^\s*(\/\/|\/\*|\*|#)/.test(line)) continue
194
+ for (const { re, nameIdx } of CODE_SYMBOL_PATTERNS) {
195
+ const m = line.match(re)
196
+ if (m) {
197
+ found.push({ name: m[nameIdx], lineIdx: i, signature: m[1].trim().replace(/\s*\{\s*$/, "").slice(0, 120) })
198
+ break
199
+ }
200
+ }
201
+ }
202
+ if (found.length === 0) {
203
+ out.push(` (${lines.length} lines, no top-level symbols matched)`)
204
+ return out.join("\n")
205
+ }
206
+ for (const s of found.slice(0, maxSymbols)) {
207
+ out.push(` L${s.lineIdx + 1}: ${s.signature}`)
208
+ }
209
+ if (found.length > maxSymbols) {
210
+ out.push(` ... (+${found.length - maxSymbols} more symbols)`)
211
+ }
212
+ return out.join("\n")
213
+ }
214
+
215
+ function resolvePathInRoot(root, p) {
216
+ const s = String(p ?? "").trim()
217
+ if (!s) return resolve(root)
218
+ return isAbsolute(s) ? resolve(s) : resolve(root, s)
219
+ }
220
+
221
+ /**
222
+ * 动作 `outline`:批量文档章节树 / 按标题抽节 / 源码顶层签名大纲。
223
+ * - 传 `paths`(数组)或 `glob`(模式)时批量扫描;若未传 `paths`/`glob` 但传了 `query` 且其为盘上路径/目录,则自动把 `query` 作为目标路径;
224
+ * - 当同时传了 `paths`/`glob` 且传了 `query` 时,对 Markdown 按章节标题精准抽取原文(类似原 `peek(mode="sections")`)。
225
+ */
226
+ export async function queryOutline(root, { paths, glob, query = "", depth, includeProcessDocs = false } = {}) {
227
+ const absRoot = resolve(String(root ?? "."))
228
+ // 归属判据 = 包含关系:本根只报本根**之下**的档。绝对形、`../` 逃逸形与指向根外的目录目标都经此收敛 ——
229
+ // 父工作区扇出时同一个绝对档只有包含它的那个子仓收得进,其余子仓自然空仓过滤;显示形也就永不出现 `../`。
230
+ const rootKey = process.platform === "win32" ? absRoot.toLowerCase() : absRoot
231
+ const rootPrefix = rootKey.endsWith(sep) ? rootKey : `${rootKey}${sep}`
232
+ const underRoot = (abs) => {
233
+ const k = process.platform === "win32" ? String(abs).toLowerCase() : String(abs)
234
+ return k === rootKey || k.startsWith(rootPrefix)
235
+ }
236
+ const procCache = new Map()
237
+ const layerCache = new Map()
238
+ const targets = []
239
+ const seen = new Set()
240
+ let excluded = 0
241
+ let includedProc = 0
242
+
243
+ const isProc = (abs, display) =>
244
+ isProcessDocPath(abs, procCache) || /(^|\/)(docs\/batches\/|batches\/|_archive\/|CHANGELOG\.md$)/i.test(display)
245
+
246
+ const addFile = (abs, display, explicit = false) => {
247
+ if (!underRoot(abs)) return
248
+ const key = process.platform === "win32" ? abs.toLowerCase() : abs
249
+ if (seen.has(key)) return
250
+ seen.add(key)
251
+ const proc = isProc(abs, display)
252
+ if (!explicit && !includeProcessDocs && proc) {
253
+ excluded += 1
254
+ return
255
+ }
256
+ if (proc && includeProcessDocs) includedProc += 1
257
+ targets.push({ abs, display })
258
+ }
259
+
260
+ let effectivePaths = Array.isArray(paths) ? paths.filter((p) => typeof p === "string" && p.trim()) : []
261
+ let sectionQuery = typeof query === "string" ? query.trim() : ""
262
+
263
+ // 便捷路由:未传 paths 与 glob 时,允许直接用 query 传文件/目录路径(或 glob 模式)
264
+ let effectiveGlob = typeof glob === "string" ? glob.trim() : ""
265
+ if (effectivePaths.length === 0 && !effectiveGlob && sectionQuery) {
266
+ if (looksLikeGlob(sectionQuery)) {
267
+ effectiveGlob = sectionQuery
268
+ sectionQuery = ""
269
+ } else {
270
+ const candAbs = resolvePathInRoot(absRoot, sectionQuery)
271
+ const st = await stat(candAbs).catch(() => null)
272
+ if (st) {
273
+ effectivePaths = [sectionQuery]
274
+ sectionQuery = ""
275
+ }
276
+ }
277
+ }
278
+
279
+ if (effectivePaths.length === 0 && !effectiveGlob) {
280
+ throw new Error("repo_graph(outline):请提供 `glob`(如 `docs/core/design/*.md`)、`paths`(文件/目录数组)或指向文件/目录的 `query`")
281
+ }
282
+
283
+ for (const p of effectivePaths) {
284
+ const abs = resolvePathInRoot(absRoot, p)
285
+ const st = await stat(abs).catch(() => null)
286
+ if (!st) continue
287
+ if (st.isDirectory()) {
288
+ for await (const rel of walkFiles(abs)) {
289
+ const childAbs = join(abs, rel)
290
+ addFile(childAbs, relative(absRoot, childAbs).replace(/\\/g, "/"), false)
291
+ }
292
+ } else if (st.isFile()) {
293
+ addFile(abs, relative(absRoot, abs).replace(/\\/g, "/") || p, true)
294
+ }
295
+ }
296
+
297
+ if (effectiveGlob) {
298
+ const parts = splitGlobPatterns(effectiveGlob)
299
+ if (parts.length === 0) throw new Error(`repo_graph(outline):非法 glob:${effectiveGlob}`)
300
+ // glob 匹配的是根内 rel 路径:绝对模式永远匹配不上任何 rel,只会静默零匹配 —— 明确拒绝,不把「用错了」说成「没有」。
301
+ const absPart = firstAbsoluteGlobPattern(effectiveGlob)
302
+ if (absPart) throw absoluteGlobRejection(absPart)
303
+ let match
304
+ try {
305
+ match = compileGlobMatchers(parts).test
306
+ } catch (e) {
307
+ throw new Error(`repo_graph(outline):非法 glob "${effectiveGlob}":${e.message}`)
308
+ }
309
+ for await (const rel of walkFiles(absRoot)) {
310
+ if (!match(rel)) continue
311
+ addFile(join(absRoot, rel), rel, false)
312
+ }
313
+ }
314
+
315
+ if (targets.length === 0) {
316
+ if (excluded > 0) {
317
+ return `[Outline] 未匹配到任何可判文件:匹配 ${excluded} 档,均为过程档并已默认过滤;传 includeProcessDocs=true 可取回。`
318
+ }
319
+ return "[Outline] 未匹配到任何文件。"
320
+ }
321
+
322
+ // 标题层级与紧凑度:显式传 depth (1–4) 时按指定深度;否则按扫描档数自适应防爆上下文
323
+ const explicitDepth = Number.isFinite(Number(depth)) && Number(depth) >= 1
324
+ ? Math.max(1, Math.min(4, Math.floor(Number(depth))))
325
+ : null
326
+ const mdMaxLevel = explicitDepth ?? (targets.length <= 5 ? 4 : 2)
327
+ const mdCompact = explicitDepth !== null ? (explicitDepth <= 2 && targets.length > 12) : targets.length > 15
328
+ const mdMaxHeadings = mdCompact ? 18 : (targets.length > 5 ? 25 : 45)
329
+
330
+ const blocks = []
331
+ let hitCount = 0
332
+ let skippedBinary = 0
333
+ for (const t of targets) {
334
+ const st = await stat(t.abs).catch(() => null)
335
+ if (!st || st.size > MAX_FILE_BYTES) continue
336
+ let buf
337
+ try { buf = await readFile(t.abs) } catch { continue }
338
+ if (buf.subarray(0, 512).includes(0)) { skippedBinary++; continue }
339
+ const content = buf.toString("utf8")
340
+ const ext = extname(t.display).toLowerCase()
341
+ const isMd = MARKDOWN_EXTS.has(ext)
342
+ const lineCount = normalizeEOL(content).split("\n").length
343
+ const layer = docLayerName(t.abs, layerCache)
344
+ const tag = layer && layer !== "unlayered" ? ` [${layer}]` : ""
345
+
346
+ let body = null
347
+ if (sectionQuery) {
348
+ if (isMd) body = extractMarkdownSections(content, sectionQuery)
349
+ else continue
350
+ } else if (isMd) {
351
+ body = outlineMarkdown(content, { maxLevel: mdMaxLevel, compact: mdCompact, maxHeadings: mdMaxHeadings })
352
+ } else if (CODE_EXTS.has(ext)) {
353
+ body = outlineCode(content, { maxSymbols: targets.length > 15 ? 20 : 50 })
354
+ } else {
355
+ const head = normalizeEOL(content).split("\n").slice(0, 6).map((l) => ` ${l.slice(0, 120)}`).join("\n")
356
+ body = ` (${lineCount} lines)\n${head}`
357
+ }
358
+
359
+ if (body) {
360
+ hitCount++
361
+ blocks.push(`=== ${t.display} (${lineCount} 行)${tag} ===\n${body}`)
362
+ }
363
+ }
364
+
365
+ const modeLabel = sectionQuery ? `sections /${sectionQuery}/` : `outline · H1-H${mdMaxLevel}${mdCompact ? " 紧凑" : ""}`
366
+ const metaParts = [`扫描 ${targets.length} 档`]
367
+ if (sectionQuery) metaParts.push(`命中 ${hitCount} 档`)
368
+ if (skippedBinary > 0) metaParts.push(`跳过 ${skippedBinary} 个二进制文件`)
369
+ const procCount = includeProcessDocs ? includedProc : excluded
370
+ if (procCount > 0) metaParts.push(processDocsReport(procCount, includeProcessDocs))
371
+
372
+ const head = `[Outline · ${modeLabel}] ${metaParts.join(" · ")}`
373
+ const foot = blocks.length > 0
374
+ ? "\n\n提示:源码实现理解或修改请直接用 `read` 整档读入目标文件;查模块上下游依赖与所属文档用 `repo_graph(action=\"context\")`。"
375
+ : ""
376
+ return truncate(`${head}\n\n${blocks.join("\n\n") || "(无匹配内容)"}${foot}`)
377
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * repo_graph 输出归属注解:文档分域、同域判断与断链迁移候选。
3
+ * 纯路径/集合计算,不读盘、不碰 sqlite;真实文件集合由查询入口提供。
4
+ */
5
+
6
+ const slash = (p) => String(p ?? "").replace(/\\/g, "/")
7
+ const DOC_LAYER_DIRS = new Set(["requirements", "design", "standards", "manuals"])
8
+
9
+ /** 文档根认到声明层目录(如 docs/core/design);域是其直接子目录,根级文件单列。 */
10
+ export function docLocation(path) {
11
+ const parts = slash(path).split("/").filter((p) => p && p !== ".")
12
+ if (parts.length <= 1) return { root: ".", domain: "根级" }
13
+ const layerIdx = parts.findIndex((p) => DOC_LAYER_DIRS.has(p.toLowerCase()))
14
+ let rootEnd
15
+ if (layerIdx >= 0) rootEnd = layerIdx + 1
16
+ else rootEnd = parts.length - 1
17
+ const root = parts.slice(0, rootEnd).join("/") || "."
18
+ const rest = parts.slice(rootEnd)
19
+ return { root, domain: rest.length > 1 ? rest[0] : "根级" }
20
+ }
21
+
22
+ export function sameDocDomain(a, b) {
23
+ const da = docLocation(a)
24
+ const db = docLocation(b)
25
+ if (da.domain === "根级" || db.domain === "根级") {
26
+ return da.root === db.root && da.domain === db.domain
27
+ }
28
+ return da.domain === db.domain
29
+ }
30
+
31
+ export function buildDocDistribution(docFiles) {
32
+ const roots = new Map()
33
+ for (const file of docFiles) {
34
+ const { root, domain } = docLocation(file.path)
35
+ if (!roots.has(root)) roots.set(root, { root, total: 0, domains: new Map() })
36
+ const item = roots.get(root)
37
+ item.total += 1
38
+ item.domains.set(domain, (item.domains.get(domain) ?? 0) + 1)
39
+ }
40
+ return [...roots.values()]
41
+ .map((item) => ({
42
+ root: item.root,
43
+ total: item.total,
44
+ domains: [...item.domains.entries()]
45
+ .map(([name, count]) => ({ name, count }))
46
+ .sort((a, b) => b.count - a.count || a.name.localeCompare(b.name)),
47
+ }))
48
+ .sort((a, b) => a.root.localeCompare(b.root))
49
+ }
50
+
51
+ export function uniqueMigrationCandidate(missingPath, files) {
52
+ const missing = slash(missingPath)
53
+ const parts = missing.split("/")
54
+ if (!parts.some((p) => DOC_LAYER_DIRS.has(p.toLowerCase()))) return ""
55
+ const name = parts.at(-1)
56
+ const extAt = name.lastIndexOf(".")
57
+ if (!name || extAt <= 0) return ""
58
+ const ext = name.slice(extAt)
59
+ const sourceRoot = docLocation(missing).root
60
+ const candidates = files.filter((file) => {
61
+ if (file.kind !== "doc") return false
62
+ const candidate = slash(file.path)
63
+ const candidateName = candidate.split("/").at(-1)
64
+ return candidate !== missing
65
+ && candidateName === name
66
+ && candidateName.slice(candidateName.lastIndexOf(".")) === ext
67
+ && docLocation(candidate).root === sourceRoot
68
+ })
69
+ return candidates.length === 1 ? slash(candidates[0].path) : ""
70
+ }
71
+
72
+ export function formatDocDistribution(distribution, { compact = false } = {}) {
73
+ if (distribution.length === 0) return compact ? [] : ["文档层分布:", " - (无权威文档)"]
74
+ const domainCap = compact ? 3 : 8
75
+ const rows = distribution.map((root) => {
76
+ const shown = root.domains.slice(0, domainCap)
77
+ const rest = root.domains.length - shown.length
78
+ const domains = shown.map((d) => `${d.name} ${d.count}`).join(" / ")
79
+ const rootLabel = root.root === "." ? "根级文档" : `${root.root}/`
80
+ return ` - ${rootLabel} ${root.total} 档 · ${domains}${rest > 0 ? ` / …(尚有 ${rest} 域)` : ""}`
81
+ })
82
+ return compact
83
+ ? rows.map((row) => row.trimStart())
84
+ : ["文档层分布(全部已入图非过程文档):", ...rows]
85
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * doc-graph/process-docs.mjs — 过程档判据单源(图谱面的唯一取法)。
3
+ *
4
+ * 为什么单独一档:判据原先散在两处 —— `code-parsers.isProcessDocPath`(正则硬编码,`doc-graph.mjs`
5
+ * 九处消费面在用)与 `store.walkRepoFiles` 内联的三行(声明面 + 两族补判)。同一份「哪份档是过程档」
6
+ * 出现两个实现,判不同档时没有任何地方能说清哪个对。本档是**唯一**实现,两处都调它。
7
+ *
8
+ * 判据本体 = 三段并集:
9
+ * 1. 声明面 `isExcludedRelPath(rel, decl, root)`(`index.excludePaths` 前缀 ∪ `docRoot.batches` 段序列);
10
+ * 2. 任意深度的 `batches/` 段(声明面只声明一个根,而旧正则覆盖任意深度);
11
+ * 3. 任意深度 `changelog.md`(子包更新日志同判)。
12
+ *
13
+ * 依赖面:本档静态引 `../declaration.mjs`,它的静态闭包经 `memory/file-walk.mjs` 达
14
+ * `memory/schema.mjs`(`node:sqlite`)。所以**只有已动态 import 的图形面能引本档** ——
15
+ * `store.mjs`(动态)、`doc-graph.mjs`(入口处动态 import 取谓词)。端壳静态闭包不得命中本档。
16
+ */
17
+
18
+ import { isExcludedRelPath, loadProjectDeclaration } from "../declaration.mjs"
19
+
20
+ const BATCH_ANY_SEGMENT = /(?:^|\/)batches\//
21
+ // 任意深度 `changelog.md`(不是只管根):这一族从旧 `code-parsers.isProcessDocPath` 原封不动过来,
22
+ // 子包自己的更新日志同样不是权威依据。原名 `CHANGELOG_AT_ROOT` 与行为不符,名字先改对。
23
+ const CHANGELOG_ANY_DEPTH = /(?:^|\/)changelog\.md$/i
24
+
25
+ /**
26
+ * 判一条**根相对**路径是否属于过程档。
27
+ * @param {string} rel 根相对路径(`/` 分隔)
28
+ * @param {Readonly<object>} decl 该项目根所属声明对象(`loadProjectDeclaration` 回执)
29
+ * @param {string} root 项目根绝对路径(声明面换算与面① 判定的锚)
30
+ * @returns {boolean}
31
+ */
32
+ export function isProcessDocInRepo(rel, decl, root) {
33
+ const s = String(rel ?? "")
34
+ if (!s) return false
35
+ return isExcludedRelPath(s, decl, root) || BATCH_ANY_SEGMENT.test(s) || CHANGELOG_ANY_DEPTH.test(s)
36
+ }
37
+
38
+ /**
39
+ * 目录剪枝谓词:只认 `index.excludePaths` 前缀,**不**用文件级判据。
40
+ *
41
+ * 为什么两把而不能合一把:过目录剪枝会连里面**要入图**的档一起挡掉,而过程档目录里可以有活测试
42
+ * (`docs/batches/x.test.mjs` —— 文件级判据对它留了口子:`isProcessDocInRepo(rel) && !isTestFilePath(rel)`),
43
+ * 所以 `docs/batches` 这类目录不能剪。前綕排除目录则可以整棵剪:里面每个档都会被面① 挡掉。
44
+ * 比较口径与声明面面① 逐字相同(原样、大小写敏感):不去大小写归一,两面就不会对同一份
45
+ * `excludePaths` 给出不同答案。
46
+ * @param {string} root 项目根
47
+ * @returns {(rel: string) => boolean}
48
+ */
49
+ export function excludedDirPredicate(root) {
50
+ const decl = loadProjectDeclaration(root)
51
+ const list = Array.isArray(decl?.index?.excludePaths) ? decl.index.excludePaths : []
52
+ return (rel) => {
53
+ const s = String(rel ?? "").replace(/\\/g, "/")
54
+ if (!s) return false
55
+ return list.some((p) => p && (s === p || s.startsWith(`${p}/`)))
56
+ }
57
+ }
58
+
59
+ /**
60
+ * 按项目根出一次谓词。谓词只认根相对路径;一次查询入口建一个(不设模块级缓存:
61
+ * 并发查询不同 root 时同一模块共享一份缓存会串味,WAL 下并发读是常态)。
62
+ * @param {string} root 项目根绝对路径
63
+ * @returns {(rel: string) => boolean}
64
+ */
65
+ export function processDocPredicate(root) {
66
+ const decl = loadProjectDeclaration(root)
67
+ return (rel) => isProcessDocInRepo(rel, decl, root)
68
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * doc-graph/read-work-graph.mjs — `read` 返回值里的**图谱头**(2026-12-03 批,台账 #135,需求 F8 与验收 11)。
3
+ *
4
+ * 为什么在这一层:`read` 的输出本体是「这份档的内容」(`L<n>\t正文` 是逐字格式),图谱只能在**层标识之后、
5
+ * 正文之前**附一段独立的元信息 —— 与层标识同一条规矩(元信息单起一行、绝不掺进正文行)。本档只产出那一段
6
+ * 文本,正文、层标识、双端截断一个字节都不动。
7
+ *
8
+ * 三条纪律:
9
+ * - **不阻塞读档,但「没有头」的各种情形必须分清** —— 下面这份枚举是**唯一出处**(`tools/file.mjs` 两处
10
+ * 只指过来,不各自报计数:重复必漂,本批已经漂过一次):
11
+ * ① 档不在盘上 ⇒ `""`(`read` 自己的「路径不存在」已经说明,图谱再插一句是重复);
12
+ * ② 扩展名不在图谱准入名单 ⇒ `""`(图外档问也没用);
13
+ * ③ 文档档落 `unlayered`(不在任何文档根声明内)⇒ `""`(Q4 裁定:只认声明内的档);
14
+ * ④ 图**确实**没有未读关联面 ⇒ `""`(真静默,也是唯一该静默的一种);
15
+ * ⑤ **图谱没用成**(无仓根 / 超阈值冷仓 / 查询或取数出错,含增强模块取不到)⇒ **出一条与
16
+ * `glob`/`ls`/`grep` 同规的 `[graph] …` 降级行**(需求 F8「给出可见降级说明」)。
17
+ * ④ 与 ⑤ 混作一谈会让读的人把「没有注记」读成「没有关联」—— 那是这条通道最不该犯的错。
18
+ * - **无开关**:与 `ls`/`tree`/`glob`/`grep` 的注记一致(需求 F8「不提供 on/off 开关」);
19
+ * - **不写已读状态**:只读会话已读集(`agent._graphFullReadFiles`)来过滤,绝不回写;图谱头不等于已读全文
20
+ * (需求 §1),也不写 `_graphReadingPack`。
21
+ *
22
+ * 闭包纪律:本档**只由 `tools/file.mjs` 动态 `import`**(与 `tools/search.mjs` 取 `search-augment.mjs` /
23
+ * `glob-work-graph.mjs` / `ls-work-graph.mjs` 同一条),故它的取数链不进程壳静态闭包。
24
+ */
25
+ import { existsSync } from "node:fs"
26
+
27
+ import { getMissingReadingPack } from "../doc-graph.mjs"
28
+ import { CODE_EXTENSIONS, DOC_EXTENSIONS } from "./code-parsers.mjs"
29
+ import { graphMissingRows } from "./format.mjs"
30
+
31
+ /** 扩展名(含点、小写);取不到点 ⇒ 空串。 */
32
+ function extOf(p) {
33
+ const i = String(p ?? "").lastIndexOf(".")
34
+ return i < 0 ? "" : String(p).slice(i).toLowerCase()
35
+ }
36
+
37
+ /** 图谱没用成时的可见降级说明(需求 F8)。与 `glob`/`ls`/`grep` 的降级行同规:说清原因,并说清读档本身没受影响。 */
38
+ function degradationLine(diag) {
39
+ const tail = "read 正文不受影响。"
40
+ if (diag.reason === "cold-skipped") {
41
+ return `[graph] Cold graph skipped: ${diag.fileCount ?? "?"} files exceed 2500; ${tail}需覆盖时显式建图:repo_graph(action="overview")。\n`
42
+ }
43
+ if (diag.reason === "root-missing") return `[graph] 项目根不存在,本次无图谱注记;${tail}\n`
44
+ return `[graph] ${diag.message || "图谱增强失败"};${tail}\n`
45
+ }
46
+
47
+ /**
48
+ * 产出 `read` 的图谱头(含尾换行;无可报内容时返回 `""`)。
49
+ *
50
+ * @param {{ abs?: string, ctx?: any, selfFullRead?: boolean }} input
51
+ * `abs` = 已解析出的档绝对路径;`ctx` = 工具上下文(取 `cwd` 与会话已读集);
52
+ * `selfFullRead` = 本次是默认整档读(不传 `offset`/`limit`)—— 那种场合把该档自身从清单里排除:
53
+ * 正在整档读它,再把它列成「尚未整档 read」是误导。窗口读**不**豁免:你确实只读了片段。
54
+ * @returns {Promise<string>}
55
+ */
56
+ export async function buildReadGraphHead({ abs, ctx, selfFullRead = false } = {}) {
57
+ try {
58
+ const root = ctx?.cwd
59
+ if (!abs) return ""
60
+ // 档本身不在盘上 ⇒ `read` 自己会报「路径不存在」,无需图谱再插一句。
61
+ if (!existsSync(abs)) return ""
62
+ // 有档却没仓根:这是「图谱没用成」的一种,要可见降级 —— 不是「没有关联面」。
63
+ if (!root) return degradationLine({ reason: "root-missing" })
64
+ // 前置闸:只对图谱准入的档种取数(名单源 = `code-parsers.mjs`,不自造一份)。
65
+ // 图外的档问也没用,且能省掉每读一个 `.json` / 无扩展名档都要走一次建图核对的成本。
66
+ const ext = extOf(abs)
67
+ if (!CODE_EXTENSIONS.has(ext) && !DOC_EXTENSIONS.has(ext)) return ""
68
+ // 文档档还要过**层标识判据**(Q4 裁定:只认文档根声明内的档)—— 与注入侧的 `filterSeedsByLayer`
69
+ // 同一判据、同一个单源(`docLayerName`)。`README.md` / `AGENTS.md` 一类落 `unlayered`,不给头。
70
+ // 走动态 `import`:`process-doc-mark.mjs` 的静态闭包经 `declaration.mjs` → `memory/file-walk.mjs`
71
+ // 达 `memory/schema.mjs`(`node:sqlite`),不静态引它。
72
+ if (DOC_EXTENSIONS.has(ext)) {
73
+ const { docLayerName } = await import("../tools/process-doc-mark.mjs")
74
+ if (docLayerName(abs) === "unlayered") return ""
75
+ }
76
+ const readSet = new Set(ctx?.agent?._graphFullReadFiles instanceof Set ? ctx.agent._graphFullReadFiles : [])
77
+ if (selfFullRead) readSet.add(abs)
78
+ const diag = {}
79
+ const pack = await getMissingReadingPack(root, { targetFiles: [abs], fullReadFiles: readSet, diagnostics: diag })
80
+ const rows = graphMissingRows(pack)
81
+ // 「图确实没有关联面」与「图谱没用成」必须分开处置 —— 五种情形的唯一枚举在本档头,这里不重复。
82
+ if (diag.available === false) return degradationLine(diag)
83
+ if (rows.length === 0) return ""
84
+ // 措辞必须写成关于**那一刻**的事实:这一段随本次返回值进永久历史,写成「当前尚未读」在后续轮次里会过期误导
85
+ // (需求 F8、设计 §4.1)。`grep` 的注记同样进历史、同样以「尚未整档 read」立论,形态一致。
86
+ return `[repo_graph · 读到这一档时,图谱显示以下高关联档尚未整档 read:\n${rows.join("\n")}\n图谱注记不等于已读全文,先补读再改。]`
87
+ } catch (error) {
88
+ // 意外异常同样走可见降级(需求 F8):静默会把「图谱没用成」读成「没有关联」。
89
+ return degradationLine({ reason: "error", message: error?.message })
90
+ }
91
+ }