@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.
- package/CHANGELOG.md +27 -0
- package/abort-provenance.mjs +23 -0
- package/advisor/citations.mjs +5 -1
- package/advisor/compaction.mjs +13 -10
- package/advisor/history.mjs +6 -1
- package/advisor/loop.mjs +35 -10
- package/advisor/messages.mjs +31 -43
- package/advisor/project-context.mjs +49 -45
- package/advisor/run.mjs +82 -26
- package/advisor.mjs +40 -11
- package/agent/assemble.mjs +5 -5
- package/agent/chat-call.mjs +21 -1
- package/agent/completion.mjs +1 -20
- package/agent/dispatch-gates.mjs +8 -3
- package/agent/dispatch-run.mjs +131 -20
- package/agent/dispatch.mjs +23 -22
- package/agent/family-tools.mjs +4 -7
- package/agent/goal-judge.mjs +99 -0
- package/agent/goal-state.mjs +96 -0
- package/agent/helpers.mjs +13 -4
- package/agent/offload.mjs +1 -1
- package/agent/planning-graph-guardrail.mjs +224 -0
- package/agent/planning-prompt.mjs +179 -0
- package/agent/planning-step.mjs +460 -173
- package/agent/post-turn.mjs +23 -33
- package/agent/record-results.mjs +8 -5
- package/agent/run-stages.mjs +18 -38
- package/agent/run-start.mjs +26 -19
- package/agent/setup-reminders.mjs +16 -14
- package/agent/setup.mjs +3 -2
- package/agent/spawn-child.mjs +17 -4
- package/agent/suspension.mjs +42 -21
- package/agent/task-lifecycle.mjs +165 -52
- package/agent/timers.mjs +9 -1
- package/agent/turn-loop.mjs +160 -69
- package/agent/turn-projection.mjs +26 -15
- package/agent/turn-task-state.mjs +4 -4
- package/agent/write-gate-ledger.mjs +1 -1
- package/agent/write-gate.mjs +14 -11
- package/agent-tools/advisor-async.mjs +2 -0
- package/agent-tools/advisor-launch.mjs +27 -13
- package/agent-tools/advisor-settle.mjs +19 -18
- package/agent-tools/advisor.mjs +90 -13
- package/agent-tools/bash-async.mjs +3 -3
- package/agent-tools/batch-ledger-bind.mjs +8 -5
- package/agent-tools/batch-read.mjs +42 -0
- package/agent-tools/batch-record-write.mjs +20 -12
- package/agent-tools/batch-segment-vocab.mjs +6 -4
- package/agent-tools/batch-skeleton.mjs +43 -12
- package/agent-tools/consult.mjs +5 -1
- package/agent-tools/context.mjs +5 -4
- package/agent-tools/design-slots.mjs +7 -4
- package/agent-tools/design-token.mjs +3 -2
- package/agent-tools/doc-graph.mjs +257 -95
- package/agent-tools/escalate-async.mjs +4 -1
- package/agent-tools/goal.mjs +28 -95
- package/agent-tools/plan.mjs +1 -1
- package/agent-tools/review-facts.mjs +56 -7
- package/agent-tools/settings.mjs +35 -1
- package/agent-tools/ssh-transport.mjs +23 -22
- package/agent-tools/step.mjs +24 -4
- package/agent-tools/subagent-actions.mjs +6 -2
- package/agent-tools/subagent-async.mjs +4 -2
- package/agent-tools/subagent.mjs +1 -1
- package/agent-tools/task.mjs +73 -65
- package/agent-tools.mjs +3 -3
- package/agent.mjs +12 -3
- package/auto-think.mjs +16 -3
- package/browser/actions.mjs +5 -1
- package/browser/cdp.mjs +1 -1
- package/browser/pool.mjs +110 -17
- package/compaction-work-state.mjs +103 -13
- package/compress-form.mjs +29 -3
- package/config-defaults.mjs +27 -3
- package/config-io.mjs +3 -14
- package/config-normalize.mjs +24 -4
- package/config-presets.mjs +40 -26
- package/config-warn.mjs +30 -0
- package/config.mjs +139 -63
- package/context-degrade.mjs +4 -4
- package/context-push.mjs +20 -9
- package/context.mjs +65 -20
- package/doc-graph/anchors.mjs +39 -40
- package/doc-graph/clusters.mjs +49 -0
- package/doc-graph/code-parsers.mjs +494 -0
- package/doc-graph/context-pack.mjs +392 -0
- package/doc-graph/dir-signals.mjs +228 -0
- package/doc-graph/edges.mjs +231 -0
- package/doc-graph/format.mjs +70 -0
- package/doc-graph/gc-cmd.mjs +104 -0
- package/doc-graph/gc.mjs +112 -0
- package/doc-graph/glob-work-graph.mjs +307 -0
- package/doc-graph/golden-set.mjs +131 -0
- package/doc-graph/ls-work-graph.mjs +534 -0
- package/doc-graph/outline.mjs +377 -0
- package/doc-graph/output-annotations.mjs +85 -0
- package/doc-graph/process-docs.mjs +68 -0
- package/doc-graph/read-work-graph.mjs +91 -0
- package/doc-graph/rebuild-cmd.mjs +75 -0
- package/doc-graph/resolvers.mjs +322 -0
- package/doc-graph/roots.mjs +86 -0
- package/doc-graph/schema.mjs +110 -0
- package/doc-graph/search-augment.mjs +418 -0
- package/doc-graph/store.mjs +231 -0
- package/doc-graph/target-resolve.mjs +352 -0
- package/doc-graph/walk.mjs +87 -0
- package/doc-graph.mjs +583 -707
- package/explore-distill.mjs +52 -17
- package/generate-title.mjs +7 -4
- package/ledger-close.mjs +6 -6
- package/ledger-cmd.mjs +3 -3
- package/ledger-consistency.mjs +8 -6
- package/ledger-db.mjs +45 -10
- package/ledger-migrate.mjs +25 -10
- package/ledger-read.mjs +1 -1
- package/ledger-write-ops.mjs +6 -6
- package/ledger.mjs +2 -2
- package/model-context.mjs +54 -18
- package/model-specs.mjs +86 -67
- package/package.json +1 -1
- package/prompt-overlays.mjs +3 -3
- package/prompts/advisor-round1.md +6 -5
- package/prompts/common.md +16 -6
- package/prompts/consult-base.md +2 -1
- package/prompts/discipline-engineering.md +1 -1
- package/prompts/discipline-normal.md +12 -8
- package/prompts/knowledge/doc-lookup.md +2 -2
- package/prompts/knowledge/normal-batch-discipline.md +2 -2
- package/prompts/knowledge/normal-delivery-collaboration.md +3 -3
- package/prompts/knowledge/tool-advisor.md +2 -2
- package/prompts/knowledge/tool-apply-patch.md +1 -1
- package/prompts/knowledge/tool-bash.md +2 -2
- package/prompts/knowledge/tool-batch.md +4 -4
- package/prompts/knowledge/tool-glob.md +9 -2
- package/prompts/knowledge/tool-goal.md +9 -6
- package/prompts/knowledge/tool-grep.md +7 -2
- package/prompts/knowledge/tool-ls.md +11 -5
- package/prompts/knowledge/tool-lsp.md +1 -1
- package/prompts/knowledge/tool-operations.md +3 -2
- package/prompts/knowledge/tool-plan.md +1 -1
- package/prompts/knowledge/tool-read.md +7 -6
- package/prompts/knowledge/tool-repo-graph-read.md +12 -0
- package/prompts/knowledge/tool-repo-graph.md +12 -0
- package/prompts/knowledge/tool-step.md +1 -1
- package/prompts/knowledge/tool-subagent.md +2 -2
- package/prompts/knowledge/tool-task.md +10 -9
- package/prompts/knowledge/tool-tree.md +7 -1
- package/prompts/persona-eng-coder.md +1 -1
- package/prompts/persona-eng-designer.md +1 -1
- package/prompts/persona-engineering.md +2 -1
- package/prompts/persona-explore.md +1 -1
- package/prompts/persona-normal.md +7 -6
- package/prompts/persona-plan.md +2 -2
- package/prompts/planning-next-moves.md +7 -8
- package/provider/anthropic.mjs +53 -51
- package/provider/core.mjs +85 -34
- package/provider/errors.mjs +33 -10
- package/provider/google.mjs +244 -37
- package/provider/list-models.mjs +28 -14
- package/provider/responses-request.mjs +15 -9
- package/provider/responses.mjs +10 -8
- package/provider/sse.mjs +3 -6
- package/proxy-transport.mjs +228 -119
- package/rules-file.mjs +79 -0
- package/rules.mjs +13 -51
- package/session-lifecycle.mjs +32 -20
- package/team-ledger.mjs +7 -7
- package/think-off.mjs +37 -18
- package/token-window.mjs +48 -31
- package/tool-args.mjs +8 -8
- package/tool-docs/bash.md +1 -1
- package/tool-docs/glob.md +3 -1
- package/tool-docs/goal.md +2 -2
- package/tool-docs/grep.md +3 -1
- package/tool-docs/ls.md +7 -1
- package/tool-docs/read.md +1 -1
- package/tool-docs/repo_graph-read.md +3 -0
- package/tool-docs/repo_graph.md +3 -0
- package/tool-docs/tree.md +1 -1
- package/tools/bash.mjs +53 -8
- package/tools/browser.mjs +4 -4
- package/tools/file.mjs +34 -7
- package/tools/glob-dialect.mjs +57 -7
- package/tools/index.mjs +3 -7
- package/tools/patch.mjs +8 -7
- package/tools/process-doc-mark.mjs +13 -0
- package/tools/search.mjs +152 -37
- package/tools/shared.mjs +6 -0
- package/tools/tree.mjs +211 -8
- package/window-policy.mjs +205 -126
- package/prompts/knowledge/tool-doc-graph-read.md +0 -20
- package/prompts/knowledge/tool-doc-graph.md +0 -49
- package/prompts/knowledge/tool-peek.md +0 -10
- package/prompts/knowledge/tool-repo-outline.md +0 -4
- package/tool-docs/doc_graph-read.md +0 -3
- package/tool-docs/doc_graph.md +0 -3
- package/tool-docs/peek.md +0 -3
- package/tool-docs/repo_outline.md +0 -3
- package/tools/peek.mjs +0 -447
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* doc-graph/context-pack.mjs — 「动笔前必读上下文包」的拼装(源码向 + 文档向两支)。
|
|
3
|
+
*
|
|
4
|
+
* 只做一件事:给定一个已解析的目标档 + 一个已打开的 db,按四层静态边拼出必读清单并排版。
|
|
5
|
+
* 取库、开库、关库、判定过程档都在调用方 —— 本档不 import 任何带 `node:sqlite` 的模块,
|
|
6
|
+
* 端壳静态闭包因此可以安全地静态引它(W8 契约②)。
|
|
7
|
+
*
|
|
8
|
+
* 两个关键取舍留在这里,不要挪到别处:
|
|
9
|
+
* - `expandPairedAuthoritativeDocs` 把「1 跳 doc-cites 引用的需求/设计档」只作参考(`direct: false`),
|
|
10
|
+
* 不进强制 readingPack,也不许借引用加分反超直接归属档;
|
|
11
|
+
* - 未被任何档直接点名的源码,回溯 1 跳上游调用方所属文档补齐上下文,否则必读包会空;
|
|
12
|
+
* 同时用模块同源亲和给「碰巧被一个大综合文档提到一次」的档降权。
|
|
13
|
+
*/
|
|
14
|
+
import { basename, dirname } from "node:path"
|
|
15
|
+
|
|
16
|
+
import { fmtItem, truncNote } from "./format.mjs"
|
|
17
|
+
import { docLocation, sameDocDomain } from "./output-annotations.mjs"
|
|
18
|
+
import { docPriorityRank, isNonAuthDocPath } from "./target-resolve.mjs"
|
|
19
|
+
|
|
20
|
+
const slash = (p) => String(p ?? "").replace(/\\/g, "/")
|
|
21
|
+
|
|
22
|
+
const GENERIC_DIR_TOKENS = new Set([
|
|
23
|
+
"src", "lib", "dist", "build", "app", "apps", "packages", "pkg", "core",
|
|
24
|
+
"thincoder-core", "thincoder-cli", "thincoder-vscode",
|
|
25
|
+
"index", "utils", "util", "helpers", "helper", "common", "shared", "internal", "types",
|
|
26
|
+
])
|
|
27
|
+
|
|
28
|
+
/** 评估源码文件路径与权威文档名之间的模块同源亲和分(如 provider/list-models.mjs ↔ PROVIDER.md)。 */
|
|
29
|
+
function docModuleAffinity(targetPath, docPath) {
|
|
30
|
+
const docStem = basename(docPath).replace(/\.md$/i, "").toLowerCase()
|
|
31
|
+
if (!docStem || docStem.length < 3) return 0
|
|
32
|
+
const fileStem = basename(targetPath).replace(/\.[^.]+$/, "").toLowerCase()
|
|
33
|
+
const dirParts = slash(dirname(targetPath)).toLowerCase().split("/").filter((s) => s && s !== "." && !GENERIC_DIR_TOKENS.has(s))
|
|
34
|
+
const parentDir = dirParts.at(-1) ?? ""
|
|
35
|
+
const grandDir = dirParts.length >= 2 ? dirParts.at(-2) : ""
|
|
36
|
+
|
|
37
|
+
const exactTokens = [fileStem, parentDir, grandDir].filter((t) => t && t.length >= 3 && !GENERIC_DIR_TOKENS.has(t))
|
|
38
|
+
for (const tok of exactTokens) {
|
|
39
|
+
if (docStem === tok) return 4
|
|
40
|
+
}
|
|
41
|
+
for (const tok of exactTokens) {
|
|
42
|
+
if (docStem.startsWith(`${tok}-`) || docStem.endsWith(`-${tok}`) || tok.startsWith(`${docStem}-`)) return 2
|
|
43
|
+
}
|
|
44
|
+
return 0
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function callerPriorityRank(relPath) {
|
|
48
|
+
const low = slash(relPath).toLowerCase()
|
|
49
|
+
if (/(?:^|\/)(?:bench|benchmarks|examples?|demos?|fixtures?)\//.test(low)) return 2
|
|
50
|
+
if (/(?:^|\/)scripts\//.test(low)) return 1
|
|
51
|
+
return 0
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** 根据已命中的设计/需求档,顺手拉出同主题配对的需求档或设计档(如 design/X.md ↔ requirements/X.md);1 跳 doc-cites 仅作信息参考,不进入强制 readingPack 也不反超直接归属档。 */
|
|
55
|
+
function expandPairedAuthoritativeDocs(db, seedDocs, byPath, isProc) {
|
|
56
|
+
const scored = new Map() // docPath -> { score, reasons: Set, direct: boolean, weak: boolean }
|
|
57
|
+
for (const [p, meta] of seedDocs.entries()) {
|
|
58
|
+
if (isNonAuthDocPath(p, isProc) || !byPath.has(p)) continue
|
|
59
|
+
scored.set(p, {
|
|
60
|
+
score: meta.score,
|
|
61
|
+
reasons: new Set(meta.reasons),
|
|
62
|
+
direct: meta.direct !== false,
|
|
63
|
+
weak: Boolean(meta.weak),
|
|
64
|
+
})
|
|
65
|
+
}
|
|
66
|
+
const addDirect = (p, score, reason) => {
|
|
67
|
+
if (isNonAuthDocPath(p, isProc) || !byPath.has(p)) return
|
|
68
|
+
const cur = scored.get(p)
|
|
69
|
+
if (cur) {
|
|
70
|
+
cur.score += score
|
|
71
|
+
cur.direct = true
|
|
72
|
+
cur.weak = false
|
|
73
|
+
cur.reasons.add(reason)
|
|
74
|
+
} else {
|
|
75
|
+
scored.set(p, { score, reasons: new Set([reason]), direct: true, weak: false })
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const addCitedOnly = (p, reason) => {
|
|
79
|
+
if (isNonAuthDocPath(p, isProc) || !byPath.has(p)) return
|
|
80
|
+
// 已是直接归属种子档的不叠加 doc-cites 分数,防止相邻参考文档借引用加分反超直接归属档
|
|
81
|
+
if (scored.has(p)) return
|
|
82
|
+
scored.set(p, { score: 0.5, reasons: new Set([reason]), direct: false, weak: false })
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
for (const [docPath, meta] of [...scored.entries()]) {
|
|
86
|
+
if (!meta.direct || meta.weak) continue
|
|
87
|
+
// 1. 同名需求/设计配对(docs/.../design/FOO.md ↔ docs/.../requirements/FOO.md)
|
|
88
|
+
if (/\/design\//i.test(docPath)) {
|
|
89
|
+
const reqPeer = docPath.replace(/\/design\//i, "/requirements/")
|
|
90
|
+
if (byPath.has(reqPeer)) addDirect(reqPeer, scored.has(reqPeer) ? 1.5 : 2.5, "同主题需求档")
|
|
91
|
+
} else if (/\/requirements\//i.test(docPath)) {
|
|
92
|
+
const desPeer = docPath.replace(/\/requirements\//i, "/design/")
|
|
93
|
+
if (byPath.has(desPeer)) addDirect(desPeer, scored.has(desPeer) ? 1.5 : 2.5, "同主题设计档")
|
|
94
|
+
}
|
|
95
|
+
// 2. 1 跳 doc-cites 指向的需求/设计档(仅参考引用,不进强制 readingPack)
|
|
96
|
+
const cited = db.prepare("SELECT dst FROM edges WHERE src = ? AND kind = 'doc-cites' AND state = 'ok'").all(docPath)
|
|
97
|
+
for (const { dst } of cited) {
|
|
98
|
+
if (/\/(?:requirements|design)\//i.test(dst) && byPath.has(dst)) {
|
|
99
|
+
addCitedOnly(dst, `被 ${basename(docPath)} 引用(参考)`)
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return [...scored.entries()]
|
|
105
|
+
.map(([path, meta]) => ({
|
|
106
|
+
path,
|
|
107
|
+
lines: byPath.get(path)?.lines ?? 0,
|
|
108
|
+
score: meta.score,
|
|
109
|
+
direct: meta.direct,
|
|
110
|
+
weak: meta.weak,
|
|
111
|
+
rank: docPriorityRank(path),
|
|
112
|
+
reason: [...meta.reasons].slice(0, 2).join(";"),
|
|
113
|
+
}))
|
|
114
|
+
.sort((a, b) => {
|
|
115
|
+
if (a.direct !== b.direct) return a.direct ? -1 : 1
|
|
116
|
+
if (a.weak !== b.weak) return a.weak ? 1 : -1
|
|
117
|
+
if (b.score !== a.score) return b.score - a.score
|
|
118
|
+
return a.rank - b.rank || a.path.localeCompare(b.path)
|
|
119
|
+
})
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function buildCodeContextPack(db, target, byPath, matchedSymbol, isProc) {
|
|
123
|
+
// 1. 所属需求与设计档(排除批档/过程档与 test/**/*.md 测试追踪矩阵)
|
|
124
|
+
const docSeed = new Map()
|
|
125
|
+
const addDocSeed = (p, score, reason, { isDirectCover = false } = {}) => {
|
|
126
|
+
if (isNonAuthDocPath(p, isProc) || !byPath.has(p)) return
|
|
127
|
+
const cur = docSeed.get(p)
|
|
128
|
+
if (cur) {
|
|
129
|
+
cur.score += score
|
|
130
|
+
cur.reasons.add(reason)
|
|
131
|
+
if (isDirectCover) cur.hasCover = true
|
|
132
|
+
} else {
|
|
133
|
+
docSeed.set(p, { score, reasons: new Set([reason]), hasCover: isDirectCover, direct: true, weak: false })
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
const docEdges = db.prepare(
|
|
137
|
+
"SELECT src, kind, detail FROM edges WHERE dst = ? AND kind IN ('doc-covers', 'doc-symbol') AND state = 'ok'",
|
|
138
|
+
).all(target.path)
|
|
139
|
+
for (const e of docEdges) {
|
|
140
|
+
if (e.kind === "doc-covers") addDocSeed(e.src, 4, "直接提及本文件", { isDirectCover: true })
|
|
141
|
+
else addDocSeed(e.src, 1.5, `引用符号 ${e.detail}`)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// 2. 直接上游调用方(code)与关联测试(test)
|
|
145
|
+
const inbound = db.prepare(
|
|
146
|
+
"SELECT src, group_concat(NULLIF(symbol, ''), ',') AS detail FROM edges WHERE dst = ? AND kind = 'imports' AND state = 'ok' GROUP BY src",
|
|
147
|
+
).all(target.path)
|
|
148
|
+
const callers1 = []
|
|
149
|
+
const directTests = []
|
|
150
|
+
for (const e of inbound) {
|
|
151
|
+
const f = byPath.get(e.src)
|
|
152
|
+
if (!f) continue
|
|
153
|
+
if (f.kind === "test") directTests.push({ path: f.path, lines: f.lines, detail: e.detail })
|
|
154
|
+
else if (f.kind === "code") callers1.push({ path: f.path, lines: f.lines, detail: e.detail, hop: 1 })
|
|
155
|
+
}
|
|
156
|
+
callers1.sort((a, b) => callerPriorityRank(a.path) - callerPriorityRank(b.path) || a.path.localeCompare(b.path))
|
|
157
|
+
directTests.sort((a, b) => a.path.localeCompare(b.path))
|
|
158
|
+
|
|
159
|
+
// 2-hop 上游编排者(最多补 4 个,如 turn-loop.mjs -> agent.mjs)
|
|
160
|
+
const callers2 = []
|
|
161
|
+
const seenCaller = new Set([target.path, ...callers1.map((c) => c.path)])
|
|
162
|
+
for (const c1 of callers1.slice(0, 6)) {
|
|
163
|
+
const up2 = db.prepare("SELECT src, group_concat(NULLIF(symbol, ''), ',') AS detail FROM edges WHERE dst = ? AND kind = 'imports' AND state = 'ok' GROUP BY src").all(c1.path)
|
|
164
|
+
for (const e of up2) {
|
|
165
|
+
if (seenCaller.has(e.src)) continue
|
|
166
|
+
const f = byPath.get(e.src)
|
|
167
|
+
if (!f || f.kind !== "code") continue
|
|
168
|
+
seenCaller.add(e.src)
|
|
169
|
+
callers2.push({ path: f.path, lines: f.lines, via: c1.path, hop: 2 })
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
callers2.sort((a, b) => callerPriorityRank(a.path) - callerPriorityRank(b.path) || a.path.localeCompare(b.path))
|
|
173
|
+
|
|
174
|
+
// 若目标档本身未被文档直接点名(无 doc-covers),回溯 1 跳上游调用方所属文档补齐上下文
|
|
175
|
+
const hasAnyDirectCover = [...docSeed.values()].some((m) => m.hasCover)
|
|
176
|
+
if (!hasAnyDirectCover) {
|
|
177
|
+
for (const c1 of callers1.slice(0, 3)) {
|
|
178
|
+
const upDocs = db.prepare(
|
|
179
|
+
"SELECT src FROM edges WHERE dst = ? AND kind = 'doc-covers' AND state = 'ok'",
|
|
180
|
+
).all(c1.path)
|
|
181
|
+
for (const { src } of upDocs) addDocSeed(src, 2, `覆盖上游 ${basename(c1.path)}`, { isDirectCover: true })
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
// 模块名同源亲和加权 + 对仅靠单符号碰巧命中的超大综合文档降权(防 1600 行大档压过模块归属档)
|
|
185
|
+
for (const [docPath, meta] of docSeed.entries()) {
|
|
186
|
+
const aff = docModuleAffinity(target.path, docPath)
|
|
187
|
+
if (aff > 0) {
|
|
188
|
+
meta.score += aff
|
|
189
|
+
meta.reasons.add("模块同源归属")
|
|
190
|
+
} else if (!meta.hasCover && (byPath.get(docPath)?.lines ?? 0) > 600) {
|
|
191
|
+
meta.score = Math.min(meta.score, 0.7)
|
|
192
|
+
meta.weak = true
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
const allDocs = expandPairedAuthoritativeDocs(db, docSeed, byPath, isProc)
|
|
196
|
+
const directDocs = allDocs.filter((d) => d.direct)
|
|
197
|
+
const directDocsAll = directDocs.length
|
|
198
|
+
const citedDocs = allDocs.filter((d) => !d.direct).slice(0, Math.max(0, Math.min(2, 6 - directDocs.length)))
|
|
199
|
+
const docs = [...directDocs.slice(0, 6), ...citedDocs].slice(0, 6)
|
|
200
|
+
|
|
201
|
+
// 3. 直接下游依赖(我调用谁)
|
|
202
|
+
const outbound = db.prepare(
|
|
203
|
+
"SELECT dst, group_concat(NULLIF(symbol, ''), ',') AS detail FROM edges WHERE src = ? AND kind = 'imports' AND state = 'ok' GROUP BY dst",
|
|
204
|
+
).all(target.path)
|
|
205
|
+
const deps = outbound
|
|
206
|
+
.map((e) => {
|
|
207
|
+
const f = byPath.get(e.dst)
|
|
208
|
+
return f && f.kind === "code" ? { path: f.path, lines: f.lines, detail: e.detail } : null
|
|
209
|
+
})
|
|
210
|
+
.filter(Boolean)
|
|
211
|
+
.sort((a, b) => a.path.localeCompare(b.path))
|
|
212
|
+
|
|
213
|
+
// 4. 同级兄弟 / 共享编排点(同上游编排者引入的同目录/同域兄弟模块,专治漏看同类接线!)
|
|
214
|
+
const targetDir = dirname(target.path)
|
|
215
|
+
const excludedSib = new Set([target.path, ...callers1.map((c) => c.path), ...callers2.map((c) => c.path), ...deps.map((d) => d.path)])
|
|
216
|
+
const siblingScores = new Map()
|
|
217
|
+
const orchestrators = [...callers1.slice(0, 4), ...callers2.slice(0, 4)]
|
|
218
|
+
for (const orch of orchestrators) {
|
|
219
|
+
const peerEdges = db.prepare("SELECT DISTINCT dst FROM edges WHERE src = ? AND kind = 'imports' AND state = 'ok'").all(orch.path)
|
|
220
|
+
for (const { dst } of peerEdges) {
|
|
221
|
+
if (excludedSib.has(dst)) continue
|
|
222
|
+
const f = byPath.get(dst)
|
|
223
|
+
if (!f || f.kind !== "code") continue
|
|
224
|
+
const sameDir = dirname(f.path) === targetDir
|
|
225
|
+
const score = (sameDir ? 3 : 1) + (orch.hop === 1 ? 1 : 0.5)
|
|
226
|
+
const cur = siblingScores.get(f.path)
|
|
227
|
+
if (cur) { cur.score += score; cur.via.add(basename(orch.path)) }
|
|
228
|
+
else siblingScores.set(f.path, { path: f.path, lines: f.lines, score, sameDir, via: new Set([basename(orch.path)]) })
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
const siblings = [...siblingScores.values()]
|
|
232
|
+
.sort((a, b) => (b.score !== a.score ? b.score - a.score : a.path.localeCompare(b.path)))
|
|
233
|
+
.slice(0, 6)
|
|
234
|
+
|
|
235
|
+
// 5. 关联测试(直接测试不足 6 个时,补 1 跳上游调用方的测试)
|
|
236
|
+
const tests = [...directTests]
|
|
237
|
+
const seenTest = new Set(tests.map((t) => t.path))
|
|
238
|
+
if (tests.length < 6) {
|
|
239
|
+
for (const c1 of callers1.slice(0, 4)) {
|
|
240
|
+
const cTests = db.prepare("SELECT DISTINCT src FROM edges WHERE dst = ? AND kind = 'imports' AND state = 'ok'").all(c1.path)
|
|
241
|
+
for (const { src } of cTests) {
|
|
242
|
+
if (seenTest.has(src)) continue
|
|
243
|
+
const f = byPath.get(src)
|
|
244
|
+
if (!f || f.kind !== "test") continue
|
|
245
|
+
seenTest.add(src)
|
|
246
|
+
tests.push({ path: f.path, lines: f.lines, via: basename(c1.path) })
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// 构造给 Planning next moves 对账用的核心必读清单(仅收直接归属文档,不把 1 跳参考引用塞进强制必读)
|
|
252
|
+
const readingPack = []
|
|
253
|
+
const pushPack = (path, lines, role) => {
|
|
254
|
+
if (!path || readingPack.some((x) => x.path === path)) return
|
|
255
|
+
readingPack.push({ path, lines: lines ?? 0, role })
|
|
256
|
+
}
|
|
257
|
+
const strongDirectDocs = directDocs.filter((d) => !d.weak)
|
|
258
|
+
const packDocs = strongDirectDocs.length > 0 ? strongDirectDocs.slice(0, 3) : directDocs.slice(0, 1)
|
|
259
|
+
for (const d of packDocs) pushPack(d.path, d.lines, "doc")
|
|
260
|
+
pushPack(target.path, target.lines, "target")
|
|
261
|
+
for (const c of callers1.slice(0, 4)) pushPack(c.path, c.lines, "caller")
|
|
262
|
+
for (const s of siblings.filter((x) => x.sameDir).slice(0, 3)) pushPack(s.path, s.lines, "sibling")
|
|
263
|
+
|
|
264
|
+
const lines = [
|
|
265
|
+
`[Context Pack] ${target.path} (${target.lines} 行 · ${target.lang}${matchedSymbol ? ` · 符号 ${matchedSymbol}` : ""})`,
|
|
266
|
+
"",
|
|
267
|
+
"1. 所属需求与设计(动笔前必读):",
|
|
268
|
+
...(docs.length > 0
|
|
269
|
+
? [
|
|
270
|
+
...docs.map((d) => fmtItem(d, d.reason)),
|
|
271
|
+
...truncNote(directDocsAll, docs.length, "所属文档尚有"),
|
|
272
|
+
]
|
|
273
|
+
: [" - (未检测到直接覆盖本文件的需求/设计档;建议用 doc_search 或 manifest 复核)"]),
|
|
274
|
+
"",
|
|
275
|
+
"2. 上游调用方(谁调用本文件):",
|
|
276
|
+
...(callers1.length > 0
|
|
277
|
+
? [
|
|
278
|
+
...callers1.slice(0, 8).map((c) => fmtItem(c, c.detail ? `imports: ${c.detail}` : "direct import")),
|
|
279
|
+
...callers2.slice(0, 4).map((c) => fmtItem(c, `2跳上游 via ${basename(c.via)}`)),
|
|
280
|
+
...truncNote(callers1.length, Math.min(8, callers1.length), "1跳上游尚有"),
|
|
281
|
+
...truncNote(callers2.length, Math.min(4, callers2.length), "2跳上游尚有"),
|
|
282
|
+
]
|
|
283
|
+
: [" - (无仓内直接上游导入方——可能是入口文件或动态加载点)"]),
|
|
284
|
+
"",
|
|
285
|
+
"3. 同级兄弟/共享编排模块(防另起炉灶,核对同类既有实现):",
|
|
286
|
+
...(siblings.length > 0
|
|
287
|
+
? [
|
|
288
|
+
...siblings.map((s) => fmtItem(s, `同由 ${[...s.via].slice(0, 2).join(" / ")} 编排`)),
|
|
289
|
+
...truncNote(siblingScores.size, siblings.length, "同级兄弟尚有"),
|
|
290
|
+
]
|
|
291
|
+
: [" - (无)"]),
|
|
292
|
+
"",
|
|
293
|
+
"4. 直接下游依赖(本文件调用谁):",
|
|
294
|
+
...(deps.length > 0
|
|
295
|
+
? [
|
|
296
|
+
...deps.slice(0, 10).map((d) => fmtItem(d, d.detail ? `imports: ${d.detail}` : "")),
|
|
297
|
+
...truncNote(deps.length, Math.min(10, deps.length), "下游依赖尚有"),
|
|
298
|
+
]
|
|
299
|
+
: [" - (无仓内相对依赖)"]),
|
|
300
|
+
"",
|
|
301
|
+
"5. 关联测试(改后定向验收):",
|
|
302
|
+
...(tests.length > 0
|
|
303
|
+
? [
|
|
304
|
+
...tests.slice(0, 8).map((t) => fmtItem(t, t.via ? `测上游 ${t.via}` : "直接导入本文件")),
|
|
305
|
+
...truncNote(tests.length, Math.min(8, tests.length), "关联测试尚有"),
|
|
306
|
+
]
|
|
307
|
+
: [" - (未发现直接导入本文件的测试文件)"]),
|
|
308
|
+
"",
|
|
309
|
+
"下一步建议:并发调用 `read`(不传小 limit)完整读入以上未读的需求/设计档、本文件与关键上下游源码后再设计改动。",
|
|
310
|
+
]
|
|
311
|
+
|
|
312
|
+
return {
|
|
313
|
+
ok: true,
|
|
314
|
+
target: target.path,
|
|
315
|
+
targetInfo: target,
|
|
316
|
+
docs,
|
|
317
|
+
callers: [...callers1, ...callers2],
|
|
318
|
+
siblings,
|
|
319
|
+
deps,
|
|
320
|
+
tests,
|
|
321
|
+
readingPack,
|
|
322
|
+
text: lines.join("\n"),
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
export function buildDocContextPack(db, target, byPath, isProc) {
|
|
327
|
+
const pairedAll = expandPairedAuthoritativeDocs(db, new Map([[target.path, { score: 10, reasons: new Set(["本档"]) }]]), byPath, isProc)
|
|
328
|
+
.filter((d) => d.path !== target.path)
|
|
329
|
+
const paired = pairedAll.slice(0, 6)
|
|
330
|
+
const citedByAll = db.prepare("SELECT src, line FROM edges WHERE dst = ? AND kind = 'doc-cites' AND state = 'ok'").all(target.path)
|
|
331
|
+
.filter((r) => !isProc(r.src) && byPath.has(r.src))
|
|
332
|
+
const citedBy = citedByAll.slice(0, 8)
|
|
333
|
+
const covered = db.prepare("SELECT dst, kind, detail FROM edges WHERE src = ? AND kind IN ('doc-covers', 'doc-symbol') AND state = 'ok'").all(target.path)
|
|
334
|
+
const codeMap = new Map()
|
|
335
|
+
for (const e of covered) {
|
|
336
|
+
const f = byPath.get(e.dst)
|
|
337
|
+
if (!f || f.kind === "doc") continue
|
|
338
|
+
const cur = codeMap.get(f.path)
|
|
339
|
+
const tag = e.kind === "doc-covers" ? "路径引用" : `符号 ${e.detail}`
|
|
340
|
+
if (cur) cur.tags.add(tag)
|
|
341
|
+
else codeMap.set(f.path, { path: f.path, lines: f.lines, kind: f.kind, tags: new Set([tag]) })
|
|
342
|
+
}
|
|
343
|
+
const coveredCodeAll = [...codeMap.values()].sort((a, b) => a.path.localeCompare(b.path))
|
|
344
|
+
const coveredCode = coveredCodeAll.slice(0, 12)
|
|
345
|
+
const missing = db.prepare("SELECT dst, line FROM edges WHERE src = ? AND state = 'missing'").all(target.path)
|
|
346
|
+
|
|
347
|
+
const readingPack = [{ path: target.path, lines: target.lines, role: "doc" }]
|
|
348
|
+
for (const d of paired.filter((x) => x.direct).slice(0, 2)) readingPack.push({ path: d.path, lines: d.lines, role: "doc" })
|
|
349
|
+
for (const c of coveredCode.filter((x) => x.kind === "code").slice(0, 4)) readingPack.push({ path: c.path, lines: c.lines, role: "target" })
|
|
350
|
+
|
|
351
|
+
const targetLocation = docLocation(target.path)
|
|
352
|
+
const hasCrossDomain = pairedAll.some((d) => !sameDocDomain(target.path, d.path))
|
|
353
|
+
const sameDomain = paired.filter((d) => sameDocDomain(target.path, d.path))
|
|
354
|
+
const crossDomain = paired.filter((d) => !sameDocDomain(target.path, d.path))
|
|
355
|
+
const pairedLines = !hasCrossDomain
|
|
356
|
+
? paired.map((d) => fmtItem(d, d.reason))
|
|
357
|
+
: [
|
|
358
|
+
...(sameDomain.length > 0 ? [` 同域 ${targetLocation.root} · ${targetLocation.domain}(${sameDomain.length} 档):`, ...sameDomain.map((d) => fmtItem(d, d.reason))] : []),
|
|
359
|
+
...(crossDomain.length > 0 ? [` 跨域(${crossDomain.length} 档):`, ...crossDomain.map((d) => fmtItem(d, d.reason))] : []),
|
|
360
|
+
]
|
|
361
|
+
|
|
362
|
+
const lines = [
|
|
363
|
+
`[Context Pack · Doc] ${target.path} (${target.lines} 行)`,
|
|
364
|
+
`引用面总览:配对 ${pairedAll.length} · 被引 ${citedByAll.length} · 覆盖源码 ${coveredCodeAll.length} · 断链 ${missing.length}`,
|
|
365
|
+
"",
|
|
366
|
+
"1. 配对/关联文档:",
|
|
367
|
+
...(paired.length > 0
|
|
368
|
+
? [
|
|
369
|
+
...pairedLines,
|
|
370
|
+
...truncNote(pairedAll.length, paired.length, "配对文档尚有"),
|
|
371
|
+
]
|
|
372
|
+
: [" - (无)"]),
|
|
373
|
+
"",
|
|
374
|
+
"2. 被谁引用(非过程档):",
|
|
375
|
+
...(citedBy.length > 0
|
|
376
|
+
? [
|
|
377
|
+
...citedBy.map((r) => fmtItem({ path: r.src, lines: byPath.get(r.src)?.lines ?? 0 }, `L${r.line}`)),
|
|
378
|
+
...truncNote(citedByAll.length, citedBy.length, "被引尚有"),
|
|
379
|
+
]
|
|
380
|
+
: [" - (无)"]),
|
|
381
|
+
"",
|
|
382
|
+
"3. 对应源码与测试:",
|
|
383
|
+
...(coveredCode.length > 0
|
|
384
|
+
? [
|
|
385
|
+
...coveredCode.map((c) => fmtItem(c, [...c.tags].slice(0, 3).join(", "))),
|
|
386
|
+
...truncNote(coveredCodeAll.length, coveredCode.length, "覆盖源码尚有"),
|
|
387
|
+
]
|
|
388
|
+
: [" - (未检测到直接映射的源码文件)"]),
|
|
389
|
+
...(missing.length > 0 ? ["", "4. 文档内疑似断链:", ...missing.slice(0, 8).map((m) => ` - ${m.dst} (L${m.line} · missing)`), ...truncNote(missing.length, Math.min(8, missing.length), "断链尚有")] : []),
|
|
390
|
+
]
|
|
391
|
+
return { ok: true, target: target.path, targetInfo: target, docs: paired, coveredCode, readingPack, text: lines.join("\n") }
|
|
392
|
+
}
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dir-signals.mjs — 目录级图谱信号(`tree` 摘要模式的图列)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么住在这里而不在 `tree.mjs`:`tree` 是**磁盘视角**(连没入图的目录也照列规模),
|
|
5
|
+
* 而这三列是**索引视角**的读数。两者必须同源,否则同一个目录在 `tree` 与 `repo_graph(overview)`
|
|
6
|
+
* 里给出两套数——2026-12-01 实测反馈的原话是「三份图三套口径,要靠手工加总」。
|
|
7
|
+
* 所以判据只写一遍(入边按 `DISTINCT src,dst`、环用三色 DFS、入口 = 无仓内上游导入的源码档),
|
|
8
|
+
* 与 `doc-graph.mjs` 的 `queryOverview` 完全一致;本档只多做「按目录聚合到行上」。
|
|
9
|
+
*
|
|
10
|
+
* 不碰磁盘:`tree` 的档数仍由它自己按同一套过滤数出来,图列是**附加**,不是替代。
|
|
11
|
+
*/
|
|
12
|
+
import { relative } from "node:path"
|
|
13
|
+
|
|
14
|
+
const parentOf = (dir) => {
|
|
15
|
+
const i = dir.lastIndexOf("/")
|
|
16
|
+
return i < 0 ? "" : dir.slice(0, i)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** `""` 是仓根;每一级祖先都算,含自身。 */
|
|
20
|
+
function ancestors(dir) {
|
|
21
|
+
const out = []
|
|
22
|
+
let cur = dir
|
|
23
|
+
for (;;) {
|
|
24
|
+
out.push(cur)
|
|
25
|
+
if (cur === "") break
|
|
26
|
+
cur = parentOf(cur)
|
|
27
|
+
}
|
|
28
|
+
return out
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const inSubtree = (dir, root) => root === "" || dir === root || dir.startsWith(`${root}/`)
|
|
32
|
+
|
|
33
|
+
/** 把绝对目录换成仓内相对目录(`/` 分隔);出仓返回 `null`。 */
|
|
34
|
+
export function relDirOf(projectRoot, absDir) {
|
|
35
|
+
const r = relative(projectRoot, absDir).replace(/\\/g, "/")
|
|
36
|
+
if (r === "" || r === ".") return ""
|
|
37
|
+
if (r === ".." || r.startsWith("../")) return null
|
|
38
|
+
return r.replace(/\/+$/, "")
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 多个目录的最长公共前缀(按路径段)。 */
|
|
42
|
+
function commonPrefix(dirs) {
|
|
43
|
+
const lists = dirs.map((d) => (d === "" ? [] : d.split("/")))
|
|
44
|
+
const first = lists[0] ?? []
|
|
45
|
+
let n = 0
|
|
46
|
+
while (n < first.length && lists.every((l) => l[n] === first[n])) n += 1
|
|
47
|
+
return first.slice(0, n).join("/")
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** 图谱库里的文件表与 import 边——两条查询只写一遍,入度、目录依赖与环都从这里出发。 */
|
|
51
|
+
function readFiles(db) {
|
|
52
|
+
return db.prepare("SELECT path, kind FROM files").all()
|
|
53
|
+
}
|
|
54
|
+
function readEdges(db) {
|
|
55
|
+
return db.prepare("SELECT DISTINCT src, dst FROM edges WHERE kind = 'imports' AND state = 'ok'").all()
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 单档入度(键 = 仓内相对路径):判据与目录级 `←N`、`repo_graph(overview)` 完全同一条——
|
|
60
|
+
* `DISTINCT src,dst` 且两端都是 `code`。`grep` 命中行尾的 `←N` 用的就是这一份,
|
|
61
|
+
* 同一个档在 `grep` / `ls` / `tree` 里必须是同一个数。
|
|
62
|
+
*
|
|
63
|
+
* `keep > 0` 时顺带留下该档的 `keep` 个引用方路径(按路径升序、只留前几个):
|
|
64
|
+
* 「←43 是谁在调」与「←43」是同一批边上的两列,不能为了拿名单再查一遍库。
|
|
65
|
+
*/
|
|
66
|
+
export function inboundOfFilesDetail(files, edges, keep = 0) {
|
|
67
|
+
const kind = new Map(files.map((f) => [f.path, f.kind]))
|
|
68
|
+
const out = new Map()
|
|
69
|
+
for (const { src, dst } of edges) {
|
|
70
|
+
if (kind.get(src) !== "code" || kind.get(dst) !== "code") continue
|
|
71
|
+
let entry = out.get(dst)
|
|
72
|
+
if (!entry) {
|
|
73
|
+
entry = { count: 0, refs: [] }
|
|
74
|
+
out.set(dst, entry)
|
|
75
|
+
}
|
|
76
|
+
entry.count += 1
|
|
77
|
+
if (keep > 0) keepRef(entry.refs, src, keep)
|
|
78
|
+
}
|
|
79
|
+
return out
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** 按路径升序留住最小的 `keep` 个引用方(`edges` 已 `DISTINCT src,dst`,同一 src 不会重复进来)。 */
|
|
83
|
+
function keepRef(refs, path, keep) {
|
|
84
|
+
if (refs.length === keep && path >= refs[keep - 1]) return
|
|
85
|
+
let at = refs.length
|
|
86
|
+
while (at > 0 && refs[at - 1] > path) at -= 1
|
|
87
|
+
refs.splice(at, 0, path)
|
|
88
|
+
if (refs.length > keep) refs.pop()
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** 只要数的那一面(`tree` / `ls` / 目录信号用):与上面同一份实现,不另写一遍口径。 */
|
|
92
|
+
export function inboundOfFiles(files, edges) {
|
|
93
|
+
const out = new Map()
|
|
94
|
+
for (const [dst, entry] of inboundOfFilesDetail(files, edges)) out.set(dst, entry.count)
|
|
95
|
+
return out
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** 已开库句柄上的单档入度(`grep` 走这条:一次调用一个库,不为每个命中档各查一遍)。 */
|
|
99
|
+
export function fileInbound(db) {
|
|
100
|
+
return inboundOfFiles(readFiles(db), readEdges(db))
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** 已开库句柄上的单档入度 + 前 `keep` 个引用方(`grep` 的 `←N` 与 `↳ 引用者:` 同一次扫描取回)。 */
|
|
104
|
+
export function fileInboundWithRefs(db, keep = 3) {
|
|
105
|
+
return inboundOfFilesDetail(readFiles(db), readEdges(db), keep)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* 从已建好的图谱库算出四样东西,全部以**仓内相对目录**为键(`""` = 仓根):
|
|
110
|
+
* - `crossInbound`:该目录子树被**子树之外**的目录依赖的入边数(目录行上的 `←N`)
|
|
111
|
+
* - `hub`:子树内被依赖最多的那个源码档(`hub name(N)`,只给 Top1)
|
|
112
|
+
* - `entries`:子树内没有任何仓内上游导入的源码档数(`入口 N`)
|
|
113
|
+
* - `cycles`:目录级环,带其公共祖先 `lca` 与可读标签(`⚠环 a↔b`)
|
|
114
|
+
*/
|
|
115
|
+
export function buildDirSignals(db) {
|
|
116
|
+
const files = readFiles(db)
|
|
117
|
+
const byPath = new Map(files.map((f) => [f.path, f]))
|
|
118
|
+
const edges = readEdges(db)
|
|
119
|
+
|
|
120
|
+
const inboundOfFile = inboundOfFiles(files, edges)
|
|
121
|
+
const dirDeps = new Map()
|
|
122
|
+
const crossPairs = []
|
|
123
|
+
for (const { src, dst } of edges) {
|
|
124
|
+
const sf = byPath.get(src)
|
|
125
|
+
const df = byPath.get(dst)
|
|
126
|
+
// 与 overview 同一条判据:只有 code → code 的导入才算(doc/test 边不进这几列)
|
|
127
|
+
if (!sf || !df || sf.kind !== "code" || df.kind !== "code") continue
|
|
128
|
+
const sd = parentOf(src)
|
|
129
|
+
const dd = parentOf(dst)
|
|
130
|
+
if (sd === dd) continue
|
|
131
|
+
if (!dirDeps.has(sd)) dirDeps.set(sd, new Set())
|
|
132
|
+
dirDeps.get(sd).add(dd)
|
|
133
|
+
crossPairs.push([sd, dd])
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// 跨目录入边按子树累加:一条边 (sd → dd) 对 dd 的每一级祖先 A 都有贡献,
|
|
137
|
+
// 但只当 sd 不在 A 之下时它才是「从外面打进来的」——`A = 仓根` 因此恒不受贡献(根本身没有外面)。
|
|
138
|
+
const crossInbound = new Map()
|
|
139
|
+
for (const [sd, dd] of crossPairs) {
|
|
140
|
+
for (const a of ancestors(dd)) {
|
|
141
|
+
if (inSubtree(sd, a)) continue
|
|
142
|
+
crossInbound.set(a, (crossInbound.get(a) ?? 0) + 1)
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const hub = new Map()
|
|
147
|
+
const entryCount = new Map()
|
|
148
|
+
for (const f of files) {
|
|
149
|
+
if (f.kind !== "code") continue
|
|
150
|
+
const n = inboundOfFile.get(f.path) ?? 0
|
|
151
|
+
const chain = ancestors(parentOf(f.path))
|
|
152
|
+
if (n === 0) {
|
|
153
|
+
for (const a of chain) entryCount.set(a, (entryCount.get(a) ?? 0) + 1)
|
|
154
|
+
continue
|
|
155
|
+
}
|
|
156
|
+
for (const a of chain) {
|
|
157
|
+
const cur = hub.get(a)
|
|
158
|
+
if (!cur || n > cur.count || (n === cur.count && f.path.localeCompare(cur.file) < 0)) {
|
|
159
|
+
hub.set(a, { file: f.path, count: n })
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
return { crossInbound, hub, entries: entryCount, cycles: findDirCycles(dirDeps), inboundOfFile }
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* 子树内入度最高几个源码档(`hubs: name(492)`)。`ls` 的目录行用 Top2、`tree` 用 Top1;
|
|
169
|
+
* 两处必须同源:数来自 `buildDirSignals` 交回的 `inboundOfFile`(DISTINCT src,dst · code→code),
|
|
170
|
+
* 排序也与 `hub` 那条判据一致(度数降序、同度按路径升序)——否则同一个档在两个工具里写出两个数。
|
|
171
|
+
*/
|
|
172
|
+
export function topInbound(files, inboundOfFile, n = 2) {
|
|
173
|
+
const out = []
|
|
174
|
+
for (const file of files) {
|
|
175
|
+
const count = inboundOfFile.get(file) ?? 0
|
|
176
|
+
if (count > 0) out.push({ file, count })
|
|
177
|
+
}
|
|
178
|
+
out.sort((a, b) => b.count - a.count || a.file.localeCompare(b.file))
|
|
179
|
+
return out.slice(0, n)
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** 目录级环:三色 DFS(与 `doc-graph.mjs` 的 overview 同一实现,方向 = 依赖方向)。 */
|
|
183
|
+
function findDirCycles(dirDeps) {
|
|
184
|
+
const WHITE = 0
|
|
185
|
+
const GRAY = 1
|
|
186
|
+
const BLACK = 2
|
|
187
|
+
const color = new Map()
|
|
188
|
+
const raw = []
|
|
189
|
+
const path = []
|
|
190
|
+
const dfs = (node) => {
|
|
191
|
+
color.set(node, GRAY)
|
|
192
|
+
path.push(node)
|
|
193
|
+
for (const nxt of [...(dirDeps.get(node) ?? [])].sort()) {
|
|
194
|
+
const c = color.get(nxt) ?? WHITE
|
|
195
|
+
if (c === WHITE) dfs(nxt)
|
|
196
|
+
else if (c === GRAY) {
|
|
197
|
+
const at = path.indexOf(nxt)
|
|
198
|
+
if (at >= 0) raw.push([...path.slice(at)])
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
path.pop()
|
|
202
|
+
color.set(node, BLACK)
|
|
203
|
+
}
|
|
204
|
+
for (const d of [...dirDeps.keys()].sort()) {
|
|
205
|
+
if ((color.get(d) ?? WHITE) === WHITE) dfs(d)
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const out = []
|
|
209
|
+
const seen = new Set()
|
|
210
|
+
for (const nodes of raw) {
|
|
211
|
+
const lca = commonPrefix(nodes)
|
|
212
|
+
// 标签取「LCA 之下第一段」:`case↔doc` 读得出是 v2 下的两个子目录;跨库环则落到仓根,
|
|
213
|
+
// 标签变成 `bms_v2↔bms_op`——那不是失败,是那个环真的横跨两大目录。
|
|
214
|
+
const keys = []
|
|
215
|
+
for (const n of nodes) {
|
|
216
|
+
// LCA 自身也可能是环里的节点(`procedures → v2_acc/… → procedures`)——那样标签若只写
|
|
217
|
+
// 剩下的那一段,读者看不出对端是谁;记 `自身` 才读得出「这层和它下面某层互相依赖」。
|
|
218
|
+
const seg = n === lca ? "自身" : n.slice(lca === "" ? 0 : lca.length + 1).split("/")[0]
|
|
219
|
+
if (seg && !keys.includes(seg)) keys.push(seg)
|
|
220
|
+
}
|
|
221
|
+
const id = `${lca}\u0000${keys.join("\u0000")}`
|
|
222
|
+
if (seen.has(id)) continue
|
|
223
|
+
seen.add(id)
|
|
224
|
+
const shown = keys.slice(0, 3).join("↔")
|
|
225
|
+
out.push({ lca, nodes, label: keys.length > 3 ? `${shown}+${keys.length - 3}` : shown })
|
|
226
|
+
}
|
|
227
|
+
return out
|
|
228
|
+
}
|