dsh-knit 0.20.0 → 0.22.0

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/src/host/links.js CHANGED
@@ -35,38 +35,56 @@
35
35
  /** 解析一篇正文时最多认多少条候选,防御性上限(正常文档远低于此)。 */
36
36
  const MAX_REFS_PER_DOC = 500
37
37
 
38
+ /** 行首偏移表 + 二分:把「字符下标」换成 1 起的行号(同一篇正文只建一次)。 */
39
+ function startsOf(text) {
40
+ const starts = [0]
41
+ for (let i = 0; i < text.length; i++) if (text.charCodeAt(i) === 10) starts.push(i + 1)
42
+ return starts
43
+ }
44
+ function lineAt(starts, idx) {
45
+ let lo = 0
46
+ let hi = starts.length - 1
47
+ while (lo < hi) {
48
+ const mid = (lo + hi + 1) >> 1
49
+ if (starts[mid] <= idx) lo = mid
50
+ else hi = mid - 1
51
+ }
52
+ return lo + 1
53
+ }
54
+
38
55
  /**
39
- * 从正文里抽出**候选**引用(还没解析成 rel)。
40
- *
41
- * 三种真实写法,按语料出现频次排:
42
- * 1. 反引号包裹的路径 —— `` `docs/A.md` ``(946 次,主力)
43
- * 2. 标准 Markdown 链接 —— `[文字](docs/A.md)`(15 次)
44
- * 3. 裸路径提及 —— `见 docs/A.md`(前面必须是空白或括号,避免咬到 `a.md.bak` 这类)
56
+ * 与 `extractRefs()` **同一套规则、同一套顺序**,只是额外给出每一处提及的真实行号。
45
57
  *
46
- * **不含 `[[wikilink]]`** —— 真实语料 0 次,不做。
58
+ * v0.21 新增,唯一理由:关系投影要的是「第几行」(`{type, dir, other, line}`),
59
+ * 而证据必须能按 `other` + `line` 读回原文核验(需求 §6.8)。**不另写一套解析**。
47
60
  *
48
- * @param {string} text - 正文(原文,**不是**小写化的 haystack)
49
- * @returns {string[]} 去重后的候选项,保持出现顺序
61
+ * @param {string} text - 正文(原文)
62
+ * @param {{anyExt?: boolean}} [options] - 同 `extractRefs()`
63
+ * @returns {Array<{raw: string, line: number}>} 去重(保留首次出现),保持出现顺序
50
64
  */
