dsh-knit 0.16.0 → 0.18.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,513 @@
1
+ /**
2
+ * Knit v0.17 · Document Lifecycle —— **单元层**
3
+ *
4
+ * 这一层只测三件事,全部是纯逻辑,不碰文件系统(版本标记用 `stat` 注入):
5
+ *
6
+ * 1. 四态生命周期:`unread` / `read` / `updated_after_read` / `reread_after_update`
7
+ * 2. 两个派生投影:最近读取(按事件 `seq` 认)与包外明细(当前层口径)
8
+ * 3. 冻结与幂等:历史归因不漂移、`stats` 键集不变、同一事件重复派发不重复计数、
9
+ * 拿不到版本标记就**不做变化判断**
10
+ *
11
+ * ⚠️ 规格里最要紧的一条纪律:`mtimeMs` 是**版本标记**,不是内容证明。它没变时不许说
12
+ * 「内容没变」,拿不到时更不许猜(宁可少说,也不乱说)。
13
+ */
14
+ import test from 'node:test'
15
+ import assert from 'node:assert/strict'
16
+
17
+ import {
18
+ createStore, activateAudit, ingestEvents, noteSnapshot, usageFor, usageFrom,
19
+ lifecycleOf, latestReadOf, outsideDocsOf, markBackfilled, isBackfilled,
20
+ } from '../src/host/feedback.js'
21
+ import { publicUsage } from '../src/host/index.js'
22
+
23
+ const ROOT = '/w'
24
+
25
+ /** 造一份 Context Pack(只给测试要用的字段)。 */
26
+ function pack(options = {}) {
27
+ const rows = (list) => (list || []).map((rel) => ({ rel }))
28
+ return {
29
+ mode: 'relevance',
30
+ topic: options.topic || 'knit',
31
+ task: options.task || '',
32
+ primary: rows(options.primary),
33
+ supporting: rows(options.supporting),
34
+ related: rows(options.related),
35
+ totals: { total: 10 },
36
+ }
37
+ }
38
+
39
+ /**
40
+ * 一次成功的读 = `tool/call` + `tool/result` 两件事(与宿主事件流同形)。
41
+ * 归因认的是**结果**那件事的 seq,所以 `readAt('a.md', 10)` 记下来的是 seq 11。
42
+ * @param {string} rel - 路径
43
+ * @param {number} seq - `tool/call` 的 seq
44
+ * @returns {object[]} 两件事
45
+ */
46
+ function readAt(rel, seq) {
47
+ const callId = `c${seq}`
48
+ return [
49
+ {
50
+ type: 'tool/call',
51
+ seq,
52
+ time: seq,
53
+ data: { turn: 1, step: 1, callId, name: 'read', arguments: JSON.stringify({ file_path: rel }) },
54
+ },
55
+ {
56
+ type: 'tool/result',
57
+ seq: seq + 1,
58
+ time: seq + 1,
59
+ data: { message: { role: 'tool', toolCallId: callId, source: { kind: 'tool', callId }, isError: false } },
60
+ },
61
+ ]
62
+ }
63
+
64
+ /** 一次**失败**的读(`isError: true`)—— 不算读过,也不许影响已有生命周期。 */
65
+ function failedRead(rel, seq) {
66
+ const events = readAt(rel, seq)
67
+ events[1].data.message.isError = true
68
+ return events
69
+ }
70
+
71
+ /** 一次搜索类调用(`grep` / `glob` / `bash`)—— 命中不算读过。 */
72
+ function searchCall(name, seq) {
73
+ const callId = `x${seq}`
74
+ return [
75
+ {
76
+ type: 'tool/call',
77
+ seq,
78
+ time: seq,
79
+ data: {
80
+ turn: 1,
81
+ step: 1,
82
+ callId,
83
+ name,
84
+ arguments: JSON.stringify({ pattern: 'a', file_path: 'a.md', command: 'ls' }),
85
+ },
86
+ },
87
+ {
88
+ type: 'tool/result',
89
+ seq: seq + 1,
90
+ time: seq + 1,
91
+ data: { message: { role: 'tool', toolCallId: callId, source: { kind: 'tool', callId }, isError: false } },
92
+ },
93
+ ]
94
+ }
95
+
96
+ /** 一个开着账的会话。 */
97
+ function audited(id) {
98
+ const store = createStore()
99
+ activateAudit(store, id)
100
+ return store
101
+ }
102
+
103
+ /**
104
+ * 一次成功读 + 注入「读那一刻」观察到的版本标记。
105
+ * @param {object} store - store
106
+ * @param {string} id - 会话 id
107
+ * @param {string} rel - 路径
108
+ * @param {number} seq - `tool/call` 的 seq
109
+ * @param {number} mtimeMs - 这次读观察到的版本标记
110
+ * @param {{statCalls: number}} [counter] - 可选:统计取样次数
111
+ * @returns {object} `ingestEvents()` 的结果
112
+ */
113
+ function readWith(store, id, rel, seq, mtimeMs, counter) {
114
+ return ingestEvents(store, id, readAt(rel, seq), {
115
+ root: ROOT,
116
+ stat: () => {
117
+ if (counter) counter.statCalls += 1
118
+ return mtimeMs
119
+ },
120
+ })
121
+ }
122
+
123
+ const stateOf = (store, id) => store.sessions.get(id)
124
+ const statusOf = (usage, rel) => (usage.lifecycle[rel] || {}).status
125
+
126
+ /* ── 1. 四态 ─────────────────────────────────────────────────── */
127
+
128
+ test('未读:Context 里有它、但一次成功读都没有 → lifecycle 里根本不出现这篇', () => {
129
+ const store = audited('s1')
130
+ noteSnapshot(store, 's1', pack({ primary: ['a.md'] }), { seq: 1, at: 1 })
131
+ const usage = usageFor(store, 's1', { mtimes: { 'a.md': 2000 } })
132
+
133
+ assert.equal(usage.lifecycle['a.md'], undefined, '没有读证据就不出现在 lifecycle 里(UI 自行落回未读)')
134
+ assert.deepEqual(usage.lifecycle, {})
135
+ assert.equal(usage.recentRead, null)
136
+ })
137
+
138
+ test('已读:一次成功读 → read、count=1;拿不到当前版本标记也不会多加状态', () => {
139
+ const store = audited('s1')
140
+ noteSnapshot(store, 's1', pack({ primary: ['a.md'] }), { seq: 1, at: 1 })
141
+ readWith(store, 's1', 'a.md', 10, 1000)
142
+
143
+ const usage = usageFor(store, 's1')
144
+ assert.equal(statusOf(usage, 'a.md'), 'read')
145
+ assert.equal(usage.lifecycle['a.md'].count, 1)
146
+ assert.equal(usage.lifecycle['a.md'].lastReadMtimeMs, 1000)
147
+ assert.equal(usage.lifecycle['a.md'].changedAfterLastRead, false)
148
+ assert.equal(usage.lifecycle['a.md'].rereadAfterChange, false)
149
+ assert.equal(usage.lifecycle['a.md'].lastReadAt, 11, 'lastReadAt 是结果那件事的墙钟')
150
+ })
151
+
152
+ test('读后已更新:读之后当前版本标记变了 → updated_after_read', () => {
153
+ const store = audited('s1')
154
+ noteSnapshot(store, 's1', pack({ primary: ['a.md'] }), { seq: 1, at: 1 })
155
+ readWith(store, 's1', 'a.md', 10, 1000)
156
+
157
+ const usage = usageFor(store, 's1', { mtimes: { 'a.md': 2000 } })
158
+ assert.equal(statusOf(usage, 'a.md'), 'updated_after_read')
159
+ assert.equal(usage.lifecycle['a.md'].changedAfterLastRead, true)
160
+ assert.equal(usage.lifecycle['a.md'].lastReadMtimeMs, 1000, '冻结的是读那一刻看到的标记')
161
+ assert.equal(usage.lifecycle['a.md'].count, 1)
162
+ })
163
+
164
+ test('修改后已重新读取:变化之后又成功读了一次 → reread_after_update、count=2', () => {
165
+ const store = audited('s1')
166
+ noteSnapshot(store, 's1', pack({ primary: ['a.md'] }), { seq: 1, at: 1 })
167
+ readWith(store, 's1', 'a.md', 10, 1000)
168
+ // 当前标记已经是 2000(所以第一次读之后状态是 updated_after_read),这次读观察到 2000
169
+ assert.equal(statusOf(usageFor(store, 's1', { mtimes: { 'a.md': 2000 } }), 'a.md'), 'updated_after_read')
170
+ readWith(store, 's1', 'a.md', 20, 2000)
171
+
172
+ const usage = usageFor(store, 's1')
173
+ assert.equal(statusOf(usage, 'a.md'), 'reread_after_update')
174
+ assert.equal(usage.lifecycle['a.md'].count, 2)
175
+ assert.equal(usage.lifecycle['a.md'].lastReadMtimeMs, 2000)
176
+ assert.equal(usage.lifecycle['a.md'].rereadAfterChange, true)
177
+ })
178
+
179
+ test('再次变化 → 回到读后已更新(判定优先级是硬顺序)', () => {
180
+ const store = audited('s1')
181
+ noteSnapshot(store, 's1', pack({ primary: ['a.md'] }), { seq: 1, at: 1 })
182
+ readWith(store, 's1', 'a.md', 10, 1000)
183
+ readWith(store, 's1', 'a.md', 20, 2000)
184
+
185
+ const usage = usageFor(store, 's1', { mtimes: { 'a.md': 3000 } })
186
+ assert.equal(statusOf(usage, 'a.md'), 'updated_after_read', 'changedAfterLastRead 先于 rereadAfterChange')
187
+ assert.equal(usage.lifecycle['a.md'].rereadAfterChange, true, '旧事实仍然留着,只是不再是当前状态')
188
+ assert.equal(usage.lifecycle['a.md'].count, 2)
189
+ })
190
+
191
+ test('同一版本重复读:count +1,不会变成「修改后已重新读取」', () => {
192
+ const store = audited('s1')
193
+ noteSnapshot(store, 's1', pack({ primary: ['a.md'] }), { seq: 1, at: 1 })
194
+ readWith(store, 's1', 'a.md', 10, 1000)
195
+ readWith(store, 's1', 'a.md', 20, 1000)
196
+
197
+ const usage = usageFor(store, 's1', { mtimes: { 'a.md': 1000 } })
198
+ assert.equal(statusOf(usage, 'a.md'), 'read')
199
+ assert.equal(usage.lifecycle['a.md'].count, 2)
200
+ assert.equal(usage.lifecycle['a.md'].rereadAfterChange, false)
201
+ })
202
+
203
+ /* ── 2. 哪些不算读 ───────────────────────────────────────────── */
204
+
205
+ test('失败的读不记账,也不影响已有的 lifecycle', () => {
206
+ const store = audited('s1')
207
+ noteSnapshot(store, 's1', pack({ primary: ['a.md', 'b.md'] }), { seq: 1, at: 1 })
208
+ readWith(store, 's1', 'a.md', 10, 1000)
209
+ ingestEvents(store, 's1', failedRead('b.md', 20), { root: ROOT, stat: () => 5000 })
210
+
211
+ const usage = usageFor(store, 's1')
212
+ assert.equal(usage.reads.length, 1, '失败读不产生 entry')
213
+ assert.equal(usage.stats.reads, 1)
214
+ assert.equal(statusOf(usage, 'b.md'), undefined)
215
+ assert.equal(usage.lifecycle['a.md'].lastReadMtimeMs, 1000, '失败读连取样都不该发生')
216
+ })
217
+
218
+ test('grep / glob / bash 都不算读', () => {
219
+ const store = audited('s1')
220
+ noteSnapshot(store, 's1', pack({ primary: ['a.md'] }), { seq: 1, at: 1 })
221
+ ingestEvents(store, 's1', searchCall('grep', 10), { root: ROOT, stat: () => 1000 })
222
+ ingestEvents(store, 's1', searchCall('glob', 20), { root: ROOT, stat: () => 1000 })
223
+ ingestEvents(store, 's1', searchCall('bash', 30), { root: ROOT, stat: () => 1000 })
224
+
225
+ const usage = usageFor(store, 's1')
226
+ assert.equal(usage.reads.length, 0)
227
+ assert.deepEqual(usage.lifecycle, {})
228
+ assert.equal(usage.recentRead, null)
229
+ assert.equal(usage.stats.reads, 0)
230
+ })
231
+
232
+ /* ── 3. 最近读取 ─────────────────────────────────────────────── */
233
+
234
+ test('最近读取:按事件 seq 认最近一次,墙钟只用来显示相对时间', () => {
235
+ const store = audited('s1')
236
+ noteSnapshot(store, 's1', pack({ primary: ['a.md', 'b.md'] }), { seq: 1, at: 1 })
237
+ readWith(store, 's1', 'a.md', 10, 1000)
238
+ readWith(store, 's1', 'b.md', 20, 1000)
239
+
240
+ const usage = usageFor(store, 's1')
241
+ assert.equal(usage.recentRead.rel, 'b.md')
242
+ assert.equal(usage.recentRead.seq, 21)
243
+ assert.equal(usage.recentRead.tier, 'primary', '层的归因也是读那一刻冻结的')
244
+ assert.equal(usage.recentRead.rank, 2)
245
+ assert.equal(usage.recentRead.inside, true)
246
+
247
+ readWith(store, 's1', 'a.md', 30, 1000)
248
+ const next = usageFor(store, 's1')
249
+ assert.equal(next.recentRead.rel, 'a.md', 'seq 更大者才是最近一次')
250
+ assert.equal(next.recentRead.seq, 31)
251
+ })
252
+
253
+ test('最近读取照实返回包外文档(inside: false),不做任何解释', () => {
254
+ const store = audited('s1')
255
+ noteSnapshot(store, 's1', pack({ primary: ['a.md'] }), { seq: 1, at: 1 })
256
+ readWith(store, 's1', 'docs/old-plan.md', 10, 1000)
257
+
258
+ const usage = usageFor(store, 's1')
259
+ assert.equal(usage.recentRead.rel, 'docs/old-plan.md')
260
+ assert.equal(usage.recentRead.inside, false)
261
+ assert.equal(usage.recentRead.tier, null)
262
+ })
263
+
264
+ /* ── 4. Context Gap(当前层)─────────────────────────────────── */
265
+
266
+ test('包外明细:当前包外、且真实成功读取过的文档,按首次读顺序排列', () => {
267
+ const store = audited('s1')
268
+ noteSnapshot(store, 's1', pack({ primary: ['a.md'], supporting: ['b.md'] }), { seq: 1, at: 1 })
269
+ readWith(store, 's1', 'docs/old-plan.md', 10, 1000)
270
+ readWith(store, 's1', 'docs/test-case.md', 20, 1000)
271
+ readWith(store, 's1', 'docs/old-plan.md', 30, 1000)
272
+ readWith(store, 's1', 'a.md', 40, 1000)
273
+
274
+ const usage = usageFor(store, 's1')
275
+ assert.deepEqual(usage.outsideDocs.map((row) => row.rel), ['docs/old-plan.md', 'docs/test-case.md'])
276
+ assert.equal(usage.outsideDocs[0].count, 2, '明细行要能显示「已读 ×N」')
277
+ assert.equal(usage.outsideDocs[1].count, 1)
278
+ assert.equal(usage.outsideDocs[0].seq, 11, 'seq 是首次读那件事的 seq(排序依据)')
279
+ assert.equal(usage.outsideDocs[0].lastReadAt, 31)
280
+ assert.ok(!usage.outsideDocs.some((row) => row.rel === 'a.md'), '包内的读不算包外')
281
+ })
282
+
283
+ test('两个「包外」口径必须都留着:历史层不漂移,当前层随包变', () => {
284
+ const store = audited('s1')
285
+ // Epoch 1:a.md 在包里,读它 —— 这一读**发生在包内**
286
+ noteSnapshot(store, 's1', pack({ primary: ['a.md'], supporting: ['b.md'] }), { seq: 10, at: 1000 })
287
+ readWith(store, 's1', 'a.md', 20, 1000)
288
+ // Epoch 2:换任务,a.md 掉出当前包
289
+ noteSnapshot(store, 's1', pack({ topic: 'other', primary: ['c.md'] }), { seq: 40, at: 2000 })
290
+
291
+ const usage = usageFor(store, 's1', { mtimes: { 'a.md': 1000 } })
292
+ const row = usage.reads.find((item) => item.rel === 'a.md')
293
+ assert.equal(row.firstRead.epochId, 1, '历史归因冻结在 Epoch 1')
294
+ assert.equal(row.firstRead.tier, 'primary')
295
+ assert.equal(row.firstRead.rank, 1)
296
+ assert.equal(row.firstRead.inside, true)
297
+ assert.equal(row.tier, 'primary', '兼容别名也是首次读的层')
298
+ assert.equal(usage.stats.firstReadTier, 'primary')
299
+
300
+ assert.equal(usage.stats.outside, 0, 'v0.16 口径:读发生在当时的包内 → 不算包外')
301
+ assert.deepEqual(usage.stats.outsideReads, [])
302
+ assert.deepEqual(usage.outsideDocs.map((item) => item.rel), ['a.md'], 'v0.17 口径:当前包外、被读过')
303
+ })
304
+
305
+ /* ── 5. 最近一次 Delta ───────────────────────────────────────── */
306
+
307
+ test('最近一次 Delta 只取最后一条,且与 delta 同引用(不新建 Delta Store)', () => {
308
+ const store = audited('s1')
309
+ noteSnapshot(store, 's1', pack({ primary: ['a.md'], supporting: ['b.md'], related: ['c.md'] }), { seq: 1, at: 1 })
310
+ noteSnapshot(store, 's1', pack({ primary: ['b.md'], supporting: ['c.md'] }), { seq: 2, at: 2 })
311
+ noteSnapshot(store, 's1', pack({ primary: ['b.md'], related: ['d.md'] }), { seq: 3, at: 3 })
312
+
313
+ const state = stateOf(store, 's1')
314
+ const usage = usageFor(store, 's1')
315
+ assert.equal(usage.latestDelta, usage.delta, '同一个对象的两个引用')
316
+ assert.equal(usage.latestDelta, state.deltas[state.deltas.length - 1])
317
+ assert.deepEqual(usage.latestDelta.appeared.map((item) => item.rel), ['d.md'])
318
+ assert.deepEqual(usage.latestDelta.disappeared.map((item) => item.rel), ['c.md'])
319
+ assert.deepEqual(usage.latestDelta.moved, [])
320
+ assert.equal(usage.latestDelta.fromEpoch, 2)
321
+ assert.equal(usage.latestDelta.toEpoch, 3)
322
+ assert.equal(usage.stats.churn.changes, 2, '三份包 = 两次变化')
323
+ assert.equal(usageFrom(state).latestDelta, state.deltas[state.deltas.length - 1], '纯投影:再算一次还是同一条')
324
+ })
325
+
326
+ test('没有交过第二份包时 latestDelta 是 null(不编造变化)', () => {
327
+ const store = audited('s1')
328
+ noteSnapshot(store, 's1', pack({ primary: ['a.md'] }), { seq: 1, at: 1 })
329
+ const usage = usageFor(store, 's1')
330
+ assert.equal(usage.delta, null)
331
+ assert.equal(usage.latestDelta, null)
332
+ })
333
+
334
+ /* ── 6. 幂等、冻结与确定性 ───────────────────────────────────── */
335
+
336
+ test('同一事件重复派发:count 只 +1,版本标记也只取一次样', () => {
337
+ const store = audited('s1')
338
+ noteSnapshot(store, 's1', pack({ primary: ['a.md'] }), { seq: 1, at: 1 })
339
+ const counter = { statCalls: 0 }
340
+ const events = readAt('a.md', 10)
341
+ ingestEvents(store, 's1', events, { root: ROOT, stat: () => { counter.statCalls += 1; return 1000 } })
342
+ ingestEvents(store, 's1', events, { root: ROOT, stat: () => { counter.statCalls += 1; return 9999 } })
343
+
344
+ const usage = usageFor(store, 's1')
345
+ assert.equal(usage.reads.length, 1)
346
+ assert.equal(usage.reads[0].count, 1)
347
+ assert.equal(usage.stats.reads, 1)
348
+ assert.equal(counter.statCalls, 1, '重复派发不重复取样')
349
+ assert.equal(usage.lifecycle['a.md'].lastReadMtimeMs, 1000, '第二次投喂不许改写冻结的标记')
350
+ })
351
+
352
+ test('不传 mtimes 时永远不出现 updated_after_read(拿不到证据就不说)', () => {
353
+ const store = audited('s1')
354
+ noteSnapshot(store, 's1', pack({ primary: ['a.md'] }), { seq: 1, at: 1 })
355
+ readWith(store, 's1', 'a.md', 10, 1000)
356
+
357
+ const usage = usageFor(store, 's1')
358
+ assert.equal(statusOf(usage, 'a.md'), 'read')
359
+ assert.equal(usage.lifecycle['a.md'].changedAfterLastRead, false)
360
+ assert.ok(!JSON.stringify(usage.lifecycle).includes('updated_after_read'))
361
+ // 什么都不传时四个新投影都老实退化
362
+ const empty = usageFrom(stateOf(store, 's1'))
363
+ assert.deepEqual(empty.outsideDocs, [])
364
+ assert.equal(empty.latestDelta, null)
365
+ assert.equal(Object.keys(empty.lifecycle).length, 1)
366
+ })
367
+
368
+ test('stats 键集冻结(v0.16 的 15 个,一个不多一个不少)', () => {
369
+ const store = audited('s1')
370
+ noteSnapshot(store, 's1', pack({ primary: ['a.md'], supporting: ['b.md'], related: ['c.md'] }), { seq: 1, at: 1 })
371
+ const usage = usageFrom(stateOf(store, 's1'))
372
+ assert.deepEqual(Object.keys(usage.stats).sort(), [
373
+ 'byTier', 'churn', 'continuedReadsAfterExit', 'distinct', 'firstReadAt', 'firstReadEpoch',
374
+ 'firstReadRel', 'firstReadTier', 'outside', 'outsideReads', 'primaryFollowThrough',
375
+ 'primaryRel', 'reEntries', 'reads', 'supportingCoverage',
376
+ ])
377
+ // 四个新投影在**顶层**,不许混进 stats
378
+ assert.deepEqual(
379
+ Object.keys(usage).filter((key) => ['lifecycle', 'recentRead', 'outsideDocs', 'latestDelta'].includes(key)).sort(),
380
+ ['latestDelta', 'lifecycle', 'outsideDocs', 'recentRead'],
381
+ )
382
+ })
383
+
384
+ test('确定性:同样的输入喂两个 store,逐字段 deepEqual', () => {
385
+ const build = () => {
386
+ const store = audited('s1')
387
+ noteSnapshot(store, 's1', pack({ primary: ['a.md'], supporting: ['b.md'] }), { seq: 1, at: 1 })
388
+ readWith(store, 's1', 'a.md', 10, 1000)
389
+ readWith(store, 's1', 'docs/outside.md', 20, 1000)
390
+ return usageFor(store, 's1', { mtimes: { 'a.md': 2000, 'docs/outside.md': 1000 } })
391
+ }
392
+ assert.deepEqual(build(), build())
393
+ })
394
+
395
+ /* ── 7. 兜底与线路裁剪 ───────────────────────────────────────── */
396
+
397
+ test('畸形输入不抛:lifecycleOf / latestReadOf / outsideDocsOf 的兜底', () => {
398
+ assert.equal(lifecycleOf(null).status, 'unread')
399
+ assert.equal(lifecycleOf(undefined, 100).status, 'unread')
400
+ assert.equal(lifecycleOf({ count: 'x' }, 100).status, 'unread')
401
+ assert.equal(lifecycleOf({ count: 2, lastReadMtimeMs: null, rereadAfterChange: true }, 500).status,
402
+ 'reread_after_update', '没有「上次读到的标记」就不做变化判断')
403
+ assert.equal(lifecycleOf({ count: 2, lastReadMtimeMs: 1000, rereadAfterChange: false }, Number.NaN).status,
404
+ 'read', '当前标记缺失/非有限 → 不做变化判断')
405
+ assert.equal(latestReadOf(null), null)
406
+ assert.equal(latestReadOf([]), null)
407
+ assert.deepEqual(outsideDocsOf(null, null), [])
408
+ assert.deepEqual(outsideDocsOf([{ rel: 'a.md', count: 0, firstRead: { seq: 1 }, lastRead: { at: 1 } }], []), [],
409
+ 'count 为 0 的 entry 不算读过')
410
+ })
411
+
412
+ test('publicUsage:lifecycle 按 rels 裁剪、outsideDocs 按 limit 截断,四个新键都在', () => {
413
+ const store = audited('s1')
414
+ noteSnapshot(store, 's1', pack({ primary: ['a.md', 'b.md'] }), { seq: 1, at: 1 })
415
+ readWith(store, 's1', 'a.md', 10, 1000)
416
+ readWith(store, 's1', 'c.md', 20, 1000)
417
+
418
+ const usage = usageFor(store, 's1', { mtimes: { 'a.md': 2000, 'c.md': 1000 } })
419
+ const wire = publicUsage(usage, 20, new Set(['a.md']))
420
+ assert.deepEqual(Object.keys(wire.lifecycle), ['a.md'], '只发真正会渲染的那些行')
421
+ assert.equal(wire.lifecycle['a.md'].status, 'updated_after_read')
422
+ assert.deepEqual(Object.keys(wire.lifecycle['a.md']).sort(), ['count', 'lastReadAt', 'status'],
423
+ '线路上的每条只带 UI 要的三个字段(中文文案不进数据层)')
424
+ assert.deepEqual(wire.outsideDocs.map((row) => row.rel), ['c.md'])
425
+ assert.equal(wire.recentRead.rel, 'c.md')
426
+ assert.equal(wire.latestDelta, wire.delta)
427
+ assert.deepEqual(Object.keys(wire.stats).sort(), Object.keys(usage.stats).sort(), 'stats 键集一个字不动')
428
+
429
+ const full = publicUsage(usage, 20, null)
430
+ assert.deepEqual(Object.keys(full.lifecycle).sort(), ['a.md', 'c.md'], 'rels 省略时不裁剪')
431
+ assert.equal(publicUsage(usage, 1).outsideDocs.length, 1, 'outsideDocs 按 limit 截断')
432
+ assert.equal(publicUsage(null), null)
433
+ })
434
+
435
+ /* ── 8. 回填(v0.17 修订,用户拍板)────────────────────────────────
436
+ *
437
+ * 真实用法是**读完才想起来看面板**。闸门只在 `usage=1` 那一刻才开,所以开闸时
438
+ * 要把会话已有的事件补一次(宿主的 `backfillFeedback`)。这一节钉住三件事:
439
+ * 补记的读**按我们已知最早的那份包**归因(不许说成包外)、只影响第一份快照、
440
+ * 以及「没回填的会话行为一字不变」。
441
+ */
442
+
443
+ test('回填:补记的读归到「我们已知最早的那份包」,不是包外', () => {
444
+ const store = audited('s1')
445
+ // ① 开闸那一 tick:宿主先标记「这份状态的历史是补记的」
446
+ assert.equal(isBackfilled(store, 's1'), false)
447
+ assert.equal(markBackfilled(store, 's1'), true)
448
+ assert.equal(isBackfilled(store, 's1'), true)
449
+ // ② 顺序关键:**先记下手上这份包**(此刻还没有任何事件,所以 seq 钉在会话开头)
450
+ noteSnapshot(store, 's1', pack({ primary: ['a.md'] }), { at: 5000 })
451
+ assert.equal(stateOf(store, 's1').snapshots[0].seq, -1, '第一份快照必须在会话开头')
452
+ // ③ 再把闸门开之前真实发生过的读补进来(面板打开前用户就已经读过了)
453
+ ingestEvents(store, 's1', readAt('a.md', 10), { root: ROOT, stat: () => 1000 })
454
+
455
+ const usage = usageFor(store, 's1', { mtimes: { 'a.md': 1000 } })
456
+ assert.equal(usage.stats.reads, 1)
457
+ assert.equal(usage.lifecycle['a.md'].status, 'read')
458
+ assert.equal(usage.stats.firstReadTier, 'primary', '补记的读按第一份包归因')
459
+ assert.equal(usage.stats.firstReadEpoch, 1)
460
+ assert.equal(usage.stats.outside, 0, '说它是包外就是假话')
461
+ assert.deepEqual(usage.outsideDocs, [])
462
+ assert.equal(usage.recentRead.rel, 'a.md')
463
+ assert.equal(usage.recentRead.inside, true)
464
+ })
465
+
466
+ test('没有回填的会话照旧:第一份包之前的读算包外(v0.16 行为一字不动)', () => {
467
+ const store = audited('s1')
468
+ ingestEvents(store, 's1', readAt('a.md', 10), { root: ROOT, stat: () => 1000 })
469
+ noteSnapshot(store, 's1', pack({ primary: ['a.md'] }), { at: 5000 })
470
+
471
+ const usage = usageFor(store, 's1', { mtimes: { 'a.md': 1000 } })
472
+ assert.equal(usage.stats.reads, 1, '读照样记下来')
473
+ assert.equal(usage.stats.outside, 1, '只是口径不同:没有它当时在包里的证据')
474
+ assert.equal(usage.stats.firstReadTier, 'outside', '没有回填就没有可归的包,宁可说包外')
475
+ // 「包外明细」看的是**当前**这份包:a.md 现在就在主要层里,所以它不是缺口。
476
+ // 两个「包外」口径拆开正是 v0.16 的设计(历史层不漂移 / 当前层随包变)。
477
+ assert.deepEqual(usage.outsideDocs, [], '历史归因是包外,但当前包里有它 ⇒ 不算缺口')
478
+ })
479
+
480
+ test('回填只影响第一份快照:第二份起照旧按事件水位归因(历史归因不漂移)', () => {
481
+ const store = audited('s2')
482
+ markBackfilled(store, 's2')
483
+ noteSnapshot(store, 's2', pack({ primary: ['a.md'] }), { at: 1 }) // 第一份:seq = -1(会话开头)
484
+ ingestEvents(store, 's2', readAt('a.md', 10), { root: ROOT, stat: () => 1000 })
485
+ noteSnapshot(store, 's2', pack({ related: ['a.md'] }), { at: 2 }) // 第二份:seq = 当时的水位
486
+ ingestEvents(store, 's2', readAt('a.md', 30), { root: ROOT, stat: () => 1000 })
487
+
488
+ const state = stateOf(store, 's2')
489
+ assert.equal(state.reads.get('a.md').count, 2)
490
+ assert.equal(state.reads.get('a.md').firstRead.tier, 'primary', '补记那次按第一份包')
491
+ assert.equal(state.reads.get('a.md').lastRead.tier, 'related', '后来那次按第二份包')
492
+ assert.equal(state.reads.get('a.md').lastRead.epochId, 2, '归因钉在读的那一刻的 Epoch')
493
+
494
+ const usage = usageFor(store, 's2', { mtimes: { 'a.md': 1000 } })
495
+ assert.equal(usage.lifecycle['a.md'].status, 'read')
496
+ assert.equal(usage.stats.firstReadTier, 'primary', '冻结的归因不因后来的上下文变化而重算')
497
+ })
498
+
499
+ test('回填与订阅幂等:同一个事件先被回填、再从订阅派发一次,count 只 +1', () => {
500
+ const store = audited('s3')
501
+ const events = readAt('a.md', 10)
502
+ ingestEvents(store, 's3', events, { root: ROOT, stat: () => 1000 }) // 回填
503
+ markBackfilled(store, 's3')
504
+ noteSnapshot(store, 's3', pack({ primary: ['a.md'] }), { at: 1 })
505
+ // 宿主之后照常按条派发同一个事件(顺序与真机一致:先 call 后 result)
506
+ for (const event of events) {
507
+ ingestEvents(store, 's3', [event], { root: ROOT, stat: () => 1000 })
508
+ }
509
+
510
+ const state = stateOf(store, 's3')
511
+ assert.equal(state.reads.get('a.md').count, 1, '同一次读只算一次')
512
+ assert.equal(usageFor(store, 's3', { mtimes: { 'a.md': 1000 } }).stats.reads, 1)
513
+ })
package/test/harness.mjs CHANGED
@@ -64,12 +64,18 @@ export function loadClientModule(options = {}) {
64
64
  + 'sessionFileAddress, relTime, resolveRelative, pathImagesFor, clampRatio, splitRelPath, '
65
65
  + 'openKnitPanel, makeEntryButton, KnitGlyph, KnitTitle, KNIT_ICON_PATH, openLocalPath, '
66
66
  + 'requestPreview, fmtDuration, readKindPref, mediaUrl, isMedia, mediaLayoutFor, '
67
- + 'nextIndexFor, docOptionId, '
67
+ + 'nextIndexFor, docOptionId, planRowMotion, mergeGhostRows, motionAllowed, motionShift, '
68
+ + 'rowLayoutPoint, applyRowFlips, '
69
+ + 'MOTION_ENTER_MS, MOTION_EXIT_MS, MOTION_STAGGER_MS, MOTION_STAGGER_MAX, MOTION_EASE, '
70
+ + 'MOTION_MOVE_MS, MOTION_MOVE_EPS, '
68
71
  // ⚠️ 右栏那套名字(clampPackW / clampFloatPos / nearRightEdge / PACK_*)已随
69
72
  // 右栏一起删除(2026-09-29)。名字留在这里,模块一加载就 ReferenceError ——
70
73
  // 这个替身是**只增不减**的重灾区,删功能时记得同步删名字。
71
74
  + 'MIN_RATIO, MAX_RATIO, ALL_DOC_CAP, MEDIA_MAX_ITEMS, MEDIA_TRACK_PX, '
72
- + 'MEDIA_LABEL_MIN_PX, MEDIA_GAP_PX }\n'
75
+ + 'MEDIA_LABEL_MIN_PX, MEDIA_GAP_PX, '
76
+ // v0.18 Context Usage Lens:纯函数与阈值(渲染层的东西仍走 DOM 断言)。
77
+ + 'LIFE_GLYPH, lifeStatusOf, coverageOf, groupOutsideDocs, groupDelta, '
78
+ + 'COMPACT_PANEL_PX, MAX_OUTSIDE_SHOWN, MAX_DELTA_SHOWN, MAX_DELTA_GROUP, FLASH_MS }\n'
73
79
  + " module.exports.inject = ['slots', 'locale']",
74
80
  )
75
81
 
@@ -115,6 +121,9 @@ export function createHarness() {
115
121
  },
116
122
  useCallback: (fn) => fn,
117
123
  useEffect: (fn) => { pendingEffects.push(fn) },
124
+ // 真实 React 里 layout effect 跑在 DOM 变更之后、paint 之前。替身没有 DOM,排进同一队
125
+ // 即可 —— 客户端那两段进出动效在 Node 里被 `motionAllowed()` 挡掉,不会真的碰节点。
126
+ useLayoutEffect: (fn) => { pendingEffects.push(fn) },
118
127
  // 测试里不做记忆化:每次渲染重算即可,行为与真实 useMemo 等价
119
128
  useMemo: (fn) => fn(),
120
129
  // 真实 useRef 跨渲染稳定(与 useState 共用槽位空间,同 React)