dsh-context-compression-improved 0.9.0 → 0.9.5
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/CHANGELOG.md +56 -0
- package/package.json +2 -1
- package/packages/selector/dsh.plugin.json +1 -1
- package/packages/selector/lib/client.d.ts +1 -0
- package/packages/selector/lib/client.js +86 -32
- package/packages/selector/lib/config.js +71 -7
- package/packages/selector/lib/index.js +120 -20
- package/packages/selector/lib/pruner.d.ts +158 -107
- package/packages/selector/lib/pruner.js +336 -21
- package/packages/selector/package.json +1 -1
- package/packages/selector/src/client/index.ts +55 -20
- package/packages/selector/src/client/locales/de.ts +1 -0
- package/packages/selector/src/client/locales/es.ts +1 -0
- package/packages/selector/src/client/locales/fr.ts +1 -0
- package/packages/selector/src/client/locales/it.ts +1 -0
- package/packages/selector/src/client/locales/ja.ts +1 -0
- package/packages/selector/src/client/locales/ko.ts +1 -0
- package/packages/selector/src/client/locales/ru.ts +1 -0
- package/packages/selector/src/client/locales.ts +2 -0
- package/packages/selector/src/client/monitor-fab.ts +19 -4
- package/packages/selector/src/preset-overlay.ts +145 -22
- package/packages/selector/src/pruner/content.ts +1 -1
- package/packages/selector/src/pruner/state.ts +4 -0
- package/packages/selector/src/pruner.ts +120 -16
- package/packages/selector/src/runtime/config.ts +1 -1
- package/packages/selector/src/runtime/measurement.ts +14 -1
- package/packages/selector/src/runtime/reducers.ts +81 -1
- package/packages/selector/src/runtime/retrieve.ts +4 -3
- package/packages/selector/src/runtime/savings-projection.ts +226 -0
- package/packages/selector/src/runtime/savings.ts +83 -3
- package/packages/selector/tests/runtime/fresh-gate.spec.ts +43 -0
- package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +79 -0
- package/packages/selector/tests/runtime/public/public-runtime.spec.ts +48 -0
- package/packages/selector/tests/runtime/savings-projection.spec.ts +89 -0
- package/packages/selector/tests/runtime/savings.spec.ts +22 -3
- package/packages/selector/tests/runtime/settings-unwrap.spec.ts +58 -0
- package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +5 -2
- package/scripts/cell-browser-e2e.mjs +354 -0
|
@@ -27,6 +27,8 @@ export interface SavingsEntry {
|
|
|
27
27
|
tokens: number
|
|
28
28
|
basis: SavingsBasis
|
|
29
29
|
at: number
|
|
30
|
+
/** 落盘替换事件的 seq;'saving' 条目靠它判定"当前是否仍在 surface 中生效"。 */
|
|
31
|
+
replacementSeq?: number
|
|
30
32
|
note?: string
|
|
31
33
|
}
|
|
32
34
|
|
|
@@ -95,7 +97,12 @@ export class SavingsLedger {
|
|
|
95
97
|
`requests=${snap.usage.requests} cacheHit=${hit === null ? '–' : `${Math.round(hit * 100)}%`}`
|
|
96
98
|
}
|
|
97
99
|
|
|
98
|
-
/**
|
|
100
|
+
/**
|
|
101
|
+
* 记录一次已落盘的压缩节省(land 成功后调用;tokensRemoved ≤ 0 忽略)。
|
|
102
|
+
*
|
|
103
|
+
* 仪表口径:该条目在替换事件离开当前 surface 前一直计入"当前生效毛节省"
|
|
104
|
+
* (由 {@link observeActive} 每回合收敛),不再一次性永久累加。
|
|
105
|
+
*/
|
|
99
106
|
recordSaving(input: {
|
|
100
107
|
sessionId: string
|
|
101
108
|
component: string
|
|
@@ -103,6 +110,8 @@ export class SavingsLedger {
|
|
|
103
110
|
tokensAfter: number
|
|
104
111
|
basis: SavingsBasis
|
|
105
112
|
sourceSeq: number
|
|
113
|
+
/** 落盘替换事件的 seq;仪表口径用它判定"当前是否仍生效"。 */
|
|
114
|
+
replacementSeq?: number
|
|
106
115
|
/** 原文全文(配对键;哈希后不存原文)。 */
|
|
107
116
|
originalText?: string
|
|
108
117
|
}): void {
|
|
@@ -114,6 +123,7 @@ export class SavingsLedger {
|
|
|
114
123
|
tokens: removed,
|
|
115
124
|
basis: input.basis,
|
|
116
125
|
at: Date.now(),
|
|
126
|
+
...(input.replacementSeq === undefined ? {} : { replacementSeq: input.replacementSeq }),
|
|
117
127
|
})
|
|
118
128
|
if (typeof input.originalText === 'string' && input.originalText.length > 0) {
|
|
119
129
|
const hash = savingsHash(input.originalText)
|
|
@@ -153,8 +163,9 @@ export class SavingsLedger {
|
|
|
153
163
|
this.seenFullText.add(seenKey)
|
|
154
164
|
}
|
|
155
165
|
const hit = this.registry.get(savingsHash(input.text))
|
|
156
|
-
if (hit === undefined || hit.
|
|
157
|
-
|
|
166
|
+
if (hit === undefined || hit.sessionId !== input.sessionId) return
|
|
167
|
+
// 每次重读都罚:不再一次性消费——只要首次压缩(骨架/老化/去重/尾裁)存在,
|
|
168
|
+
// 之后每次把该原文全文重新读入上下文都记一条负项。
|
|
158
169
|
const { tokens, basis } = input.measure(input.text)
|
|
159
170
|
if (tokens <= 0) return
|
|
160
171
|
this.push(input.sessionId, {
|
|
@@ -200,6 +211,75 @@ export class SavingsLedger {
|
|
|
200
211
|
if (list.length > MAX_ENTRIES_PER_SESSION) list.splice(0, list.length - MAX_ENTRIES_PER_SESSION)
|
|
201
212
|
}
|
|
202
213
|
|
|
214
|
+
/**
|
|
215
|
+
* 仪表口径收敛:一个 'saving' 条目只在其替换事件仍位于当前 surface 时计为
|
|
216
|
+
* "当前生效毛节省"。pruner 每回合传入存活 seq 集合,离开 surface 的替换
|
|
217
|
+
* (被后续压缩/裁剪替换)即从毛节省中扣除,数字随压缩内容进出而涨落。
|
|
218
|
+
* 无 replacementSeq 的条目保持原样(无法追踪者不收敛)。
|
|
219
|
+
*/
|
|
220
|
+
observeActive(sessionId: string, liveSeqs: ReadonlySet<number>): void {
|
|
221
|
+
const list = this.entries.get(sessionId)
|
|
222
|
+
if (list === undefined) return
|
|
223
|
+
const kept = list.filter(entry =>
|
|
224
|
+
entry.kind !== 'saving'
|
|
225
|
+
|| entry.replacementSeq === undefined
|
|
226
|
+
|| liveSeqs.has(entry.replacementSeq))
|
|
227
|
+
if (kept.length !== list.length) this.entries.set(sessionId, kept)
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** 该会话是否已有账本条目(重进会话时用于避免投影与实时叠加)。 */
|
|
231
|
+
hasSession(sessionId: string): boolean {
|
|
232
|
+
return this.entries.has(sessionId)
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* 用会话日志投影播种一个会话的账本(重进/重启会话时调用一次)。写入
|
|
237
|
+
* savings/offsets 条目及其原文配对 registry,后续实时增量(observeActive /
|
|
238
|
+
* noteFullText)在同一条目集合上继续工作。调用方负责只播种一次。
|
|
239
|
+
*/
|
|
240
|
+
seedProjected(sessionId: string, projection: {
|
|
241
|
+
savings: readonly { component: string; tokens: number; basis: SavingsBasis; at: number; replacementSeq: number }[]
|
|
242
|
+
offsets: readonly { component: string; tokens: number; basis: SavingsBasis; at: number; note?: string }[]
|
|
243
|
+
registry: readonly { hash: string; claimedTokens: number; basis: SavingsBasis; sourceSeq: number }[]
|
|
244
|
+
}): void {
|
|
245
|
+
for (const entry of projection.savings) {
|
|
246
|
+
if (!Number.isFinite(entry.tokens) || entry.tokens <= 0) continue
|
|
247
|
+
this.push(sessionId, {
|
|
248
|
+
kind: 'saving',
|
|
249
|
+
component: entry.component,
|
|
250
|
+
tokens: entry.tokens,
|
|
251
|
+
basis: entry.basis,
|
|
252
|
+
at: entry.at,
|
|
253
|
+
replacementSeq: entry.replacementSeq,
|
|
254
|
+
})
|
|
255
|
+
}
|
|
256
|
+
for (const entry of projection.offsets) {
|
|
257
|
+
if (!Number.isFinite(entry.tokens) || entry.tokens <= 0) continue
|
|
258
|
+
this.push(sessionId, {
|
|
259
|
+
kind: 'offset',
|
|
260
|
+
component: entry.component,
|
|
261
|
+
tokens: entry.tokens,
|
|
262
|
+
basis: entry.basis,
|
|
263
|
+
at: entry.at,
|
|
264
|
+
...(entry.note === undefined ? {} : { note: entry.note }),
|
|
265
|
+
})
|
|
266
|
+
}
|
|
267
|
+
for (const item of projection.registry) {
|
|
268
|
+
if (this.registry.size >= MAX_REGISTRY && !this.registry.has(item.hash)) {
|
|
269
|
+
const oldest = this.registry.keys().next().value
|
|
270
|
+
if (oldest !== undefined) this.registry.delete(oldest)
|
|
271
|
+
}
|
|
272
|
+
this.registry.set(item.hash, {
|
|
273
|
+
sessionId,
|
|
274
|
+
component: 'projection',
|
|
275
|
+
claimedTokens: item.claimedTokens,
|
|
276
|
+
basis: item.basis,
|
|
277
|
+
sourceSeq: item.sourceSeq,
|
|
278
|
+
consumed: false,
|
|
279
|
+
})
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
203
283
|
/** 汇总快照。sessionId 缺省 = 全会话聚合。两个 basis 分列,永不合并。 */
|
|
204
284
|
snapshot(sessionId?: string): SavingsSnapshot {
|
|
205
285
|
const scope = sessionId === undefined ? [...this.entries.keys()] : [sessionId]
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { freshBelowTrigger } from '../../src/pruner.ts'
|
|
3
|
+
import { charsForTokens } from '../../src/runtime/config.ts'
|
|
4
|
+
import type { SnapshotCandidate } from '../../src/pruner/types.ts'
|
|
5
|
+
import type { CompressionPolicy } from '../../src/runtime/types.ts'
|
|
6
|
+
|
|
7
|
+
const TRIGGER = 4_096
|
|
8
|
+
const policy = { freshTriggerTokens: TRIGGER } as unknown as CompressionPolicy
|
|
9
|
+
|
|
10
|
+
const exact = (tokens: number, characterPressure: number): SnapshotCandidate =>
|
|
11
|
+
({ count: { kind: 'exact-tokenizer', tokens }, characterPressure }) as unknown as SnapshotCandidate
|
|
12
|
+
const unavailable = (characterPressure: number): SnapshotCandidate =>
|
|
13
|
+
({ count: { kind: 'unavailable', reason: 'no tokenizer' }, characterPressure }) as unknown as SnapshotCandidate
|
|
14
|
+
const estimate = (characterPressure: number): SnapshotCandidate =>
|
|
15
|
+
({ count: { kind: 'tokenizer-estimate', tokens: 999_999 }, characterPressure }) as unknown as SnapshotCandidate
|
|
16
|
+
|
|
17
|
+
describe('freshBelowTrigger (real-token fresh gate with char fallback)', () => {
|
|
18
|
+
it('exact tokenizer: triggers on CJK where the 4.0 char estimate would NOT', () => {
|
|
19
|
+
// 8,000 chars is below charsForTokens(4096)=16,384, but 5,000 real tokens
|
|
20
|
+
// is above the 4,096 trigger → must trigger (return false = not below).
|
|
21
|
+
expect(charsForTokens(TRIGGER)).toBe(16_384)
|
|
22
|
+
expect(freshBelowTrigger(exact(5_000, 8_000), policy)).toBe(false)
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
it('exact tokenizer: below trigger when real tokens do not exceed it', () => {
|
|
26
|
+
expect(freshBelowTrigger(exact(3_000, 20_000), policy)).toBe(true)
|
|
27
|
+
expect(freshBelowTrigger(exact(TRIGGER, 20_000), policy)).toBe(true) // boundary: <= is below
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
it('unavailable (local Qwen): falls back to the char basis, byte-for-byte old behavior', () => {
|
|
31
|
+
for (const chars of [10_000, 16_384, 20_000, 40_000]) {
|
|
32
|
+
expect(freshBelowTrigger(unavailable(chars), policy)).toBe(chars <= charsForTokens(TRIGGER))
|
|
33
|
+
}
|
|
34
|
+
expect(freshBelowTrigger(unavailable(20_000), policy)).toBe(false) // > 16,384 → triggers
|
|
35
|
+
expect(freshBelowTrigger(unavailable(10_000), policy)).toBe(true) // <= 16,384 → skipped
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
it('tokenizer-estimate is NOT treated as exact; uses the char fallback', () => {
|
|
39
|
+
// tokens field is huge but kind !== 'exact-tokenizer', so the char basis decides.
|
|
40
|
+
expect(freshBelowTrigger(estimate(10_000), policy)).toBe(true)
|
|
41
|
+
expect(freshBelowTrigger(estimate(20_000), policy)).toBe(false)
|
|
42
|
+
})
|
|
43
|
+
})
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { reduceFreshToolResult, type ReducerInput } from '../../src/runtime/reducers.ts'
|
|
3
|
+
|
|
4
|
+
const SOURCE_REF = 'session://s1/event/7'
|
|
5
|
+
|
|
6
|
+
function input(text: string, budgetChars: number, toolName = 'bash'): ReducerInput {
|
|
7
|
+
return {
|
|
8
|
+
toolName,
|
|
9
|
+
argumentsText: toolName === 'read_file' ? '{"path":"logs.jsonl"}' : '{"command":"cat logs.jsonl"}',
|
|
10
|
+
text,
|
|
11
|
+
budgetChars,
|
|
12
|
+
sourceRef: SOURCE_REF,
|
|
13
|
+
isError: false,
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function jsonlStream(count: number, pad = 120): string {
|
|
18
|
+
return Array.from({ length: count }, (_, index) =>
|
|
19
|
+
JSON.stringify({ seq: index, status: 'ok', payload: 'x'.repeat(pad), note: `record ${String(index)}` }))
|
|
20
|
+
.join('\n')
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
describe('JSONL / NDJSON reducer (jsonl-structure-preview)', () => {
|
|
24
|
+
it('samples head + tail records and collapses the middle into an omitted count', () => {
|
|
25
|
+
const output = reduceFreshToolResult(input(jsonlStream(50), 2_000))
|
|
26
|
+
expect(output).not.toBeNull()
|
|
27
|
+
expect(output!.reducer).toBe('jsonl-structure-preview')
|
|
28
|
+
expect(output!.text).toContain(SOURCE_REF)
|
|
29
|
+
expect(output!.text).toContain('"$dsh_omitted_records"')
|
|
30
|
+
expect(output!.text).toContain('"seq": 0')
|
|
31
|
+
expect(output!.text).toContain('"seq": 49')
|
|
32
|
+
expect(output!.text).not.toContain('"seq": 25')
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
it('still fires through the host read gutter (N: prefix) via the content view', () => {
|
|
36
|
+
const gutted = jsonlStream(40)
|
|
37
|
+
.split('\n')
|
|
38
|
+
.map((line, index) => `${String(index + 1)}: ${line}`)
|
|
39
|
+
.join('\n')
|
|
40
|
+
const output = reduceFreshToolResult(input(gutted, 2_000, 'read_file'))
|
|
41
|
+
expect(output).not.toBeNull()
|
|
42
|
+
expect(output!.reducer).toBe('jsonl-structure-preview')
|
|
43
|
+
expect(output!.text).toContain('"seq": 0')
|
|
44
|
+
expect(output!.text).toContain('"seq": 39')
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
it('does not steal a pretty-printed single JSON (regression: json-* branch intact)', () => {
|
|
48
|
+
// Unique-key lines so the adjacent/non-adjacent fold leaves the blob intact
|
|
49
|
+
// and reduceJson actually parses it (repeating structural lines would fold
|
|
50
|
+
// into markers and is a pre-existing, unrelated bail).
|
|
51
|
+
const record: Record<string, string> = { fetched_at: '2026-10-15T15:26:14Z' }
|
|
52
|
+
for (let index = 0; index < 200; index += 1) record[`field_${String(index)}`] = 'v'.repeat(60)
|
|
53
|
+
const pretty = JSON.stringify(record, null, 2)
|
|
54
|
+
const output = reduceFreshToolResult(input(pretty, 2_000))
|
|
55
|
+
expect(output).not.toBeNull()
|
|
56
|
+
expect(output!.reducer).not.toBe('jsonl-structure-preview')
|
|
57
|
+
expect(output!.reducer).toMatch(/^json-/)
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
it('treats a multi-record stream as JSONL but a one-line array as single JSON', () => {
|
|
61
|
+
const many = jsonlStream(20)
|
|
62
|
+
expect(reduceFreshToolResult(input(many, 2_000))?.reducer).toBe('jsonl-structure-preview')
|
|
63
|
+
const oneLine = JSON.stringify(Array.from({ length: 20 }, (_, index) => ({ seq: index, payload: 'x'.repeat(120) })))
|
|
64
|
+
expect(reduceFreshToolResult(input(oneLine, 2_000))?.reducer).not.toBe('jsonl-structure-preview')
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
it('fails open (no jsonl preview) when the sampled envelope cannot fit the budget', () => {
|
|
68
|
+
const wide = jsonlStream(30, 900)
|
|
69
|
+
const output = reduceFreshToolResult(input(wide, 1_200))
|
|
70
|
+
// Must not throw, and must never land a jsonl preview that busts the budget.
|
|
71
|
+
expect(output === null || output.reducer !== 'jsonl-structure-preview' || output.text.length <= 1_200).toBe(true)
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
it('leaves a two-record stream alone (nothing to omit) rather than inflating it', () => {
|
|
75
|
+
const two = `${JSON.stringify({ a: 'x'.repeat(200) })}\n${JSON.stringify({ b: 'y'.repeat(200) })}`
|
|
76
|
+
const output = reduceFreshToolResult(input(two, 1_200))
|
|
77
|
+
expect(output?.reducer ?? 'none').not.toBe('jsonl-structure-preview')
|
|
78
|
+
})
|
|
79
|
+
})
|
|
@@ -417,6 +417,54 @@ describe('standalone runtime on published Harness APIs', () => {
|
|
|
417
417
|
expect(record?.tokensRemoved).toBe((record?.tokensBefore ?? 0) - (record?.tokensAfter ?? 0))
|
|
418
418
|
})
|
|
419
419
|
|
|
420
|
+
it('tokenpilot-inspired default threshold lands a fresh replace end-to-end (no explicit override)', async () => {
|
|
421
|
+
const ctx = await runtimeContext()
|
|
422
|
+
const audit = captureAudit(ctx)
|
|
423
|
+
// No freshTriggerTokens passed → the profile default governs. The lowered
|
|
424
|
+
// default (4096) must reduce a large fresh result through the real cordis
|
|
425
|
+
// path, mirroring what the desktop panel observes at turn tail.
|
|
426
|
+
await ctx.plugin(ToolResultPruner, { profile: 'tokenpilot-inspired' }).await()
|
|
427
|
+
const session = Session.create(SessionId('public-tokenpilot-default-fresh'))
|
|
428
|
+
const fixture = Array.from({ length: 1_200 }, (_, index) =>
|
|
429
|
+
`row ${String(index)} :: ${['alpha', 'bravo', 'charlie', 'delta', 'echo'][index % 5]}-${String((index * 7) % 997)} payload ${String(index)}`).join('\n')
|
|
430
|
+
appendToolTurn(session, 1, fixture, false, undefined, 'deepseek-official')
|
|
431
|
+
|
|
432
|
+
const result = ctx.toolResultPruner.pruneSession(session, {
|
|
433
|
+
stage: 'fresh',
|
|
434
|
+
freshTurn: 1,
|
|
435
|
+
freshStep: 1,
|
|
436
|
+
})
|
|
437
|
+
|
|
438
|
+
expect(result.pruned.length).toBeGreaterThanOrEqual(1)
|
|
439
|
+
const record = rewrites(audit.records()).find(entry => entry.component === 'fresh')
|
|
440
|
+
expect(record).toBeDefined()
|
|
441
|
+
expect(record?.reducer).toEqual(expect.any(String))
|
|
442
|
+
})
|
|
443
|
+
|
|
444
|
+
it('tokenpilot-inspired lands a fresh replace on an UNAVAILABLE-tokenizer route (local Qwen)', async () => {
|
|
445
|
+
const ctx = await runtimeContext()
|
|
446
|
+
const audit = captureAudit(ctx)
|
|
447
|
+
await ctx.plugin(ToolResultPruner, { profile: 'tokenpilot-inspired' }).await()
|
|
448
|
+
const session = Session.create(SessionId('public-tokenpilot-qwen-fresh'))
|
|
449
|
+
// A ~40KB JSONL result — the exact shape the desktop test feeds. local-35 has
|
|
450
|
+
// no bundled tokenizer, so every node count is 'unavailable' and the fresh
|
|
451
|
+
// gate + land must run entirely on the character basis.
|
|
452
|
+
const jsonl = Array.from({ length: 150 }, (_, index) =>
|
|
453
|
+
JSON.stringify({ qid: index, question: `Janet's ducks lay ${index} eggs. How many remain after ${index + 3}?`, answer: `step ${index} ... #### ${index * 2}` })).join('\n')
|
|
454
|
+
appendToolTurn(session, 1, jsonl, false, undefined, 'local-35', 'Qwen3.6-35B-A3B')
|
|
455
|
+
|
|
456
|
+
const result = ctx.toolResultPruner.pruneSession(session, {
|
|
457
|
+
stage: 'fresh',
|
|
458
|
+
freshTurn: 1,
|
|
459
|
+
freshStep: 1,
|
|
460
|
+
})
|
|
461
|
+
|
|
462
|
+
const record = rewrites(audit.records()).find(entry => entry.component === 'fresh')
|
|
463
|
+
// eslint-disable-next-line no-console
|
|
464
|
+
console.log('QWEN_FRESH pruned=', result.pruned.length, 'reducer=', record?.reducer ?? 'none', 'basis=', record?.measurementBasis ?? 'none')
|
|
465
|
+
expect(result.pruned.length).toBeGreaterThanOrEqual(1)
|
|
466
|
+
})
|
|
467
|
+
|
|
420
468
|
it('threads the reducer elided-line count from a fresh plan into the rewrite audit', async () => {
|
|
421
469
|
// The skeleton reducer counts the lines it hid behind elision markers; that
|
|
422
470
|
// count must survive the whole planning middle (plan options → planned
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import type { SessionEvent } from '@deepseek-ai/dsh-session'
|
|
3
|
+
import { projectSavingsCore, type SavingsTextCounter } from '../../src/runtime/savings-projection.ts'
|
|
4
|
+
|
|
5
|
+
/** 假规范化计数器:直接按字符数出精确口径,便于断言。 */
|
|
6
|
+
const counter: SavingsTextCounter = text => Object.freeze({
|
|
7
|
+
kind: 'exact-tokenizer',
|
|
8
|
+
tokens: text.length,
|
|
9
|
+
tokenizerId: 'test',
|
|
10
|
+
tokenizerRevision: 'r1',
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
function toolResult(seq: number, time: number, text: string, surfaceOp?: unknown): SessionEvent {
|
|
14
|
+
return {
|
|
15
|
+
type: 'tool/result',
|
|
16
|
+
seq,
|
|
17
|
+
time,
|
|
18
|
+
...(surfaceOp === undefined ? {} : { surfaceOp }),
|
|
19
|
+
data: { message: { content: [{ type: 'text', text }] } },
|
|
20
|
+
} as unknown as SessionEvent
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function manifest(seq: number, time: number): SessionEvent {
|
|
24
|
+
return { type: 'compaction/prune', seq, time, data: {} } as unknown as SessionEvent
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const replace0 = { op: 'replace', startSeq: 0, endSeq: 0 }
|
|
28
|
+
|
|
29
|
+
describe('savings projection(会话日志投影重建)', () => {
|
|
30
|
+
it('surface 中的替换计为当前生效毛节省;重读原文计负项', () => {
|
|
31
|
+
const original = 'A'.repeat(400)
|
|
32
|
+
const events = [
|
|
33
|
+
toolResult(0, 1, original),
|
|
34
|
+
manifest(1, 2),
|
|
35
|
+
toolResult(2, 3, 'A'.repeat(100), replace0),
|
|
36
|
+
toolResult(3, 4, original), // 全文重读
|
|
37
|
+
]
|
|
38
|
+
const projection = projectSavingsCore({ events, surfaceNodes: [2], counter })
|
|
39
|
+
expect(projection.savings).toHaveLength(1)
|
|
40
|
+
expect(projection.savings[0]).toMatchObject({ tokens: 300, basis: 'exact-tokenizer', replacementSeq: 2 })
|
|
41
|
+
expect(projection.offsets).toHaveLength(1)
|
|
42
|
+
expect(projection.offsets[0]).toMatchObject({ component: 'full-read', tokens: 400, basis: 'exact-tokenizer' })
|
|
43
|
+
expect(projection.offsets[0]?.note).toContain('#0')
|
|
44
|
+
expect(projection.registry).toHaveLength(1)
|
|
45
|
+
expect(projection.registry[0]).toMatchObject({ claimedTokens: 300, sourceSeq: 0 })
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
it('替换离开 surface → 毛节省回落为 0(仪表)', () => {
|
|
49
|
+
const events = [
|
|
50
|
+
toolResult(0, 1, 'A'.repeat(400)),
|
|
51
|
+
toolResult(2, 3, 'A'.repeat(100), replace0),
|
|
52
|
+
]
|
|
53
|
+
const still = projectSavingsCore({ events, surfaceNodes: [2], counter })
|
|
54
|
+
expect(still.savings).toHaveLength(1)
|
|
55
|
+
const gone = projectSavingsCore({ events, surfaceNodes: [0], counter })
|
|
56
|
+
expect(gone.savings).toHaveLength(0)
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
it('每次重读都罚(不再一次性消费)', () => {
|
|
60
|
+
const original = 'B'.repeat(500)
|
|
61
|
+
const events = [
|
|
62
|
+
toolResult(0, 1, original),
|
|
63
|
+
toolResult(2, 3, 'B'.repeat(120), replace0),
|
|
64
|
+
toolResult(3, 4, original),
|
|
65
|
+
toolResult(4, 5, original),
|
|
66
|
+
]
|
|
67
|
+
const projection = projectSavingsCore({ events, surfaceNodes: [2], counter })
|
|
68
|
+
expect(projection.offsets).toHaveLength(2)
|
|
69
|
+
expect(projection.offsets.every(entry => entry.tokens === 500)).toBe(true)
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
it('首次压缩之前的重复读取不算惩罚(必须有"第一次的压缩"才配对)', () => {
|
|
73
|
+
const original = 'C'.repeat(300)
|
|
74
|
+
const events = [
|
|
75
|
+
toolResult(0, 1, original),
|
|
76
|
+
toolResult(1, 2, original), // 压缩前重复:registry 还空,不计
|
|
77
|
+
toolResult(2, 3, 'C'.repeat(80), replace0),
|
|
78
|
+
toolResult(3, 4, original), // 压缩后重读:计
|
|
79
|
+
]
|
|
80
|
+
const projection = projectSavingsCore({ events, surfaceNodes: [2], counter })
|
|
81
|
+
expect(projection.offsets).toHaveLength(1)
|
|
82
|
+
expect(projection.registry).toHaveLength(1)
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
it('空事件流返回空投影', () => {
|
|
86
|
+
const projection = projectSavingsCore({ events: [], surfaceNodes: [1, 2], counter })
|
|
87
|
+
expect(projection).toEqual({ savings: [], offsets: [], registry: [] })
|
|
88
|
+
})
|
|
89
|
+
})
|
|
@@ -26,6 +26,25 @@ describe('savings ledger(诚实口径)', () => {
|
|
|
26
26
|
expect(ledger.snapshot('s1').gross.exact).toBe(8_000)
|
|
27
27
|
})
|
|
28
28
|
|
|
29
|
+
it('仪表口径:替换离开 surface 后毛节省回落;仍在 surface 时保持', () => {
|
|
30
|
+
ledger.recordSaving({
|
|
31
|
+
sessionId: 's1',
|
|
32
|
+
component: 'fresh',
|
|
33
|
+
tokensBefore: 9_000,
|
|
34
|
+
tokensAfter: 1_000,
|
|
35
|
+
basis: 'exact-tokenizer',
|
|
36
|
+
sourceSeq: 5,
|
|
37
|
+
replacementSeq: 100,
|
|
38
|
+
})
|
|
39
|
+
expect(ledger.snapshot('s1').gross.exact).toBe(8_000)
|
|
40
|
+
// 替换仍在 surface → 保持
|
|
41
|
+
ledger.observeActive('s1', new Set([100, 101]))
|
|
42
|
+
expect(ledger.snapshot('s1').gross.exact).toBe(8_000)
|
|
43
|
+
// 替换离开 surface → 回落为 0
|
|
44
|
+
ledger.observeActive('s1', new Set([101]))
|
|
45
|
+
expect(ledger.snapshot('s1').gross.exact).toBe(0)
|
|
46
|
+
})
|
|
47
|
+
|
|
29
48
|
it('**先骨架后全文 = 负节省**:全文重读抵消原声称,净额可为负', () => {
|
|
30
49
|
const original = 'export function readFile() {\n // ...long body...\n}\n'.repeat(200)
|
|
31
50
|
ledger.recordSaving({
|
|
@@ -52,15 +71,15 @@ describe('savings ledger(诚实口径)', () => {
|
|
|
52
71
|
expect(snap.recentOffsets[0]?.note).toContain('#7')
|
|
53
72
|
})
|
|
54
73
|
|
|
55
|
-
it('同一 (session, seq)
|
|
74
|
+
it('同一 (session, seq) 的全文只探测一次;每次重读都记负项(不再一次性消费)', () => {
|
|
56
75
|
const text = 'payload-body\n'.repeat(100)
|
|
57
76
|
ledger.recordSaving({ sessionId: 's1', component: 'history', tokensBefore: 900, tokensAfter: 100, basis: 'characters', sourceSeq: 3, originalText: text })
|
|
58
77
|
const measure = () => ({ tokens: 900, basis: 'characters' as const })
|
|
59
78
|
ledger.noteFullText({ sessionId: 's1', seq: 30, text, measure })
|
|
60
79
|
ledger.noteFullText({ sessionId: 's1', seq: 30, text, measure }) // 同 seq 重放:忽略
|
|
61
80
|
expect(ledger.snapshot('s1').offsets.estimated).toBe(900)
|
|
62
|
-
ledger.noteFullText({ sessionId: 's1', seq: 31, text: text + '\n', measure }) // 新 seq
|
|
63
|
-
expect(ledger.snapshot('s1').offsets.estimated).toBe(
|
|
81
|
+
ledger.noteFullText({ sessionId: 's1', seq: 31, text: text + '\n', measure }) // 新 seq、同哈希:再次记负
|
|
82
|
+
expect(ledger.snapshot('s1').offsets.estimated).toBe(1_800)
|
|
64
83
|
})
|
|
65
84
|
|
|
66
85
|
it('跨会话不串账;retrieve 抵消走估算口径分列', () => {
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { unwrapSettingsEntry } from '../../src/pruner.ts'
|
|
3
|
+
import { parseContextCompressionSettings } from '../../src/runtime/config.ts'
|
|
4
|
+
|
|
5
|
+
// The desktop 0.2.0 host hands back the whole entry config `{ settings: <subtree> }`;
|
|
6
|
+
// the parser only understands the subtree. Regression guard for the fail-open-to-off
|
|
7
|
+
// bug that silently disabled fresh/aggregate on the desktop (0 compression).
|
|
8
|
+
const SUBTREE = {
|
|
9
|
+
profile: 'tokenpilot-inspired',
|
|
10
|
+
custom: {
|
|
11
|
+
version: 3,
|
|
12
|
+
unit: 'tokens',
|
|
13
|
+
fresh: { enabled: true, trigger: 8192, target: 3072 },
|
|
14
|
+
aggregate: { enabled: true, trigger: 32768, target: 12288 },
|
|
15
|
+
history: { enabled: true, trigger: 500000, keepRecentToolCalls: 10, keepRecentTokens: 64000, minReclaim: 96000 },
|
|
16
|
+
prefixPolicy: 'pressure-break',
|
|
17
|
+
tailTrim: { enabled: false, trigger: 700000 },
|
|
18
|
+
},
|
|
19
|
+
autoCompact: { thresholdPercent: 80 },
|
|
20
|
+
codeSkeleton: { enabled: true },
|
|
21
|
+
intentSummary: { enabled: true },
|
|
22
|
+
monitorPanel: { enabled: true },
|
|
23
|
+
presetOptions: { estimatorMode: 'host', estimatorProvider: 'local-35', estimatorModel: 'Qwen3.6-35B-A3B' },
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
describe('unwrapSettingsEntry (0.2.0 host config wrapper)', () => {
|
|
27
|
+
it('descends a single {settings:<obj>} wrapper when the root has no profile', () => {
|
|
28
|
+
expect(unwrapSettingsEntry({ settings: SUBTREE })).toBe(SUBTREE)
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('leaves a bare subtree (root already has profile) untouched', () => {
|
|
32
|
+
expect(unwrapSettingsEntry(SUBTREE)).toBe(SUBTREE)
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
it('leaves non-object and array values untouched', () => {
|
|
36
|
+
expect(unwrapSettingsEntry(undefined)).toBe(undefined)
|
|
37
|
+
expect(unwrapSettingsEntry(null)).toBe(null)
|
|
38
|
+
expect(unwrapSettingsEntry('x')).toBe('x')
|
|
39
|
+
const arr = [1, 2]
|
|
40
|
+
expect(unwrapSettingsEntry(arr)).toBe(arr)
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
it('does NOT descend when `settings` is not an object (keeps exotic rejection intact)', () => {
|
|
44
|
+
const exotic = { settings: 'not-an-object' }
|
|
45
|
+
expect(unwrapSettingsEntry(exotic)).toBe(exotic)
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
it('round-trips the wrapped desktop value where the bare parse would throw', () => {
|
|
49
|
+
// The exact desktop failure: wrapped shape → parse throws "missing its
|
|
50
|
+
// complete shape" → activeSettings fails open to profile:'off'. After the
|
|
51
|
+
// one-level unwrap the same value parses to tokenpilot-inspired (fresh on).
|
|
52
|
+
const wrapped = { settings: SUBTREE }
|
|
53
|
+
expect(() => parseContextCompressionSettings(wrapped)).toThrow(/complete shape|plain/)
|
|
54
|
+
const parsed = parseContextCompressionSettings(unwrapSettingsEntry(wrapped) as never)
|
|
55
|
+
expect(parsed.profile).toBe('tokenpilot-inspired')
|
|
56
|
+
expect(parsed.presetOptions?.estimatorMode).toBe('host')
|
|
57
|
+
})
|
|
58
|
+
})
|
|
@@ -47,8 +47,11 @@ describe('tokenpilot-inspired preset', () => {
|
|
|
47
47
|
expect(policy.freshEnabled).toBe(true)
|
|
48
48
|
expect(policy.aggregateEnabled).toBe(true)
|
|
49
49
|
expect(policy.historyMode).toBe('routine')
|
|
50
|
-
|
|
51
|
-
|
|
50
|
+
// tokenpilot-inspired ships a lower fresh trigger (4096/1536, aligned to the
|
|
51
|
+
// savings tier) so moderate results — and CJK/JSON under a real tokenizer —
|
|
52
|
+
// compress sooner. Intentional divergence from balanced's 8192/3072.
|
|
53
|
+
expect(policy.freshTriggerTokens).toBe(4_096)
|
|
54
|
+
expect(policy.freshTargetTokens).toBe(1_536)
|
|
52
55
|
expect(policy.aggregateTriggerTokens).toBe(32_768)
|
|
53
56
|
expect(policy.aggregateTargetTokens).toBe(12_288)
|
|
54
57
|
expect(policy.historyTriggerTokens).toBe(500_000)
|