@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,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* doc-graph/rebuild-cmd.mjs — `thincoder graph rebuild` 的命令面(`#65-4` 的显式入口)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么需要它:`edges` 是从 `files` / `exports` / `raw_refs` 重建出来的派生态。边语义改过之后、
|
|
5
|
+
* 或 `edges` 与 raw 面漂了的时候,原先唯一的重算入口是 `syncGraph(..., { forceRebuild: true })`
|
|
6
|
+
* ——那是**全档重抽**(重读并重解析每一个源档),代价远大于一次边重建。
|
|
7
|
+
*
|
|
8
|
+
* 界线说清:本命令只从**已落库的 `raw_refs`** 重算边,不读源档。源档改过(新增 / 删掉一条头注)
|
|
9
|
+
* 仍要让一次查询触发 `syncGraph` 重新解析 —— 回执与设计档同此口径,不写成「改了源档跑一下就好」。
|
|
10
|
+
*
|
|
11
|
+
* 判根:`--root` 缺省时按 cwd 上溯(`resolveQueryRoot`);判不出项目根就不猜 —— 在对的仓上重建是维护,
|
|
12
|
+
* 在对的仓之外重建是白改一个缓存库。库不存在(还没查过图谱)也直接报错,不去凭空建一个空库。
|
|
13
|
+
*/
|
|
14
|
+
import { existsSync } from "node:fs"
|
|
15
|
+
import { resolve } from "node:path"
|
|
16
|
+
|
|
17
|
+
const USAGE = "Usage: thincoder graph rebuild [--root <dir>]"
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* 只重建边表。
|
|
21
|
+
* @param {string[]} args `graph rebuild` 之后的参数
|
|
22
|
+
* @returns {Promise<number>} 进程退出码(0 成 ∥ 1 参数错 / 判根失败 / 库不存在)
|
|
23
|
+
*/
|
|
24
|
+
export async function runGraphRebuild(args = []) {
|
|
25
|
+
const argv = Array.isArray(args) ? args.slice() : []
|
|
26
|
+
let root = null
|
|
27
|
+
|
|
28
|
+
for (let i = 0; i < argv.length; i++) {
|
|
29
|
+
const a = argv[i]
|
|
30
|
+
if (a === "--root") {
|
|
31
|
+
const d = argv[++i]
|
|
32
|
+
if (!d) {
|
|
33
|
+
console.error(`[graph rebuild] --root 需要一个路径\n${USAGE}`)
|
|
34
|
+
return 1
|
|
35
|
+
}
|
|
36
|
+
root = resolve(d)
|
|
37
|
+
continue
|
|
38
|
+
}
|
|
39
|
+
console.error(`[graph rebuild] 未知参数 ${JSON.stringify(a)}\n${USAGE}`)
|
|
40
|
+
return 1
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
let target = root
|
|
44
|
+
if (!target) {
|
|
45
|
+
try {
|
|
46
|
+
const mod = await import("../doc-graph.mjs")
|
|
47
|
+
const r = mod.resolveQueryRoot(process.cwd())
|
|
48
|
+
if (!r.ok) {
|
|
49
|
+
console.error(`[graph rebuild] 判不出项目根(${r.reason === "missing" ? "cwd 不存在" : "多项目父工作区"})—— 传 --root <dir> 指名\n${USAGE}`)
|
|
50
|
+
return 1
|
|
51
|
+
}
|
|
52
|
+
target = r.root
|
|
53
|
+
} catch (err) {
|
|
54
|
+
console.error(`[graph rebuild] 判根失败:${String(err?.message ?? err)}\n${USAGE}`)
|
|
55
|
+
return 1
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const { graphDbPath, rebuildEdgesOnly } = await import("./store.mjs")
|
|
60
|
+
if (!existsSync(graphDbPath(target))) {
|
|
61
|
+
console.error(`[graph rebuild] ${target} 还没有图谱库 —— 先对这个仓调一次 repo_graph(任意动作)建库,再重建边表`)
|
|
62
|
+
return 1
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const out = rebuildEdgesOnly(target)
|
|
66
|
+
if (out.files === 0) {
|
|
67
|
+
// 库档在、但 raw 面是空的:典型来路是旧 schema(`openGraphDb` 已按版本清表)或半途留下的空库。
|
|
68
|
+
// 这不是「重建成功」,而是这张库没有可重建的原料 —— 按失败报,否则用户会把 `档 0 · 边 0` 读成做完了。
|
|
69
|
+
console.error(`[graph rebuild] ${target} 的图谱库没有可用 raw 面(0 档)—— 先对这个仓调一次 repo_graph 重建库,再谈边表`)
|
|
70
|
+
return 1
|
|
71
|
+
}
|
|
72
|
+
console.log(`[graph rebuild] ${target} · 档 ${out.files} · 边 ${out.edges} · ${out.ms}ms`)
|
|
73
|
+
console.log("[graph rebuild] 只从已落库的 raw_refs 重算边,未重读源档;源档改过请先查询一次触发 sync")
|
|
74
|
+
return 0
|
|
75
|
+
}
|
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* doc-graph/resolvers.mjs — 跨档引用的解析:把一条 raw 引用落到仓内真实路径。
|
|
3
|
+
*
|
|
4
|
+
* 五种语言各一支(JS/TS 含 monorepo 与 tsconfig paths、Python、Go、Rust、C# 命名空间由调用方处理),
|
|
5
|
+
* 加文档路径(后缀唯一 / 裸名唯一)与文件查找索引 `buildFileLookup`。
|
|
6
|
+
*
|
|
7
|
+
* 全是纯函数:进 raw 串、出绝对仓内相对路径,不碰库、不落边 —— 落边在 `edges.mjs`。
|
|
8
|
+
*/
|
|
9
|
+
import { existsSync, readFileSync } from "node:fs"
|
|
10
|
+
import { basename, dirname, join } from "node:path"
|
|
11
|
+
|
|
12
|
+
import { isTestFilePath } from "./code-parsers.mjs"
|
|
13
|
+
|
|
14
|
+
const slash = (p) => String(p ?? "").replace(/\\/g, "/")
|
|
15
|
+
|
|
16
|
+
/** 构造文件查找索引(精确路径、无扩展名路径、文件名后缀、C# 命名空间、Go 包目录)。 */
|
|
17
|
+
export function buildFileLookup(files) {
|
|
18
|
+
const exact = new Map() // lowerRel -> rel
|
|
19
|
+
const noExt = new Map() // lowerRelWithoutExt -> [rel]
|
|
20
|
+
const byBase = new Map() // lowerBasename -> [rel]
|
|
21
|
+
const byDir = new Map() // lowerDir -> [rel]
|
|
22
|
+
const byNamespace = new Map() // namespace -> [rel]
|
|
23
|
+
const fileExports = new Map() // rel -> Set<symbol>
|
|
24
|
+
|
|
25
|
+
for (const f of files) {
|
|
26
|
+
const low = f.path.toLowerCase()
|
|
27
|
+
exact.set(low, f.path)
|
|
28
|
+
const stripped = low.replace(/\.[a-z0-9]+$/, "")
|
|
29
|
+
if (!noExt.has(stripped)) noExt.set(stripped, [])
|
|
30
|
+
noExt.get(stripped).push(f.path)
|
|
31
|
+
const base = basename(f.path).toLowerCase()
|
|
32
|
+
if (!byBase.has(base)) byBase.set(base, [])
|
|
33
|
+
byBase.get(base).push(f.path)
|
|
34
|
+
const dir = slash(dirname(f.path)).toLowerCase()
|
|
35
|
+
const normDir = dir === "." ? "" : dir
|
|
36
|
+
if (!byDir.has(normDir)) byDir.set(normDir, [])
|
|
37
|
+
byDir.get(normDir).push(f.path)
|
|
38
|
+
if (f.namespace) {
|
|
39
|
+
if (!byNamespace.has(f.namespace)) byNamespace.set(f.namespace, [])
|
|
40
|
+
byNamespace.get(f.namespace).push(f.path)
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return { exact, noExt, byBase, byDir, byNamespace, fileExports }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function readGoModulePrefix(root) {
|
|
47
|
+
const goMod = join(root, "go.mod")
|
|
48
|
+
if (!existsSync(goMod)) return null
|
|
49
|
+
try {
|
|
50
|
+
const m = /^\s*module\s+(\S+)/m.exec(readFileSync(goMod, "utf8"))
|
|
51
|
+
return m ? m[1].trim() : null
|
|
52
|
+
} catch {
|
|
53
|
+
return null
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function stripJsonc(raw) {
|
|
58
|
+
return String(raw ?? "")
|
|
59
|
+
.replace(/("(?:\\.|[^"\\])*")|\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, (m, str) => (str ? str : ""))
|
|
60
|
+
.replace(/,\s*([}\]])/g, "$1")
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function readJsonLoose(filePath) {
|
|
64
|
+
if (!existsSync(filePath)) return null
|
|
65
|
+
try {
|
|
66
|
+
return JSON.parse(stripJsonc(readFileSync(filePath, "utf8")))
|
|
67
|
+
} catch {
|
|
68
|
+
return null
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function pickPackageEntry(pkgDirRel, pkgJson) {
|
|
73
|
+
const pickTarget = (val) => {
|
|
74
|
+
if (typeof val === "string") return val
|
|
75
|
+
if (val && typeof val === "object") {
|
|
76
|
+
return pickTarget(val.import ?? val.default ?? val.types ?? val.require ?? Object.values(val)[0])
|
|
77
|
+
}
|
|
78
|
+
return null
|
|
79
|
+
}
|
|
80
|
+
let entry = null
|
|
81
|
+
if (typeof pkgJson.exports === "string") entry = pkgJson.exports
|
|
82
|
+
else if (pkgJson.exports && typeof pkgJson.exports === "object") {
|
|
83
|
+
entry = pickTarget(pkgJson.exports["."])
|
|
84
|
+
}
|
|
85
|
+
if (!entry) entry = pkgJson.module ?? pkgJson.main ?? null
|
|
86
|
+
if (typeof entry !== "string" || !entry.trim()) return null
|
|
87
|
+
return slash(join(pkgDirRel, entry.replace(/^\.\//, ""))).toLowerCase()
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* 构建仓内 JS/TS 解析器元数据:
|
|
92
|
+
* 1) Workspace / Monorepo 内部包映射(扫描已索引文件所在目录的祖先 `package.json` 的 `name` + `exports`/`main`);
|
|
93
|
+
* 2) 根 `tsconfig.json` / `tsconfig.base.json` / `jsconfig.json` 的 `compilerOptions.paths` 与 `baseUrl`。
|
|
94
|
+
*/
|
|
95
|
+
export function buildJsResolver(root, files) {
|
|
96
|
+
const pkgDirs = new Set([""])
|
|
97
|
+
for (const f of files) {
|
|
98
|
+
if (f.lang !== "js" && f.lang !== "ts") continue
|
|
99
|
+
const segs = f.path.split("/")
|
|
100
|
+
// 最多探 3 层包目录(覆盖 root / pkg / packages/<group>/<pkg>)
|
|
101
|
+
for (let d = 1; d <= Math.min(3, segs.length - 1); d++) {
|
|
102
|
+
pkgDirs.add(segs.slice(0, d).join("/"))
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
const workspacePkgs = new Map() // pkgName -> { dirRel, entryRel, subpathMap }
|
|
106
|
+
for (const dirRel of pkgDirs) {
|
|
107
|
+
const pkgPath = dirRel ? join(root, dirRel, "package.json") : join(root, "package.json")
|
|
108
|
+
const pkg = readJsonLoose(pkgPath)
|
|
109
|
+
if (!pkg || typeof pkg.name !== "string" || !pkg.name.trim()) continue
|
|
110
|
+
const name = pkg.name.trim()
|
|
111
|
+
const subpathMap = []
|
|
112
|
+
if (pkg.exports && typeof pkg.exports === "object") {
|
|
113
|
+
for (const [k, v] of Object.entries(pkg.exports)) {
|
|
114
|
+
if (!k.startsWith("./")) continue
|
|
115
|
+
const targetStr = typeof v === "string" ? v : (v && typeof v === "object" ? (v.import ?? v.default ?? v.require ?? null) : null)
|
|
116
|
+
if (typeof targetStr === "string") {
|
|
117
|
+
subpathMap.push({ key: k.slice(2), target: targetStr.replace(/^\.\//, "") })
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
workspacePkgs.set(name, {
|
|
122
|
+
dirRel,
|
|
123
|
+
entryRel: pickPackageEntry(dirRel, pkg),
|
|
124
|
+
subpathMap,
|
|
125
|
+
})
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const tsPaths = [] // { prefix, suffix, targets: string[] }
|
|
129
|
+
let baseUrl = ""
|
|
130
|
+
for (const cfgName of ["tsconfig.json", "tsconfig.base.json", "jsconfig.json"]) {
|
|
131
|
+
const cfg = readJsonLoose(join(root, cfgName))
|
|
132
|
+
const co = cfg?.compilerOptions
|
|
133
|
+
if (!co) continue
|
|
134
|
+
if (!baseUrl && typeof co.baseUrl === "string") baseUrl = slash(co.baseUrl).replace(/^\.\//, "").replace(/\/+$/, "")
|
|
135
|
+
if (co.paths && typeof co.paths === "object") {
|
|
136
|
+
for (const [pattern, arr] of Object.entries(co.paths)) {
|
|
137
|
+
if (!Array.isArray(arr) || arr.length === 0) continue
|
|
138
|
+
const star = pattern.indexOf("*")
|
|
139
|
+
const prefix = star >= 0 ? pattern.slice(0, star) : pattern
|
|
140
|
+
const suffix = star >= 0 ? pattern.slice(star + 1) : ""
|
|
141
|
+
tsPaths.push({
|
|
142
|
+
prefix,
|
|
143
|
+
suffix,
|
|
144
|
+
hasStar: star >= 0,
|
|
145
|
+
targets: arr.filter((x) => typeof x === "string"),
|
|
146
|
+
})
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
// 长前缀优先匹配
|
|
151
|
+
tsPaths.sort((a, b) => b.prefix.length - a.prefix.length)
|
|
152
|
+
return { workspacePkgs, tsPaths, baseUrl }
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export function matchJsCandidate(baseLower, lookup) {
|
|
156
|
+
const clean = baseLower.replace(/^\.\//, "")
|
|
157
|
+
if (lookup.exact.has(clean)) return lookup.exact.get(clean)
|
|
158
|
+
const stripped = clean.replace(/\.(?:m?js|cjs|jsx|tsx?)$/i, "")
|
|
159
|
+
for (const cand of [
|
|
160
|
+
`${stripped}.mjs`, `${stripped}.js`, `${stripped}.ts`, `${stripped}.tsx`, `${stripped}.jsx`, `${stripped}.cjs`,
|
|
161
|
+
`${stripped}/index.mjs`, `${stripped}/index.js`, `${stripped}/index.ts`, `${stripped}/index.tsx`,
|
|
162
|
+
`${stripped}/src/index.ts`, `${stripped}/src/index.mjs`, `${stripped}/src/index.js`,
|
|
163
|
+
]) {
|
|
164
|
+
if (lookup.exact.has(cand)) return lookup.exact.get(cand)
|
|
165
|
+
}
|
|
166
|
+
return null
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export function resolveJsImport(fromPath, raw, lookup, jsResolver) {
|
|
170
|
+
if (raw.startsWith(".")) {
|
|
171
|
+
const dir = dirname(fromPath)
|
|
172
|
+
const base = slash(join(dir === "." ? "" : dir, raw)).replace(/^\.\//, "").toLowerCase()
|
|
173
|
+
return matchJsCandidate(base, lookup)
|
|
174
|
+
}
|
|
175
|
+
if (!jsResolver) return null
|
|
176
|
+
|
|
177
|
+
// 1. tsconfig / jsconfig paths(如 @/*、@deepseek-ai/dsh-*)
|
|
178
|
+
for (const rule of jsResolver.tsPaths) {
|
|
179
|
+
let matched = false
|
|
180
|
+
let wildcard = ""
|
|
181
|
+
if (rule.hasStar) {
|
|
182
|
+
if (raw.startsWith(rule.prefix) && raw.endsWith(rule.suffix) && raw.length >= rule.prefix.length + rule.suffix.length) {
|
|
183
|
+
matched = true
|
|
184
|
+
wildcard = raw.slice(rule.prefix.length, raw.length - rule.suffix.length)
|
|
185
|
+
}
|
|
186
|
+
} else if (raw === rule.prefix) {
|
|
187
|
+
matched = true
|
|
188
|
+
}
|
|
189
|
+
if (!matched) continue
|
|
190
|
+
for (const tpl of rule.targets) {
|
|
191
|
+
const sub = rule.hasStar ? tpl.replace("*", wildcard) : tpl
|
|
192
|
+
const joined = jsResolver.baseUrl ? slash(join(jsResolver.baseUrl, sub)) : slash(sub)
|
|
193
|
+
const hit = matchJsCandidate(joined.toLowerCase(), lookup)
|
|
194
|
+
if (hit) return hit
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// 2. Monorepo / Workspace 内部包名(如 @thincoder/core/agent/planning-step.mjs 或 @deepseek-ai/dsh-shell)
|
|
199
|
+
for (const [pkgName, info] of jsResolver.workspacePkgs) {
|
|
200
|
+
if (raw === pkgName) {
|
|
201
|
+
if (info.entryRel) {
|
|
202
|
+
const hit = matchJsCandidate(info.entryRel, lookup)
|
|
203
|
+
if (hit) return hit
|
|
204
|
+
}
|
|
205
|
+
const fallback = matchJsCandidate(info.dirRel ? info.dirRel.toLowerCase() : "index", lookup)
|
|
206
|
+
if (fallback) return fallback
|
|
207
|
+
continue
|
|
208
|
+
}
|
|
209
|
+
if (raw.startsWith(`${pkgName}/`)) {
|
|
210
|
+
const sub = raw.slice(pkgName.length + 1)
|
|
211
|
+
// 先查 package.json exports 子路径映射
|
|
212
|
+
for (const sm of info.subpathMap) {
|
|
213
|
+
if (sm.key === sub) {
|
|
214
|
+
const hit = matchJsCandidate(slash(join(info.dirRel, sm.target)).toLowerCase(), lookup)
|
|
215
|
+
if (hit) return hit
|
|
216
|
+
} else if (sm.key.endsWith("/*")) {
|
|
217
|
+
const kp = sm.key.slice(0, -1)
|
|
218
|
+
if (sub.startsWith(kp)) {
|
|
219
|
+
const rest = sub.slice(kp.length)
|
|
220
|
+
const mapped = sm.target.replace("*", rest)
|
|
221
|
+
const hit = matchJsCandidate(slash(join(info.dirRel, mapped)).toLowerCase(), lookup)
|
|
222
|
+
if (hit) return hit
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
// 直接按包目录 + 子路径解析(覆盖 @thincoder/core/agent/relay-prefix.mjs 与 src/ 子路径)
|
|
227
|
+
const direct = matchJsCandidate(slash(join(info.dirRel, sub)).toLowerCase(), lookup)
|
|
228
|
+
if (direct) return direct
|
|
229
|
+
const viaSrc = matchJsCandidate(slash(join(info.dirRel, "src", sub)).toLowerCase(), lookup)
|
|
230
|
+
if (viaSrc) return viaSrc
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return null
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export function resolvePyImport(fromPath, raw, lookup) {
|
|
237
|
+
const dir = dirname(fromPath)
|
|
238
|
+
let base
|
|
239
|
+
if (raw.startsWith(".")) {
|
|
240
|
+
const dots = raw.match(/^\.+/)[0].length
|
|
241
|
+
const rest = raw.slice(dots).replace(/\./g, "/")
|
|
242
|
+
const up = "../".repeat(Math.max(0, dots - 1))
|
|
243
|
+
base = slash(join(dir === "." ? "" : dir, `${up}${rest}`)).replace(/^\.\//, "").toLowerCase()
|
|
244
|
+
} else {
|
|
245
|
+
base = raw.replace(/\./g, "/").toLowerCase()
|
|
246
|
+
}
|
|
247
|
+
for (const cand of [`${base}.py`, `${base}/__init__.py`]) {
|
|
248
|
+
if (lookup.exact.has(cand)) return lookup.exact.get(cand)
|
|
249
|
+
}
|
|
250
|
+
return null
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export function resolveGoImport(raw, goMod, lookup) {
|
|
254
|
+
let sub = raw
|
|
255
|
+
if (goMod && (raw === goMod || raw.startsWith(`${goMod}/`))) {
|
|
256
|
+
sub = raw.slice(goMod.length).replace(/^\//, "")
|
|
257
|
+
} else if (!raw.startsWith(".")) {
|
|
258
|
+
// 尝试按目录尾段精确匹配本地包目录
|
|
259
|
+
const low = raw.toLowerCase()
|
|
260
|
+
if (!lookup.byDir.has(low)) return []
|
|
261
|
+
sub = raw
|
|
262
|
+
}
|
|
263
|
+
const files = lookup.byDir.get(sub.toLowerCase()) ?? []
|
|
264
|
+
return files.filter((p) => p.endsWith(".go") && !isTestFilePath(p))
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
export function resolveRustImport(fromPath, raw, lookup) {
|
|
268
|
+
const dir = dirname(fromPath)
|
|
269
|
+
if (raw.startsWith("mod:")) {
|
|
270
|
+
const name = raw.slice(4).toLowerCase()
|
|
271
|
+
const baseDir = dir === "." ? "" : dir
|
|
272
|
+
for (const cand of [
|
|
273
|
+
slash(join(baseDir, `${name}.rs`)).toLowerCase(),
|
|
274
|
+
slash(join(baseDir, name, "mod.rs")).toLowerCase(),
|
|
275
|
+
]) {
|
|
276
|
+
if (lookup.exact.has(cand)) return lookup.exact.get(cand)
|
|
277
|
+
}
|
|
278
|
+
return null
|
|
279
|
+
}
|
|
280
|
+
const segs = raw.split("::").map((s) => s.replace(/\{.*$/, "").trim()).filter(Boolean)
|
|
281
|
+
if (segs.length < 2) return null
|
|
282
|
+
let baseDir = ""
|
|
283
|
+
if (segs[0] === "crate") baseDir = fromPath.startsWith("src/") ? "src" : ""
|
|
284
|
+
else if (segs[0] === "self") baseDir = dir === "." ? "" : dir
|
|
285
|
+
else if (segs[0] === "super") baseDir = slash(dirname(dir === "." ? "" : dir)).replace(/^\.$/, "")
|
|
286
|
+
const modSegs = segs.slice(1)
|
|
287
|
+
for (let len = modSegs.length; len >= 1; len--) {
|
|
288
|
+
const sub = modSegs.slice(0, len).join("/").toLowerCase()
|
|
289
|
+
for (const cand of [
|
|
290
|
+
slash(join(baseDir, `${sub}.rs`)).toLowerCase(),
|
|
291
|
+
slash(join(baseDir, sub, "mod.rs")).toLowerCase(),
|
|
292
|
+
]) {
|
|
293
|
+
if (lookup.exact.has(cand)) return lookup.exact.get(cand)
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
return null
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
export function resolveDocPath(fromDoc, raw, lookup) {
|
|
300
|
+
const norm = slash(raw).replace(/^\.\//, "").toLowerCase()
|
|
301
|
+
if (lookup.exact.has(norm)) return lookup.exact.get(norm)
|
|
302
|
+
// 相对当前文档目录解析
|
|
303
|
+
const fromDir = dirname(fromDoc)
|
|
304
|
+
if (fromDir && fromDir !== ".") {
|
|
305
|
+
const relJoined = slash(join(fromDir, raw)).replace(/^\.\//, "").toLowerCase()
|
|
306
|
+
if (lookup.exact.has(relJoined)) return lookup.exact.get(relJoined)
|
|
307
|
+
}
|
|
308
|
+
// 后缀唯一匹配(如文档里写 `agent/planning-step.mjs` 匹配 `thincoder-core/agent/planning-step.mjs`)
|
|
309
|
+
if (norm.includes("/")) {
|
|
310
|
+
const suffix = `/${norm}`
|
|
311
|
+
const hits = []
|
|
312
|
+
for (const [k, v] of lookup.exact) {
|
|
313
|
+
if (k.endsWith(suffix)) hits.push(v)
|
|
314
|
+
}
|
|
315
|
+
if (hits.length === 1) return hits[0]
|
|
316
|
+
} else {
|
|
317
|
+
// 裸文件名仅当全仓唯一时匹配(防 README.md 等重名误连)
|
|
318
|
+
const hits = lookup.byBase.get(norm) ?? []
|
|
319
|
+
if (hits.length === 1) return hits[0]
|
|
320
|
+
}
|
|
321
|
+
return null
|
|
322
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* doc-graph/roots.mjs — 「这次要查哪棵树」的判定(零 sqlite:只读 `node:fs` / `node:path`)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么单独一档:这两个判定与「库怎么建、边怎么落」不是同一件事。消费方(`advisor/run.mjs`、`gc-cmd.mjs`)
|
|
5
|
+
* 经门面 `doc-graph.mjs` 取它们,所以门面的静态闭包会包含本档;本档只读 `node:fs` / `node:path`,
|
|
6
|
+
* 门面静态闭包因此仍不达 `node:sqlite`(W8 契约②)。
|
|
7
|
+
*
|
|
8
|
+
* 三条判定各管一件事,不互相兜底:
|
|
9
|
+
* - `resolveProjectRootForFile`:给一个具体档,向上找它所属的项目根(最近标记);
|
|
10
|
+
* - `discoverSubProjects`:给一个父工作区目录,列出直接子项目;
|
|
11
|
+
* - `resolveQueryRoot`:给一个 `target` 入参,决定「建哪棵树的图」—— 判不出就不猜。
|
|
12
|
+
*/
|
|
13
|
+
import { existsSync, readdirSync, statSync } from "node:fs"
|
|
14
|
+
import { dirname, isAbsolute, join, resolve } from "node:path"
|
|
15
|
+
|
|
16
|
+
export function hasProjectMarker(dir) {
|
|
17
|
+
return existsSync(join(dir, "PROJECT-MANIFEST.json")) || existsSync(join(dir, ".git"))
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* 根据目标文件路径向上定位所属项目根(最近的含 `PROJECT-MANIFEST.json` 或 `.git` 的目录)。
|
|
22
|
+
* 在多项目父工作区(如 `D:\teamcode` 下含多个子仓)中自动落到真实子仓根,避免整父目录超阈值或跨仓失焦。
|
|
23
|
+
*/
|
|
24
|
+
export function resolveProjectRootForFile(filePath, fallbackRoot) {
|
|
25
|
+
const fb = resolve(String(fallbackRoot ?? "."))
|
|
26
|
+
const raw = String(filePath ?? "").trim()
|
|
27
|
+
if (!raw) return fb
|
|
28
|
+
const abs = isAbsolute(raw) ? resolve(raw) : resolve(fb, raw)
|
|
29
|
+
let cur = existsSync(abs) && statSync(abs).isDirectory() ? abs : dirname(abs)
|
|
30
|
+
while (true) {
|
|
31
|
+
if (hasProjectMarker(cur)) return cur
|
|
32
|
+
const parent = dirname(cur)
|
|
33
|
+
if (parent === cur) break
|
|
34
|
+
cur = parent
|
|
35
|
+
}
|
|
36
|
+
return fb
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 若 `dir` 本身无项目标记,则发现其直接子目录中的项目根(优先含 `PROJECT-MANIFEST.json`,其次 `.git`)。 */
|
|
40
|
+
export function discoverSubProjects(dir) {
|
|
41
|
+
const abs = resolve(String(dir ?? "."))
|
|
42
|
+
if (!existsSync(abs) || hasProjectMarker(abs)) return []
|
|
43
|
+
let entries
|
|
44
|
+
try { entries = readdirSync(abs, { withFileTypes: true }) } catch { return [] }
|
|
45
|
+
const found = []
|
|
46
|
+
for (const e of entries) {
|
|
47
|
+
if (!e.isDirectory()) continue
|
|
48
|
+
if (e.name.startsWith(".") || e.name.startsWith("_") || e.name === "node_modules") continue
|
|
49
|
+
const child = join(abs, e.name)
|
|
50
|
+
const hasManifest = existsSync(join(child, "PROJECT-MANIFEST.json"))
|
|
51
|
+
const hasGit = existsSync(join(child, ".git"))
|
|
52
|
+
if (hasManifest || hasGit) {
|
|
53
|
+
found.push({ name: e.name, root: child, hasManifest })
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return found.sort((a, b) => (Number(b.hasManifest) - Number(a.hasManifest)) || a.name.localeCompare(b.name))
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* 查询根的判定单源(P0-3 `target` 上溯):目标绝对路径 ⇒ 由图谱真正要建的那棵树的根。
|
|
61
|
+
* - 目标不存在 ⇒ `{ ok: false, reason: "missing" }`(调用面据此报错,不静默换成会话锚);
|
|
62
|
+
* - 目标是档 ⇒ 从其目录起算;
|
|
63
|
+
* - 目录带项目标记(`PROJECT-MANIFEST.json` / `.git`)⇒ 就是它;
|
|
64
|
+
* - 自己无标记但祖先链上有 ⇒ **最近**那个(子目录入参自动上溯到项目根,不按子目录建图);
|
|
65
|
+
* - 祖先链也无标记但直接子目录含项目根 ⇒ `{ ok: false, reason: "workspace", candidates }`
|
|
66
|
+
* (多项目父工作区:由调用面决定拒绝还是按既有行为列子仓清单,绝不当一棵树建图);
|
|
67
|
+
* - 以上都不成立 ⇒ 就是它自己(独立目录,不强绑 manifest —— 需求 F3)。
|
|
68
|
+
* @param {string} absTarget 目标绝对路径(目录或档)
|
|
69
|
+
* @returns {{ok: true, root: string} | {ok: false, reason: "missing"|"workspace", abs: string, candidates?: Array<{name: string, root: string, hasManifest: boolean}>}}
|
|
70
|
+
*/
|
|
71
|
+
export function resolveQueryRoot(absTarget) {
|
|
72
|
+
const abs = resolve(String(absTarget ?? "."))
|
|
73
|
+
let st
|
|
74
|
+
try { st = statSync(abs) } catch { return { ok: false, reason: "missing", abs } }
|
|
75
|
+
const dir = st.isDirectory() ? abs : dirname(abs)
|
|
76
|
+
let cur = dir
|
|
77
|
+
while (true) {
|
|
78
|
+
if (hasProjectMarker(cur)) return { ok: true, root: cur }
|
|
79
|
+
const parent = dirname(cur)
|
|
80
|
+
if (parent === cur) break
|
|
81
|
+
cur = parent
|
|
82
|
+
}
|
|
83
|
+
const candidates = discoverSubProjects(dir)
|
|
84
|
+
if (candidates.length > 0) return { ok: false, reason: "workspace", abs: dir, candidates }
|
|
85
|
+
return { ok: true, root: dir }
|
|
86
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* doc-graph/schema.mjs — 图谱库的结构与落盘位置(`openGraphDb` 是唯一建库入口)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么单独一档:库结构(六张表 + 两套 kind 词表)、迁移顺序(补 `symbol` 列**再**建索引)、
|
|
5
|
+
* 版本失配清表、以及 `~/.thincoder/graphs/<sha1(normalizeCwd(root))[:16]>.db` 的路径算法,
|
|
6
|
+
* 原先与「目录扫描 / 导入解析 / 落边 / 增量同步」挤在一档 824 行里。结构改一次要在几个无关话题之间翻。
|
|
7
|
+
*
|
|
8
|
+
* 路径状态只有这一份:`_setGraphDirForTest` 改的是本档的 `graphDir`,`openGraphDb` 读的也是它 ——
|
|
9
|
+
* 测试隔离与生产路径不可能指向两个目录。
|
|
10
|
+
*/
|
|
11
|
+
import { createHash } from "node:crypto"
|
|
12
|
+
import { mkdirSync } from "node:fs"
|
|
13
|
+
import { join, resolve } from "node:path"
|
|
14
|
+
import { DatabaseSync } from "node:sqlite"
|
|
15
|
+
|
|
16
|
+
import { configDir } from "../config-io.mjs"
|
|
17
|
+
import { normalizeCwd } from "../session-slots.mjs"
|
|
18
|
+
|
|
19
|
+
export const GRAPH_SCHEMA_VERSION = 5
|
|
20
|
+
|
|
21
|
+
const DDL = `
|
|
22
|
+
CREATE TABLE IF NOT EXISTS meta (
|
|
23
|
+
key TEXT PRIMARY KEY,
|
|
24
|
+
value TEXT NOT NULL
|
|
25
|
+
);
|
|
26
|
+
CREATE TABLE IF NOT EXISTS files (
|
|
27
|
+
path TEXT PRIMARY KEY,
|
|
28
|
+
kind TEXT NOT NULL,
|
|
29
|
+
lang TEXT NOT NULL,
|
|
30
|
+
mtime_ms REAL NOT NULL,
|
|
31
|
+
size INTEGER NOT NULL,
|
|
32
|
+
lines INTEGER NOT NULL,
|
|
33
|
+
namespace TEXT
|
|
34
|
+
);
|
|
35
|
+
CREATE TABLE IF NOT EXISTS exports (
|
|
36
|
+
file TEXT NOT NULL,
|
|
37
|
+
symbol TEXT NOT NULL,
|
|
38
|
+
PRIMARY KEY (file, symbol)
|
|
39
|
+
);
|
|
40
|
+
CREATE INDEX IF NOT EXISTS idx_exports_symbol ON exports(symbol);
|
|
41
|
+
CREATE TABLE IF NOT EXISTS raw_refs (
|
|
42
|
+
file TEXT NOT NULL,
|
|
43
|
+
kind TEXT NOT NULL,
|
|
44
|
+
raw TEXT NOT NULL,
|
|
45
|
+
detail TEXT NOT NULL,
|
|
46
|
+
line INTEGER NOT NULL
|
|
47
|
+
);
|
|
48
|
+
CREATE INDEX IF NOT EXISTS idx_raw_refs_file ON raw_refs(file);
|
|
49
|
+
CREATE TABLE IF NOT EXISTS edges (
|
|
50
|
+
src TEXT NOT NULL,
|
|
51
|
+
dst TEXT NOT NULL,
|
|
52
|
+
kind TEXT NOT NULL,
|
|
53
|
+
detail TEXT NOT NULL,
|
|
54
|
+
line INTEGER NOT NULL,
|
|
55
|
+
state TEXT NOT NULL,
|
|
56
|
+
symbol TEXT NOT NULL DEFAULT '',
|
|
57
|
+
PRIMARY KEY (src, dst, kind, detail)
|
|
58
|
+
);
|
|
59
|
+
CREATE INDEX IF NOT EXISTS idx_edges_src ON edges(src);
|
|
60
|
+
CREATE INDEX IF NOT EXISTS idx_edges_dst ON edges(dst);
|
|
61
|
+
CREATE TABLE IF NOT EXISTS headings (
|
|
62
|
+
file TEXT NOT NULL,
|
|
63
|
+
title TEXT NOT NULL,
|
|
64
|
+
level INTEGER NOT NULL,
|
|
65
|
+
line INTEGER NOT NULL
|
|
66
|
+
);
|
|
67
|
+
CREATE INDEX IF NOT EXISTS idx_headings_file ON headings(file);
|
|
68
|
+
`
|
|
69
|
+
|
|
70
|
+
let graphDir = join(configDir, "graphs")
|
|
71
|
+
export function _setGraphDirForTest(dir) { graphDir = dir }
|
|
72
|
+
export function _resetGraphDirForTest() { graphDir = join(configDir, "graphs") }
|
|
73
|
+
/** 图库目录(`thincoder graph gc` 的唯一取法——不另造第二份路径来源)。 */
|
|
74
|
+
export function graphDirPath() { return graphDir }
|
|
75
|
+
|
|
76
|
+
export function graphKey(root) {
|
|
77
|
+
return createHash("sha1").update(normalizeCwd(resolve(root))).digest("hex").slice(0, 16)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function graphDbPath(root) {
|
|
81
|
+
return join(graphDir, `${graphKey(root)}.db`)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* 唯一建库入口:开库 + DDL + 迁移(补 `symbol` 列 → 建索引 → 版本失配清表),返回裸 `DatabaseSync`。
|
|
86
|
+
* **内部建库面**——只做「打开或建出一张结构最新的空库」,不解析任何源档。
|
|
87
|
+
* 调用方二分:① 同步门面 `store.mjs` 的 `syncGraph` / `rebuildEdgesOnly`(要先解析落库请走它们,
|
|
88
|
+
* 返回形 = `{ db, …读数 }`);② 已知库新鲜的直调方(`gc-cmd.mjs` 只读、`rebuild-cmd.mjs` 配合重算)。
|
|
89
|
+
*/
|
|
90
|
+
export function openGraphDb(root) {
|
|
91
|
+
mkdirSync(graphDir, { recursive: true })
|
|
92
|
+
const dbPath = graphDbPath(root)
|
|
93
|
+
const db = new DatabaseSync(dbPath)
|
|
94
|
+
db.exec("PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA busy_timeout = 3000;")
|
|
95
|
+
db.exec(DDL)
|
|
96
|
+
// P0-1 迁移:`CREATE TABLE IF NOT EXISTS` 不会给既有表补列,旧库(schema 4 及以前)的 `edges`
|
|
97
|
+
// 没有 `symbol`。这里补一列;版本失配路径随后会清空行并由全量重建填回(不依赖行级迁移)。
|
|
98
|
+
const edgeCols = db.prepare("PRAGMA table_info(edges)").all().map((c) => c.name)
|
|
99
|
+
if (!edgeCols.includes("symbol")) {
|
|
100
|
+
db.exec("ALTER TABLE edges ADD COLUMN symbol TEXT NOT NULL DEFAULT ''")
|
|
101
|
+
}
|
|
102
|
+
// 符号索引建在补列之后:旧库若先建索引会因缺列直接抛错(DDL 在迁移前执行)。
|
|
103
|
+
db.exec("CREATE INDEX IF NOT EXISTS idx_edges_symbol ON edges(symbol)")
|
|
104
|
+
const ver = db.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get()?.value
|
|
105
|
+
if (String(ver ?? "") !== String(GRAPH_SCHEMA_VERSION)) {
|
|
106
|
+
db.exec("DELETE FROM files; DELETE FROM exports; DELETE FROM raw_refs; DELETE FROM edges; DELETE FROM headings;")
|
|
107
|
+
db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES ('schema_version', ?)").run(String(GRAPH_SCHEMA_VERSION))
|
|
108
|
+
}
|
|
109
|
+
return db
|
|
110
|
+
}
|