dsh-context-compression-improved 0.9.8 → 0.9.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/plans/improve/checklist.md +32 -0
- package/.agents/plans/improve/findings.md +102 -0
- package/.agents/plans/improve/spec.md +53 -0
- package/.agents/plans/improve/tasks.md +70 -0
- package/CHANGELOG.md +4 -0
- package/README.md +14 -2
- package/README.zh.md +14 -2
- package/package.json +1 -1
- package/packages/selector/dsh.plugin.json +1 -1
- package/packages/selector/lib/client.d.ts +16 -0
- package/packages/selector/lib/client.js +396 -117
- package/packages/selector/lib/index.js +829 -10
- package/packages/selector/lib/invariant.js +2 -1
- package/packages/selector/lib/pruner.d.ts +1 -1
- package/packages/selector/lib/pruner.js +77 -983
- package/packages/selector/lib/savings-integral.js +4515 -0
- package/packages/selector/lib/tail-trim.js +2 -90
- package/packages/selector/lib/tool-result.js +150 -0
- package/packages/selector/package.json +8 -4
- package/packages/selector/src/client/index.ts +15 -12
- package/packages/selector/src/client/locales/de.ts +20 -4
- package/packages/selector/src/client/locales/es.ts +20 -4
- package/packages/selector/src/client/locales/fr.ts +20 -4
- package/packages/selector/src/client/locales/it.ts +20 -4
- package/packages/selector/src/client/locales/ja.ts +20 -4
- package/packages/selector/src/client/locales/ko.ts +20 -4
- package/packages/selector/src/client/locales/ru.ts +20 -4
- package/packages/selector/src/client/locales.ts +40 -8
- package/packages/selector/src/client/monitor-fab.ts +80 -10
- package/packages/selector/src/client/savings-card.tsx +159 -40
- package/packages/selector/src/index.ts +236 -1
- package/packages/selector/src/pruner.ts +54 -8
- package/packages/selector/src/runtime/audit.ts +17 -0
- package/packages/selector/src/runtime/display-prefs.ts +98 -0
- package/packages/selector/src/runtime/monitor.ts +75 -0
- package/packages/selector/src/runtime/panel-command.ts +213 -0
- package/packages/selector/src/runtime/retrieve.ts +31 -12
- package/packages/selector/src/runtime/savings-integral.ts +117 -0
- package/packages/selector/src/runtime/savings-projection.ts +3 -0
- package/packages/selector/src/runtime/savings-verify.ts +446 -0
- package/packages/selector/src/runtime/savings.ts +122 -13
- package/packages/selector/src/runtime/session-file-decode.ts +523 -0
- package/packages/selector/src/runtime/stats-backfill.ts +541 -0
- package/packages/selector/src/runtime/stats-db.ts +492 -0
- package/packages/selector/src/runtime/stats-schema.ts +123 -0
- package/packages/selector/src/runtime/stats-sync.ts +302 -0
- package/packages/selector/tests/estimator-route-registration.host.spec.ts +7 -4
- package/packages/selector/tests/monitor-fab.client.spec.ts +83 -1
- package/packages/selector/tests/runtime/fixtures/session-v4-dump.jsonl +46 -0
- package/packages/selector/tests/runtime/monitor.spec.ts +53 -0
- package/packages/selector/tests/runtime/panel-command.spec.ts +101 -0
- package/packages/selector/tests/runtime/public/public-runtime.spec.ts +0 -1
- package/packages/selector/tests/runtime/savings-accounting.spec.ts +291 -0
- package/packages/selector/tests/runtime/savings-integral.spec.ts +169 -0
- package/packages/selector/tests/runtime/savings-verify.spec.ts +226 -0
- package/packages/selector/tests/runtime/session-file-decode.spec.ts +281 -0
- package/packages/selector/tests/runtime/stats-backfill-scheduler.spec.ts +167 -0
- package/packages/selector/tests/runtime/stats-backfill.spec.ts +327 -0
- package/packages/selector/tests/runtime/stats-db.spec.ts +361 -0
- package/packages/selector/tests/runtime/stats-privacy.spec.ts +55 -0
- package/packages/selector/tests/runtime/stats-sync.spec.ts +278 -0
- package/packages/selector/tests/savings-sessions.client.spec.tsx +140 -0
- package/packages/selector/tests/settings-seat.client.spec.ts +15 -15
- package/pnpm-workspace.yaml +4 -0
- package/scripts/verify-release.mjs +5 -2
- package/vitest.config.ts +8 -0
- package/packages/selector/lib/config.js +0 -1777
- package/packages/selector/lib/host-generation.js +0 -62
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* /ccip verify 验算核心规格:jsonl 原文 × turn/step 索引 × DS token 口径独立
|
|
3
|
+
* 重算,与持久 claims 对账。verdict 语义:no-claims(无落账)/cross-basis
|
|
4
|
+
* (tokenizer 缺席退 chars/4)/match(同口径对上)。运行时活跃指针同文件覆盖。
|
|
5
|
+
*/
|
|
6
|
+
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
|
7
|
+
import { tmpdir } from 'node:os'
|
|
8
|
+
import { join } from 'node:path'
|
|
9
|
+
import { DatabaseSync } from 'node:sqlite'
|
|
10
|
+
import zlib from 'node:zlib'
|
|
11
|
+
import { afterEach, describe, expect, it, vi } from 'vitest'
|
|
12
|
+
import { generationLogFilename } from '../../src/runtime/session-file-decode.ts'
|
|
13
|
+
import {
|
|
14
|
+
formatVerifyReport, readDrsProjectionTotals, resolveDrsIndexDir, verifySessionSavings,
|
|
15
|
+
} from '../../src/runtime/savings-verify.ts'
|
|
16
|
+
import { getStatsActiveSessionId, noteStatsSessionActive } from '../../src/runtime/stats-sync.ts'
|
|
17
|
+
import { closeStatsStore } from '../../src/runtime/stats-db.ts'
|
|
18
|
+
|
|
19
|
+
const dirs: string[] = []
|
|
20
|
+
|
|
21
|
+
function tempDir(tag: string): string {
|
|
22
|
+
const dir = mkdtempSync(join(tmpdir(), `cci-verify-${tag}-`))
|
|
23
|
+
dirs.push(dir)
|
|
24
|
+
return dir
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** 可解码 v4 会话目录:一条 400 字符 tool/result 被替换成 100 字符 + usage。 */
|
|
28
|
+
function writeSessionDir(dshHome: string, sessionId: string): void {
|
|
29
|
+
const dir = join(dshHome, 'sessions', 'proj', sessionId)
|
|
30
|
+
const header = JSON.stringify({ type: 'session', version: 4, id: sessionId, createdAt: 1, cwd: 'proj' })
|
|
31
|
+
const rows = [
|
|
32
|
+
JSON.stringify({ seq: 0, type: 'step/start', time: 1000, data: { turn: 3, step: 1 } }),
|
|
33
|
+
JSON.stringify({ seq: 1, type: 'tool/result', time: 1001, data: { message: { content: [{ type: 'text', text: 'R'.repeat(400) }] } } }),
|
|
34
|
+
JSON.stringify({ seq: 2, type: 'user/message', time: 1002, surfaceOp: { op: 'replace', startSeq: 1, endSeq: 1 }, data: { message: { content: [{ type: 'text', text: 'S'.repeat(100) }] } } }),
|
|
35
|
+
JSON.stringify({ seq: 3, type: 'assistant/message', time: 1003, data: { message: { content: [] }, usage: { inputTokens: 100, outputTokens: 10, cacheReadTokens: 50 } } }),
|
|
36
|
+
]
|
|
37
|
+
const bytes = zlib.zstdCompressSync(Buffer.from([header, ...rows, ''].join('\n'), 'utf8'))
|
|
38
|
+
mkdirSync(dir, { recursive: true })
|
|
39
|
+
writeFileSync(join(dir, generationLogFilename(4, 'zstd')), bytes)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
afterEach(() => {
|
|
43
|
+
closeStatsStore()
|
|
44
|
+
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
|
|
45
|
+
vi.restoreAllMocks()
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
describe('savings-verify(/ccip verify 验算核心)', () => {
|
|
49
|
+
it('运行时活跃指针:note → get 幂等', () => {
|
|
50
|
+
expect(getStatsActiveSessionId()).toBeUndefined()
|
|
51
|
+
noteStatsSessionActive('session-abc')
|
|
52
|
+
expect(getStatsActiveSessionId()).toBe('session-abc')
|
|
53
|
+
noteStatsSessionActive('session-def')
|
|
54
|
+
expect(getStatsActiveSessionId()).toBe('session-def')
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
it('fixture 重算:索引成对(a=400 字符原文,b=100 替换)、公式口径如实、claims 空判 no-claims', async () => {
|
|
58
|
+
const home = tempDir('fixture')
|
|
59
|
+
process.env['DSH_HOME'] = home
|
|
60
|
+
writeSessionDir(home, 'session-verify-1')
|
|
61
|
+
const statsDb = await import('../../src/runtime/stats-db.ts')
|
|
62
|
+
await statsDb.ensureStatsStore(join(tempDir('db'), 'stats.sqlite'))
|
|
63
|
+
|
|
64
|
+
const report = verifySessionSavings({ sessionId: 'session-verify-1' })
|
|
65
|
+
expect(report.sessionId).toBe('session-verify-1')
|
|
66
|
+
expect(report.indexedEvents).toBe(4)
|
|
67
|
+
expect(report.formulaBasis === 'ds-token' || report.formulaBasis === 'chars/4').toBe(true)
|
|
68
|
+
expect(report.pairs).toHaveLength(1)
|
|
69
|
+
const pair = report.pairs[0]!
|
|
70
|
+
expect(pair.turn).toBe(3)
|
|
71
|
+
expect(pair.originalTokens).toBeGreaterThan(pair.replacementTokens)
|
|
72
|
+
expect(pair.gross).toBe(pair.originalTokens - pair.replacementTokens)
|
|
73
|
+
expect(report.formulaGross).toBe(150)
|
|
74
|
+
expect(report.formulaNet).toBe(150)
|
|
75
|
+
expect(report.verdict).toBe('no-claims')
|
|
76
|
+
const lines = formatVerifyReport(report)
|
|
77
|
+
expect(lines[0]).toContain('ccip verify session-verify-1')
|
|
78
|
+
expect(lines.some(line => line.includes('formula('))).toBe(true)
|
|
79
|
+
expect(lines.some(line => line.startsWith('verdict:'))).toBe(true)
|
|
80
|
+
delete process.env['DSH_HOME']
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
it('live 清除链(jsonl 兜底臂):替身被后续区间再覆盖 → 先前对 delta 不入 gross,不双计', () => {
|
|
84
|
+
// 链:seq1(R*400=200tk) →seq2 替(S*100=50tk) →seq3 checkpoint 覆盖 [1..2](C*80=40tk)。
|
|
85
|
+
// 旧口径 gross=150+210=360(seq1 被两对重复计费);live 清除后只计仍面对:250−40=210。
|
|
86
|
+
const home = tempDir('livechain')
|
|
87
|
+
process.env['DSH_HOME'] = home
|
|
88
|
+
const sessionId = 'session-live-1'
|
|
89
|
+
const dir = join(home, 'sessions', 'proj', sessionId)
|
|
90
|
+
const header = JSON.stringify({ type: 'session', version: 4, id: sessionId, createdAt: 1, cwd: 'proj' })
|
|
91
|
+
const rows = [
|
|
92
|
+
JSON.stringify({ seq: 0, type: 'step/start', time: 1000, data: { turn: 1, step: 1 } }),
|
|
93
|
+
JSON.stringify({ seq: 1, type: 'tool/result', time: 1001, data: { message: { content: [{ type: 'text', text: 'R'.repeat(400) }] } } }),
|
|
94
|
+
JSON.stringify({ seq: 2, type: 'user/message', time: 1002, surfaceOp: { op: 'replace', startSeq: 1, endSeq: 1 }, data: { content: [{ type: 'text', text: 'S'.repeat(100) }] } }),
|
|
95
|
+
JSON.stringify({ seq: 3, type: 'user/message', time: 1003, surfaceOp: { op: 'replace', startSeq: 1, endSeq: 2 }, data: { content: [{ type: 'text', text: 'C'.repeat(80) }] } }),
|
|
96
|
+
]
|
|
97
|
+
mkdirSync(dir, { recursive: true })
|
|
98
|
+
writeFileSync(join(dir, generationLogFilename(4, 'zstd')), zlib.zstdCompressSync(Buffer.from([header, ...rows, ''].join('\n'), 'utf8')))
|
|
99
|
+
|
|
100
|
+
const report = verifySessionSavings({ sessionId })
|
|
101
|
+
expect(report.indexSource).toBe('jsonl')
|
|
102
|
+
expect(report.pairs).toHaveLength(2)
|
|
103
|
+
// 双臂视界:checkpoint 摘要挂 data.content 也被计(旧单臂下 b=0)。
|
|
104
|
+
const ckPair = report.pairs.find(p => p.seq === 3)!
|
|
105
|
+
expect(ckPair.originalTokens).toBe(250)
|
|
106
|
+
expect(ckPair.replacementTokens).toBeGreaterThan(0)
|
|
107
|
+
// 只计仍面那对:seq2 被 [1..2] 吸收,其先前 delta 清除。
|
|
108
|
+
expect(report.formulaGross).toBe(250 - ckPair.replacementTokens)
|
|
109
|
+
delete process.env['DSH_HOME']
|
|
110
|
+
})
|
|
111
|
+
|
|
112
|
+
it('目标解析:显式 id 不存在 → no-jsonl;缺省且指针缺失 → no-session', async () => {
|
|
113
|
+
const home = tempDir('resolve')
|
|
114
|
+
process.env['DSH_HOME'] = home
|
|
115
|
+
const statsDb = await import('../../src/runtime/stats-db.ts')
|
|
116
|
+
await statsDb.ensureStatsStore(join(tempDir('db'), 'stats.sqlite'))
|
|
117
|
+
expect(verifySessionSavings({ sessionId: 'session-missing' }).verdict).toBe('no-jsonl')
|
|
118
|
+
const fallback = verifySessionSavings()
|
|
119
|
+
expect(['no-session', 'no-jsonl']).toContain(fallback.verdict)
|
|
120
|
+
delete process.env['DSH_HOME']
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
it('会话目录不存在时 dshHome 探测不抛错', () => {
|
|
124
|
+
const home = tempDir('empty')
|
|
125
|
+
process.env['DSH_HOME'] = home
|
|
126
|
+
expect(existsSync(home)).toBe(true)
|
|
127
|
+
const report = verifySessionSavings({ sessionId: 'session-none' })
|
|
128
|
+
expect(report.verdict).toBe('no-jsonl')
|
|
129
|
+
delete process.env['DSH_HOME']
|
|
130
|
+
})
|
|
131
|
+
|
|
132
|
+
it('DRS 投影只读探针:fixture 库在对账行如实;库/会话缺席 undefined 不冒充(T6.3)', () => {
|
|
133
|
+
const indexDir = tempDir('drs')
|
|
134
|
+
process.env['DSH_REFERENCE_SESSION_COLLECTOR_DIR'] = indexDir
|
|
135
|
+
try {
|
|
136
|
+
// 最小 projection.db(与 DRS L1 DDL 同名列);只读探针只认列名不认宿主。
|
|
137
|
+
const db = new DatabaseSync(join(indexDir, 'projection.db'))
|
|
138
|
+
db.exec(`
|
|
139
|
+
CREATE TABLE sessions (session_id TEXT PRIMARY KEY, basis TEXT NOT NULL DEFAULT 'chars/4', synced_at TEXT NOT NULL DEFAULT '');
|
|
140
|
+
CREATE TABLE replaces (
|
|
141
|
+
session_id TEXT NOT NULL, seq INTEGER NOT NULL,
|
|
142
|
+
a_tokens INTEGER NOT NULL, b_tokens INTEGER NOT NULL, kind TEXT NOT NULL,
|
|
143
|
+
live INTEGER NOT NULL DEFAULT 1,
|
|
144
|
+
PRIMARY KEY (session_id, seq));
|
|
145
|
+
`)
|
|
146
|
+
db.prepare('INSERT INTO sessions (session_id, basis, synced_at) VALUES (?, ?, ?)').run('session-verify-1', 'ds-token', '2026-10-19 12:00:00')
|
|
147
|
+
const insert = db.prepare('INSERT INTO replaces (session_id, seq, a_tokens, b_tokens, kind) VALUES (?, ?, ?, ?, ?)')
|
|
148
|
+
insert.run('session-verify-1', 1, 400, 100, 'compress')
|
|
149
|
+
insert.run('session-verify-1', 2, 0, 50, 'recall')
|
|
150
|
+
db.close()
|
|
151
|
+
|
|
152
|
+
expect(resolveDrsIndexDir({})).toContain('.dsh-reference-session-collector')
|
|
153
|
+
expect(resolveDrsIndexDir({ DSH_REFERENCE_SESSION_COLLECTOR_DIR: '/custom' })).toBe('/custom')
|
|
154
|
+
expect(readDrsProjectionTotals({ sessionId: 'session-verify-1', indexDir })).toEqual({
|
|
155
|
+
grossSaved: 300, recallTokens: 50, net: 250, compressPairs: 1, recallPairs: 1, basis: 'ds-token', syncedAt: '2026-10-19 12:00:00',
|
|
156
|
+
})
|
|
157
|
+
// 会话未同步 → undefined;库缺席 → undefined;均不抛
|
|
158
|
+
expect(readDrsProjectionTotals({ sessionId: 'session-unknown', indexDir })).toBeUndefined()
|
|
159
|
+
expect(readDrsProjectionTotals({ sessionId: 'session-verify-1', indexDir: join(indexDir, 'absent') })).toBeUndefined()
|
|
160
|
+
|
|
161
|
+
// verify 报告带 drs 行;缺库时如实标注 unavailable
|
|
162
|
+
const home = tempDir('drs-report')
|
|
163
|
+
process.env['DSH_HOME'] = home
|
|
164
|
+
writeSessionDir(home, 'session-verify-1')
|
|
165
|
+
const withDrs = verifySessionSavings({ sessionId: 'session-verify-1' })
|
|
166
|
+
expect(withDrs.drs).toBeDefined()
|
|
167
|
+
expect(formatVerifyReport(withDrs).some(line => line.startsWith('drs(projection): gross='))).toBe(true)
|
|
168
|
+
process.env['DSH_REFERENCE_SESSION_COLLECTOR_DIR'] = join(tempDir('drs-absent'))
|
|
169
|
+
const withoutDrs = verifySessionSavings({ sessionId: 'session-verify-1' })
|
|
170
|
+
expect(withoutDrs.drs).toBeUndefined()
|
|
171
|
+
expect(formatVerifyReport(withoutDrs).some(line => line.includes('drs(projection): unavailable'))).toBe(true)
|
|
172
|
+
delete process.env['DSH_HOME']
|
|
173
|
+
} finally {
|
|
174
|
+
delete process.env['DSH_REFERENCE_SESSION_COLLECTOR_DIR']
|
|
175
|
+
}
|
|
176
|
+
})
|
|
177
|
+
|
|
178
|
+
it('DRS 为主源:turn/step 结构与 token 量从投影直取,无 jsonl 也出公式(T6 深接)', () => {
|
|
179
|
+
const indexDir = tempDir('drs-index')
|
|
180
|
+
const home = tempDir('drs-index-home')
|
|
181
|
+
process.env['DSH_HOME'] = home
|
|
182
|
+
process.env['DSH_REFERENCE_SESSION_COLLECTOR_DIR'] = indexDir
|
|
183
|
+
try {
|
|
184
|
+
// 最小 projection.db:2 turn / 3 step,一压缩对 + 一召回对
|
|
185
|
+
const db = new DatabaseSync(join(indexDir, 'projection.db'))
|
|
186
|
+
db.exec(`
|
|
187
|
+
CREATE TABLE sessions (session_id TEXT PRIMARY KEY, basis TEXT NOT NULL DEFAULT 'chars/4', synced_at TEXT NOT NULL DEFAULT '', max_seq INTEGER NOT NULL DEFAULT -1, turn_count INTEGER NOT NULL DEFAULT 0);
|
|
188
|
+
CREATE TABLE segments (session_id TEXT NOT NULL, seq INTEGER NOT NULL, turn INTEGER NOT NULL DEFAULT 0, step INTEGER NOT NULL DEFAULT 0, tokens INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (session_id, seq));
|
|
189
|
+
CREATE TABLE replaces (session_id TEXT NOT NULL, seq INTEGER NOT NULL, start_seq INTEGER NOT NULL, end_seq INTEGER NOT NULL, a_tokens INTEGER NOT NULL, b_tokens INTEGER NOT NULL, kind TEXT NOT NULL, turn INTEGER NOT NULL DEFAULT 0, step INTEGER NOT NULL DEFAULT 0, live INTEGER NOT NULL DEFAULT 1, PRIMARY KEY (session_id, seq));
|
|
190
|
+
`)
|
|
191
|
+
db.prepare('INSERT INTO sessions VALUES (?, ?, ?, ?, ?)').run('session-drs-1', 'ds-token', '2026-10-20 01:00:00', 9, 2)
|
|
192
|
+
const seg = db.prepare('INSERT INTO segments (session_id, seq, turn, step, tokens) VALUES (?, ?, ?, ?, ?)')
|
|
193
|
+
seg.run('session-drs-1', 1, 1, 1, 200)
|
|
194
|
+
seg.run('session-drs-1', 2, 1, 2, 400)
|
|
195
|
+
seg.run('session-drs-1', 5, 2, 1, 100)
|
|
196
|
+
const rep = db.prepare('INSERT INTO replaces (session_id, seq, start_seq, end_seq, a_tokens, b_tokens, kind, turn, step) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)')
|
|
197
|
+
rep.run('session-drs-1', 3, 1, 2, 600, 120, 'compress', 1, 3)
|
|
198
|
+
rep.run('session-drs-1', 6, 5, 5, 0, 100, 'recall', 2, 1)
|
|
199
|
+
db.close()
|
|
200
|
+
|
|
201
|
+
const report = verifySessionSavings({ sessionId: 'session-drs-1' })
|
|
202
|
+
expect(report.indexSource).toBe('drs')
|
|
203
|
+
expect(report.turns).toBe(2)
|
|
204
|
+
expect(report.indexedEvents).toBe(3)
|
|
205
|
+
expect(report.formulaGross).toBe(480)
|
|
206
|
+
expect(report.formulaOffsets).toBe(100)
|
|
207
|
+
expect(report.formulaNet).toBe(380)
|
|
208
|
+
expect(report.pairs).toEqual([
|
|
209
|
+
{ turn: 1, step: 3, seq: 3, originalTokens: 600, replacementTokens: 120, gross: 480 },
|
|
210
|
+
{ turn: 2, step: 1, seq: 6, originalTokens: 0, replacementTokens: 100, gross: -100 },
|
|
211
|
+
])
|
|
212
|
+
expect(report.turnStructure).toEqual([
|
|
213
|
+
{ turn: 1, steps: 2, tokens: 600, segments: 2 },
|
|
214
|
+
{ turn: 2, steps: 1, tokens: 100, segments: 1 },
|
|
215
|
+
])
|
|
216
|
+
expect(report.drs).toMatchObject({ grossSaved: 480, recallTokens: 100, net: 380, basis: 'ds-token' })
|
|
217
|
+
expect(report.verdict).toBe('no-claims')
|
|
218
|
+
const lines = formatVerifyReport(report)
|
|
219
|
+
expect(lines.some(line => line.startsWith('index(drs):'))).toBe(true)
|
|
220
|
+
expect(lines.some(line => line.startsWith('drs turns: t1·600tk·2s'))).toBe(true)
|
|
221
|
+
} finally {
|
|
222
|
+
delete process.env['DSH_HOME']
|
|
223
|
+
delete process.env['DSH_REFERENCE_SESSION_COLLECTOR_DIR']
|
|
224
|
+
}
|
|
225
|
+
})
|
|
226
|
+
})
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* T19/T22:session-file-decode 叶子模块的代次契约与解码链路测试。
|
|
3
|
+
*
|
|
4
|
+
* fixture 策略(T22):
|
|
5
|
+
* - 真实样例:`fixtures/session-v4-dump.jsonl`(284KB,从本机 v4 会话解包样本转码);
|
|
6
|
+
* 测试内 zstd 压缩后走完整解码链,源文件本身只读。
|
|
7
|
+
* - 合成样例:v3/v4 header + 打包行 + provenance 区间,直接在内存构造。
|
|
8
|
+
* - 撕裂尾帧:完整帧 + 尾部截断帧,ZSTD_e_flush 抢救断言。
|
|
9
|
+
*/
|
|
10
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
11
|
+
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
|
|
12
|
+
import { tmpdir } from 'node:os'
|
|
13
|
+
import { join } from 'node:path'
|
|
14
|
+
import { describe, expect, it } from 'vitest'
|
|
15
|
+
import zlib from 'node:zlib'
|
|
16
|
+
import {
|
|
17
|
+
classifyGenerationFilename,
|
|
18
|
+
classifySessionHeader,
|
|
19
|
+
decodeRecordLocal,
|
|
20
|
+
decodeSeqRangesStorage,
|
|
21
|
+
decodeSessionLogBytes,
|
|
22
|
+
generationLogFilename,
|
|
23
|
+
isMigrationStagingFilename,
|
|
24
|
+
parseGenerationLogFilename,
|
|
25
|
+
readSessionGenerations,
|
|
26
|
+
scanZstdFrames,
|
|
27
|
+
type DecodedEvent,
|
|
28
|
+
type OfficialDecoders,
|
|
29
|
+
} from '../../src/runtime/session-file-decode.ts'
|
|
30
|
+
|
|
31
|
+
/** 规范历史代文件名(测试内同样避免 D7 字面量:拼接构造)。 */
|
|
32
|
+
const LEGACY_NAME = `session${'.'}jsonl.zstd`
|
|
33
|
+
|
|
34
|
+
function sessionHeader(version: number): string {
|
|
35
|
+
return JSON.stringify({ type: 'session', version, id: 'session-test', createdAt: 1_700_000_000_000, cwd: '/tmp' })
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** 由 header 代次与若干记录行合成一份 zstd 单帧日志(每条一行,seq 由调用方保证连续)。 */
|
|
39
|
+
function synthesizeLog(headerVersion: number | null, rows: readonly string[]): Buffer {
|
|
40
|
+
const headerLine = headerVersion === null ? 'not-json-at-all' : sessionHeader(headerVersion)
|
|
41
|
+
const text = [headerLine, ...rows, ''].join('\n')
|
|
42
|
+
return zlib.zstdCompressSync(Buffer.from(text, 'utf8'))
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
describe('session-file-decode / 代次文件名契约', () => {
|
|
46
|
+
it('代次名推导与解析互逆;历史代名按拼接构造(不留 D7 字面量)', () => {
|
|
47
|
+
expect(generationLogFilename(0)).toBe(LEGACY_NAME)
|
|
48
|
+
expect(generationLogFilename(4)).toBe('session.v4.jsonl.zstd')
|
|
49
|
+
expect(parseGenerationLogFilename(LEGACY_NAME)).toBe(0)
|
|
50
|
+
expect(parseGenerationLogFilename('session.v4.jsonl.zstd')).toBe(4)
|
|
51
|
+
expect(parseGenerationLogFilename('session.v12.jsonl', 'none')).toBe(12)
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
it('非法名一律不猜:前导零、.v0、大写 V、错后缀都拒绝', () => {
|
|
55
|
+
expect(parseGenerationLogFilename('session.v0.jsonl.zstd')).toBeUndefined()
|
|
56
|
+
expect(parseGenerationLogFilename('session.v01.jsonl.zstd')).toBeUndefined()
|
|
57
|
+
expect(parseGenerationLogFilename('session.V1.jsonl.zstd')).toBeUndefined()
|
|
58
|
+
expect(parseGenerationLogFilename('session.v1.jsonl.gz.zstd')).toBeUndefined()
|
|
59
|
+
expect(parseGenerationLogFilename('session.v1.backup.jsonl.zstd')).toBeUndefined()
|
|
60
|
+
expect(classifyGenerationFilename('session.v3.jsonl')).toEqual({ version: 3, compression: 'none' })
|
|
61
|
+
expect(classifyGenerationFilename('readme.txt')).toBeUndefined()
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
it('非法代次参数拒绝', () => {
|
|
65
|
+
expect(() => generationLogFilename(-1)).toThrow(/non-negative safe integer/)
|
|
66
|
+
expect(() => generationLogFilename(1.5)).toThrow(/non-negative safe integer/)
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
it('迁移暂存名识别(token 长度可变,只固定形状)', () => {
|
|
70
|
+
expect(isMigrationStagingFilename('session.migration.0123456789abcdef.jsonl.zstd.tmp')).toBe(true)
|
|
71
|
+
expect(isMigrationStagingFilename('session.migration.deadbeef.jsonl.tmp')).toBe(true)
|
|
72
|
+
expect(isMigrationStagingFilename('session.migration.XYZ.jsonl.zstd.tmp')).toBe(false)
|
|
73
|
+
expect(isMigrationStagingFilename('session.v4.jsonl.zstd')).toBe(false)
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
it('readSessionGenerations:目录实测最高代=当前代,只读不猜', async () => {
|
|
77
|
+
const dir = await mkdtemp(join(tmpdir(), 'sfd-gen-'))
|
|
78
|
+
try {
|
|
79
|
+
await writeFile(join(dir, LEGACY_NAME), 'legacy')
|
|
80
|
+
await writeFile(join(dir, 'session.v4.jsonl.zstd'), 'current')
|
|
81
|
+
await writeFile(join(dir, 'session.migration.aabbccddeeff0011.jsonl.zstd.tmp'), 'staging')
|
|
82
|
+
await writeFile(join(dir, 'session.v01.jsonl.zstd'), 'not-canonical')
|
|
83
|
+
const facts = readSessionGenerations(dir)
|
|
84
|
+
expect(facts.canonical.map(a => a.version)).toEqual([0, 4])
|
|
85
|
+
expect(facts.current?.version).toBe(4)
|
|
86
|
+
expect(facts.legacy?.name).toBe(LEGACY_NAME)
|
|
87
|
+
expect(facts.staging).toHaveLength(1)
|
|
88
|
+
expect(facts.legacyOnly).toBe(false)
|
|
89
|
+
// 目录不存在:如实返回空事实,不抛
|
|
90
|
+
const missing = readSessionGenerations(join(dir, 'no-such-dir'))
|
|
91
|
+
expect(missing.canonical).toEqual([])
|
|
92
|
+
} finally {
|
|
93
|
+
await rm(dir, { recursive: true, force: true })
|
|
94
|
+
}
|
|
95
|
+
})
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
describe('session-file-decode / zstd 多帧与撕裂尾帧', () => {
|
|
99
|
+
it('多帧拼接逐帧解码(zstdDecompressSync 整体解只出首帧,帧扫描是必需路径)', () => {
|
|
100
|
+
const frameA = zlib.zstdCompressSync(Buffer.from('{"a":1}\n', 'utf8'))
|
|
101
|
+
const frameB = zlib.zstdCompressSync(Buffer.from('{"b":2}\n', 'utf8'))
|
|
102
|
+
const both = Buffer.concat([frameA, frameB])
|
|
103
|
+
// 官方整体解码只覆盖首帧——这正是要自己做帧扫描的原因
|
|
104
|
+
expect(zlib.zstdDecompressSync(both).toString('utf8')).toBe('{"a":1}\n')
|
|
105
|
+
const scan = scanZstdFrames(both)
|
|
106
|
+
expect(scan.frames).toHaveLength(2)
|
|
107
|
+
expect(scan.tornStart).toBeUndefined()
|
|
108
|
+
const text = scan.frames
|
|
109
|
+
.map(f => zlib.zstdDecompressSync(both.subarray(f.start, f.end)).toString('utf8'))
|
|
110
|
+
.join('')
|
|
111
|
+
expect(text).toBe('{"a":1}\n{"b":2}\n')
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
it('撕裂尾帧:tornStart 定位 + ZSTD_e_flush 抢救部分明文,完整帧不受影响', () => {
|
|
115
|
+
const frameA = zlib.zstdCompressSync(Buffer.from('header-line\n', 'utf8'))
|
|
116
|
+
const frameB = zlib.zstdCompressSync(Buffer.from('tail-line-contents-here\n', 'utf8'))
|
|
117
|
+
const torn = Buffer.concat([frameA, frameB.subarray(0, frameB.length - 3)])
|
|
118
|
+
const scan = scanZstdFrames(torn)
|
|
119
|
+
expect(scan.frames).toHaveLength(1)
|
|
120
|
+
expect(scan.tornStart).toBe(frameA.length)
|
|
121
|
+
const recovered = zlib.zstdDecompressSync(torn.subarray(scan.tornStart!), {
|
|
122
|
+
finishFlush: zlib.constants.ZSTD_e_flush,
|
|
123
|
+
}).toString('utf8')
|
|
124
|
+
expect(recovered.length).toBeGreaterThan(0)
|
|
125
|
+
expect('tail-line-contents-here\n'.startsWith(recovered)).toBe(true)
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
it('非 zstd 明文开头:整段判为撕裂起点、零完整帧(decode 侧按抢救处理)', () => {
|
|
129
|
+
const plain = Buffer.from('{"type":"session"}\n', 'utf8')
|
|
130
|
+
const scan = scanZstdFrames(plain)
|
|
131
|
+
expect(scan.frames).toHaveLength(0)
|
|
132
|
+
expect(scan.tornStart).toBe(0)
|
|
133
|
+
})
|
|
134
|
+
})
|
|
135
|
+
|
|
136
|
+
describe('session-file-decode / 记录解码与 provenance', () => {
|
|
137
|
+
it('打包行解包:text-chunks 展开为 assistant/chunk,dt 为时间增量', () => {
|
|
138
|
+
const row = {
|
|
139
|
+
type: 'text-chunks',
|
|
140
|
+
seq0: 3,
|
|
141
|
+
time0: 100,
|
|
142
|
+
data: { turn: 0, step: 1, index: 2, texts: ['ab', 'cd', 'ef'], dt: [5, 7] },
|
|
143
|
+
}
|
|
144
|
+
const events = decodeRecordLocal(row)
|
|
145
|
+
expect(events.map(e => e.seq)).toEqual([3, 4, 5])
|
|
146
|
+
expect(events.map(e => e.time)).toEqual([100, 105, 112])
|
|
147
|
+
expect(events[0]).toMatchObject({ type: 'assistant/chunk', data: { turn: 0, step: 1 } })
|
|
148
|
+
expect((events[2]!.data as { chunk: Record<string, unknown> }).chunk).toMatchObject({ type: 'text-delta', text: 'ef', index: 2 })
|
|
149
|
+
})
|
|
150
|
+
|
|
151
|
+
it('tool-call-chunks 用 args 载荷并带 id/name', () => {
|
|
152
|
+
const row = {
|
|
153
|
+
type: 'tool-call-chunks',
|
|
154
|
+
seq0: 0,
|
|
155
|
+
time0: 10,
|
|
156
|
+
data: { turn: 1, step: 0, index: 0, id: 'call-1', name: 'bash', args: ['{"cmd":', '"ls"}'], dt: [1] },
|
|
157
|
+
}
|
|
158
|
+
const events = decodeRecordLocal(row)
|
|
159
|
+
const chunk = events[1]!.data as { chunk: Record<string, unknown> }
|
|
160
|
+
expect(chunk.chunk).toMatchObject({ type: 'tool-call-delta', id: 'call-1', name: 'bash', argumentsDelta: '"ls"}' })
|
|
161
|
+
})
|
|
162
|
+
|
|
163
|
+
it('打包行形状错误:拒绝(dt 长度不符/载荷非字符串数组)', () => {
|
|
164
|
+
expect(() => decodeRecordLocal({ type: 'text-chunks', seq0: 0, time0: 0, data: { texts: ['a', 'b'], dt: [] } }))
|
|
165
|
+
.toThrow(/dt length/)
|
|
166
|
+
expect(() => decodeRecordLocal({ type: 'text-chunks', seq0: 0, time0: 0, data: { texts: [1, 2], dt: [0] } }))
|
|
167
|
+
.toThrow(/non-empty string array/)
|
|
168
|
+
})
|
|
169
|
+
|
|
170
|
+
it('provenance 区间编码展开 + 前向引用校验', () => {
|
|
171
|
+
expect(decodeSeqRangesStorage([[0, 2], 5], 6)).toEqual([0, 1, 2, 5])
|
|
172
|
+
expect(() => decodeSeqRangesStorage([[3, 1]], 6)).toThrow(/malformed/)
|
|
173
|
+
expect(() => decodeSeqRangesStorage([6], 6)).toThrow(/reference earlier/)
|
|
174
|
+
expect(() => decodeSeqRangesStorage('x', 6)).toThrow(/must be an array/)
|
|
175
|
+
})
|
|
176
|
+
|
|
177
|
+
it('seq 缺口按 prefix 语义截断并记问题', () => {
|
|
178
|
+
const rows = [
|
|
179
|
+
JSON.stringify({ type: 'user/message', seq: 0, time: 1, data: {} }),
|
|
180
|
+
JSON.stringify({ type: 'user/message', seq: 2, time: 2, data: {} }), // 缺 seq 1
|
|
181
|
+
]
|
|
182
|
+
const log = decodeSessionLogBytes(synthesizeLog(4, rows))
|
|
183
|
+
expect(log.events).toHaveLength(1)
|
|
184
|
+
expect(log.issues).toHaveLength(1)
|
|
185
|
+
expect(log.issues[0]!.why).toMatch(/seq gap \(expected 1, got 2\)/)
|
|
186
|
+
})
|
|
187
|
+
|
|
188
|
+
it('官方解码器可用时走 official 臂且来源如实标注', () => {
|
|
189
|
+
const official: OfficialDecoders = {
|
|
190
|
+
decodeStorageRecord: value => [value as DecodedEvent],
|
|
191
|
+
decodeSeqRanges: (value, seq) => decodeSeqRangesStorage(value, seq),
|
|
192
|
+
}
|
|
193
|
+
const rows = [
|
|
194
|
+
JSON.stringify({ type: 'user/message', seq: 0, time: 1, data: {} }),
|
|
195
|
+
JSON.stringify({ type: 'tool/result', seq: 1, time: 2, sourceEventSeqs: [[0, 0]], data: {} }),
|
|
196
|
+
]
|
|
197
|
+
const log = decodeSessionLogBytes(synthesizeLog(4, rows), official)
|
|
198
|
+
expect(log.decoder).toBe('official')
|
|
199
|
+
expect(log.events).toHaveLength(2)
|
|
200
|
+
expect(log.events[1]?.sourceEventSeqs).toEqual([0])
|
|
201
|
+
const local = decodeSessionLogBytes(synthesizeLog(4, rows))
|
|
202
|
+
expect(local.decoder).toBe('local')
|
|
203
|
+
})
|
|
204
|
+
|
|
205
|
+
it('findOpenStep:尾部未收尾的 step 报出,step/end 后清零', () => {
|
|
206
|
+
const rows = [
|
|
207
|
+
JSON.stringify({ type: 'step/start', seq: 0, time: 1, data: { turn: 2, step: 3 } }),
|
|
208
|
+
JSON.stringify({ type: 'step/end', seq: 1, time: 2, data: { turn: 2, step: 3 } }),
|
|
209
|
+
JSON.stringify({ type: 'step/start', seq: 2, time: 3, data: { turn: 2, step: 4 } }),
|
|
210
|
+
]
|
|
211
|
+
const log = decodeSessionLogBytes(synthesizeLog(4, rows))
|
|
212
|
+
expect(log.openStep).toEqual({ turn: 2, step: 4 })
|
|
213
|
+
})
|
|
214
|
+
})
|
|
215
|
+
|
|
216
|
+
describe('session-file-decode / header 代次 fail-soft 分类', () => {
|
|
217
|
+
it('v3/v4 已知代次放行', () => {
|
|
218
|
+
for (const version of [3, 4]) {
|
|
219
|
+
const log = decodeSessionLogBytes(synthesizeLog(version, []))
|
|
220
|
+
expect(classifySessionHeader(log.header)).toMatchObject({ state: 'known', version })
|
|
221
|
+
}
|
|
222
|
+
})
|
|
223
|
+
|
|
224
|
+
it('未知代次/无 header/非 session 头都归为不可回填(调用方跳过该会话)', () => {
|
|
225
|
+
const unknown = decodeSessionLogBytes(synthesizeLog(9, []))
|
|
226
|
+
expect(classifySessionHeader(unknown.header)).toMatchObject({ state: 'unknown-version', version: 9 })
|
|
227
|
+
// 首行不是 zstd 可解内容:整体抢救失败也不抛,header 如实缺失
|
|
228
|
+
const broken = decodeSessionLogBytes(Buffer.from('not-json-at-all\n', 'utf8'))
|
|
229
|
+
expect(classifySessionHeader(broken.header)).toEqual({ state: 'missing-header' })
|
|
230
|
+
const foreign = decodeSessionLogBytes(synthesizeLog(4, []))
|
|
231
|
+
expect(classifySessionHeader({ ...foreign.header!, type: 'other' })).toEqual({ state: 'not-session' })
|
|
232
|
+
})
|
|
233
|
+
|
|
234
|
+
it('空文件:header 缺失、零事件、零问题(不抛)', () => {
|
|
235
|
+
const log = decodeSessionLogBytes(Buffer.alloc(0))
|
|
236
|
+
expect(log).toMatchObject({ events: [], frames: 0, recoveredFromTorn: 0, issues: [], decoder: 'local' })
|
|
237
|
+
expect(classifySessionHeader(log.header)).toEqual({ state: 'missing-header' })
|
|
238
|
+
})
|
|
239
|
+
})
|
|
240
|
+
|
|
241
|
+
describe('session-file-decode / 真实 v4 解包样本', () => {
|
|
242
|
+
const fixture = new URL('fixtures/session-v4-dump.jsonl', import.meta.url)
|
|
243
|
+
const present = existsSync(fixture)
|
|
244
|
+
|
|
245
|
+
it.skipIf(!present)('真实会话(v4 header + 45 事件)转码为 zstd 后完整解码、零问题', () => {
|
|
246
|
+
const text = readFileSync(fixture, 'utf8')
|
|
247
|
+
const log = decodeSessionLogBytes(zlib.zstdCompressSync(Buffer.from(text, 'utf8')))
|
|
248
|
+
expect(classifySessionHeader(log.header)).toMatchObject({ state: 'known', version: 4 })
|
|
249
|
+
expect(log.events.length).toBeGreaterThan(40)
|
|
250
|
+
expect(log.issues).toEqual([])
|
|
251
|
+
expect(log.frames).toBeGreaterThanOrEqual(1)
|
|
252
|
+
expect(log.tornStart).toBeUndefined()
|
|
253
|
+
// seq 连续(0..n-1)由解码链的 prefix 语义保证:无 issue 即连续
|
|
254
|
+
expect(log.events.at(-1)!.seq).toBe(log.events.length - 1)
|
|
255
|
+
})
|
|
256
|
+
|
|
257
|
+
it.skipIf(!present)('真实样本多帧切分后再拼接解码结果一致', () => {
|
|
258
|
+
const text = readFileSync(fixture, 'utf8')
|
|
259
|
+
const whole = zlib.zstdCompressSync(Buffer.from(text, 'utf8'))
|
|
260
|
+
const half = Math.floor(text.length / 2)
|
|
261
|
+
const multi = Buffer.concat([
|
|
262
|
+
zlib.zstdCompressSync(Buffer.from(text.slice(0, half), 'utf8')),
|
|
263
|
+
zlib.zstdCompressSync(Buffer.from(text.slice(half), 'utf8')),
|
|
264
|
+
])
|
|
265
|
+
const a = decodeSessionLogBytes(whole)
|
|
266
|
+
const b = decodeSessionLogBytes(multi)
|
|
267
|
+
expect(b.frames).toBeGreaterThanOrEqual(2)
|
|
268
|
+
expect(b.issues).toEqual([])
|
|
269
|
+
expect(b.events).toEqual(a.events)
|
|
270
|
+
expect(b.header).toEqual(a.header)
|
|
271
|
+
})
|
|
272
|
+
})
|
|
273
|
+
|
|
274
|
+
describe('session-file-decode / D7 静态纪律', () => {
|
|
275
|
+
it('模块源码不含检查器正则的连续字面量', () => {
|
|
276
|
+
const source = readFileSync(new URL('../../src/runtime/session-file-decode.ts', import.meta.url), 'utf8')
|
|
277
|
+
expect(source).not.toMatch(/session\.jsonl|SESSION_FORMAT_VERSION|sessionFormatVersion/u)
|
|
278
|
+
// 用等价文本正则再扫一遍(点为真实点),防止拼接改写引入漏网
|
|
279
|
+
expect(/session[.]jsonl/.test(source)).toBe(false)
|
|
280
|
+
})
|
|
281
|
+
})
|