dsh-knit 0.23.0 → 0.24.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,1238 @@
1
+ /**
2
+ * Knit v0.25 · **Git 变更关联检索**(`src/host/git.js` + `src/host/changes.js` + 装配层的接线)。
3
+ *
4
+ * 三件事各测各的,**不混着测**:
5
+ *
6
+ * 1. **状态读取**(`git.js`):`--porcelain=v1 -z` 的解析、五种降级、缓存与并发去重、
7
+ * 以及「只跑哪两个子命令」的**安全守卫**。全部用注入的 `exec` 或手写字节串 ⇒ 确定性,
8
+ * 不需要真的建一个仓库、也不依赖这台机器上 git 的版本与配置。
9
+ * 2. **关联投影**(`changes.js`):四类证据、已删除/重命名前的路径当种子、无证据不硬凑、
10
+ * 截断与确定性排序。用**手写的候选记录**直接喂 `buildRelationFacts()`,零 I/O。
11
+ * 3. **接线**(`index.js` 的 `buildContextFor`):关闭时**包逐字不变**、打开时只多一个平行区、
12
+ * 三层与固定区一个字节都不动。
13
+ *
14
+ * ⚠️ 一份**真机** fixture(真的 `git init` 一个临时仓库、真的跑一条 `git status`)也在这里 ——
15
+ * `test/fixture.mjs` 的纪律:样本工作区一律自己造、路径用 `os.tmpdir()`,断言里不出现 `knit/` 前缀。
16
+ * 那是唯一会 spawn 进程的用例;它证明「我们解析的是**真 git** 的输出」,而不是我们以为的格式。
17
+ */
18
+
19
+ import test from 'node:test'
20
+ import assert from 'node:assert/strict'
21
+ import { execFileSync, spawnSync } from 'node:child_process'
22
+ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, existsSync } from 'node:fs'
23
+ import { tmpdir } from 'node:os'
24
+ import { join } from 'node:path'
25
+
26
+ import {
27
+ parseStatusZ, kindsOf, createGitReader, spawnGit, gitEnv,
28
+ GIT_STATUS_ARGS, GIT_PREFIX_ARGS, GIT_ENV_ALLOW, MUTATING_VERBS,
29
+ MAX_CHANGED_FILES, MAX_REPORTED_FILES,
30
+ } from '../src/host/git.js'
31
+ import {
32
+ splitSeeds, ghostCandidates, projectChangeRelated, MAX_CHANGE_RELATED,
33
+ } from '../src/host/changes.js'
34
+ import { buildRelationFacts, resetRelationCache, testsOf } from '../src/host/relations.js'
35
+ import { changesPayload, corpusForChanges, scanMemo, resetScanMemo, resetGitReaderCache } from '../src/host/index.js'
36
+ import { createIndex } from '../src/host/links.js'
37
+ import { startKnitServer } from './http-harness.mjs'
38
+ import { scan, buildContextFor, publicScanPayload } from '../src/host/index.js'
39
+ import { knitDocsDefinition } from '../src/host/tool.js'
40
+ // `scan` 已在 import 列表里(独立验收案例要真的扫一遍临时仓库)
41
+
42
+ /* ── 1. 状态读取 ─────────────────────────────────────── */
43
+
44
+ test('git: `--porcelain=v1 -z` 的解析 —— 五种状态各就各位(含重命名的新/原路径顺序)', () => {
45
+ // 这一串的形状是**实测**来的(2026-10-13,真 git 2.x 的 od 输出):
46
+ // R <新路径>\0<原路径>\0 重命名:**新在前**,后面紧跟一个原路径字段
47
+ // MM <路径>\0 索引与工作区**都**改了
48
+ // D <路径>\0 工作区删除(索引里还在)
49
+ // ?? <路径>\0 未跟踪
50
+ const raw = 'R new-name.ts\0old-name.ts\0MM src/foo.ts\0 D tests/foo.test.ts\0?? src/brand-new.ts\0'
51
+ const files = parseStatusZ(raw)
52
+ assert.deepEqual(files.map((f) => f.rel), ['new-name.ts', 'src/brand-new.ts', 'src/foo.ts', 'tests/foo.test.ts'],
53
+ '按路径字典序(确定性),不是按 git 的输出顺序')
54
+
55
+ const byRel = new Map(files.map((f) => [f.rel, f]))
56
+ assert.deepEqual(byRel.get('new-name.ts').kinds, ['renamed', 'staged'])
57
+ assert.equal(byRel.get('new-name.ts').origRel, 'old-name.ts', '重命名的**原路径**要留下来(它也是一个种子)')
58
+ assert.deepEqual(byRel.get('src/foo.ts').kinds, ['staged', 'unstaged'], '`MM` = 暂存与未暂存**同时**成立,不许压成一个标签')
59
+ assert.deepEqual(byRel.get('tests/foo.test.ts').kinds, ['deleted', 'unstaged'])
60
+ assert.deepEqual(byRel.get('src/brand-new.ts').kinds, ['untracked'])
61
+ assert.equal(byRel.get('src/foo.ts').origRel, undefined, '没有原路径时**不给这个键**(不是给个空串)')
62
+ })
63
+
64
+ test('git: `kindsOf` 把 XY 两位翻成状态集合(X=索引侧、Y=工作区侧)', () => {
65
+ assert.deepEqual(kindsOf('?', '?'), ['untracked'])
66
+ assert.deepEqual(kindsOf('M', ' '), ['staged'])
67
+ assert.deepEqual(kindsOf(' ', 'M'), ['unstaged'])
68
+ assert.deepEqual(kindsOf('M', 'M'), ['staged', 'unstaged'])
69
+ assert.deepEqual(kindsOf('A', ' '), ['added', 'staged'])
70
+ assert.deepEqual(kindsOf(' ', 'D'), ['deleted', 'unstaged'])
71
+ assert.deepEqual(kindsOf('D', ' '), ['deleted', 'staged'])
72
+ assert.deepEqual(kindsOf('R', ' '), ['renamed', 'staged'])
73
+ assert.deepEqual(kindsOf('U', 'U'), ['unmerged'], '冲突态不许被说成「已暂存 + 未暂存」')
74
+ assert.deepEqual(kindsOf('D', 'D'), ['deleted', 'unmerged'], '`DD` 两种事实都在:既冲突、也确实删了')
75
+ assert.deepEqual(kindsOf('A', 'A'), ['unmerged'])
76
+ })
77
+
78
+ test('git: 工作区是仓库的子目录时,路径按**工作区**基准给出(减掉 --show-prefix)', () => {
79
+ const raw = 'MM src/foo.ts\0?? src/new.ts\0?? outside/other.ts\0'
80
+ const files = parseStatusZ(raw, { prefix: 'src/' })
81
+ assert.deepEqual(files.map((f) => f.rel), ['foo.ts', 'new.ts'],
82
+ '工作区之外的路径(同一个仓库里)**直接丢弃**,不算这个工作区的变更')
83
+ })
84
+
85
+ test('git: 解析对残缺输入不抛(半截条目 / 空串 / 只有状态位)', () => {
86
+ for (const raw of ['', '\0', 'M\0', 'M \0', 'QQ\0', null, undefined, 123]) {
87
+ assert.doesNotThrow(() => parseStatusZ(raw))
88
+ }
89
+ assert.deepEqual(parseStatusZ('M \0'), [], '「状态位 + 空格 + 空路径」不算一条变更')
90
+ })
91
+
92
+ test('git: 五种降级各有各的 reason,且**一条都不抛**', async () => {
93
+ const mk = (impl) => createGitReader({ exec: impl, now: () => 0 })
94
+ const cases = [
95
+ ['not-a-repo', (args) => (args.includes('rev-parse')
96
+ ? { code: 128, stdout: '', stderr: 'fatal: not a git repository (or any of the parent directories): .git' }
97
+ : { code: 0, stdout: '', stderr: '' })],
98
+ ['git-missing', () => ({ code: null, stdout: '', stderr: '', spawnError: true })],
99
+ ['timeout', (args) => (args.includes('rev-parse')
100
+ ? { code: 0, stdout: '', stderr: '' }
101
+ : { code: null, stdout: '', stderr: '', killed: 'timeout' })],
102
+ ['output-too-large', (args) => (args.includes('rev-parse')
103
+ ? { code: 0, stdout: '', stderr: '' }
104
+ : { code: null, stdout: '', stderr: '', killed: 'too-large' })],
105
+ ['failed-fatal', (args) => (args.includes('rev-parse')
106
+ ? { code: 0, stdout: '', stderr: '' }
107
+ : { code: 1, stdout: '', stderr: 'boom' })],
108
+ ]
109
+ for (const [reason, impl] of cases) {
110
+ const result = await mk(impl).read('/w')
111
+ assert.equal(result.available, false, `${reason} 必须是 available:false`)
112
+ assert.equal(result.reason, reason)
113
+ assert.deepEqual(result.files, [], '读不到时**不给半份变更清单**')
114
+ }
115
+ // exec 自己抛(比如 spawn 抛 EACCES)也不许冒出去
116
+ const throwing = createGitReader({ exec: async () => { throw new Error('EACCES') }, now: () => 0 })
117
+ const res = await throwing.read('/w')
118
+ assert.equal(res.available, false)
119
+ assert.equal(res.reason, 'failed-fatal')
120
+ })
121
+
122
+ test('git: 非 Git 工作区只问一次 —— 负结论也缓存(不然面板每轮都白跑一条 git)', async () => {
123
+ let calls = 0
124
+ const impl = async (args) => {
125
+ calls += 1
126
+ void args
127
+ return { code: 128, stdout: '', stderr: 'fatal: not a git repository' }
128
+ }
129
+ const reader = createGitReader({ exec: impl, now: () => 0 })
130
+ assert.equal((await reader.read('/w')).reason, 'not-a-repo')
131
+ assert.equal((await reader.read('/w')).reason, 'not-a-repo')
132
+ assert.equal(calls, 1, `` + `负结论必须被缓存(实测调用 ${calls} 次)`)
133
+ })
134
+
135
+ test('git: 结果缓存命中时不再 spawn;并发的两轮共用同一次调用', async () => {
136
+ let calls = 0
137
+ let clock = 0
138
+ const impl = async (args) => {
139
+ calls += 1
140
+ if (args.includes('rev-parse')) return { code: 0, stdout: '', stderr: '' }
141
+ await new Promise((r) => setTimeout(r, 5))
142
+ return { code: 0, stdout: 'M a.ts\0', stderr: '' }
143
+ }
144
+ const reader = createGitReader({ exec: impl, now: () => clock, ttlMs: 1000 })
145
+ const [a, b] = await Promise.all([reader.read('/w'), reader.read('/w')])
146
+ assert.deepEqual(a.files.map((f) => f.rel), ['a.ts'])
147
+ assert.deepEqual(b.files.map((f) => f.rel), ['a.ts'])
148
+ assert.equal(calls, 2, 'rev-parse 1 次 + status 1 次:并发的两轮**共用**了同一次 git')
149
+ clock = 500
150
+ await reader.read('/w')
151
+ assert.equal(calls, 2, 'TTL 之内命中缓存,不再 spawn')
152
+ clock = 2000
153
+ await reader.read('/w')
154
+ assert.equal(calls, 3, 'TTL 过了才重新问一次')
155
+ })
156
+
157
+ test('git: 条目数超过上限时截断并如实标记(不静默丢)', async () => {
158
+ const many = Array.from({ length: MAX_CHANGED_FILES + 5 }, (_, i) => `M f${String(i).padStart(4, '0')}.ts`).join('\0') + '\0'
159
+ const impl = async (args) => (args.includes('rev-parse')
160
+ ? { code: 0, stdout: '', stderr: '' }
161
+ : { code: 0, stdout: many, stderr: '' })
162
+ const result = await createGitReader({ exec: impl, now: () => 0 }).read('/w')
163
+ assert.equal(result.truncated, true)
164
+ assert.equal(result.filesTotal, MAX_CHANGED_FILES)
165
+ assert.equal(result.files.length, MAX_CHANGED_FILES)
166
+ })
167
+
168
+ test('安全:只跑 `status` 与 `rev-parse --show-prefix`,两个 argv 里一个写动词都没有', () => {
169
+ assert.equal(GIT_STATUS_ARGS[0], 'status')
170
+ assert.equal(GIT_PREFIX_ARGS[0], 'rev-parse')
171
+ for (const verb of MUTATING_VERBS) {
172
+ assert.ok(!GIT_STATUS_ARGS.includes(verb), `status 的 argv 里出现了写动词 ${verb}`)
173
+ assert.ok(!GIT_PREFIX_ARGS.includes(verb), `rev-parse 的 argv 里出现了写动词 ${verb}`)
174
+ }
175
+ // `--untracked-files=all` 是**有界**的:它不会展开被忽略的目录(`--ignored` 没开)
176
+ assert.ok(GIT_STATUS_ARGS.includes('--untracked-files=all'))
177
+ assert.ok(!GIT_STATUS_ARGS.includes('--ignored'), '不主动去看被忽略的文件(node_modules 那类)')
178
+ })
179
+
180
+ /* ── 2. 与**真 git** 对一次账(唯一会 spawn 的用例)──────── */
181
+
182
+ test('真机:真的 git init 一个临时仓库,五种状态都解析得出来', async (t) => {
183
+ let repo
184
+ try {
185
+ repo = mkdtempSync(join(tmpdir(), 'knit-git-'))
186
+ const git = (...args) => execFileSync('git', ['-C', repo, ...args], { stdio: ['ignore', 'pipe', 'pipe'] })
187
+ execFileSync('git', ['init', '-q', repo], { stdio: 'ignore' })
188
+ git('config', 'user.email', 't@t')
189
+ git('config', 'user.name', 't')
190
+ mkdirSync(join(repo, 'src'))
191
+ mkdirSync(join(repo, 'tests'))
192
+ writeFileSync(join(repo, 'src', 'foo.ts'), 'export const a = 1\n')
193
+ writeFileSync(join(repo, 'tests', 'foo.test.ts'), 'import "../src/foo"\n')
194
+ writeFileSync(join(repo, 'old-name.ts'), 'x\n')
195
+ git('add', '-A')
196
+ git('commit', '-qm', 'init')
197
+
198
+ writeFileSync(join(repo, 'src', 'foo.ts'), 'export const a = 2\n')
199
+ git('add', 'src/foo.ts')
200
+ writeFileSync(join(repo, 'src', 'foo.ts'), 'export const a = 3\n') // 暂存 + 未暂存
201
+ writeFileSync(join(repo, 'src', 'brand-new.ts'), 'new\n') // 未跟踪
202
+ rmSync(join(repo, 'tests', 'foo.test.ts')) // 删除
203
+ git('mv', 'old-name.ts', 'new-name.ts') // 重命名
204
+
205
+ const result = await createGitReader().read(repo)
206
+ assert.equal(result.available, true, `真机读取必须成功(reason=${result.reason})`)
207
+ const byRel = new Map(result.files.map((f) => [f.rel, f]))
208
+ assert.deepEqual(byRel.get('src/foo.ts').kinds, ['staged', 'unstaged'])
209
+ assert.deepEqual(byRel.get('src/brand-new.ts').kinds, ['untracked'])
210
+ assert.deepEqual(byRel.get('tests/foo.test.ts').kinds, ['deleted', 'unstaged'])
211
+ assert.deepEqual(byRel.get('new-name.ts').kinds, ['renamed', 'staged'])
212
+ assert.equal(byRel.get('new-name.ts').origRel, 'old-name.ts')
213
+ } finally {
214
+ if (repo) rmSync(repo, { recursive: true, force: true })
215
+ }
216
+ void t
217
+ })
218
+
219
+ test('真机:非仓库目录如实回 not-a-repo(用 os.tmpdir(),不碰任何真实项目)', async () => {
220
+ const dir = mkdtempSync(join(tmpdir(), 'knit-norepo-'))
221
+ try {
222
+ const result = await createGitReader().read(dir)
223
+ assert.equal(result.available, false)
224
+ assert.equal(result.reason, 'not-a-repo')
225
+ } finally {
226
+ rmSync(dir, { recursive: true, force: true })
227
+ }
228
+ })
229
+
230
+ test('真机:默认 exec 是 spawnGit,且它把「命令不存在」也收敛成结果而不是抛', async () => {
231
+ const res = await spawnGit(['--version'], { cwd: tmpdir(), timeoutMs: 5000 })
232
+ assert.equal(typeof res.code, 'number')
233
+ assert.match(res.stdout, /git version/)
234
+ // 拿一个不存在的可执行名不行(argv[0] 固定是 git),所以这里只证明「不抛 + 有上限参数」
235
+ assert.equal(res.killed, null)
236
+ })
237
+
238
+ /* ── 3. 关联投影(纯函数)────────────────────────────── */
239
+
240
+ /** 手写一份最小候选集:代码互相 import、一个测试、一篇文档提到代码。 */
241
+ function candidateCorpus() {
242
+ return [
243
+ { rel: 'src/foo.ts', kind: 'code', head: "import { x } from './bar'\nexport const foo = x\n", mtimeMs: 1 },
244
+ { rel: 'src/bar.ts', kind: 'code', head: 'export const x = 1\n', mtimeMs: 1 },
245
+ { rel: 'tests/foo.test.ts', kind: 'code', head: "import { foo } from '../src/foo'\n", mtimeMs: 1 },
246
+ { rel: 'docs/readme.md', kind: 'md', head: '# Doc\n\nsee src/foo.ts for details\n', mtimeMs: 1 },
247
+ { rel: 'docs/other.md', kind: 'md', head: '# Other\n\nnothing to see\n', mtimeMs: 1 },
248
+ ]
249
+ }
250
+
251
+ test('关联:四类证据都能从变更文件找出来,且每条都写明**起点 / 类型 / 行号**', () => {
252
+ resetRelationCache()
253
+ const corpus = candidateCorpus()
254
+ const rels = new Set(corpus.map((d) => d.rel))
255
+ const facts = buildRelationFacts(corpus, { root: '/t1' })
256
+ const out = projectChangeRelated({ seeds: ['src/foo.ts'], incident: facts.incident, itemRels: rels })
257
+ const byRel = new Map(out.related.map((r) => [r.rel, r]))
258
+
259
+ assert.ok(byRel.has('src/bar.ts'), 'imports:foo 导入了 bar')
260
+ // 方向的口径:`dir` 说的是**目标**这一侧的视角 —— `in` = 起点(变更文件)指向它
261
+ assert.deepEqual(byRel.get('src/bar.ts').evidence[0], { type: 'imports', dir: 'in', other: 'src/foo.ts', line: 1 })
262
+ assert.ok(byRel.has('tests/foo.test.ts'), 'tests:文件名约定(foo ↔ foo.test)')
263
+ // 同一个目标可以**同时**有两条不同证据:这个测试既是被测关系(tests),又真的 import 了 foo
264
+ const tEv = byRel.get('tests/foo.test.ts').evidence
265
+ assert.ok(tEv.some((e) => e.type === 'tests'), 'tests:文件名约定那条必须在')
266
+ assert.deepEqual(tEv.find((e) => e.type === 'tests'), { type: 'tests', dir: 'out', other: 'src/foo.ts' },
267
+ 'tests 这一类**没有行号** —— 证据是文件名约定,不编一个出来;叙述方是测试文件自己(所以是 out)')
268
+ assert.ok(tEv.some((e) => e.type === 'imports' && e.line === 1), '同一个目标上的第二条证据(imports + 行号)也要在')
269
+ assert.ok(byRel.has('docs/readme.md'), 'documents:文档提到了代码路径')
270
+ assert.deepEqual(byRel.get('docs/readme.md').evidence[0], { type: 'documents', dir: 'out', other: 'src/foo.ts', line: 3 })
271
+ assert.ok(!byRel.has('docs/other.md'), '没提到它的文档**不许**被拉进来')
272
+ assert.deepEqual(out.unresolved, [], 'foo.ts 有证据 ⇒ 不算 unresolved')
273
+ })
274
+
275
+ test('关联:变更文件**自己**不当结果(这一区回答的是「还该看什么」)', () => {
276
+ resetRelationCache()
277
+ const corpus = candidateCorpus()
278
+ const rels = new Set(corpus.map((d) => d.rel))
279
+ const facts = buildRelationFacts(corpus, { root: '/t2' })
280
+ // 两个文件都被改了:foo 与 bar 之间有 imports 边,但谁也不该出现在对方的关联结果里
281
+ const out = projectChangeRelated({
282
+ seeds: ['src/foo.ts', 'src/bar.ts'],
283
+ incident: facts.incident,
284
+ itemRels: rels,
285
+ exclude: new Set(['src/foo.ts', 'src/bar.ts']),
286
+ })
287
+ const got = out.related.map((r) => r.rel)
288
+ assert.ok(!got.includes('src/bar.ts'))
289
+ assert.ok(!got.includes('src/foo.ts'))
290
+ assert.ok(got.includes('tests/foo.test.ts'), '别的证据照常工作')
291
+ })
292
+
293
+ test('关联:**已删除**的文件也能当种子 —— 删掉测试,还能找回它的被测文件', () => {
294
+ resetRelationCache()
295
+ // 磁盘上只有 foo.ts(测试已经被删了)⇒ 候选集里没有 tests/foo.test.ts
296
+ const corpus = candidateCorpus().filter((d) => d.rel !== 'tests/foo.test.ts')
297
+ const rels = new Set(corpus.map((d) => d.rel))
298
+ const changeSet = {
299
+ available: true, reason: null, truncated: false, filesTotal: 1,
300
+ files: [{ rel: 'tests/foo.test.ts', kinds: ['deleted', 'unstaged'] }],
301
+ }
302
+ const { seeds, gone, outside, seedRels } = splitSeeds(changeSet, rels)
303
+ assert.deepEqual(seeds, [], '被删掉的文件不在候选集里')
304
+ assert.deepEqual(gone, ['tests/foo.test.ts'])
305
+ assert.deepEqual(outside, ['tests/foo.test.ts'], '它也要被算进「不在本档语料」的计数')
306
+ assert.deepEqual(seedRels, ['tests/foo.test.ts'], '但它**仍然要当种子**')
307
+
308
+ // 有合成候选 ⇒ 别人指向它的边解析得出来
309
+ const withGhost = buildRelationFacts([...corpus, ...ghostCandidates(gone)], { root: '/t3' })
310
+ const out = projectChangeRelated({ seeds: seedRels, incident: withGhost.incident, itemRels: rels })
311
+ const byRel = new Map(out.related.map((r) => [r.rel, r]))
312
+ assert.ok(byRel.has('src/foo.ts'), '删掉 tests/foo.test.ts ⇒ 它的被测文件 src/foo.ts 就是该一起看的')
313
+ assert.deepEqual(byRel.get('src/foo.ts').evidence[0].type, 'tests')
314
+ assert.equal(byRel.get('src/foo.ts').evidence[0].other, 'tests/foo.test.ts', '证据的起点是那个被删掉的文件')
315
+
316
+ // 没有合成候选 ⇒ 一条都找不到(这正是加 ghost 的理由)
317
+ resetRelationCache()
318
+ const without = buildRelationFacts(corpus, { root: '/t3b' })
319
+ const bare = projectChangeRelated({ seeds: ['tests/foo.test.ts'], incident: without.incident, itemRels: rels })
320
+ assert.equal(bare.relatedTotal, 0, '证伪:不给合成候选时这条链是断的')
321
+ assert.deepEqual(bare.unresolved, ['tests/foo.test.ts'])
322
+ })
323
+
324
+ test('关联:重命名**前后的两个路径**都当种子', () => {
325
+ const rels = new Set(['new-name.ts', 'docs/readme.md'])
326
+ const changeSet = {
327
+ available: true, reason: null, truncated: false, filesTotal: 1,
328
+ files: [{ rel: 'new-name.ts', kinds: ['renamed', 'staged'], origRel: 'old-name.ts' }],
329
+ }
330
+ const { seeds, seedRels, gone } = splitSeeds(changeSet, rels)
331
+ assert.deepEqual(seeds, ['new-name.ts'], '新路径在候选集里 ⇒ 能当结果')
332
+ assert.ok(seedRels.includes('new-name.ts'))
333
+ assert.ok(seedRels.includes('old-name.ts'), '原路径也要去查(别人引用的还是旧名字)')
334
+ assert.ok(!seeds.includes('old-name.ts'), '但原路径**不能当结果**(那个名字已经不存在了)')
335
+ assert.deepEqual(gone, ['old-name.ts'])
336
+ })
337
+
338
+ test('关联:没有任何证据的变更文件如实进 unresolved,**不硬凑**', () => {
339
+ resetRelationCache()
340
+ const corpus = candidateCorpus()
341
+ const rels = new Set(corpus.map((d) => d.rel))
342
+ const facts = buildRelationFacts(corpus, { root: '/t4' })
343
+ const out = projectChangeRelated({
344
+ seeds: ['docs/other.md', 'src/foo.ts'],
345
+ incident: facts.incident,
346
+ itemRels: rels,
347
+ })
348
+ assert.deepEqual(out.unresolved, ['docs/other.md'], '没人提到它 ⇒ 如实说「没有证据」')
349
+ assert.ok(out.related.length > 0)
350
+ })
351
+
352
+ test('关联:结果有条数上限,且排序是确定性的(同样的输入永远同样的顺序)', () => {
353
+ resetRelationCache()
354
+ const corpus = candidateCorpus()
355
+ const rels = new Set(corpus.map((d) => d.rel))
356
+ const facts = buildRelationFacts(corpus, { root: '/t5' })
357
+ const a = projectChangeRelated({ seeds: ['src/foo.ts'], incident: facts.incident, itemRels: rels, limit: 2 })
358
+ const b = projectChangeRelated({ seeds: ['src/foo.ts'], incident: facts.incident, itemRels: rels, limit: 2 })
359
+ assert.deepEqual(a, b)
360
+ assert.ok(a.related.length <= 2)
361
+ assert.equal(a.relatedTotal, 3, 'relatedTotal 说的是**截断前**的总数(面板据此说「还有 N 条」)')
362
+ assert.ok(MAX_CHANGE_RELATED >= 2)
363
+ })
364
+
365
+ /* ── 4. **接口隔离**:变更关联是一条独立接口,普通检索一个字节都不变 ─────────
366
+ v0.25 第二轮:`/api/recent` 的响应与 v0.24 **逐字相同**(`changes` 这个键根本不存在),
367
+ 变更关联走 `/knit/api/changes`。下面三条就是那道闸门:
368
+ ① 常规检索(含显式传旧选项)里不许出现任何变更字段;
369
+ ② 新接口的结构是**专用**的(起点 / 目标 / 类型 / 行号),不借 Context Pack 的词汇;
370
+ ③ 关闭时宿主不读 git(一次都不问)。 */
371
+
372
+ /** 一份最小的 `ranked`(`buildContextFor` 要的形状)。 */
373
+ function rankedCorpus() {
374
+ return candidateCorpus().map((d, i) => ({
375
+ ...d,
376
+ raw: i === 0 ? 3 : 0,
377
+ matchedTerms: i === 0 ? [{ term: 'foo', fields: { title: true, summary: false, body: false } }] : [],
378
+ }))
379
+ }
380
+
381
+ test('隔离:常规检索载荷里**一个变更字段都没有**(连显式传旧选项也一样)', async () => {
382
+ const ranked = rankedCorpus()
383
+ const pack = await buildContextFor('/t6', {
384
+ ranked, topic: 't', task: '', total: ranked.length, withRelations: false,
385
+ })
386
+ assert.ok(!('changes' in pack), 'Context Pack 里不许有 `changes`')
387
+ // 把 v0.25 第一版用过的那两个选项**原样再传一遍** —— 现在它们应当是彻底的噪音
388
+ const alsoOff = await buildContextFor('/t6', {
389
+ ranked, topic: 't', task: '', total: ranked.length, withRelations: false,
390
+ changes: true, changeCorpus: rankedCorpus(), gitReader: { read: async () => { throw new Error('不该被调用') } },
391
+ })
392
+ assert.ok(!('changes' in alsoOff), '传了旧选项也不许冒出来(这条路已经整体删掉了)')
393
+ assert.deepEqual(alsoOff, pack, '两条路径的包必须逐字相同')
394
+ // 变更词汇也不许在任何一层里出现
395
+ const text = JSON.stringify(alsoOff)
396
+ assert.ok(!/changeRelated|"provenance":"change"/.test(text), `包里不许出现变更词汇:${text.slice(0, 200)}`)
397
+ })
398
+
399
+ test('隔离:关闭时**一次 git 都不问**(独立接口自己才是唯一的 git 调用方)', async () => {
400
+ const ranked = rankedCorpus()
401
+ let reads = 0
402
+ const counting = { read: async () => { reads += 1; return { available: true, reason: null, filesTotal: 0, files: [], truncated: false } } }
403
+ await buildContextFor('/t11', {
404
+ ranked, topic: 't', task: '', total: ranked.length, withRelations: false, gitReader: counting,
405
+ })
406
+ assert.equal(reads, 0, '默认路径:一个 git 进程都不 spawn')
407
+ const payload = await changesPayload('/t11', { corpus: ranked, gitReader: counting })
408
+ assert.equal(reads, 1, '独立接口:一次调用只问一次 git')
409
+ assert.equal(payload.mode, 'changes')
410
+ })
411
+
412
+ test('隔离:新接口的结构是**专用**的 —— 起点 / 目标 / 类型 / 行号,不借 Context Pack 的词汇', async () => {
413
+ resetRelationCache()
414
+ const corpus = candidateCorpus()
415
+ const payload = await changesPayload('/t7', {
416
+ corpus,
417
+ changeSet: {
418
+ available: true, reason: null, truncated: false, filesTotal: 2,
419
+ files: [
420
+ { rel: 'src/foo.ts', kinds: ['unstaged'] },
421
+ { rel: 'docs/other.md', kinds: ['untracked'] },
422
+ ],
423
+ },
424
+ })
425
+ // 顶层形状:**没有** `root` / `hostRoot`(绝对路径不外发),也**没有** `sort` / `kind`
426
+ assert.deepEqual(Object.keys(payload).sort(),
427
+ ['git', 'links', 'linksTotal', 'mode', 'ok', 'outOfScope', 'unresolved'].sort())
428
+ assert.ok(!JSON.stringify(payload).includes('/t7'), '载荷里不许出现绝对路径(工作区相对路径足够)')
429
+ assert.equal(payload.mode, 'changes')
430
+ assert.equal(payload.git.available, true)
431
+ assert.equal(payload.git.filesTotal, 2)
432
+ // 顺序由 `git.js` 的解析保证(字典序);这里注入的是手写 changeSet,所以只比集合
433
+ assert.deepEqual(payload.git.files.map((f) => f.rel).sort(), ['docs/other.md', 'src/foo.ts'])
434
+ // 变更文件自己不当结果;两条有证据的目标 + 两条证据行
435
+ const byTarget = new Map(payload.links.map((l) => [l.target, l]))
436
+ assert.ok(!byTarget.has('src/foo.ts'), '变更文件自己不当结果')
437
+ assert.ok(!byTarget.has('docs/other.md'), '没有证据的变更文件不许硬凑成关联结果')
438
+ assert.deepEqual([...byTarget.keys()].sort(), ['docs/readme.md', 'src/bar.ts', 'tests/foo.test.ts'])
439
+ assert.equal(payload.linksTotal, 3)
440
+ assert.deepEqual(payload.unresolved, ['docs/other.md'], '无证据的如实进 unresolved')
441
+ assert.deepEqual(payload.outOfScope, [], '两条变更都在语料里 ⇒ 没有「不在检索范围」的')
442
+
443
+ // 每一条:**起点 / 类型 / 方向 / 行号**四件齐全,且没有一个 Context Pack 的字段
444
+ for (const link of payload.links) {
445
+ assert.deepEqual(Object.keys(link).sort(),
446
+ ['evidence', 'evidenceTotal', 'kind', 'mtimeMs', 'source', 'summary', 'target', 'title', 'types'].sort())
447
+ assert.ok(!('provenance' in link) && !('reason' in link) && !('relations' in link),
448
+ '不许借 Context Pack 条目的词汇(provenance / reason / relations)')
449
+ assert.ok(link.evidence.length > 0, '没有证据就不该出现在这里')
450
+ for (const e of link.evidence) {
451
+ assert.deepEqual(Object.keys(e).sort(), ['dir', 'line', 'origin', 'type'])
452
+ assert.equal(e.origin, 'src/foo.ts', '起点必须是那个**被改过的**文件')
453
+ assert.ok(['references', 'imports', 'tests', 'documents'].includes(e.type), `关系类型 ${e.type}`)
454
+ assert.ok(e.line === null || Number.isInteger(e.line), '行号要么是真实整数、要么是 null')
455
+ }
456
+ }
457
+ // `tests` 是文件名约定 ⇒ `line` 必须是 `null`(不是 0、不是省略)
458
+ const testsEv = byTarget.get('tests/foo.test.ts').evidence.find((e) => e.type === 'tests')
459
+ assert.equal(testsEv.line, null, 'tests 这一类没有行号,专用结构里如实给 null')
460
+ // imports / documents 有真行号
461
+ assert.deepEqual(byTarget.get('src/bar.ts').evidence[0], { origin: 'src/foo.ts', type: 'imports', dir: 'in', line: 1 })
462
+ assert.deepEqual(byTarget.get('docs/readme.md').evidence[0], { origin: 'src/foo.ts', type: 'documents', dir: 'out', line: 3 })
463
+ })
464
+
465
+ test('隔离:读不到 git / 非 Git / 没有关联 —— 三种降级都安全且结构齐全', async () => {
466
+ const corpus = candidateCorpus()
467
+ // ① 非 Git:`git.available=false` + 原因,links 空,但仍然是一份**结构齐全**的载荷
468
+ const noRepo = await changesPayload('/t8', {
469
+ corpus,
470
+ changeSet: { available: false, reason: 'not-a-repo', files: [], filesTotal: 0, truncated: false },
471
+ })
472
+ assert.equal(noRepo.ok, true)
473
+ assert.equal(noRepo.git.available, false)
474
+ assert.equal(noRepo.git.reason, 'not-a-repo')
475
+ assert.deepEqual(noRepo.links, [])
476
+ assert.deepEqual(noRepo.unresolved, [])
477
+ assert.equal(noRepo.linksTotal, 0)
478
+ // ② 一条变更都没有
479
+ const clean = await changesPayload('/t9', {
480
+ corpus,
481
+ changeSet: { available: true, reason: null, files: [], filesTotal: 0, truncated: false },
482
+ })
483
+ assert.equal(clean.git.available, true)
484
+ assert.equal(clean.git.filesTotal, 0)
485
+ assert.deepEqual(clean.links, [])
486
+ // ③ 有变更但一条关联都没有(全是语料之外的路径)
487
+ const none = await changesPayload('/t10', {
488
+ corpus,
489
+ changeSet: {
490
+ available: true, reason: null, truncated: false, filesTotal: 1,
491
+ files: [{ rel: 'zz/nowhere.ts', kinds: ['untracked'] }],
492
+ },
493
+ })
494
+ assert.deepEqual(none.links, [], '一条证据都没有 ⇒ 一条结果都不给')
495
+ assert.deepEqual(none.outOfScope, ['zz/nowhere.ts'], '语料之外 ⇒ 只进 outOfScope')
496
+ assert.deepEqual(none.unresolved, [], '语料之外的**不算** unresolved(两个计数不许重复算同一篇)')
497
+ })
498
+
499
+ test('隔离:下发的变更清单有上限,但 `filesTotal` 仍是**全量**(不许因为截断少报)', async () => {
500
+ const many = Array.from({ length: MAX_REPORTED_FILES + 10 }, (_, i) => ({ rel: `f${i}.ts`, kinds: ['unstaged'] }))
501
+ const payload = await changesPayload('/t10', {
502
+ corpus: rankedCorpus(),
503
+ changeSet: { available: true, reason: null, files: many, filesTotal: many.length, truncated: false },
504
+ })
505
+ assert.equal(payload.git.files.length, MAX_REPORTED_FILES, '载荷里只带前 N 个(体积有界)')
506
+ assert.equal(payload.git.filesTotal, many.length, '但计数是全量')
507
+ })
508
+
509
+ test('隔离:**几百个变更文件**也不会放大输出 —— 清单 / 结果 / 证据各有一道上限', async () => {
510
+ const many = Array.from({ length: 300 }, (_, i) => ({ rel: `zz/not-in-corpus-${i}.ts`, kinds: ['unstaged'] }))
511
+ const payload = await changesPayload('/t12', {
512
+ corpus: rankedCorpus(),
513
+ changeSet: { available: true, reason: null, truncated: false, files: many, filesTotal: many.length },
514
+ })
515
+ assert.equal(payload.git.files.length, MAX_REPORTED_FILES)
516
+ assert.equal(payload.git.filesTotal, 300)
517
+ assert.ok(payload.links.length <= MAX_CHANGE_RELATED, '关联结果有上限')
518
+ assert.equal(payload.outOfScope.length, 300, '300 条全都不在语料里 —— 如实计数,不硬凑')
519
+ assert.deepEqual(payload.links, [])
520
+ })
521
+
522
+ /* ── 5. 复用:两个接口**共用**一次扫描与一次 git(不重复 walk、不重复 spawn)── */
523
+
524
+ test('复用:`scan()` 记一份备忘,独立接口**直接复用**它(TTL 内不再走目录树)', async () => {
525
+ const repo = makeAcceptanceRepo()
526
+ try {
527
+ resetScanMemo()
528
+ assert.equal(scanMemo(), null, '清掉之后没有可复用的扫描')
529
+ const session = {
530
+ header: { cwd: repo, id: 'memo' },
531
+ snapshotEvents: () => [],
532
+ }
533
+ const payload = await scan(repo, 40, { session, sessionId: 'memo-1', sort: 'relevance', kind: 'context' })
534
+ const memo = scanMemo()
535
+ assert.equal(memo.root, repo, '扫完就记下这个工作区')
536
+
537
+ // **可观测的复用证明**:把一个文件删掉,再问一次语料 —— 复用的那份里**仍然**有它
538
+ // (如果这里重新走了目录树,它就该消失了)。
539
+ rmSync(join(repo, 'docs', 'guide.md'))
540
+ const reused = await corpusForChanges(repo, { limit: 40, options: { session, sessionId: 'memo-2', sort: 'relevance', kind: 'context' } })
541
+ assert.ok(reused.contextCorpus.some((d) => d.rel === 'docs/guide.md'),
542
+ 'TTL 内复用的是**同一份**语料(没有重新 walk)')
543
+ assert.equal(reused, payload, '复用的就是同一个对象(连引用都相同)')
544
+
545
+ // 清掉备忘之后必须真扫 —— 这时那个文件才该消失(证明上面那条不是「怎么扫都还在」)
546
+ resetScanMemo()
547
+ const fresh = await corpusForChanges(repo, { limit: 40, options: { session, sessionId: 'memo-3', sort: 'relevance', kind: 'context' } })
548
+ assert.ok(!fresh.contextCorpus.some((d) => d.rel === 'docs/guide.md'), '清掉备忘后真的重扫,删掉的文件不再出现')
549
+ } finally {
550
+ rmSync(repo, { recursive: true, force: true })
551
+ }
552
+ })
553
+
554
+ test('接线:`contextCorpus` 是内部字段,`publicScanPayload()` 必须把它剥掉', () => {
555
+ const payload = {
556
+ ok: true, docs: [], contextCorpus: [{ rel: 'a.ts' }], ranked: [], task: '', allDocs: [], stats: {},
557
+ }
558
+ const pub = publicScanPayload(payload)
559
+ assert.ok(!('contextCorpus' in pub), '内部候选集不下发')
560
+ assert.ok(!('ranked' in pub) && !('allDocs' in pub) && !('stats' in pub) && !('task' in pub))
561
+ assert.equal(pub.ok, true)
562
+ })
563
+
564
+ /* ── 6. **契约守卫**:这个功能**不许**渗进 agent 工具 ─────────────
565
+ `knit_docs` 的输入 / 输出 schema 是既有接口契约(`additionalProperties: false`)。
566
+ 把「Git 变更关联」做成平行区时,它只走**面板那一侧**(HTTP 的 `context.changes`);
567
+ 工具那一侧的入参、返回值与 `ITEM_SCHEMA` 一个字节都不许动。下面这条就是那道闸门。 */
568
+
569
+ test('契约:`knit_docs` 的入参与输出 schema **完全没变**(这个功能不进 agent 工具)', () => {
570
+ const definition = knitDocsDefinition(() => {})
571
+ assert.deepEqual(Object.keys(definition.parameters.properties), ['query', 'limit', 'audit', 'retrieval'],
572
+ '参数集合不许变(变更关联没有 `changes` 这个参数)')
573
+ assert.equal(definition.parameters.properties.changes, undefined)
574
+ // 输出 schema:多一个属性就会在**校验层**静默失败(v0.14 的 kind 那次教训)
575
+ assert.equal(definition.output.schema.properties.changes, undefined, '输出里不许有 `changes`')
576
+ assert.deepEqual(definition.output.schema.required,
577
+ ['mode', 'topic', 'total', 'primary', 'supporting', 'related'])
578
+ for (const tier of ['primary', 'supporting', 'related', 'pinned']) {
579
+ const items = definition.output.schema.properties[tier].items
580
+ assert.deepEqual(items.properties.provenance.enum, ['retrieval', 'relation', 'manual', 'semantic'],
581
+ `${tier}:来源枚举不许扩(change 不进契约)`)
582
+ assert.ok(!items.properties.reason.properties.code.enum.includes('changeRelated'),
583
+ `${tier}:理由码枚举不许扩(changeRelated 不进契约)`)
584
+ }
585
+ })
586
+
587
+ /* ── 7. 解析边界:NUL 分隔、空格 / 换行文件名、重命名、前缀过滤与截断顺序 ── */
588
+
589
+ test('解析:文件名含**空格**与**换行**时按 NUL 切分仍然正确(`-z` 不转义)', () => {
590
+ const raw = 'M src/a b.ts\0?? weird\nname.ts\0?? tab\tname.ts\0'
591
+ const files = parseStatusZ(raw)
592
+ assert.deepEqual(files.map((f) => f.rel).sort(), ['src/a b.ts', 'tab\tname.ts', 'weird\nname.ts'].sort())
593
+ const byRel = new Map(files.map((f) => [f.rel, f]))
594
+ assert.deepEqual(byRel.get('src/a b.ts').kinds, ['staged'])
595
+ assert.deepEqual(byRel.get('weird\nname.ts').kinds, ['untracked'])
596
+ })
597
+
598
+ test('解析:重命名只吃**紧跟其后的那一个**原路径字段(后面的条目不许被吃掉)', () => {
599
+ const raw = 'R new name.ts\0old name.ts\0M after.ts\0R b.ts\0a.ts\0'
600
+ const files = parseStatusZ(raw)
601
+ assert.deepEqual(files.map((f) => f.rel), ['after.ts', 'b.ts', 'new name.ts'])
602
+ const byRel = new Map(files.map((f) => [f.rel, f]))
603
+ assert.equal(byRel.get('new name.ts').origRel, 'old name.ts')
604
+ assert.equal(byRel.get('b.ts').origRel, 'a.ts')
605
+ assert.equal(byRel.get('after.ts').origRel, undefined, '普通条目不许被前一条的重命名字段串位')
606
+ })
607
+
608
+ test('解析:**先按工作区前缀过滤、再算条目数** —— 工作区外的条目不许占用 200 条上限', () => {
609
+ const outside = Array.from({ length: 250 }, (_, i) => `M outside/f${String(i).padStart(4, '0')}.ts`).join('\0') + '\0'
610
+ const inside = Array.from({ length: 5 }, (_, i) => `M src/keep${i}.ts`).join('\0') + '\0'
611
+ const files = parseStatusZ(outside + inside, { prefix: 'src/' })
612
+ assert.equal(files.length, 5, '前缀之外的 250 条都被丢掉,不占上限')
613
+ assert.ok(files.every((f) => f.rel.startsWith('keep')))
614
+
615
+ const capped = parseStatusZ(
616
+ Array.from({ length: MAX_CHANGED_FILES + 7 }, (_, i) => `M src/f${String(i).padStart(4, '0')}.ts`).join('\0') + '\0',
617
+ )
618
+ assert.equal(capped.length, MAX_CHANGED_FILES + 7, '`parseStatusZ` 自己**不截断**(截断是读取器的事)')
619
+ })
620
+
621
+ test('读取器:截断发生在前缀过滤**之后**(截到的是这个工作区的文件)', async () => {
622
+ const outside = Array.from({ length: 260 }, (_, i) => `M outside/f${String(i).padStart(4, '0')}.ts`).join('\0') + '\0'
623
+ const inside = Array.from({ length: 12 }, (_, i) => `M src/keep${i}.ts`).join('\0') + '\0'
624
+ const impl = async (args) => (args.includes('rev-parse')
625
+ ? { code: 0, stdout: 'src/\n', stderr: '' }
626
+ : { code: 0, stdout: outside + inside, stderr: '' })
627
+ const result = await createGitReader({ exec: impl, now: () => 0 }).read('/w')
628
+ assert.equal(result.truncated, false, '工作区内只有 12 条 ⇒ 不截断')
629
+ assert.equal(result.filesTotal, 12)
630
+ assert.ok(result.files.every((f) => f.rel.startsWith('keep')))
631
+ })
632
+
633
+ /* ── 8. 安全边界:**真机**证明 fsmonitor 钩子不会被拉起 ─────────
634
+ 这一条是「只读」这条承诺的闭合处:固定 argv 只挡住我们主动写,
635
+ 挡不住 git 被 `core.fsmonitor` 牵着去执行外部命令 / 起守护进程。 */
636
+
637
+ test('安全(真机):`core.fsmonitor` 指向外部钩子时,我们的读取**不会**执行它', async () => {
638
+ const repo = mkdtempSync(join(tmpdir(), 'knit-git-fsmon-'))
639
+ const log = join(repo, 'hook-ran.log')
640
+ const hook = join(repo, 'fsmonitor.sh')
641
+ try {
642
+ writeFileSync(hook, `#!/bin/sh\necho ran >> ${log}\n echo "/"\n`, { mode: 0o755 })
643
+ const git = (...args) => execFileSync('git', ['-C', repo, ...args], { stdio: ['ignore', 'pipe', 'pipe'] })
644
+ execFileSync('git', ['init', '-q', repo], { stdio: 'ignore' })
645
+ git('config', 'user.email', 't@t')
646
+ git('config', 'user.name', 't')
647
+ writeFileSync(join(repo, 'a.ts'), 'x\n')
648
+ git('add', '-A')
649
+ git('commit', '-qm', 'init')
650
+ git('config', 'core.fsmonitor', hook)
651
+
652
+ const result = await createGitReader({ now: () => 0 }).read(repo)
653
+ assert.equal(result.available, true, `读取必须成功(reason=${result.reason})`)
654
+ let ran = true
655
+ try { readFileSync(log) } catch { ran = false }
656
+ assert.equal(ran, false, '`core.fsmonitor` 的钩子**一次都不许被执行**(-c core.fsmonitor=false)')
657
+ } finally {
658
+ rmSync(repo, { recursive: true, force: true })
659
+ }
660
+ })
661
+
662
+ /* ── 9. 独立验收案例:一个**确定性的临时仓库**,只改一个文件 ─────────
663
+ 它不是「在脏工作区上跑一遍」,而是一份**受控**夹具:唯一的变更文件 = `src/foo.ts`,
664
+ 四类关系里预置三类(imports / tests / documents)+ 一组**干扰项**。
665
+ 每个结果的起点、目标、类型、行号都要能回到原文核对;干扰项一个都不许进来。 */
666
+
667
+ /**
668
+ * 造出这一份夹具 → 返回仓库路径(调用方负责 `rmSync`)。
669
+ *
670
+ * @param {{extraTest?: boolean}} [options] - `extraTest` 会在**初始提交之前**再放一个
671
+ * `src/foo.test.ts`(用来验「同名测试出现在两个候选位置」时的方向性)。
672
+ * ⚠️ 必须写在初始提交之前 —— 测试里再 `git add -A && commit` 会把那一处变更一起提交掉,
673
+ * 工作树因此变干净、变更集为空(第一版这么写错过一次)。
674
+ */
675
+ function makeAcceptanceRepo(options = {}) {
676
+ const repo = mkdtempSync(join(tmpdir(), 'knit-git-case-'))
677
+ const w = (rel, text) => {
678
+ const abs = join(repo, rel)
679
+ mkdirSync(join(abs, '..'), { recursive: true })
680
+ writeFileSync(abs, text)
681
+ }
682
+ const git = (...args) => execFileSync('git', ['-C', repo, ...args], { stdio: ['ignore', 'pipe', 'pipe'] })
683
+ execFileSync('git', ['init', '-q', repo], { stdio: 'ignore' })
684
+ git('config', 'user.email', 't@t')
685
+ git('config', 'user.name', 't')
686
+
687
+ // 变更文件:第 1 行就是 import(行号证据)
688
+ w('src/foo.ts', "import { b } from './bar'\nexport const foo = () => b + 1\n")
689
+ w('src/bar.ts', 'export const b = 1\n')
690
+ // ⚠️ 测试文件的目录必须是 `test/`(`testsOf()` 的候选只有 `<dir>/` 与 `test/`)
691
+ w('test/foo.test.ts', "import { foo } from '../src/foo'\nexport const t = foo()\n")
692
+ w('docs/guide.md', '# Guide\n\nsee src/foo.ts for details\n')
693
+ // 干扰项:谁都不引用、也不 import 谁
694
+ w('src/util.ts', 'export const u = 2\n')
695
+ w('src/other.ts', 'export const o = 3\n')
696
+ w('test/other.test.ts', "import { o } from '../src/other'\n")
697
+ w('docs/notes.md', '# Notes\n\nnothing about code here\n')
698
+ // 同名测试的第二个候选位置(只由 `extraTest` 用例打开)
699
+ if (options.extraTest === true) w('src/foo.test.ts', "import './foo'\n")
700
+ git('add', '-A')
701
+ git('commit', '-qm', 'init')
702
+ // **只**改 src/foo.ts(暂存 + 未暂存都占上)
703
+ w('src/foo.ts', "import { b } from './bar'\nexport const foo = () => b + 2\n")
704
+ git('add', 'src/foo.ts')
705
+ w('src/foo.ts', "import { b } from './bar'\nexport const foo = () => b + 3\n")
706
+ return repo
707
+ }
708
+
709
+ test('独立案例:只改 `src/foo.ts` ⇒ 精确找到它的测试 / 被导入模块 / 提到它的文档,干扰项一个不进', async () => {
710
+ const repo = makeAcceptanceRepo()
711
+ try {
712
+ const session = {
713
+ header: { cwd: repo, id: 'accept' },
714
+ // 任务原话**刻意与这些文件无关**:变更关联不该依赖对话提到什么
715
+ snapshotEvents: () => [{ seq: 1, type: 'user/message', data: { role: 'user', content: [{ type: 'text', text: '天气 阴天 出门带伞' }], source: { kind: 'user' } } }],
716
+ }
717
+ const payload = await scan(repo, 40, { session, sessionId: 'accept-1', sort: 'relevance', kind: 'context' })
718
+ const off = await buildContextFor(repo, { ranked: payload.ranked, topic: payload.topic, task: payload.task, total: payload.total })
719
+ // v0.25 第二轮:变更关联走**独立接口**(这里是它的载荷构造函数,等价于 `/api/changes` 的内核)
720
+ const on = await changesPayload(repo, { corpus: payload.contextCorpus })
721
+
722
+ // ① git 事实:**只有**一个变更文件,而且是暂存 + 未暂存都占
723
+ assert.equal(on.git.available, true, `git 读取必须成功(reason=${on.git.reason})`)
724
+ assert.equal(on.git.filesTotal, 1, `只改了一个文件,实测 ${JSON.stringify(on.git.files.map((f) => f.rel))}`)
725
+ assert.deepEqual(on.git.files.map((f) => f.rel), ['src/foo.ts'])
726
+ assert.deepEqual(on.git.files[0].kinds, ['staged', 'unstaged'])
727
+
728
+ // ② 关联结果**恰好**是这三条(多一条都算误报)
729
+ const got = on.links.map((i) => i.target).sort()
730
+ assert.deepEqual(got, ['docs/guide.md', 'src/bar.ts', 'test/foo.test.ts'],
731
+ `结果集合必须精确:${JSON.stringify(got)}`)
732
+ // ③ 干扰项一个都不许进来
733
+ for (const noise of ['src/util.ts', 'src/other.ts', 'test/other.test.ts', 'docs/notes.md']) {
734
+ assert.ok(!got.includes(noise), `没有证据的文件不许被标成关联结果:${noise}`)
735
+ }
736
+ assert.deepEqual(on.unresolved, [], 'foo.ts 有证据 ⇒ 不算 unresolved')
737
+ assert.equal(on.linksTotal, 3)
738
+
739
+ // ④ 每条证据的**起点 / 类型 / 行号**都要与原文一致
740
+ const readLine = (rel, line) => readFileSync(join(repo, rel), 'utf8').split('\n')[line - 1]
741
+ const byRel = new Map(on.links.map((i) => [i.target, i]))
742
+ const evOf = (rel, type) => byRel.get(rel).evidence.find((e) => e.type === type)
743
+
744
+ const imp = evOf('src/bar.ts', 'imports')
745
+ assert.deepEqual({ type: imp.type, dir: imp.dir, origin: imp.origin, line: imp.line },
746
+ { type: 'imports', dir: 'in', origin: 'src/foo.ts', line: 1 })
747
+ assert.match(readLine('src/foo.ts', imp.line), /from '\.\/bar'/, '行号指的必须真是那一行')
748
+
749
+ const tst = evOf('test/foo.test.ts', 'tests')
750
+ assert.deepEqual({ type: tst.type, dir: tst.dir, origin: tst.origin }, { type: 'tests', dir: 'out', origin: 'src/foo.ts' })
751
+ assert.equal(tst.line, null, 'tests 是文件名约定 ⇒ 如实给 null,**不许**编一个行号')
752
+
753
+ const doc = evOf('docs/guide.md', 'documents')
754
+ assert.deepEqual({ type: doc.type, dir: doc.dir, origin: doc.origin, line: doc.line },
755
+ { type: 'documents', dir: 'out', origin: 'src/foo.ts', line: 3 })
756
+ assert.match(readLine('docs/guide.md', doc.line), /src\/foo\.ts/, '文档那一行必须真的提到它')
757
+
758
+ // ⑤ 每一条证据的起点都必须是那个**变更文件**(不许拿别的文件当起点)
759
+ for (const link of on.links) {
760
+ for (const e of link.evidence) assert.equal(e.origin, 'src/foo.ts', `${link.target} 的证据起点错了`)
761
+ assert.ok(!('provenance' in link) && !('reason' in link), '专用结构里没有 Context Pack 的词汇')
762
+ }
763
+ // ⑥ 变更文件**自己**不当结果
764
+ assert.ok(!got.includes('src/foo.ts'))
765
+
766
+ // ⑦ 原有行为:独立接口**完全不碰** Context Pack(三层的唯一来源是 `buildContextFor`)
767
+ assert.ok(!('changes' in off), '默认路径连这个键都不该有')
768
+ assert.ok(!('links' in off) && !('git' in off), '包与独立接口的载荷是两套结构')
769
+ } finally {
770
+ rmSync(repo, { recursive: true, force: true })
771
+ }
772
+ })
773
+
774
+ test('独立案例(约定边界):同名测试有两个候选位置时,边**只从测试那一侧**建立', async () => {
775
+ // 语义(读 `relations.js` 的实现得出,不是猜的):
776
+ // · `testsOf(源文件)` 会去 `<dir>/x.test.*` 与 `test/x.test.*` 两处找 —— **两个都在 ⇒ 歧义 ⇒ null**;
777
+ // · `testsOf(测试文件)` 按 stem 找唯一同名非测试文件 —— 唯一 ⇒ 认。
778
+ // 所以「源 → 测试」那一侧不猜,而每个测试文件各自**唯一地**指向它的被测文件,那条边照常成立。
779
+ // 这是可核验的路径事实(文件名一致),不是推断;本用例把这个方向性钉住。
780
+ const repo = makeAcceptanceRepo({ extraTest: true })
781
+ try {
782
+ const session = {
783
+ header: { cwd: repo, id: 'accept2' },
784
+ snapshotEvents: () => [{ seq: 1, type: 'user/message', data: { role: 'user', content: [{ type: 'text', text: '天气 阴天 出门带伞' }], source: { kind: 'user' } } }],
785
+ }
786
+ const payload = await scan(repo, 40, { session, sessionId: 'accept-2', sort: 'relevance', kind: 'context' })
787
+ const on = await changesPayload(repo, { corpus: payload.contextCorpus })
788
+
789
+ // ① 两个测试文件**各自**都指向 src/foo.ts(这就是要的结果:两个都该看)
790
+ const testsTargets = on.links
791
+ .filter((i) => i.evidence.some((e) => e.type === 'tests'))
792
+ .map((i) => i.target)
793
+ .sort()
794
+ assert.deepEqual(testsTargets, ['src/foo.test.ts', 'test/foo.test.ts'],
795
+ `两个同名测试都该被找出来:${JSON.stringify(testsTargets)}`)
796
+ for (const link of on.links) {
797
+ for (const e of link.evidence.filter((x) => x.type === 'tests')) {
798
+ assert.equal(e.origin, 'src/foo.ts', 'tests 边的起点永远是**测试文件自己**(叙述方)')
799
+ assert.equal(e.line, null, 'tests 不给行号(专用结构里是 null)')
800
+ }
801
+ }
802
+ // ② 反向(源 → 测试)确实是歧义的:这一侧**不猜**,回 null
803
+ assert.equal(
804
+ testsOf('src/foo.ts', createIndex(['src/foo.ts', 'src/foo.test.ts', 'test/foo.test.ts'])),
805
+ null,
806
+ '两个候选位置都在 ⇒ 源→测试这一侧不许猜',
807
+ )
808
+ } finally {
809
+ rmSync(repo, { recursive: true, force: true })
810
+ }
811
+ })
812
+
813
+ test('真机:工作区是仓库的**子目录**时,路径按工作区基准给出,工作区之外的改动被丢掉', async () => {
814
+ const repo = mkdtempSync(join(tmpdir(), 'knit-git-sub-'))
815
+ try {
816
+ const git = (...args) => execFileSync('git', ['-C', repo, ...args], { stdio: ['ignore', 'pipe', 'pipe'] })
817
+ execFileSync('git', ['init', '-q', repo], { stdio: 'ignore' })
818
+ git('config', 'user.email', 't@t')
819
+ git('config', 'user.name', 't')
820
+ mkdirSync(join(repo, 'app', 'src'), { recursive: true })
821
+ mkdirSync(join(repo, 'outside'), { recursive: true })
822
+ writeFileSync(join(repo, 'app', 'src', 'in.ts'), 'a\n')
823
+ writeFileSync(join(repo, 'outside', 'out.ts'), 'b\n')
824
+ git('add', '-A')
825
+ git('commit', '-qm', 'init')
826
+ writeFileSync(join(repo, 'app', 'src', 'in.ts'), 'a2\n')
827
+ writeFileSync(join(repo, 'outside', 'out.ts'), 'b2\n')
828
+ // 工作区根 = 仓库里的 app/ 子目录
829
+ const result = await createGitReader({ now: () => 0 }).read(join(repo, 'app'))
830
+ assert.equal(result.available, true, `子目录也必须能读(reason=${result.reason})`)
831
+ assert.deepEqual(result.files.map((f) => f.rel), ['src/in.ts'],
832
+ `只报工作区内的那条,且路径**不含** app/ 前缀:${JSON.stringify(result.files.map((f) => f.rel))}`)
833
+ assert.equal(result.filesTotal, 1, '工作区外那条不许计入')
834
+ } finally {
835
+ rmSync(repo, { recursive: true, force: true })
836
+ }
837
+ })
838
+
839
+ /* ── 10. **真接口**:在真实回环端口上验 `/api/changes` 与 `/api/recent` 的隔离 ─────
840
+ 前面那些用例验的是载荷构造函数(等价于路由内核);这一条验**接口本身**:
841
+ 路由存在、query 解析、响应形状、以及「常规检索请求里没有变更字段」这条隔离纪律。 */
842
+
843
+ test('独立接口(真端口):`/api/changes` 返回夹具里那三条关联,且 `/api/recent` 完全不受影响', async () => {
844
+ const repo = makeAcceptanceRepo()
845
+ let server
846
+ try {
847
+ server = await startKnitServer({ root: repo, sessionId: 's' })
848
+ // ① 常规检索:**一个变更字段都没有**
849
+ const recent = await (await fetch(`${server.base}/api/recent?sessionId=s&sort=relevance&kind=doc&limit=40`)).json()
850
+ assert.equal(recent.ok, true)
851
+ assert.ok(!('changes' in recent), '`/api/recent` 顶层不许有 changes')
852
+ assert.ok(!('changes' in (recent.context || {})), '`context` 里也不许有')
853
+ assert.ok(!/changeRelated|"provenance":"change"/.test(JSON.stringify(recent.context || {})), '包里不许有变更词汇')
854
+
855
+ // ② 独立接口:三条关联,起点 / 类型 / 行号逐条对得上
856
+ const res = await fetch(`${server.base}/api/changes?sessionId=s&sort=relevance&kind=doc&limit=40`)
857
+ assert.equal(res.status, 200)
858
+ const body = await res.json()
859
+ assert.equal(body.ok, true)
860
+ assert.equal(body.mode, 'changes')
861
+ assert.equal(body.git.available, true)
862
+ assert.equal(body.git.filesTotal, 1)
863
+ assert.deepEqual(body.git.files.map((f) => f.rel), ['src/foo.ts'])
864
+ assert.deepEqual(body.links.map((l) => l.target).sort(), ['docs/guide.md', 'src/bar.ts', 'test/foo.test.ts'])
865
+ assert.equal(body.linksTotal, 3)
866
+ const byTarget = new Map(body.links.map((l) => [l.target, l]))
867
+ assert.deepEqual(byTarget.get('src/bar.ts').evidence[0], { origin: 'src/foo.ts', type: 'imports', dir: 'in', line: 1 })
868
+ assert.deepEqual(byTarget.get('docs/guide.md').evidence[0], { origin: 'src/foo.ts', type: 'documents', dir: 'out', line: 3 })
869
+ const tEv = byTarget.get('test/foo.test.ts').evidence.find((e) => e.type === 'tests')
870
+ assert.equal(tEv.line, null, 'tests 那一类没有行号 ⇒ null')
871
+ // 干扰项一个都不许进来
872
+ for (const noise of ['src/util.ts', 'src/other.ts', 'test/other.test.ts', 'docs/notes.md']) {
873
+ assert.ok(!byTarget.has(noise), `误报:${noise}`)
874
+ }
875
+
876
+ // ③ 时间序:如实说「这条口径下没有变更关联」,不是空壳
877
+ const timeBody = await (await fetch(`${server.base}/api/changes?sessionId=s&sort=time`)).json()
878
+ assert.equal(timeBody.ok, true)
879
+ assert.equal(timeBody.git.available, false)
880
+ assert.equal(timeBody.git.reason, 'not-relevance-order')
881
+ assert.deepEqual(timeBody.links, [])
882
+ } finally {
883
+ if (server) await server.close()
884
+ rmSync(repo, { recursive: true, force: true })
885
+ }
886
+ })
887
+
888
+ test('独立接口(真端口):**非 Git 工作区**安全降级,`/api/recent` 照旧可用', async () => {
889
+ const dir = mkdtempSync(join(tmpdir(), 'knit-nogit-'))
890
+ let server
891
+ try {
892
+ writeFileSync(join(dir, 'a.md'), '# a\n\nhello\n')
893
+ server = await startKnitServer({ root: dir, sessionId: 's' })
894
+ const recent = await (await fetch(`${server.base}/api/recent?sessionId=s&sort=relevance&limit=10`)).json()
895
+ assert.equal(recent.ok, true, '非 Git 工作区里列表这条路必须照常')
896
+ assert.ok(Array.isArray(recent.docs))
897
+ const body = await (await fetch(`${server.base}/api/changes?sessionId=s&sort=relevance&limit=10`)).json()
898
+ assert.equal(body.ok, true)
899
+ assert.equal(body.git.available, false)
900
+ assert.equal(body.git.reason, 'not-a-repo')
901
+ assert.deepEqual(body.links, [])
902
+ assert.deepEqual(body.unresolved, [])
903
+ assert.deepEqual(body.outOfScope, [])
904
+ } finally {
905
+ if (server) await server.close()
906
+ rmSync(dir, { recursive: true, force: true })
907
+ }
908
+ })
909
+
910
+ test('独立接口(真端口):同窗内两个接口**共用**一次扫描与一次 git —— 说清「为什么相同」', async () => {
911
+ /* 这个用例的**前置状态 / 命中结果 / 清掉之后的结果**必须逐段写清,否则「结果相同」
912
+ 证明不了复用。三段是:
913
+ ① 前置:`/api/recent` 先扫一次(备忘建立)→ `/api/changes` 再读一次 git(缓存建立);
914
+ ② 缓存热:**在扫描之后**把 `docs/guide.md` 删掉,两条接口都还按**旧快照**回答 ——
915
+ 它仍是被关联目标(语料里还有它),而删除**没有**进变更集(git 也没重读);
916
+ ③ 缓存冷:把扫描备忘与 git 缓存都清掉之后再问 —— 删除**必须**同时出现在两处:
917
+ 它不再是关联目标,而且变成第二条变更(`deleted`)。
918
+ 只有 ②③ 都在,才能说 ② 的「看不见」是缓存造成的,而不是接口对文件增删无感。 */
919
+ const repo = makeAcceptanceRepo()
920
+ let server
921
+ try {
922
+ server = await startKnitServer({ root: repo, sessionId: 's' })
923
+ const url = `${server.base}/api/changes?sessionId=s&sort=relevance&limit=40`
924
+ const expected = ['docs/guide.md', 'src/bar.ts', 'test/foo.test.ts']
925
+
926
+ // ① 前置:扫描(recent)+ git(changes)
927
+ await fetch(`${server.base}/api/recent?sessionId=s&sort=relevance&kind=doc&limit=40`)
928
+ const memoAt = scanMemo().at
929
+ const before = await (await fetch(url)).json()
930
+ assert.deepEqual(before.links.map((l) => l.target).sort(), expected)
931
+ assert.equal(before.git.filesTotal, 1)
932
+ assert.equal(scanMemo().at, memoAt, '这次请求**没有**重新扫(备忘时间戳没变)—— 这就是复用的直接证据')
933
+
934
+ // ② 缓存热:删掉那个「提到过 foo.ts 的文档」
935
+ rmSync(join(repo, 'docs', 'guide.md'))
936
+ const after = await (await fetch(url)).json()
937
+ assert.equal(scanMemo().at, memoAt, '仍然没有重扫')
938
+ assert.deepEqual(after.links.map((l) => l.target).sort(), expected,
939
+ '语料还是旧快照 ⇒ guide.md 仍能当被关联目标')
940
+ assert.equal(after.git.filesTotal, 1,
941
+ 'git 也是旧快照 ⇒ 这次删除还没有变成第二条变更(它确实是一次已提交文件的删除)')
942
+
943
+ // ③ 缓存冷:两个缓存都清掉,同一份请求必须**同时**反映那次删除
944
+ resetScanMemo()
945
+ resetGitReaderCache()
946
+ const fresh = await (await fetch(url)).json()
947
+ assert.ok(scanMemo() && scanMemo().at > memoAt, '清掉备忘后真的重扫了')
948
+ assert.ok(!fresh.links.some((l) => l.target === 'docs/guide.md'),
949
+ '重扫之后语料里没有它了 ⇒ 不再是被关联目标')
950
+ assert.equal(fresh.git.filesTotal, 2, '重读 git 之后这次删除变成第二条变更(deleted)')
951
+ assert.ok(fresh.git.files.some((f) => f.rel === 'docs/guide.md' && f.kinds.includes('deleted')),
952
+ '而且它自己是 `deleted` —— 变更文件自己不当结果,所以它只出现在 git 清单里')
953
+ assert.ok(!fresh.links.some((l) => l.target === 'docs/guide.md'))
954
+ } finally {
955
+ if (server) await server.close()
956
+ resetScanMemo()
957
+ resetGitReaderCache()
958
+ rmSync(repo, { recursive: true, force: true })
959
+ }
960
+ })
961
+
962
+ test('独立接口(真端口):`kind` 已从契约里删除,传了也**不改变任何结果**', async () => {
963
+ // 删掉它的理由要能被验证:变更关联固定用「文档 + 代码」那一份**不分档**语料,
964
+ // 档位只切列表那一栏。所以带不带 `kind`、带哪个值,答案必须逐字相同。
965
+ const repo = makeAcceptanceRepo()
966
+ let server
967
+ try {
968
+ server = await startKnitServer({ root: repo, sessionId: 's' })
969
+ resetScanMemo()
970
+ const bare = await (await fetch(`${server.base}/api/changes?sessionId=s&sort=relevance&limit=40`)).json()
971
+ const withKind = await (await fetch(`${server.base}/api/changes?sessionId=s&sort=relevance&limit=40&kind=media`)).json()
972
+ assert.deepEqual(withKind.links, bare.links, '`kind=media` 与不带参数必须给出同样的关联')
973
+ assert.deepEqual(withKind.git, bare.git)
974
+ // 绝对路径一个都不许出现在响应体里
975
+ assert.ok(!JSON.stringify(bare).includes(repo), '响应里不许有绝对路径')
976
+ } finally {
977
+ if (server) await server.close()
978
+ resetScanMemo()
979
+ rmSync(repo, { recursive: true, force: true })
980
+ }
981
+ })
982
+
983
+ test('真机:工作区是仓库的**子目录**时,路径按工作区基准给出,工作区之外的改动被丢掉', async () => {
984
+ const repo = mkdtempSync(join(tmpdir(), 'knit-git-sub-'))
985
+ try {
986
+ const git = (...args) => execFileSync('git', ['-C', repo, ...args], { stdio: ['ignore', 'pipe', 'pipe'] })
987
+ execFileSync('git', ['init', '-q', repo], { stdio: 'ignore' })
988
+ git('config', 'user.email', 't@t')
989
+ git('config', 'user.name', 't')
990
+ mkdirSync(join(repo, 'app', 'src'), { recursive: true })
991
+ mkdirSync(join(repo, 'outside'), { recursive: true })
992
+ writeFileSync(join(repo, 'app', 'src', 'in.ts'), 'a\n')
993
+ writeFileSync(join(repo, 'outside', 'out.ts'), 'b\n')
994
+ git('add', '-A')
995
+ git('commit', '-qm', 'init')
996
+ writeFileSync(join(repo, 'app', 'src', 'in.ts'), 'a2\n')
997
+ writeFileSync(join(repo, 'outside', 'out.ts'), 'b2\n')
998
+ // 工作区根 = 仓库里的 app/ 子目录
999
+ const result = await createGitReader({ now: () => 0 }).read(join(repo, 'app'))
1000
+ assert.equal(result.available, true, `子目录也必须能读(reason=${result.reason})`)
1001
+ assert.deepEqual(result.files.map((f) => f.rel), ['src/in.ts'],
1002
+ `只报工作区内的那条,且路径**不含** app/ 前缀:${JSON.stringify(result.files.map((f) => f.rel))}`)
1003
+ assert.equal(result.filesTotal, 1, '工作区外那条不许计入')
1004
+ } finally {
1005
+ rmSync(repo, { recursive: true, force: true })
1006
+ }
1007
+ })
1008
+
1009
+ /* ── 10. **真接口**:在真实回环端口上验 `/api/changes` 与 `/api/recent` 的隔离 ─────
1010
+ 前面那些用例验的是载荷构造函数(等价于路由内核);这一条验**接口本身**:
1011
+ 路由存在、query 解析、响应形状、以及「常规检索请求里没有变更字段」这条隔离纪律。 */
1012
+
1013
+ test('独立接口(真端口):`/api/changes` 返回夹具里那三条关联,且 `/api/recent` 完全不受影响', async () => {
1014
+ const repo = makeAcceptanceRepo()
1015
+ let server
1016
+ try {
1017
+ server = await startKnitServer({ root: repo, sessionId: 's' })
1018
+ // ① 常规检索:**一个变更字段都没有**
1019
+ const recent = await (await fetch(`${server.base}/api/recent?sessionId=s&sort=relevance&kind=doc&limit=40`)).json()
1020
+ assert.equal(recent.ok, true)
1021
+ assert.ok(!('changes' in recent), '`/api/recent` 顶层不许有 changes')
1022
+ assert.ok(!('changes' in (recent.context || {})), '`context` 里也不许有')
1023
+ assert.ok(!/changeRelated|"provenance":"change"/.test(JSON.stringify(recent.context || {})), '包里不许有变更词汇')
1024
+
1025
+ // ② 独立接口:三条关联,起点 / 类型 / 行号逐条对得上
1026
+ const res = await fetch(`${server.base}/api/changes?sessionId=s&sort=relevance&kind=doc&limit=40`)
1027
+ assert.equal(res.status, 200)
1028
+ const body = await res.json()
1029
+ assert.equal(body.ok, true)
1030
+ assert.equal(body.mode, 'changes')
1031
+ assert.equal(body.git.available, true)
1032
+ assert.equal(body.git.filesTotal, 1)
1033
+ assert.deepEqual(body.git.files.map((f) => f.rel), ['src/foo.ts'])
1034
+ assert.deepEqual(body.links.map((l) => l.target).sort(), ['docs/guide.md', 'src/bar.ts', 'test/foo.test.ts'])
1035
+ assert.equal(body.linksTotal, 3)
1036
+ const byTarget = new Map(body.links.map((l) => [l.target, l]))
1037
+ assert.deepEqual(byTarget.get('src/bar.ts').evidence[0], { origin: 'src/foo.ts', type: 'imports', dir: 'in', line: 1 })
1038
+ assert.deepEqual(byTarget.get('docs/guide.md').evidence[0], { origin: 'src/foo.ts', type: 'documents', dir: 'out', line: 3 })
1039
+ const tEv = byTarget.get('test/foo.test.ts').evidence.find((e) => e.type === 'tests')
1040
+ assert.equal(tEv.line, null, 'tests 那一类没有行号 ⇒ null')
1041
+ // 干扰项一个都不许进来
1042
+ for (const noise of ['src/util.ts', 'src/other.ts', 'test/other.test.ts', 'docs/notes.md']) {
1043
+ assert.ok(!byTarget.has(noise), `误报:${noise}`)
1044
+ }
1045
+
1046
+ // ③ 时间序:如实说「这条口径下没有变更关联」,不是空壳
1047
+ const timeBody = await (await fetch(`${server.base}/api/changes?sessionId=s&sort=time`)).json()
1048
+ assert.equal(timeBody.ok, true)
1049
+ assert.equal(timeBody.git.available, false)
1050
+ assert.equal(timeBody.git.reason, 'not-relevance-order')
1051
+ assert.deepEqual(timeBody.links, [])
1052
+ } finally {
1053
+ if (server) await server.close()
1054
+ rmSync(repo, { recursive: true, force: true })
1055
+ }
1056
+ })
1057
+
1058
+ test('独立接口(真端口):**非 Git 工作区**安全降级,`/api/recent` 照旧可用', async () => {
1059
+ const dir = mkdtempSync(join(tmpdir(), 'knit-nogit-'))
1060
+ let server
1061
+ try {
1062
+ writeFileSync(join(dir, 'a.md'), '# a\n\nhello\n')
1063
+ server = await startKnitServer({ root: dir, sessionId: 's' })
1064
+ const recent = await (await fetch(`${server.base}/api/recent?sessionId=s&sort=relevance&limit=10`)).json()
1065
+ assert.equal(recent.ok, true, '非 Git 工作区里列表这条路必须照常')
1066
+ assert.ok(Array.isArray(recent.docs))
1067
+ const body = await (await fetch(`${server.base}/api/changes?sessionId=s&sort=relevance&limit=10`)).json()
1068
+ assert.equal(body.ok, true)
1069
+ assert.equal(body.git.available, false)
1070
+ assert.equal(body.git.reason, 'not-a-repo')
1071
+ assert.deepEqual(body.links, [])
1072
+ assert.deepEqual(body.unresolved, [])
1073
+ assert.deepEqual(body.outOfScope, [])
1074
+ } finally {
1075
+ if (server) await server.close()
1076
+ rmSync(dir, { recursive: true, force: true })
1077
+ }
1078
+ })
1079
+
1080
+ test('独立接口(真端口):同窗内两个接口**共用**一次扫描与一次 git —— 删掉一个文件都看不见', async () => {
1081
+ const repo = makeAcceptanceRepo()
1082
+ let server
1083
+ try {
1084
+ server = await startKnitServer({ root: repo, sessionId: 's' })
1085
+ const url = `${server.base}/api/changes?sessionId=s&sort=relevance&kind=doc&limit=40`
1086
+ const expected = ['docs/guide.md', 'src/bar.ts', 'test/foo.test.ts']
1087
+
1088
+ // 第一次:`/api/recent` 那次扫描 + 这次 git
1089
+ await fetch(`${server.base}/api/recent?sessionId=s&sort=relevance&kind=doc&limit=40`)
1090
+ const before = await (await fetch(url)).json()
1091
+ assert.deepEqual(before.links.map((l) => l.target).sort(), expected)
1092
+ assert.equal(before.git.filesTotal, 1)
1093
+
1094
+ // 窗口之内把「那个提到过 foo.ts 的文档」删掉:重新走目录树 / 重新问 git 都会**立刻**反映出来
1095
+ rmSync(join(repo, 'docs', 'guide.md'))
1096
+ const after = await (await fetch(url)).json()
1097
+ assert.deepEqual(after.links.map((l) => l.target).sort(), expected,
1098
+ '同窗内复用了那次扫描(删掉的文档还在语料里 ⇒ 仍能当关联目标)')
1099
+ assert.equal(after.git.filesTotal, 1, 'git 状态也复用了(这次删除没有变成第二条变更)')
1100
+
1101
+ // 证伪:把扫描备忘清掉之后再问,**必须**反映那次删除 —— 否则上面那条是「怎么问都这样」
1102
+ resetScanMemo()
1103
+ const fresh = await (await fetch(url)).json()
1104
+ assert.ok(!fresh.links.some((l) => l.target === 'docs/guide.md'),
1105
+ '清掉备忘后真的重扫:删掉的文档不再是被关联目标')
1106
+ } finally {
1107
+ if (server) await server.close()
1108
+ resetScanMemo()
1109
+ rmSync(repo, { recursive: true, force: true })
1110
+ }
1111
+ })
1112
+
1113
+ /* ── 11. 安全边界:**子进程环境**(第二轮边界检查,第四轮收尾)─────────────
1114
+ 固定 argv + 关 fsmonitor + 禁可选锁,挡的都是「我们主动让它做的事」;
1115
+ 挡不住「父进程的环境替我们做了决定」。这一节的规则是**白名单 + 前缀**:
1116
+ 只继承与 Git 配置无关的运行时必需品,**任何 `GIT_*` 一律不继承**。 */
1117
+
1118
+ test('安全:子进程环境是**筛选过**的 —— 任何 GIT_* 都不从父进程继承', () => {
1119
+ const env = gitEnv({
1120
+ PATH: '/usr/bin', HOME: '/home/u', LANG: 'zh_CN.UTF-8',
1121
+ GIT_DIR: '/evil/.git', GIT_WORK_TREE: '/evil', GIT_INDEX_FILE: '/evil/index',
1122
+ GIT_TRACE: '/evil/trace.log', GIT_EXEC_PATH: '/evil/bin',
1123
+ GIT_CONFIG_GLOBAL: '/evil/config', GIT_SSH_COMMAND: '/evil/ssh',
1124
+ PAGER: 'less', SSH_ASKPASS: '/evil/askpass', EDITOR: 'vim',
1125
+ })
1126
+ // ① 危险的那一族一个都不许在
1127
+ for (const bad of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_TRACE', 'GIT_EXEC_PATH',
1128
+ 'GIT_CONFIG_GLOBAL', 'GIT_SSH_COMMAND', 'PAGER', 'SSH_ASKPASS', 'EDITOR']) {
1129
+ assert.equal(env[bad], undefined, `${bad} 不许继承`)
1130
+ }
1131
+ // ② 我们自己设的只读参数**恰好**是那三个(多一个都算边界被放宽)
1132
+ assert.deepEqual(Object.keys(env).filter((k) => k.startsWith('GIT_')).sort(),
1133
+ ['GIT_OPTIONAL_LOCKS', 'GIT_PAGER', 'GIT_TERMINAL_PROMPT'])
1134
+ assert.equal(env.GIT_OPTIONAL_LOCKS, '0')
1135
+ // ③ 与 Git 配置无关的必需品照旧(`HOME` 决定全局配置与 ignore 规则从哪来,**不能抹**)
1136
+ assert.equal(env.PATH, '/usr/bin')
1137
+ assert.equal(env.HOME, '/home/u')
1138
+ assert.equal(env.LANG, 'zh_CN.UTF-8')
1139
+ // ④ 白名单自己不许含 `GIT_*`(前缀规则是冗余防线,不是主要防线)
1140
+ assert.ok(GIT_ENV_ALLOW.every((k) => !k.startsWith('GIT_')), `白名单里混进了 GIT_*:${GIT_ENV_ALLOW.filter((k) => k.startsWith('GIT_'))}`)
1141
+ })
1142
+
1143
+ test('安全(真机):父进程注入 GIT_DIR / GIT_INDEX_FILE / GIT_TRACE —— 读取仍属于指定工作区,且不产生额外写入', async () => {
1144
+ /* 这条是**注入**测试:把三个变量塞进 `process.env`(`spawnGit` 只在真机上才会继承环境,
1145
+ 注入的 `exec` 替身看不到这条路),然后走真实的读取器。
1146
+ 判据三条:① 结果属于**我们指定的工作区**;② 不读别的仓库;③ 不写日志、不碰外部索引。 */
1147
+ const ws = mkdtempSync(join(tmpdir(), 'knit-git-env-ws-'))
1148
+ const decoy = mkdtempSync(join(tmpdir(), 'knit-git-env-decoy-'))
1149
+ const trace = join(ws, 'trace.log')
1150
+ const evilIndex = join(ws, 'evil-index')
1151
+ const saved = {}
1152
+ const injected = {
1153
+ GIT_DIR: join(decoy, '.git'),
1154
+ GIT_WORK_TREE: decoy,
1155
+ GIT_INDEX_FILE: evilIndex,
1156
+ GIT_TRACE: trace,
1157
+ }
1158
+ try {
1159
+ const mk = (repo, files) => {
1160
+ const git = (...args) => execFileSync('git', ['-C', repo, ...args], { stdio: ['ignore', 'pipe', 'pipe'] })
1161
+ execFileSync('git', ['init', '-q', repo], { stdio: 'ignore' })
1162
+ git('config', 'user.email', 't@t')
1163
+ git('config', 'user.name', 't')
1164
+ for (const [rel, text] of Object.entries(files)) writeFileSync(join(repo, rel), text)
1165
+ git('add', '-A')
1166
+ git('commit', '-qm', 'init')
1167
+ }
1168
+ mk(ws, { 'a.ts': 'export const a = 1\n' })
1169
+ mk(decoy, { 'only-in-decoy.ts': 'nope\n' })
1170
+ // 让 ws 有一个**真实**的未提交改动当判据;decoy 保持干净
1171
+ writeFileSync(join(ws, 'a.ts'), 'export const a = 2\n')
1172
+
1173
+ for (const [key, value] of Object.entries(injected)) {
1174
+ saved[key] = process.env[key]
1175
+ process.env[key] = value
1176
+ }
1177
+
1178
+ const result = await createGitReader({ now: () => 0 }).read(ws)
1179
+ assert.equal(result.available, true, `读取必须成功(reason=${result.reason})`)
1180
+ // ① 结果属于我们指定的工作区
1181
+ assert.deepEqual(result.files.map((f) => f.rel), ['a.ts'],
1182
+ `必须读到 ws 的真实改动,实测 ${JSON.stringify(result.files.map((f) => f.rel))}`)
1183
+ assert.deepEqual(result.files[0].kinds, ['unstaged'])
1184
+ // ② 没有读另一个仓库
1185
+ assert.ok(!result.files.some((f) => f.rel.includes('only-in-decoy')), '不许读到 decoy 仓库的文件')
1186
+ // ③ 没有额外写入
1187
+ assert.equal(existsSync(trace), false, '`GIT_TRACE` 指向的日志**一次都不许被创建**')
1188
+ assert.equal(existsSync(evilIndex), false, '`GIT_INDEX_FILE` 指向的外部索引**不许被创建/改写**')
1189
+ } finally {
1190
+ for (const [key, value] of Object.entries(saved)) {
1191
+ if (value === undefined) delete process.env[key]
1192
+ else process.env[key] = value
1193
+ }
1194
+ rmSync(ws, { recursive: true, force: true })
1195
+ rmSync(decoy, { recursive: true, force: true })
1196
+ }
1197
+ })
1198
+
1199
+ test('安全(证伪):**不净化**环境时,上面那三个注入确实会改变行为 —— 说明那条守卫不是空转的', () => {
1200
+ /* 「守卫必须证伪一次」:这一条不用我们的代码,直接用 `spawnSync` 把**原始继承环境**交给 git,
1201
+ 证明 GIT_TRACE 真的会写文件、GIT_DIR 真的会读别的仓库。没有它,上面那条测试
1202
+ 可能只是「怎么跑都过」。 */
1203
+ const ws = mkdtempSync(join(tmpdir(), 'knit-git-raw-ws-'))
1204
+ const decoy = mkdtempSync(join(tmpdir(), 'knit-git-raw-decoy-'))
1205
+ const trace = join(ws, 'raw-trace.log')
1206
+ const evilIndex = join(ws, 'raw-evil-index')
1207
+ try {
1208
+ const mk = (repo, files) => {
1209
+ const git = (...args) => execFileSync('git', ['-C', repo, ...args], { stdio: ['ignore', 'pipe', 'pipe'] })
1210
+ execFileSync('git', ['init', '-q', repo], { stdio: 'ignore' })
1211
+ git('config', 'user.email', 't@t')
1212
+ git('config', 'user.name', 't')
1213
+ for (const [rel, text] of Object.entries(files)) writeFileSync(join(repo, rel), text)
1214
+ git('add', '-A')
1215
+ git('commit', '-qm', 'init')
1216
+ }
1217
+ mk(ws, { 'a.ts': 'export const a = 1\n' })
1218
+ mk(decoy, { 'only-in-decoy.ts': 'nope\n' })
1219
+ writeFileSync(join(ws, 'a.ts'), 'export const a = 2\n')
1220
+
1221
+ const raw = (env) => spawnSync('git', ['status', '--porcelain=v1', '-z'], {
1222
+ cwd: ws, encoding: 'utf8', env: { ...process.env, ...env },
1223
+ }).stdout || ''
1224
+
1225
+ // ① 原始继承 + GIT_TRACE ⇒ 真的写了日志(这就是我们要挡掉的写入)
1226
+ raw({ GIT_TRACE: trace })
1227
+ assert.equal(existsSync(trace), true, '原始环境下 `GIT_TRACE` 确实会写文件(所以净化是必要的)')
1228
+ // ② 原始继承 + GIT_INDEX_FILE ⇒ 索引被换掉,已提交的文件被报成 D/??
1229
+ const swapped = raw({ GIT_INDEX_FILE: evilIndex })
1230
+ assert.match(swapped, /a\.ts/, '换成空索引后,连已提交的 a.ts 都会被重新报出来')
1231
+ // ③ 原始继承 + GIT_DIR/GIT_WORK_TREE ⇒ 读的是**另一个仓库**
1232
+ const elsewhere = raw({ GIT_DIR: join(decoy, '.git'), GIT_WORK_TREE: decoy })
1233
+ assert.ok(!/a\.ts/.test(elsewhere), `GIT_DIR 让我们读到了别的仓库(ws 的改动看不见):${JSON.stringify(elsewhere)}`)
1234
+ } finally {
1235
+ rmSync(ws, { recursive: true, force: true })
1236
+ rmSync(decoy, { recursive: true, force: true })
1237
+ }
1238
+ })