51
- export function extractRefs(text) {
65
+ export function extractRefsWithLines(text, options = {}) {
52
66
  if (typeof text !== 'string' || text === '') return []
67
+ const anyExt = !!(options && options.anyExt === true)
68
+ const starts = startsOf(text)
53
69
  const out = []
54
70
  const seen = new Set()
55
- const push = (raw) => {
71
+ const push = (whole, raw, at) => {
56
72
  const v = String(raw || '').trim()
57
73
  if (!v || seen.has(v)) return
58
74
  if (out.length >= MAX_REFS_PER_DOC) return
59
75
  // 外链不是本工作区的文档
60
76
  if (/^[a-z][a-z0-9+.-]*:/i.test(v)) return
61
- if (!/\.md$/i.test(v)) return
77
+ if (anyExt ? !/\.[A-Za-z0-9]+$/.test(v) : !/\.md$/i.test(v)) return
62
78
  seen.add(v)
63
- out.push(v)
79
+ // 命中的是整个 match(含边界字符 / 反引号),路径在它里面的偏移要算上
80
+ const off = Math.max(0, whole.indexOf(String(raw)))
81
+ out.push({ raw: v, line: lineAt(starts, at + off) })
64
82
  }
65
83
 
66
84
  // ① 反引号:允许空格(`00_ Knit PRD/x.md` 这种目录名真实存在),不允许换行/反引号
67
- for (const m of text.matchAll(/`([^`\n]+?)`/g)) push(m[1])
85
+ for (const m of text.matchAll(/`([^`\n]+?)`/g)) push(m[0], m[1], m.index)
68
86
  // ② Markdown 链接:取 () 里的路径,忽略其后的 #锚点
69
- for (const m of text.matchAll(/\]\(\s*([^)\s]+?)(?:#[^)\s]*)?\s*\)/g)) push(m[1])
87
+ for (const m of text.matchAll(/\]\(\s*([^)\s]+?)(?:#[^)\s]*)?\s*\)/g)) push(m[0], m[1], m.index)
70
88
  // ③ 裸路径:前面是行首/空白/中文括号,路径本身不含空格(有空格就得用反引号),
71
89
  // 末尾用 `(?![\w.])` 挡住 `a.md.bak` 这类「更长但不是 .md」的字符串
72
90
  //
@@ -76,12 +94,35 @@ export function extractRefs(text) {
76
94
  const masked = text
77
95
  .replace(/`[^`\n]*`/g, (s) => ' '.repeat(s.length))
78
96
  .replace(/\]\([^)\n]*\)/g, (s) => ' '.repeat(s.length))
79
- const BARE = /(?:^|[\s((])((?:[\w\u4e00-\u9fa5.@+-]+\/)*[\w\u4e00-\u9fa5.@+-]+\.md)(?![\w.])/gm
80
- for (const m of masked.matchAll(BARE)) push(m[1])
97
+ const BARE = anyExt
98
+ // v0.21:同样的「裸路径」写法,只是目标不再限定 `.md`(`documents` 要认代码路径)。
99
+ ? /(?:^|[\s((])((?:[\w\u4e00-\u9fa5.@+-]+\/)*[\w\u4e00-\u9fa5.@+-]+\.[A-Za-z0-9]+)(?![\w.])/gm
100
+ : /(?:^|[\s((])((?:[\w\u4e00-\u9fa5.@+-]+\/)*[\w\u4e00-\u9fa5.@+-]+\.md)(?![\w.])/gm
101
+ for (const m of masked.matchAll(BARE)) push(m[0], m[1], m.index)
81
102
 
82
103
  return out
83
104
  }
84
105
 
106
+ /**
107
+ * 从正文里抽出**候选**引用(还没解析成 rel)。
108
+ *
109
+ * 三种真实写法,按语料出现频次排:
110
+ * 1. 反引号包裹的路径 —— `` `docs/A.md` ``(946 次,主力)
111
+ * 2. 标准 Markdown 链接 —— `[文字](docs/A.md)`(15 次)
112
+ * 3. 裸路径提及 —— `见 docs/A.md`(前面必须是空白或括号,避免咬到 `a.md.bak` 这类)
113
+ *
114
+ * **不含 `[[wikilink]]`** —— 真实语料 0 次,不做。
115
+ *
116
+ * @param {string} text - 正文(原文,**不是**小写化的 haystack)
117
+ * @param {{anyExt?: boolean}} [options] - v0.21:`anyExt` 把**目标**放开到「任何带扩展名的文件」
118
+ * (只给关系层的 `documents` 用:md → 代码)。默认**一个字不改** —— v0.12 的引用图与
119
+ * `test/code-context.test.mjs` 那条「代码只能被指向、不能当源」的守卫原样通过。
120
+ * @returns {string[]} 去重后的候选项,保持出现顺序
121
+ */
122
+ export function extractRefs(text, options = {}) {
123
+ return extractRefsWithLines(text, options).map((hit) => hit.raw)
124
+ }
125
+
85
126
  /** rel 用 `/` 连接(`index.js` 保证),所以这里也按 `/` 取目录,不碰 `node:path`。 */
86
127
  const dirOf = (rel) => {
87
128
  const i = String(rel).lastIndexOf('/')
@@ -125,13 +166,15 @@ export function createIndex(rels) {
125
166
  * @param {string} raw - 候选项
126
167
  * @param {object} index - `createIndex()` 的产物
127
168
  * @param {string} [referrerRel] - 引用方的 rel;不传则跳过第 1 步
169
+ * @param {{anyExt?: boolean}} [options] - v0.21:与 `extractRefs()` 同一个显式开关(默认只认 `.md`)
128
170
  * @returns {string|null}
129
171
  */
130
- export function resolveRef(raw, index, referrerRel) {
172
+ export function resolveRef(raw, index, referrerRel, options = {}) {
173
+ const anyExt = !!(options && options.anyExt === true)
131
174
  const v = String(raw || '').trim()
132
175
  if (!v || !index || !(index.relSet instanceof Set)) return null
133
176
  if (/^[a-z][a-z0-9+.-]*:/i.test(v)) return null
134
- if (!/\.md$/i.test(v)) return null
177
+ if (anyExt ? !/\.[A-Za-z0-9]+$/.test(v) : !/\.md$/i.test(v)) return null
135
178
 
136
179
  // 去掉 ./ 前缀(`./docs/A.md` 是常见写法,但不是本工作区的 rel)
137
180
  const clean = v.replace(/^\.\//, '')
@@ -170,14 +213,21 @@ const CACHE = new Map()
170
213
  const INFLIGHT = new Map()
171
214
 
172
215
  /**
173
- * 图签名:变了才重建。用「篇数 + 最大 mtime + 是否被扫描上限截断」——
174
- * 三个都便宜(`list()` 本身已经按 mtime 缓存了元信息),且足以发现增删改。
216
+ * 图签名:变了才重建。
217
+ *
218
+ * v0.21(D6)修掉一个真缺陷:原来的键是「篇数 + 最大 mtime + 是否被截断」,
219
+ * **不含候选集身份** —— 同一进程里连跑两个 query,只要候选数相同、最大 mtime 还落在
220
+ * 同一个文件上,第二个 query 就会拿到第一个 query 的图,**关系全部落空**(实测复现)。
221
+ * 现在键 = 每个候选的 `rel` + `mtimeMs`,排序后拼接(候选换了要重建;候选没换但内容改了也要重建)。
222
+ *
223
+ * 不用哈希:碰撞会让关系**静默错配**,而 Knit 的全部价值建立在「可核验」上;
224
+ * 拼一个 ≤1000 项的字符串,成本远低于这条路径上已经付掉的「读几十个文件的 head」。
175
225
  */
176
226
  function signatureOf(listed) {
177
227
  const docs = (listed && listed.docs) || []
178
- let max = 0
179
- for (const d of docs) if (d.mtimeMs > max) max = d.mtimeMs
180
- return `${docs.length}:${max}:${listed && listed.truncated ? 1 : 0}`
228
+ const parts = docs.map((d) => `${d.rel}\u0000${d.mtimeMs}`)
229
+ parts.sort()
230
+ return `${parts.join('\n')}\u0000${listed && listed.truncated ? 1 : 0}`
181
231
  }
182
232
 
183
233
  /**
@@ -205,23 +255,36 @@ export async function buildLinkGraph(root, io) {
205
255
  let skipped = 0
206
256
 
207
257
  for (const doc of docs) {
258
+ // v0.22 修法 ①:条目/索引里已经带了抽取结果就直接用 —— `doc.refs.md` 正是
259
+ // `extractRefs()`(默认口径、只认 `.md` 目标)的产物,连 `io.read()` 都不用调。
260
+ // 没有它时才回落去要文本(旧调用方与单测的假条目走这条路)。
261
+ const cachedRefs = doc.refs && Array.isArray(doc.refs.md) ? doc.refs.md : null
208
262
  let text = ''
209
- try {
210
- const r = await io.read(root, doc.rel)
211
- if (!r || r.ok !== true) {
263
+ if (!cachedRefs) {
264
+ try {
265
+ const r = await io.read(root, doc.rel)
266
+ if (!r || r.ok !== true) {
267
+ skipped += 1
268
+ continue
269
+ }
270
+ text = r.text || ''
271
+ } catch {
212
272
  skipped += 1
213
273
  continue
214
274
  }
215
- text = r.text || ''
216
- } catch {
217
- skipped += 1
218
- continue
219
275
  }
220
276
  parsed += 1
221
277
  const targets = new Set()
222
- for (const raw of extractRefs(text)) {
223
- const rel = resolveRef(raw, index, doc.rel)
224
- if (rel && rel !== doc.rel) targets.add(rel)
278
+ if (cachedRefs) {
279
+ for (const hit of cachedRefs) {
280
+ const rel = resolveRef(hit.raw, index, doc.rel)
281
+ if (rel && rel !== doc.rel) targets.add(rel)
282
+ }
283
+ } else {
284
+ for (const raw of extractRefs(text)) {
285
+ const rel = resolveRef(raw, index, doc.rel)
286
+ if (rel && rel !== doc.rel) targets.add(rel)
287
+ }
225
288
  }
226
289
  out.set(doc.rel, targets)
227
290
  }
@@ -0,0 +1,316 @@
1
+ /**
2
+ * Knit · **关系投影**(v0.21)
3
+ *
4
+ * 回答「这一篇为什么在这个包里」的第二种答案:不是检索命中,而是**与包内某篇有证据级关系**。
5
+ *
6
+ * ## 只做四类,每一类都必须有可核验的证据
7
+ *
8
+ * | type | 边 | 证据怎么来 |
9
+ * |---|---|---|
10
+ * | `references` | md → md | 路径提及(复用 v0.12 的抽取器) |
11
+ * | `documents` | md → 代码 | 同一条抽取,目标**显式**放开到代码 |
12
+ * | `imports` | 代码 → 代码 | 逐行正则 + 相对路径解析 |
13
+ * | `tests` | 测试 ↔ 被测 | 文件名约定,**歧义一律不算** |
14
+ *
15
+ * **不做** `calls`(没有 AST / 符号分析就是猜,且直接撞 v0.19 的禁区)、不建 import 图、
16
+ * 不解析符号、不做 Git provenance(推迟)、不参与排序(需求 §6.3)。
17
+ *
18
+ * ## 这是投影,不是第二个排序阶段
19
+ *
20
+ * 关系在 Context Pack **装配完成之后**才对**包内条目**投影:不改名次、不改分层、
21
+ * 不把任何一篇「拉进」包里。它的唯一用途是**解释**。
22
+ *
23
+ * ## 零 I/O
24
+ *
25
+ * 用的是排序器手里**已经有**的那份文本(md 的 `head` = 16 KB、代码的 `head` = 8 KB)。
26
+ * 本模块不读盘、不 spawn 子进程、不发网络请求。
27
+ *
28
+ * ## `line` 的语义
29
+ *
30
+ * `{ type, dir, other, line }` 里 `line` 是**提及所在文件的真实行号**:
31
+ * `dir:'out'` 时在本项文件里,`dir:'in'` 时在 `other` 文件里。
32
+ * `tests` 是**唯一没有 `line`** 的一类 —— 它的证据是文件名约定(一条可核验的路径事实),
33
+ * 不是某一行的文字,所以如实不给行号,而不是编一个出来。
34
+ */
35
+
36
+ import { createIndex, extractRefsWithLines, resolveRef } from './links.js'
37
+
38
+ /** 与 `links.js` 里那两个私有 helper 同一口径(那边不导出,这里只需要两行)。 */
39
+ const dirOf = (rel) => {
40
+ const i = String(rel).lastIndexOf('/')
41
+ return i < 0 ? '' : String(rel).slice(0, i)
42
+ }
43
+ const baseOf = (rel) => {
44
+ const i = String(rel).lastIndexOf('/')
45
+ return i < 0 ? String(rel) : String(rel).slice(i + 1)
46
+ }
47
+
48
+ /** 面板每项最多投影几条关系(§6.7 / D4:这是**预算约束**,不是建议)。 */
49
+ export const MAX_RELATIONS_PER_ITEM = 3
50
+
51
+ /** `knit_docs` 每项最多投影几条(§9:工具输出比面板更贵)。 */
52
+ export const MAX_TOOL_RELATIONS_PER_ITEM = 2
53
+
54
+ /** 四类关系,**这个顺序就是截断优先级**(需求 §6.2 的 ① ② ③ ④)。 */
55
+ export const RELATION_TYPES = ['references', 'imports', 'tests', 'documents']
56
+
57
+ const TYPE_RANK = new Map(RELATION_TYPES.map((t, i) => [t, i]))
58
+
59
+ /** `imports` 补全扩展名的顺序 —— 固定顺序本身就是确定性的一部分。 */
60
+ const EXTS = ['mjs', 'js', 'cjs', 'ts', 'tsx', 'jsx', 'md']
61
+
62
+ /**
63
+ * 逐行正则:`import … from '…'` / 裸 `import '…'` / `require('…')` 三种真实写法。
64
+ * 已在真数据上验证(它抓出来的第一件事就是 v0.20.1 那条包装缺陷本身)。
65
+ *
66
+ * ⚠️ 行首缩进用 `[^\S\n]*`(只吃空格与制表符),**不能用 `\s*`** —— `\s` 会吃掉前一行的
67
+ * 换行,`m.index` 就落到上一行末尾,行号整体少 1。这是测试抓出来的,不是假想。
68
+ */
69
+ const IMPORT_RE = /^[^\S\n]*(?:import\s[^\n]*?from\s*|import\s*|(?:const|let|var)\s[^\n]*?=\s*require\s*\()\s*['"]([^'"]+)['"]/gm
70
+
71
+ const isMd = (rel) => /\.md$/i.test(String(rel))
72
+ /** 测试文件的两种真实命名:`x.test.mjs` / `x.spec.js`。 */
73
+ const isTestRel = (rel) => /\.(?:test|spec)\.[A-Za-z0-9]+$/.test(String(rel))
74
+
75
+ /**
76
+ * 从代码正文里抽出**相对**导入指定符及其行号。纯函数,零 I/O。
77
+ *
78
+ * 裸指定符(`node:test`、`react`)也如实返回 —— 过滤交给 `resolveSpec()`,
79
+ * 那里才知道候选集里有什么。
80
+ *
81
+ * @param {string} text - 代码正文(原文)
82
+ * @returns {Array<{spec: string, line: number}>} 去重(保留首次出现),按出现顺序
83
+ */
84
+ export function importsOf(text) {
85
+ if (typeof text !== 'string' || text === '') return []
86
+ const out = []
87
+ const seen = new Set()
88
+ let line = 1
89
+ let from = 0
90
+ for (const m of text.matchAll(IMPORT_RE)) {
91
+ // 行号增量数出来(matchAll 的下标天然升序,所以一次线性扫描就够)
92
+ for (let i = from; i < m.index; i++) if (text.charCodeAt(i) === 10) line += 1
93
+ from = m.index
94
+ const spec = m[1]
95
+ if (seen.has(spec)) continue
96
+ seen.add(spec)
97
+ out.push({ spec, line })
98
+ }
99
+ return out
100
+ }
101
+
102
+ /**
103
+ * 把 `fromRel` 与一个相对路径拼成工作区 rel。**出了工作区就返回 null**
104
+ * (`../../../etc/passwd` 这类不产生关系,也不做任何「猜一个」)。
105
+ */
106
+ function joinRel(fromRel, spec) {
107
+ const dir = dirOf(fromRel)
108
+ const parts = (dir ? dir.split('/') : []).concat(String(spec).split('/'))
109
+ const stack = []
110
+ for (const p of parts) {
111
+ if (p === '' || p === '.') continue
112
+ if (p === '..') {
113
+ if (stack.length === 0) return null
114
+ stack.pop()
115
+ continue
116
+ }
117
+ stack.push(p)
118
+ }
119
+ return stack.length > 0 ? stack.join('/') : null
120
+ }
121
+
122
+ /**
123
+ * 把一条导入指定符解析成候选集里的 rel。**解析不出来就返回 null**。
124
+ *
125
+ * 只认相对指定符(`./` / `../`)—— 裸指定符是包,不是工作区文件。
126
+ * 扩展名补全顺序:原样 → `.mjs` / `.js` / `.ts` / `.tsx` / `.jsx` / `.md` → `/index.<ext>`。
127
+ *
128
+ * @param {string} spec - 指定符原文
129
+ * @param {string} fromRel - 导入方的 rel
130
+ * @param {object} relIndex - `createIndex()` 的产物(候选集)
131
+ * @returns {string|null}
132
+ */
133
+ export function resolveSpec(spec, fromRel, relIndex) {
134
+ const raw = String(spec || '').trim()
135
+ if (!raw || !relIndex || !(relIndex.relSet instanceof Set)) return null
136
+ if (!raw.startsWith('./') && !raw.startsWith('../')) return null
137
+ const base = joinRel(fromRel, raw)
138
+ if (!base) return null
139
+ if (relIndex.relSet.has(base)) return base
140
+ for (const ext of EXTS) {
141
+ const hit = `${base}.${ext}`
142
+ if (relIndex.relSet.has(hit)) return hit
143
+ }
144
+ for (const ext of EXTS) {
145
+ const hit = `${base}/index.${ext}`
146
+ if (relIndex.relSet.has(hit)) return hit
147
+ }
148
+ return null
149
+ }
150
+
151
+ /**
152
+ * 按文件名约定找「对面那一篇」。**歧义一律不算**(与 v0.12 的 basename 规则同一条纪律):
153
+ * 命中 0 个或多个都返回 `null`。
154
+ *
155
+ * 只有两种写法算数,都是可核验的路径事实:
156
+ * - 测试方 → 被测方:去掉 `.test` / `.spec` 标记后全库同名(去掉扩展名)的**唯一**非测试文件;
157
+ * - 被测方 → 测试方:同目录或 `test/` 下的 `<name>.test|spec.<ext>`,**唯一**的那个。
158
+ *
159
+ * @param {string} rel - 本项
160
+ * @param {object} relIndex - `createIndex()` 的产物(候选集)
161
+ * @returns {string|null}
162
+ */
163
+ export function testsOf(rel, relIndex) {
164
+ const r = String(rel || '')
165
+ if (!r || !relIndex || !Array.isArray(relIndex.rels)) return null
166
+ const stem = (x) => baseOf(x).replace(/\.[A-Za-z0-9]+$/, '')
167
+ if (isTestRel(r)) {
168
+ const name = stem(r).replace(/\.(?:test|spec)$/, '')
169
+ const hits = relIndex.rels.filter((x) => x !== r && !isTestRel(x) && stem(x) === name)
170
+ return hits.length === 1 ? hits[0] : null
171
+ }
172
+ const dir = dirOf(r)
173
+ const name = stem(r)
174
+ const hits = new Set()
175
+ for (const ext of EXTS) {
176
+ for (const mid of ['test', 'spec']) {
177
+ for (const d of dir === 'test' ? ['test'] : [dir, 'test']) {
178
+ const cand = `${d}/${name}.${mid}.${ext}`
179
+ if (relIndex.relSet.has(cand)) hits.add(cand)
180
+ }
181
+ }
182
+ }
183
+ return hits.size === 1 ? [...hits][0] : null
184
+ }
185
+
186
+ /**
187
+ * 截断顺序(确定性,D4):
188
+ * `type` 优先级(`references` > `imports` > `tests` > `documents`)→ `dir`(`in` 先)
189
+ * → `line` 升序 → `other` 字典序。
190
+ */
191
+ function compareFacts(a, b) {
192
+ const ta = TYPE_RANK.has(a.type) ? TYPE_RANK.get(a.type) : 99
193
+ const tb = TYPE_RANK.has(b.type) ? TYPE_RANK.get(b.type) : 99
194
+ if (ta !== tb) return ta - tb
195
+ const da = a.dir === 'in' ? 0 : 1
196
+ const db = b.dir === 'in' ? 0 : 1
197
+ if (da !== db) return da - db
198
+ const la = a.line === undefined ? Number.MAX_SAFE_INTEGER : a.line
199
+ const lb = b.line === undefined ? Number.MAX_SAFE_INTEGER : b.line
200
+ if (la !== lb) return la - lb
201
+ return a.other < b.other ? -1 : a.other > b.other ? 1 : 0
202
+ }
203
+
204
+ /** 模块内的缓存:一个工作区一份事实,键含**候选集身份**(D6 的同一个理由:串了就是静默错配)。 */
205
+ const CACHE = new Map()
206
+
207
+ function signatureOf(list) {
208
+ const parts = list.map((d) => `${d.rel}\u0000${d.mtimeMs}`)
209
+ parts.sort()
210
+ return parts.join('\n')
211
+ }
212
+
213
+ /**
214
+ * 候选集 → 关系事实。**同步、零 I/O**:只用记录上现成的 `head`。
215
+ *
216
+ * 返回 `incident`:每个候选**与自己有关**的边(`dir` 已按「本项」的视角算好)。
217
+ * 一条边同时登记到两端,投影时不必再扫一遍;`in` 边的 `line` 正好就是源那一行(D4)。
218
+ *
219
+ * @param {Array<object>|Map<string, object>} candidates - 含 `rel` / `kind` / `head` / `mtimeMs`
220
+ * @param {{root?: string}} [options] - `root` 只参与缓存键
221
+ * @returns {{signature: string, incident: Map<string, Array<object>>}}
222
+ */
223
+ export function buildRelationFacts(candidates, options = {}) {
224
+ const root = typeof options.root === 'string' ? options.root : ''
225
+ const list = Array.isArray(candidates)
226
+ ? candidates
227
+ : [...(candidates instanceof Map ? candidates.values() : [])]
228
+ const signature = signatureOf(list)
229
+ const hit = CACHE.get(root)
230
+ if (hit && hit.signature === signature) return hit.facts
231
+
232
+ const rels = list.map((d) => String(d.rel))
233
+ const index = createIndex(rels)
234
+ const incident = new Map(rels.map((r) => [r, []]))
235
+
236
+ const add = (rel, fact) => {
237
+ const arr = incident.get(rel)
238
+ if (!arr) return
239
+ const prev = arr.find((f) => f.type === fact.type && f.other === fact.other && f.dir === fact.dir)
240
+ if (prev) {
241
+ // 同一对(类型 + 方向 + 对端)只留一条,行号取最靠前的
242
+ if (prev.line !== undefined && fact.line !== undefined && fact.line < prev.line) prev.line = fact.line
243
+ return
244
+ }
245
+ arr.push(fact)
246
+ }
247
+ /** 一条有向边 → 两端各登记一次(`line` 属于「提及所在的那个文件」)。 */
248
+ const edge = (from, type, other, line) => {
249
+ add(from, line === undefined ? { type, dir: 'out', other } : { type, dir: 'out', other, line })
250
+ add(other, line === undefined ? { type, dir: 'in', other: from } : { type, dir: 'in', other: from, line })
251
+ }
252
+
253
+ for (const doc of list) {
254
+ const rel = String(doc.rel)
255
+ const text = typeof doc.head === 'string' ? doc.head : ''
256
+ if (isMd(rel)) {
257
+ // 只有 Markdown 能当 `references` / `documents` 的**源**(D5):源这一侧不放开关。
258
+ //
259
+ // v0.22 修法 ①:`doc.refs.any` 就是 `extractRefsWithLines(text, { anyExt: true })`
260
+ // 的产物(读盘/索引还原那一刻算好的),有它就不必再扫一遍首部 —— 这也正是
261
+ // 「重启后不重新推导关系」的实现。`text` 只作为没有 `refs` 时的回落。
262
+ const refs = doc.refs && Array.isArray(doc.refs.any)
263
+ ? doc.refs.any
264
+ : extractRefsWithLines(text, { anyExt: true })
265
+ for (const ref of refs) {
266
+ const other = resolveRef(ref.raw, index, rel, { anyExt: true })
267
+ if (!other || other === rel) continue
268
+ edge(rel, isMd(other) ? 'references' : 'documents', other, ref.line)
269
+ }
270
+ } else {
271
+ const imports = doc.refs && Array.isArray(doc.refs.imports)
272
+ ? doc.refs.imports
273
+ : importsOf(text)
274
+ for (const imp of imports) {
275
+ const other = resolveSpec(imp.spec, rel, index)
276
+ if (!other || other === rel) continue
277
+ edge(rel, 'imports', other, imp.line)
278
+ }
279
+ }
280
+ const pair = testsOf(rel, index)
281
+ if (pair && pair !== rel) {
282
+ // 「测试方」是这条关系里叙述的那一方(文件名的约定在它身上)。
283
+ if (isTestRel(rel)) edge(rel, 'tests', pair)
284
+ else edge(pair, 'tests', rel)
285
+ }
286
+ }
287
+
288
+ const facts = { signature, incident }
289
+ CACHE.set(root, { signature, facts })
290
+ return facts
291
+ }
292
+
293
+ /**
294
+ * 取某一项的投影(**只给包内条目用**)。超出上限时如实给出 `total`,
295
+ * 由调用方决定怎么说明「共 N 条」(§6.7:关系不是全量输出)。
296
+ *
297
+ * `facts` 收两种形状:`buildRelationFacts()` 的整份产物,**或**它的 `incident` 表本身
298
+ * (装配层只往下传表,不传签名 —— 签名是缓存的事,跟投影无关)。
299
+ *
300
+ * @param {{incident: Map}|Map} facts - 事实表(整份产物或 `incident`)
301
+ * @param {string} rel - 包内某一项
302
+ * @param {number} [limit] - 最多几条(默认面板上限 3)
303
+ * @returns {{relations: Array<object>, total: number}}
304
+ */
305
+ export function relationsOf(facts, rel, limit = MAX_RELATIONS_PER_ITEM) {
306
+ const table = facts instanceof Map ? facts : (facts && facts.incident)
307
+ const all = (table && table.get(rel)) || []
308
+ const cap = Number.isFinite(limit) && limit > 0 ? Math.trunc(limit) : MAX_RELATIONS_PER_ITEM
309
+ const sorted = [...all].sort(compareFacts)
310
+ return { relations: sorted.slice(0, cap), total: sorted.length }
311
+ }
312
+
313
+ /** 仅供测试:清掉缓存,避免用例之间互相污染。 */
314
+ export function resetRelationCache() {
315
+ CACHE.clear()
316
+ }