dsh-knit 0.17.0 → 0.19.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.
@@ -0,0 +1,567 @@
1
+ /**
2
+ * Knit v0.19 · **Code Context 端到端**
3
+ *
4
+ * 这个文件回答的问题不是「`.js` 能不能显示」,而是需求 §49 那一串验收:
5
+ *
6
+ * ```text
7
+ * Retrieval 代码能参与任务检索(文件名 > 路径 > 正文)
8
+ * Context Pack 代码能成为 Primary / Supporting / Related
9
+ * Read Evidence 代码被读取后归因**读时冻结**
10
+ * Lifecycle 代码走同一个四态生命周期
11
+ * Epoch / Delta 代码的进 / 出 / 换层能进当前 Context Epoch
12
+ * Filtering .map / minified / generated / lock 一条都不污染检索
13
+ * ```
14
+ *
15
+ * 与相邻文件的分工(**刻意不重叠**):
16
+ *
17
+ * - `test/classification.test.mjs` → 分类层本身(哪个后缀归哪一类、能力位)
18
+ * - `test/host.test.mjs` → 扫描 / 读取接口的单点行为
19
+ * - `test/context.test.mjs` → `buildContext()` 的规则(夹具一律 `kind:'md'`)
20
+ * - `test/eval.test.mjs` → BM25 的 top-1 / MRR(文档语料)
21
+ * - **本文件** → 代码**穿过整条链路**之后还对不对
22
+ *
23
+ * ⚠️ 一条设计约束贯穿全文件:**代码不许有第二套机制**。所以这里用的每个入口
24
+ * (`scan` / `buildContextFor` / `buildContext` / `ingestEvents` / `noteSnapshot` /
25
+ * `usageFor` / `lifecycleOf`)都是 Markdown 走的同一个入口,只是 `rel` 换成了代码路径。
26
+ * 任何一条断言如果必须靠「代码专用的分支」才能通过,那就说明实现跑偏了。
27
+ */
28
+ import test from 'node:test'
29
+ import assert from 'node:assert/strict'
30
+
31
+ import { scan, collectDocs, readDocument, buildContextFor } from '../src/host/index.js'
32
+ import { buildContext } from '../src/host/context.js'
33
+ import {
34
+ createStore, activateAudit, ingestEvents, noteSnapshot, usageFor, lifecycleOf,
35
+ } from '../src/host/feedback.js'
36
+ import { makeWorkspace } from './fixture.mjs'
37
+ import { NOISE_RELS } from './eval/fixture.mjs'
38
+
39
+ /* ── 构造工具 ─────────────────────────────────────────── */
40
+
41
+ /**
42
+ * 造一条假的 ranked 条目(照抄 `test/context.test.mjs:48-58` 的形状,**只把默认
43
+ * `kind` 换成 `'code'`**)。两个文件共用同一个形状是有意的:分层规则若对代码
44
+ * 另有一套输入约定,那就已经是第二套机制了。
45
+ *
46
+ * @param {string} rel - 相对路径
47
+ * @param {number} raw - BM25 分数(只用于判 Primary 的强度带宽)
48
+ * @param {Array<object>} [terms] - `matchedTerms` 形状
49
+ * @param {object} [extra] - 覆盖 `title` / `summary` / `mtimeMs` / `kind`
50
+ * @returns {object} 假的 ranked 条目
51
+ */
52
+ function doc(rel, raw, terms = [], extra = {}) {
53
+ return {
54
+ rel,
55
+ title: extra.title === undefined ? rel : extra.title,
56
+ summary: extra.summary === undefined ? '' : extra.summary,
57
+ mtimeMs: extra.mtimeMs === undefined ? 0 : extra.mtimeMs,
58
+ kind: extra.kind === undefined ? 'code' : extra.kind,
59
+ raw,
60
+ matchedTerms: terms,
61
+ }
62
+ }
63
+
64
+ /** 某词的字段位图。 */
65
+ const hit = (term, fields) => ({ term, fields })
66
+
67
+ /** 取某一层的 rel。 */
68
+ const rels = (items) => items.map((item) => item.rel)
69
+
70
+ const ROOT = '/w'
71
+
72
+ /**
73
+ * 造一对 `tool/call` + `tool/result` 事件 —— 这是 `read` 工具**被真正执行成功**的形状。
74
+ * 照抄 `test/document-lifecycle.test.mjs` 的写法,不改协议。
75
+ *
76
+ * @param {string} rel - 被读的文件
77
+ * @param {number} seq - 起始序号
78
+ * @returns {object[]} 两个事件
79
+ */
80
+ function readAt(rel, seq) {
81
+ const callId = `c${seq}`
82
+ return [
83
+ {
84
+ type: 'tool/call',
85
+ seq,
86
+ time: seq,
87
+ data: { turn: 1, step: 1, callId, name: 'read', arguments: JSON.stringify({ file_path: rel }) },
88
+ },
89
+ {
90
+ type: 'tool/result',
91
+ seq: seq + 1,
92
+ time: seq + 1,
93
+ data: { message: { role: 'tool', toolCallId: callId, source: { kind: 'tool', callId }, isError: false } },
94
+ },
95
+ ]
96
+ }
97
+
98
+ /**
99
+ * 一张快照用的最小 Context Pack 形状(`primary` / `supporting` / `related` + totals)。
100
+ *
101
+ * @param {object} [spec] - 三层的 rel 列表
102
+ * @returns {object} 包
103
+ */
104
+ function packOf(spec = {}) {
105
+ const wrap = (list) => (list || []).map((rel) => ({ rel, title: rel, summary: '', kind: 'code' }))
106
+ return {
107
+ mode: 'relevance',
108
+ topic: 'knit',
109
+ task: '',
110
+ primary: wrap(spec.primary),
111
+ supporting: wrap(spec.supporting),
112
+ related: wrap(spec.related),
113
+ totals: { primary: 0, supporting: 0, related: 0, matched: 0, total: 10 },
114
+ }
115
+ }
116
+
117
+ /**
118
+ * 让一个会话进入「已激活审计 + 有一张快照」的状态。
119
+ *
120
+ * @param {object} [spec] - 快照内容
121
+ * @returns {object} store
122
+ */
123
+ function storeWithSnapshot(spec = { primary: ['src/plugin-loader.js'] }) {
124
+ const store = createStore()
125
+ activateAudit(store, 's1')
126
+ noteSnapshot(store, 's1', packOf(spec), { seq: 5, at: 100 })
127
+ return store
128
+ }
129
+
130
+ /* ── 1 · Retrieval:代码参与当前任务检索 ───────────────── */
131
+
132
+ test('code: 文件名 > 路径 > 正文 —— 三档权重在真实扫描上可观测', async () => {
133
+ // 三个文件,同一个查询词,唯一的区别是它出现在哪一段:
134
+ // plugin-loader.js → 文件名 (title ×4)
135
+ // plugin/config.js → 目录 (summary ×2)
136
+ // lib/x.js → 只有正文 (body ×1)
137
+ const root = makeWorkspace([
138
+ ['src/plugin-loader.js', 'export function load () {}\n'],
139
+ ['src/plugin/config.js', 'export const config = {}\n'],
140
+ ['lib/x.js', '// plugin\n'],
141
+ ])
142
+ const r = await scan(root, 60, { sort: 'relevance', kind: 'context', query: 'plugin' })
143
+
144
+ assert.equal(r.mode, 'relevance', '有查询词就必须真的排了序')
145
+ const order = r.docs.map((d) => d.rel)
146
+ assert.equal(order[0], 'src/plugin-loader.js', '文件名命中必须压过路径命中')
147
+ assert.ok(
148
+ order.indexOf('src/plugin-loader.js') < order.indexOf('src/plugin/config.js'),
149
+ '路径命中必须压过正文命中',
150
+ )
151
+ assert.ok(
152
+ order.indexOf('src/plugin/config.js') < order.indexOf('lib/x.js'),
153
+ '路径命中必须压过正文命中',
154
+ )
155
+ })
156
+
157
+ test('code: 代码条目带的是宿主的代码字段口径(名字带扩展名、摘要是目录)', async () => {
158
+ const root = makeWorkspace([['src/plugin-loader.js', 'export function load () {}\n']])
159
+ const r = await scan(root, 60, { sort: 'relevance', kind: 'context', query: 'plugin-loader' })
160
+ const top = r.docs[0]
161
+
162
+ assert.equal(top.kind, 'code')
163
+ assert.equal(top.rel, 'src/plugin-loader.js')
164
+ // ⚠️ 带扩展名。去掉它,`plugin-loader.js` 与 `plugin.json` 就只剩同一个 stem 了。
165
+ assert.equal(top.title, 'plugin-loader.js')
166
+ // ⚠️ 目录保留结尾斜杠,与列表第二行的观感一致。
167
+ assert.equal(top.summary, 'src/')
168
+ })
169
+
170
+ test('code: 三种池子互不串门 —— doc 默认不含代码,code 只含代码,context 是两者之和', async () => {
171
+ const root = makeWorkspace([['src/plugin-loader.js', 'export function load () {}\n']])
172
+
173
+ const docPool = await scan(root, 60, { kind: 'doc' })
174
+ assert.ok(
175
+ docPool.docs.every((d) => d.kind !== 'code'),
176
+ '默认档(旧客户端 / 悬停浮层走这条)不许混进代码 —— v0.18 行为逐字不变',
177
+ )
178
+
179
+ const codePool = await scan(root, 60, { kind: 'code' })
180
+ assert.equal(codePool.kind, 'code')
181
+ assert.ok(codePool.docs.every((d) => d.kind === 'code'), 'code 档只含代码')
182
+ assert.ok(
183
+ codePool.docs.some((d) => d.rel === 'src/plugin-loader.js'),
184
+ '扫描出来的代码必须在 code 档里',
185
+ )
186
+
187
+ const ctxPool = await scan(root, 60, { kind: 'context' })
188
+ const kinds = new Set(ctxPool.docs.map((d) => d.kind))
189
+ assert.ok(kinds.has('code'), 'context 池必须有代码')
190
+ assert.ok(kinds.has('md'), 'context 池必须有文档 —— 否则不成其为「混合竞争」')
191
+ // 媒体永远不进上下文池(v0.18 的行为,不动)。
192
+ assert.ok(!kinds.has('image') && !kinds.has('video'), '媒体不进 Context')
193
+ })
194
+
195
+ test('code: 代码与文档混合竞争时,赢的是命中更好的那个,不是「代码」', async () => {
196
+ const root = makeWorkspace([
197
+ ['src/util.js', '// plugin\n'],
198
+ ['docs/plugin.md', '# plugin\n\n说明。\n'],
199
+ ])
200
+ const r = await scan(root, 60, { sort: 'relevance', kind: 'context', query: 'plugin' })
201
+
202
+ // 文档的**标题**命中了话题词,代码只在正文提了一句 —— 于是文档赢。
203
+ // 这一条是「不能因为是 Code 就天然优先」的正向证据:判据只有命中位置,
204
+ // 没有任何一处按 kind 加分。
205
+ assert.equal(r.docs[0].rel, 'docs/plugin.md')
206
+ assert.ok(
207
+ r.docs.some((d) => d.kind === 'code'),
208
+ '代码仍然要在结果里 —— 混合池不是「谁赢谁独占」',
209
+ )
210
+ })
211
+
212
+ /* ── 2 · Context Pack:代码能进三层 ───────────────────── */
213
+
214
+ test('context: 代码可以成为 Primary,理由码走 filenameMatch', () => {
215
+ const pack = buildContext({
216
+ ranked: [doc('src/plugin-loader.js', 30, [hit('plugin-loader', { title: true, body: true, bodyTf: 2 })])],
217
+ topic: 'plugin-loader',
218
+ })
219
+
220
+ assert.deepEqual(rels(pack.primary), ['src/plugin-loader.js'])
221
+ assert.equal(pack.primary[0].reason.code, 'filenameMatch', '代码的 title 位是文件名,理由码必须说实话')
222
+ assert.equal(pack.primary[0].kind, 'code')
223
+ assert.equal(pack.primary[0].source, 'impl')
224
+ })
225
+
226
+ test('context: 代码的 direct 升级仍然要求「命中词不止一个」', () => {
227
+ const pack = buildContext({
228
+ ranked: [doc('src/plugin-loader.js', 30, [
229
+ hit('plugin', { title: true, body: true, bodyTf: 2 }),
230
+ hit('loader', { title: true }),
231
+ ])],
232
+ })
233
+ assert.equal(pack.primary[0].reason.code, 'direct')
234
+ })
235
+
236
+ test('context: 代码只命中目录时理由码走 pathMatch', () => {
237
+ const pack = buildContext({
238
+ ranked: [
239
+ doc('src/plugin/loader.js', 30, [hit('plugin', { summary: true, body: true, bodyTf: 1 })], { summary: 'src/plugin/' }),
240
+ doc('docs/other.md', 10, [hit('plugin', { body: true, bodyTf: 1 })], { kind: 'md' }),
241
+ ],
242
+ topic: 'plugin',
243
+ })
244
+ assert.equal(pack.primary[0].rel, 'src/plugin/loader.js')
245
+ assert.equal(pack.primary[0].reason.code, 'pathMatch')
246
+ })
247
+
248
+ test('context: 代码可以成为 Supporting(正文真命中、但没有落脚点)', () => {
249
+ const pack = buildContext({
250
+ ranked: [
251
+ doc('src/plugin-loader.js', 30, [hit('plugin', { title: true })]),
252
+ doc('docs/plugin-notes.md', 20, [hit('plugin', { body: true, bodyTf: 3 })], { kind: 'md' }),
253
+ doc('src/plugin/registry.js', 18, [hit('plugin', { body: true, bodyTf: 3 })]),
254
+ ],
255
+ topic: 'plugin',
256
+ })
257
+
258
+ assert.deepEqual(rels(pack.primary), ['src/plugin-loader.js'])
259
+ const supporting = rels(pack.supporting)
260
+ assert.ok(supporting.includes('src/plugin/registry.js'), '正文真讲这件事的代码应当进 Supporting')
261
+ assert.ok(supporting.includes('docs/plugin-notes.md'), '同一层的文档也应当进 —— 两层共用一个池子')
262
+ })
263
+
264
+ test('context: 代码可以成为 Related(弱命中)', () => {
265
+ const pack = buildContext({
266
+ ranked: [
267
+ doc('src/plugin-loader.js', 30, [hit('plugin', { title: true })]),
268
+ doc('src/legacy/old-plugin.js', 8, [hit('plugin', { body: true, bodyTf: 1 })]),
269
+ ],
270
+ topic: 'plugin',
271
+ })
272
+ assert.ok(rels(pack.related).includes('src/legacy/old-plugin.js'))
273
+ })
274
+
275
+ test('context: 混合包的条目投影与 v0.18 逐字相同(代码不引入新字段)', () => {
276
+ const pack = buildContext({
277
+ ranked: [
278
+ doc('src/plugin-loader.js', 30, [hit('plugin', { title: true })]),
279
+ doc('docs/plugin.md', 12, [hit('plugin', { body: true, bodyTf: 2 })], { kind: 'md' }),
280
+ ],
281
+ topic: 'plugin',
282
+ })
283
+
284
+ const item = pack.primary[0]
285
+ assert.deepEqual(
286
+ Object.keys(item).sort(),
287
+ ['kind', 'mtimeMs', 'reason', 'rel', 'source', 'summary', 'title'],
288
+ 'Code Context 不许往包条目里塞新字段 —— 有的话 UI 与工具就得同步改两遍',
289
+ )
290
+ // 内部字段一个都不许漏出去。
291
+ const json = JSON.stringify(pack)
292
+ for (const leaked of ['raw', 'strength', 'rank', '"score"', 'haystack', 'termFields', 'bodyTf']) {
293
+ assert.ok(!json.includes(leaked), `内部字段 ${leaked} 漏进了包`)
294
+ }
295
+ })
296
+
297
+ test('context: 端到端 —— 真实工作区扫出来的代码能进 pack 的 Primary', async () => {
298
+ const root = makeWorkspace([
299
+ ['src/plugin-loader.js', 'export function loadPlugin (dir) { /* metadata */ }\n'],
300
+ ['docs/notes.md', '# 笔记\n\n无关内容。\n'],
301
+ ])
302
+ const r = await scan(root, 60, { sort: 'relevance', kind: 'context', query: 'plugin loader metadata' })
303
+ const pack = await buildContextFor(root, {
304
+ ranked: r.ranked, topic: r.topic, task: r.task, total: r.total,
305
+ })
306
+
307
+ assert.equal(pack.mode, 'relevance')
308
+ assert.deepEqual(rels(pack.primary), ['src/plugin-loader.js'])
309
+ assert.equal(pack.primary[0].kind, 'code')
310
+ assert.equal(pack.primary[0].source, 'impl')
311
+ })
312
+
313
+ test('context: 引用图里代码只能是「被指向」的一方,不能当源 —— 注释里写个路径不是入围依据', async () => {
314
+ // v0.19 一条**刻意的收窄**:引用图的**源**永远是 Markdown。
315
+ //
316
+ // 理由:代码进 Supporting 的正路是「任务检索命中了它」。若一个源码文件只要注释里
317
+ // 提一句 `docs/X.md` 就能把 X 拉进包、或靠这条边自己被拉进包,那就是一条不打分的后门。
318
+ // 反过来,**文档指向代码**是真实的设计证据(设计文档点名某个实现文件),
319
+ // 与文档指向文档走的是同一条规则 —— 那不是特例,所以保留。
320
+ const root = makeWorkspace([
321
+ // 零命中,唯一的「证据」是注释里写了一个 Markdown 路径。
322
+ ['src/util.js', '// see docs/real.md for details\n'],
323
+ ['docs/real.md', '# design\n\n真正的设计说明。\n'],
324
+ ])
325
+ const r = await scan(root, 60, { sort: 'relevance', kind: 'context', query: 'design' })
326
+ const pack = await buildContextFor(root, {
327
+ ranked: r.ranked, topic: r.topic, task: r.task, total: r.total, withLinks: true,
328
+ })
329
+
330
+ assert.deepEqual(rels(pack.primary), ['docs/real.md'])
331
+ const everything = [...rels(pack.primary), ...rels(pack.supporting), ...rels(pack.related)]
332
+ assert.ok(
333
+ !everything.includes('src/util.js'),
334
+ '零命中、只靠注释里写了个路径的代码不许进包',
335
+ )
336
+ })
337
+
338
+ /* ── 3 · Read Evidence:代码读取的归因在读时冻结 ──────── */
339
+
340
+ test('evidence: 代码被读取后留下证据,且认得出它当时在 Primary', () => {
341
+ const store = storeWithSnapshot({ primary: ['src/plugin-loader.js'] })
342
+ ingestEvents(store, 's1', readAt('src/plugin-loader.js', 10), { root: ROOT, stat: () => 1000 })
343
+
344
+ const usage = usageFor(store, 's1')
345
+ assert.equal(usage.reads.length, 1)
346
+ const read = usage.reads[0]
347
+ assert.equal(read.rel, 'src/plugin-loader.js')
348
+ // `tier` / `rank` / `inside` 都是**首次读时**的归因,不是「它现在在哪一层」。
349
+ assert.equal(read.tier, 'primary')
350
+ assert.equal(read.firstRead.tier, 'primary')
351
+ assert.equal(read.firstRead.inside, true)
352
+ assert.equal(read.outside, false)
353
+ assert.equal(usage.stats.outside, 0)
354
+ })
355
+
356
+ test('evidence: 包外的代码读取被认成 Outside Context(不是只认 Markdown)', () => {
357
+ const store = storeWithSnapshot({ primary: ['src/plugin-loader.js'] })
358
+ ingestEvents(store, 's1', readAt('src/plugin-loader.js', 10), { root: ROOT, stat: () => 1000 })
359
+ // Agent 自己顺手打开了另一个源码文件 —— 它不在包里。
360
+ ingestEvents(store, 's1', readAt('src/secret/hidden.ts', 20), { root: ROOT, stat: () => 1000 })
361
+
362
+ const usage = usageFor(store, 's1')
363
+ assert.equal(usage.stats.outside, 1)
364
+ assert.deepEqual(usage.outsideDocs.map((d) => d.rel), ['src/secret/hidden.ts'])
365
+ })
366
+
367
+ test('evidence: 历史归因在后续快照变化后**不许重算**(读时冻结)', () => {
368
+ const store = storeWithSnapshot({ primary: ['src/plugin-loader.js'] })
369
+ ingestEvents(store, 's1', readAt('src/plugin-loader.js', 10), { root: ROOT, stat: () => 1000 })
370
+
371
+ // 再交一张完全不同的包:这个代码文件**离开了**上下文。
372
+ noteSnapshot(
373
+ store, 's1',
374
+ packOf({ primary: ['src/context/context-manager.ts'] }),
375
+ { seq: 30, at: 200 },
376
+ )
377
+
378
+ const usage = usageFor(store, 's1')
379
+ const read = usage.reads.find((r) => r.rel === 'src/plugin-loader.js')
380
+ assert.ok(read, '证据不许因为文件离开上下文而消失')
381
+ assert.equal(read.firstRead.tier, 'primary', '读时的层必须是 primary —— 冻结在读的那一刻')
382
+ assert.equal(
383
+ read.firstRead.inside, true,
384
+ '「读的时候在不在包里」也要冻结。用今天的包去重算昨天的事实就是编造',
385
+ )
386
+ // 而**当前**包外的那一份,当然要按今天的包说 —— 这两个口径不是一回事。
387
+ assert.deepEqual(usage.outsideDocs.map((d) => d.rel), ['src/plugin-loader.js'])
388
+ })
389
+
390
+ test('evidence: 代码的重复读取累加次数,不新增条目', () => {
391
+ const store = storeWithSnapshot({ primary: ['src/plugin-loader.js'] })
392
+ ingestEvents(store, 's1', readAt('src/plugin-loader.js', 10), { root: ROOT, stat: () => 1000 })
393
+ ingestEvents(store, 's1', readAt('src/plugin-loader.js', 40), { root: ROOT, stat: () => 1000 })
394
+
395
+ const usage = usageFor(store, 's1')
396
+ assert.equal(usage.reads.length, 1)
397
+ assert.equal(usage.reads[0].count, 2)
398
+ })
399
+
400
+ /* ── 4 · Lifecycle:代码走同一个四态 ──────────────────── */
401
+
402
+ test('lifecycle: 代码的四态与文档完全同一套(纯函数层)', () => {
403
+ assert.equal(lifecycleOf(null).status, 'unread')
404
+ assert.equal(
405
+ lifecycleOf({ count: 1, lastReadMtimeMs: 1000, rereadAfterChange: false }, 1000).status,
406
+ 'read',
407
+ )
408
+ assert.equal(
409
+ lifecycleOf({ count: 1, lastReadMtimeMs: 1000, rereadAfterChange: false }, 2000).status,
410
+ 'updated_after_read',
411
+ )
412
+ assert.equal(
413
+ lifecycleOf({ count: 2, lastReadMtimeMs: null, rereadAfterChange: true }, 500).status,
414
+ 'reread_after_update',
415
+ )
416
+ })
417
+
418
+ test('lifecycle: 读过的代码被改之后,端到端报 updated_after_read', () => {
419
+ const store = storeWithSnapshot({ primary: ['src/plugin-loader.js'] })
420
+ ingestEvents(store, 's1', readAt('src/plugin-loader.js', 10), { root: ROOT, stat: () => 1000 })
421
+
422
+ const before = usageFor(store, 's1', { mtimes: { 'src/plugin-loader.js': 1000 } })
423
+ assert.equal(before.lifecycle['src/plugin-loader.js'].status, 'read')
424
+
425
+ // 文件被改(mtime 前进)—— 判据是**读时冻结的 mtime** 与今天的 mtime 之差。
426
+ const after = usageFor(store, 's1', { mtimes: { 'src/plugin-loader.js': 2000 } })
427
+ assert.equal(after.lifecycle['src/plugin-loader.js'].status, 'updated_after_read')
428
+ assert.equal(after.lifecycle['src/plugin-loader.js'].changedAfterLastRead, true)
429
+
430
+ // 改完又被读一次 → reread_after_update。**没有第二套代码专用状态机**。
431
+ ingestEvents(store, 's1', readAt('src/plugin-loader.js', 60), {
432
+ root: ROOT,
433
+ stat: () => 2000,
434
+ })
435
+ const reread = usageFor(store, 's1', { mtimes: { 'src/plugin-loader.js': 2000 } })
436
+ assert.equal(reread.lifecycle['src/plugin-loader.js'].status, 'reread_after_update')
437
+ })
438
+
439
+ /* ── 5 · Context Epoch / Delta:代码的进 / 出 / 换层 ──── */
440
+
441
+ test('epoch: 代码进入上下文产生新 epoch 与 appeared 增量', () => {
442
+ const store = createStore()
443
+ activateAudit(store, 's1')
444
+
445
+ const first = noteSnapshot(store, 's1', packOf({ primary: ['src/a.js'] }), { seq: 5, at: 100 })
446
+ assert.equal(first.delta, null, '第一张快照没有「变化」可言')
447
+
448
+ const second = noteSnapshot(
449
+ store, 's1',
450
+ packOf({ primary: ['src/b.js'], supporting: ['src/a.js'] }),
451
+ { seq: 9, at: 200 },
452
+ )
453
+ assert.deepEqual(second.delta.appeared, [{ rel: 'src/b.js', tier: 'primary', rank: 1 }])
454
+ // a.js 没有消失:它只是换了层 —— 「离开上下文」与「换层」是两件事。
455
+ assert.deepEqual(second.delta.disappeared, [])
456
+ // `moved` 的形状是 `{rel, from:{tier,rank}, to:{tier,rank}}` —— **不只跨层**,
457
+ // 同一层里换名次也算移动(这里 a.js 是从 primary 换到 supporting)。
458
+ assert.deepEqual(second.delta.moved, [
459
+ { rel: 'src/a.js', from: { tier: 'primary', rank: 1 }, to: { tier: 'supporting', rank: 1 } },
460
+ ])
461
+ assert.equal(second.delta.fromEpoch, 1)
462
+ assert.equal(second.delta.toEpoch, 2)
463
+ })
464
+
465
+ test('epoch: 包没变就不产生新 epoch(签名相同)', () => {
466
+ const store = createStore()
467
+ activateAudit(store, 's1')
468
+ noteSnapshot(store, 's1', packOf({ primary: ['src/a.js'] }), { seq: 5, at: 100 })
469
+
470
+ const again = noteSnapshot(store, 's1', packOf({ primary: ['src/a.js'] }), { seq: 12, at: 300 })
471
+ assert.equal(again, null, '同一份包不该刷出一个空 epoch')
472
+
473
+ const usage = usageFor(store, 's1')
474
+ assert.equal(usage.stats.churn.deltas, 0)
475
+ assert.equal(usage.epochs.length, 1)
476
+ })
477
+
478
+ test('epoch: 代码离开上下文后仍出现在 usage 的历史里,且不新增第二套 Delta', () => {
479
+ const store = createStore()
480
+ activateAudit(store, 's1')
481
+ noteSnapshot(store, 's1', packOf({ primary: ['src/a.js', 'src/b.js'] }), { seq: 5, at: 100 })
482
+ const drop = noteSnapshot(store, 's1', packOf({ primary: ['src/b.js'] }), { seq: 9, at: 200 })
483
+
484
+ // rank 是**层内** 1-based 序号:a.js 在 `primary:['src/a.js','src/b.js']` 里排第一。
485
+ assert.deepEqual(drop.delta.disappeared, [{ rel: 'src/a.js', tier: 'primary', rank: 1 }])
486
+ const usage = usageFor(store, 's1')
487
+ // UI 侧只说「Context Changes」—— 这里确认数据侧也只有一套 delta。
488
+ assert.equal(usage.delta, usage.latestDelta)
489
+ assert.equal(usage.delta.toEpoch, 2)
490
+ })
491
+
492
+ /* ── 6 · Negative:生成 / 噪声产物一条都不许污染检索 ──── */
493
+
494
+ test('negative: 七条生成/噪声路径在真实扫描里一条都不进候选', async () => {
495
+ const extra = NOISE_RELS.map((rel) => [rel, rel.endsWith('.map') || rel.endsWith('.json')
496
+ ? '{"version":3}\n'
497
+ : '// plugin loader metadata\n'])
498
+ // 一个**真的相关**的文件放在噪声里 —— 否则「top-1 不是噪声」可以靠什么都没有来通过。
499
+ extra.push(['src/plugin-loader.js', 'export function loadPlugin (dir) { /* metadata */ }\n'])
500
+ const root = makeWorkspace(extra)
501
+
502
+ const { docs, code, stats } = await collectDocs(root)
503
+ const admitted = [...docs, ...code].map((d) => d.rel)
504
+
505
+ for (const noise of NOISE_RELS) {
506
+ assert.ok(
507
+ !admitted.includes(noise),
508
+ `${noise} 不该出现在候选里 —— Context eligibility 与 file system visibility 是两件事`,
509
+ )
510
+ }
511
+ assert.ok(admitted.includes('src/plugin-loader.js'), '真正相关的代码必须还在')
512
+
513
+ // node_modules / dist / coverage 三条由既有的 SKIP_DIRS 挡(目录级),
514
+ // 另外四条由新增的 code-specific noise 规则挡(文件名级)。
515
+ // 无论哪一层接手,都必须被**数到** —— 沉默的排除是不可核验的。
516
+ assert.equal(stats.generated, 4, 'app.min.js / bundle.generated.js / app.js.map / package-lock.json')
517
+ })
518
+
519
+ test('negative: 噪声不进检索结果,top-1 仍是真正相关的那一个', async () => {
520
+ const extra = NOISE_RELS.map((rel) => [rel, '// plugin loader metadata plugin loader\n'])
521
+ extra.push(['src/plugin-loader.js', 'export function loadPlugin (dir) { /* metadata */ }\n'])
522
+ const root = makeWorkspace(extra)
523
+
524
+ const r = await scan(root, 60, { sort: 'relevance', kind: 'context', query: 'plugin loader metadata' })
525
+ assert.equal(r.docs[0].rel, 'src/plugin-loader.js')
526
+ for (const noise of NOISE_RELS) {
527
+ assert.ok(!r.docs.some((d) => d.rel === noise), `${noise} 漏进了检索结果`)
528
+ }
529
+ })
530
+
531
+ test('negative: 被排除的生成产物仍然**可以预览**(.map 是文件系统的一部分)', async () => {
532
+ const root = makeWorkspace([
533
+ ['app.js', 'export function load () {}\n'],
534
+ ['app.js.map', '{"version":3,"sources":["app.js"]}\n'],
535
+ ])
536
+
537
+ const r = await readDocument(root, 'app.js.map')
538
+ assert.equal(r.ok, true, '用户主动打开时不许拦 —— 被排除的是「进入检索」而不是「能不能看」')
539
+ assert.equal(r.kind, 'generated')
540
+ // `readDocument` 原样返回文件内容,不做任何重排 —— 所以断言得按原样来。
541
+ assert.match(r.text, /"version":3/)
542
+
543
+ // 而它在检索侧就是不存在。
544
+ const ctx = await scan(root, 60, { kind: 'code' })
545
+ assert.ok(ctx.docs.some((d) => d.rel === 'app.js'), '真源码在')
546
+ assert.ok(!ctx.docs.some((d) => d.rel.endsWith('.map')), 'source map 在检索侧不存在')
547
+ })
548
+
549
+ test('negative: minified 后缀不会被「也带 .js」蒙混过关', async () => {
550
+ const root = makeWorkspace([
551
+ ['app.min.js', 'x\n'],
552
+ ['app.js', 'x\n'],
553
+ ['bundle.generated.js', 'x\n'],
554
+ ['data.generated.js', 'x\n'],
555
+ ])
556
+ const { code, stats } = await collectDocs(root)
557
+
558
+ // 夹具默认还造了一个 `package.json`(v0.19 起它是合法代码候选),所以按成员断言,
559
+ // 而不是按整份清单断言 —— 否则这条测试会因为夹具变化而假红。
560
+ assert.ok(code.some((c) => c.rel === 'app.js'), '真正的源码必须留下')
561
+ for (const noise of ['app.min.js', 'bundle.generated.js', 'data.generated.js']) {
562
+ assert.ok(!code.some((c) => c.rel === noise), `${noise} 不许进候选`)
563
+ }
564
+ // ⚠️ 扩展名判定顺序是契约:这四个的 ext 都是 `.js`。
565
+ // 先看 ext 再看噪声规则的话,三个生成产物会被当成合法代码。
566
+ assert.equal(stats.generated, 3, '三个生成产物必须被数到,而不是被静默跳过')
567
+ })