dsh-context-compression-improved 0.13.1 → 0.13.3
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/package.json +1 -1
- package/packages/selector/dsh.plugin.json +1 -1
- package/packages/selector/lib/client.js +4548 -4567
- package/packages/selector/lib/savings-integral.js +2 -2
- package/packages/selector/package.json +1 -1
- package/packages/selector/src/profiles.ts +1 -1
- package/packages/selector/src/runtime/card-merge.ts +115 -0
- package/packages/selector/src/runtime/config.ts +2 -2
- package/packages/selector/src/runtime/cut-index.ts +119 -0
- package/packages/selector/tests/runtime/auto-compact-config.spec.ts +2 -2
- package/packages/selector/tests/runtime/behavior-lock-profiles.spec.ts +5 -7
- package/packages/selector/tests/runtime/card-merge.spec.ts +81 -0
- package/packages/selector/tests/runtime/cut-index.spec.ts +92 -0
|
@@ -2192,7 +2192,7 @@ function parseAutoCompactSettings(value) {
|
|
|
2192
2192
|
* present-but-invalid section is an explicitly invalid document.
|
|
2193
2193
|
*/
|
|
2194
2194
|
function parseCodeSkeletonSettings(value) {
|
|
2195
|
-
if (value === void 0) return { enabled:
|
|
2195
|
+
if (value === void 0) return { enabled: true };
|
|
2196
2196
|
if (!isPlainRecord(value)) throw new TypeError("Context-compression codeSkeleton must be a plain object");
|
|
2197
2197
|
const keys = Object.keys(value);
|
|
2198
2198
|
if (keys.length !== 1 || keys[0] !== "enabled") throw new TypeError(`Context-compression codeSkeleton: expected exactly "enabled", got "${keys.join("\", \"")}"`);
|
|
@@ -2431,7 +2431,7 @@ const DEFAULT_CONTEXT_COMPRESSION_SETTINGS = {
|
|
|
2431
2431
|
custom: structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY),
|
|
2432
2432
|
ptcCustom: structuredClone(DEFAULT_PTC_COMPRESSION_POLICY),
|
|
2433
2433
|
autoCompact: { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default },
|
|
2434
|
-
codeSkeleton: { enabled:
|
|
2434
|
+
codeSkeleton: { enabled: true },
|
|
2435
2435
|
intentSummary: { enabled: false },
|
|
2436
2436
|
monitorPanel: { enabled: false },
|
|
2437
2437
|
sediment: { ...DEFAULT_SEDIMENT_SETTINGS }
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-context-compression-improved",
|
|
3
|
-
"version": "0.13.
|
|
3
|
+
"version": "0.13.3",
|
|
4
4
|
"description": "Token-saving context-compression selector bundle for DeepSeek Harness — fewer tool-result tokens on every turn, fully auditable",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|
|
@@ -247,7 +247,7 @@ function isSafeSignalPattern(entry: string): boolean {
|
|
|
247
247
|
* never silently coerced.
|
|
248
248
|
*/
|
|
249
249
|
export function decodeCodeSkeletonSettings(value: unknown): CodeSkeletonSettings | undefined {
|
|
250
|
-
if (value === undefined) return { enabled:
|
|
250
|
+
if (value === undefined) return { enabled: true } // F4: default ON since v0.13.2
|
|
251
251
|
if (!isPlainRecord(value)) return undefined
|
|
252
252
|
const keys = Object.keys(value)
|
|
253
253
|
if (keys.length !== 1 || keys[0] !== 'enabled') return undefined
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CardMerge: multi-card consolidation (F3 — 中刀).
|
|
3
|
+
*
|
|
4
|
+
* Plan: cci-longterm-refactor v0.13.4
|
|
5
|
+
*
|
|
6
|
+
* When the surface accumulates too many individual compressed cards (each ~100-300 tokens),
|
|
7
|
+
* CardMerge takes the OLDEST N cards and merges them into a single summary card.
|
|
8
|
+
* This is the "中刀" (medium knife) level between small-knife per-message cuts and
|
|
9
|
+
* big-knife (official/sediment) turn-level compression.
|
|
10
|
+
*
|
|
11
|
+
* Default OFF: the user must explicitly enable it. Panel requires double confirmation.
|
|
12
|
+
*
|
|
13
|
+
* @module dsh-context-compression-improved/runtime/card-merge
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
export interface CardMergeSettings {
|
|
17
|
+
enabled: boolean
|
|
18
|
+
/** Minimum number of cards on surface before triggering (default 8). */
|
|
19
|
+
mergeMaxCards: number
|
|
20
|
+
/** Minimum total card tokens to justify merge (default 4000). */
|
|
21
|
+
mergeMinTokens: number
|
|
22
|
+
/** Break-even ratio: oneTimeRecompute / netGain must be <= this (default 2). */
|
|
23
|
+
mergeBreakEven: number
|
|
24
|
+
/** Cooldown between merges in ms (default 300000 = 5min). */
|
|
25
|
+
mergeCooldownMs: number
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export const DEFAULT_CARD_MERGE_SETTINGS: CardMergeSettings = {
|
|
29
|
+
enabled: false,
|
|
30
|
+
mergeMaxCards: 8,
|
|
31
|
+
mergeMinTokens: 4_000,
|
|
32
|
+
mergeBreakEven: 2,
|
|
33
|
+
mergeCooldownMs: 300_000,
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface CardInfo {
|
|
37
|
+
seq: number
|
|
38
|
+
tokens: number
|
|
39
|
+
/** The source reference(s) this card points to. */
|
|
40
|
+
sourceRefs: string[]
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface MergePlan {
|
|
44
|
+
/** Cards to merge (oldest first). */
|
|
45
|
+
readonly cards: readonly CardInfo[]
|
|
46
|
+
readonly totalTokens: number
|
|
47
|
+
readonly estimatedOutputTokens: number
|
|
48
|
+
readonly netGain: number
|
|
49
|
+
readonly recomputeEstimate: number
|
|
50
|
+
readonly breakEvenOk: boolean
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Decide whether and how to merge cards. Returns null if merge should NOT happen.
|
|
55
|
+
*
|
|
56
|
+
* @param cards - All compressed cards currently on surface, ordered by seq (oldest first)
|
|
57
|
+
* @param settings - The card merge configuration
|
|
58
|
+
* @param tailTokens - Tokens on the surface AFTER the last card (rewrite tail)
|
|
59
|
+
*/
|
|
60
|
+
export function planCardMerge(
|
|
61
|
+
cards: readonly CardInfo[],
|
|
62
|
+
settings: CardMergeSettings,
|
|
63
|
+
tailTokens: number,
|
|
64
|
+
): MergePlan | null {
|
|
65
|
+
if (!settings.enabled) return null
|
|
66
|
+
if (cards.length < settings.mergeMaxCards) return null
|
|
67
|
+
|
|
68
|
+
// Take the oldest N cards (up to chunkMax equivalent) for merging
|
|
69
|
+
const mergeable = cards.slice(0, Math.max(settings.mergeMaxCards, Math.floor(cards.length * 0.6)))
|
|
70
|
+
const totalTokens = mergeable.reduce((sum, c) => sum + c.tokens, 0)
|
|
71
|
+
|
|
72
|
+
if (totalTokens < settings.mergeMinTokens) return null
|
|
73
|
+
|
|
74
|
+
// Estimated output: roughly 15% of input (heuristic for good summary)
|
|
75
|
+
const estimatedOutputTokens = Math.ceil(totalTokens * 0.15) + 200
|
|
76
|
+
const netGain = totalTokens - estimatedOutputTokens
|
|
77
|
+
|
|
78
|
+
if (netGain <= 0) return null
|
|
79
|
+
|
|
80
|
+
// One-time recompute cost: the tail after the merged range must be resent
|
|
81
|
+
const recomputeEstimate = tailTokens
|
|
82
|
+
const breakEvenOk = recomputeEstimate / netGain <= settings.mergeBreakEven
|
|
83
|
+
|
|
84
|
+
if (!breakEvenOk) return null
|
|
85
|
+
|
|
86
|
+
return {
|
|
87
|
+
cards: mergeable,
|
|
88
|
+
totalTokens,
|
|
89
|
+
estimatedOutputTokens,
|
|
90
|
+
netGain,
|
|
91
|
+
recomputeEstimate,
|
|
92
|
+
breakEvenOk: true,
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Validate that decode of settings produces the correct shape.
|
|
98
|
+
*/
|
|
99
|
+
export function decodeCardMergeSettings(value: unknown): CardMergeSettings {
|
|
100
|
+
if (value === undefined || value === null) return { ...DEFAULT_CARD_MERGE_SETTINGS }
|
|
101
|
+
if (typeof value !== 'object' || Array.isArray(value)) return { ...DEFAULT_CARD_MERGE_SETTINGS }
|
|
102
|
+
const obj = value as Record<string, unknown>
|
|
103
|
+
return {
|
|
104
|
+
enabled: typeof obj.enabled === 'boolean' ? obj.enabled : DEFAULT_CARD_MERGE_SETTINGS.enabled,
|
|
105
|
+
mergeMaxCards: clampInt(obj.mergeMaxCards, 2, 50, DEFAULT_CARD_MERGE_SETTINGS.mergeMaxCards),
|
|
106
|
+
mergeMinTokens: clampInt(obj.mergeMinTokens, 500, 50_000, DEFAULT_CARD_MERGE_SETTINGS.mergeMinTokens),
|
|
107
|
+
mergeBreakEven: clampInt(obj.mergeBreakEven, 1, 10, DEFAULT_CARD_MERGE_SETTINGS.mergeBreakEven),
|
|
108
|
+
mergeCooldownMs: clampInt(obj.mergeCooldownMs, 60_000, 3_600_000, DEFAULT_CARD_MERGE_SETTINGS.mergeCooldownMs),
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function clampInt(value: unknown, min: number, max: number, fallback: number): number {
|
|
113
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) return fallback
|
|
114
|
+
return Math.max(min, Math.min(max, Math.round(value)))
|
|
115
|
+
}
|
|
@@ -103,7 +103,7 @@ function parseAutoCompactSettings(value: unknown): AutoCompactSettings {
|
|
|
103
103
|
* present-but-invalid section is an explicitly invalid document.
|
|
104
104
|
*/
|
|
105
105
|
function parseCodeSkeletonSettings(value: unknown): CodeSkeletonSettings {
|
|
106
|
-
if (value === undefined) return { enabled:
|
|
106
|
+
if (value === undefined) return { enabled: true } // F4: default ON since v0.13.2
|
|
107
107
|
if (!isPlainRecord(value)) {
|
|
108
108
|
throw new TypeError('Context-compression codeSkeleton must be a plain object')
|
|
109
109
|
}
|
|
@@ -383,7 +383,7 @@ export const DEFAULT_CONTEXT_COMPRESSION_SETTINGS: ContextCompressionSettings =
|
|
|
383
383
|
custom: structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY),
|
|
384
384
|
ptcCustom: structuredClone(DEFAULT_PTC_COMPRESSION_POLICY),
|
|
385
385
|
autoCompact: { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default },
|
|
386
|
-
codeSkeleton: { enabled:
|
|
386
|
+
codeSkeleton: { enabled: true }, // F4: default ON since v0.13.2
|
|
387
387
|
intentSummary: { enabled: false },
|
|
388
388
|
monitorPanel: { enabled: false },
|
|
389
389
|
sediment: { ...DEFAULT_SEDIMENT_SETTINGS },
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-cut audit index (F2).
|
|
3
|
+
*
|
|
4
|
+
* Plan: cci-longterm-refactor v0.13.3
|
|
5
|
+
*
|
|
6
|
+
* Appends one JSON line per published cut to ~/.dsh/storages/dsh-context-compression/cuts-<sessionId>.jsonl.
|
|
7
|
+
* Provides O(1) audit history without storing original content — only metadata.
|
|
8
|
+
*
|
|
9
|
+
* Fire-and-forget: write failure warns but never blocks the cut.
|
|
10
|
+
*
|
|
11
|
+
* @module dsh-context-compression-improved/runtime/cut-index
|
|
12
|
+
*/
|
|
13
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs'
|
|
14
|
+
import { join } from 'node:path'
|
|
15
|
+
|
|
16
|
+
/** Strategy classification for the panel's four-knife badges. */
|
|
17
|
+
export type CutStrategy = 'small-knife' | 'big-knife' | 'card-merge' | 'skeleton'
|
|
18
|
+
|
|
19
|
+
export interface CutEntry {
|
|
20
|
+
/** ISO timestamp of the cut landing. */
|
|
21
|
+
readonly ts: string
|
|
22
|
+
/** Session identifier. */
|
|
23
|
+
readonly sessionId: string
|
|
24
|
+
/** Which knife made this cut. */
|
|
25
|
+
readonly strategy: CutStrategy
|
|
26
|
+
/** Component within the strategy (fresh/aggregate/history/sediment/etc). */
|
|
27
|
+
readonly component: string
|
|
28
|
+
/** Event seqs shadowed by this cut. */
|
|
29
|
+
readonly eventSeqs: readonly number[]
|
|
30
|
+
/** Token count before the cut. */
|
|
31
|
+
readonly tokensBefore: number
|
|
32
|
+
/** Token count after the cut (card + overhead). */
|
|
33
|
+
readonly tokensAfter: number
|
|
34
|
+
/** Net gain: tokensBefore - tokensAfter - cardOverhead. */
|
|
35
|
+
readonly netGain: number
|
|
36
|
+
/** Estimated tail-rewrite tokens (cache recompute). */
|
|
37
|
+
readonly cacheRecomputeEst: number
|
|
38
|
+
/** Reference to the source events for retrieval. */
|
|
39
|
+
readonly cardRef: string
|
|
40
|
+
/** Active profile at cut time. */
|
|
41
|
+
readonly profile: string
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const MAX_LINES_PER_SESSION = 2000
|
|
45
|
+
|
|
46
|
+
/** Storage directory resolver (lazy, creates if missing). */
|
|
47
|
+
function getStagingDir(): string {
|
|
48
|
+
const dshHome = process.env.DSH_HOME ?? join(process.env.USERPROFILE || process.env.HOME || '', '.dsh')
|
|
49
|
+
return join(dshHome, 'storages', 'dsh-context-compression')
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function cutsFilePath(sessionId: string): string {
|
|
53
|
+
return join(getStagingDir(), `cuts-${sessionId}.jsonl`)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Append one cut entry to the session's index file.
|
|
58
|
+
* Fire-and-forget: catches all errors, warns, never throws.
|
|
59
|
+
*/
|
|
60
|
+
export function appendCut(entry: CutEntry): void {
|
|
61
|
+
try {
|
|
62
|
+
const dir = getStagingDir()
|
|
63
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
|
|
64
|
+
const filePath = cutsFilePath(entry.sessionId)
|
|
65
|
+
const line = JSON.stringify(entry) + '\n'
|
|
66
|
+
appendFileSync(filePath, line, { encoding: 'utf8', flag: 'a' })
|
|
67
|
+
// Truncation check: if file exceeds limit, keep newest half
|
|
68
|
+
enforceLimit(filePath)
|
|
69
|
+
} catch (err) {
|
|
70
|
+
// Never block a cut for index failure
|
|
71
|
+
console.warn('[cci-cut-index] write failed, skipping:', err instanceof Error ? err.message : String(err))
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Read cut entries for a session (most recent first, up to limit).
|
|
77
|
+
*/
|
|
78
|
+
export function readCuts(sessionId: string, opts?: { limit?: number; strategy?: CutStrategy }): CutEntry[] {
|
|
79
|
+
const filePath = cutsFilePath(sessionId)
|
|
80
|
+
if (!existsSync(filePath)) return []
|
|
81
|
+
try {
|
|
82
|
+
const lines = readFileSync(filePath, 'utf8').split('\n').filter(Boolean)
|
|
83
|
+
let entries: CutEntry[] = []
|
|
84
|
+
for (const line of lines) {
|
|
85
|
+
try { entries.push(JSON.parse(line) as CutEntry) } catch { /* skip malformed */ }
|
|
86
|
+
}
|
|
87
|
+
// Most recent first
|
|
88
|
+
entries.reverse()
|
|
89
|
+
// Filter by strategy
|
|
90
|
+
if (opts?.strategy !== undefined) {
|
|
91
|
+
entries = entries.filter(e => e.strategy === opts.strategy)
|
|
92
|
+
}
|
|
93
|
+
// Apply limit
|
|
94
|
+
if (opts?.limit !== undefined && opts.limit > 0) {
|
|
95
|
+
entries = entries.slice(0, opts.limit)
|
|
96
|
+
}
|
|
97
|
+
return entries
|
|
98
|
+
} catch {
|
|
99
|
+
return []
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Enforce the per-session line limit by truncating oldest half. */
|
|
104
|
+
function enforceLimit(filePath: string): void {
|
|
105
|
+
try {
|
|
106
|
+
const content = readFileSync(filePath, 'utf8')
|
|
107
|
+
const lines = content.split('\n').filter(Boolean)
|
|
108
|
+
if (lines.length <= MAX_LINES_PER_SESSION) return
|
|
109
|
+
// Keep newest half
|
|
110
|
+
const kept = lines.slice(Math.floor(lines.length / 2))
|
|
111
|
+
const { writeFileSync } = require('node:fs')
|
|
112
|
+
writeFileSync(filePath, kept.join('\n') + '\n', 'utf8')
|
|
113
|
+
} catch {
|
|
114
|
+
// Truncation failure is non-fatal
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Export the limit for testing. */
|
|
119
|
+
export { MAX_LINES_PER_SESSION }
|
|
@@ -478,9 +478,9 @@ describe('Auto Compact History linkage formula', () => {
|
|
|
478
478
|
})
|
|
479
479
|
|
|
480
480
|
describe('codeSkeleton settings validation', () => {
|
|
481
|
-
it('defaults legacy settings without a codeSkeleton section to
|
|
481
|
+
it('defaults legacy settings without a codeSkeleton section to on (F4 v0.13.2)', () => {
|
|
482
482
|
const settings = parseContextCompressionSettings(structuredClone(BASE_SETTINGS))
|
|
483
|
-
expect(settings.codeSkeleton).toEqual({ enabled:
|
|
483
|
+
expect(settings.codeSkeleton).toEqual({ enabled: true })
|
|
484
484
|
})
|
|
485
485
|
|
|
486
486
|
it('accepts an explicit boolean enabled flag on either side', () => {
|
|
@@ -52,14 +52,12 @@ describe('behavior-lock: AUTO_COMPACT defaults (v0.12.1 baseline)', () => {
|
|
|
52
52
|
})
|
|
53
53
|
})
|
|
54
54
|
|
|
55
|
-
describe('behavior-lock: codeSkeleton default (v0.
|
|
56
|
-
it('decode(undefined) returns enabled=
|
|
57
|
-
expect(decodeCodeSkeletonSettings(undefined)).toEqual({ enabled:
|
|
55
|
+
describe('behavior-lock: codeSkeleton default (BREAKING CHANGE v0.13.2: OFF→ON)', () => {
|
|
56
|
+
it('decode(undefined) returns enabled=true (F4转正)', () => {
|
|
57
|
+
expect(decodeCodeSkeletonSettings(undefined)).toEqual({ enabled: true })
|
|
58
58
|
})
|
|
59
|
-
it('codeSkeleton is
|
|
60
|
-
|
|
61
|
-
// v0.13.3 will change this for savings/adaptive — this test will need updating
|
|
62
|
-
expect(decodeCodeSkeletonSettings(undefined)!.enabled).toBe(false)
|
|
59
|
+
it('codeSkeleton is now default-enabled globally', () => {
|
|
60
|
+
expect(decodeCodeSkeletonSettings(undefined)!.enabled).toBe(true)
|
|
63
61
|
})
|
|
64
62
|
})
|
|
65
63
|
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* F3: CardMerge tests.
|
|
3
|
+
* @module dsh-context-compression-improved/tests/runtime/card-merge
|
|
4
|
+
*/
|
|
5
|
+
import { describe, expect, it } from 'vitest'
|
|
6
|
+
import {
|
|
7
|
+
planCardMerge,
|
|
8
|
+
decodeCardMergeSettings,
|
|
9
|
+
DEFAULT_CARD_MERGE_SETTINGS,
|
|
10
|
+
type CardInfo,
|
|
11
|
+
type CardMergeSettings,
|
|
12
|
+
} from '../../src/runtime/card-merge.ts'
|
|
13
|
+
|
|
14
|
+
function makeCards(count: number, tokensEach = 500): CardInfo[] {
|
|
15
|
+
return Array.from({ length: count }, (_, i) => ({
|
|
16
|
+
seq: i + 1,
|
|
17
|
+
tokens: tokensEach,
|
|
18
|
+
sourceRefs: [`session://test/event/${i + 1}`],
|
|
19
|
+
}))
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const ENABLED: CardMergeSettings = { ...DEFAULT_CARD_MERGE_SETTINGS, enabled: true }
|
|
23
|
+
|
|
24
|
+
describe('F3: planCardMerge decision logic', () => {
|
|
25
|
+
it('returns null when disabled', () => {
|
|
26
|
+
expect(planCardMerge(makeCards(20), DEFAULT_CARD_MERGE_SETTINGS, 5000)).toBeNull()
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
it('returns null when card count < mergeMaxCards', () => {
|
|
30
|
+
expect(planCardMerge(makeCards(5), ENABLED, 5000)).toBeNull()
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
it('returns null when total tokens < mergeMinTokens', () => {
|
|
34
|
+
// 8 cards × 400 tokens = 3200 < 4000
|
|
35
|
+
expect(planCardMerge(makeCards(8, 400), ENABLED, 5000)).toBeNull()
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
it('returns plan when conditions met (8 cards × 600 tokens = 4800 > 4000)', () => {
|
|
39
|
+
const plan = planCardMerge(makeCards(8, 600), ENABLED, 2000)
|
|
40
|
+
expect(plan).not.toBeNull()
|
|
41
|
+
expect(plan!.netGain).toBeGreaterThan(0)
|
|
42
|
+
expect(plan!.breakEvenOk).toBe(true)
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
it('rejects when breakEven fails (tail too large relative to gain)', () => {
|
|
46
|
+
// 8 × 600 = 4800 total, output ~920, netGain ~3880
|
|
47
|
+
// recompute 10000 → ratio = 10000/3880 ≈ 2.58 > mergeBreakEven(2) → reject
|
|
48
|
+
const plan = planCardMerge(makeCards(8, 600), ENABLED, 10_000)
|
|
49
|
+
expect(plan).toBeNull()
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
it('cooldown is a settings concern (tested at integration level)', () => {
|
|
53
|
+
// planCardMerge itself has no temporal state — cooldown lives in orchestrator
|
|
54
|
+
expect(ENABLED.mergeCooldownMs).toBe(300_000)
|
|
55
|
+
})
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
describe('F3: decodeCardMergeSettings', () => {
|
|
59
|
+
it('undefined returns defaults with enabled=false', () => {
|
|
60
|
+
const settings = decodeCardMergeSettings(undefined)
|
|
61
|
+
expect(settings.enabled).toBe(false)
|
|
62
|
+
expect(settings.mergeMaxCards).toBe(8)
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
it('explicit enabled=true is preserved', () => {
|
|
66
|
+
const settings = decodeCardMergeSettings({ enabled: true, mergeMaxCards: 10 })
|
|
67
|
+
expect(settings.enabled).toBe(true)
|
|
68
|
+
expect(settings.mergeMaxCards).toBe(10)
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
it('out-of-range values are clamped', () => {
|
|
72
|
+
const settings = decodeCardMergeSettings({ enabled: true, mergeMaxCards: 100, mergeBreakEven: 0 })
|
|
73
|
+
expect(settings.mergeMaxCards).toBe(50) // clamped to max
|
|
74
|
+
expect(settings.mergeBreakEven).toBe(1) // clamped to min
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
it('non-object input returns defaults', () => {
|
|
78
|
+
expect(decodeCardMergeSettings('invalid')).toEqual(DEFAULT_CARD_MERGE_SETTINGS)
|
|
79
|
+
expect(decodeCardMergeSettings(42)).toEqual(DEFAULT_CARD_MERGE_SETTINGS)
|
|
80
|
+
})
|
|
81
|
+
})
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* F2: Per-cut index tests.
|
|
3
|
+
*
|
|
4
|
+
* @module dsh-context-compression-improved/tests/runtime/cut-index
|
|
5
|
+
*/
|
|
6
|
+
import { mkdtemp, rm } from 'node:fs/promises'
|
|
7
|
+
import { tmpdir } from 'node:os'
|
|
8
|
+
import { join } from 'node:path'
|
|
9
|
+
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
|
10
|
+
import { appendCut, readCuts, MAX_LINES_PER_SESSION, type CutEntry } from '../../src/runtime/cut-index.ts'
|
|
11
|
+
|
|
12
|
+
let testDir: string
|
|
13
|
+
const SESSION_ID = 'test-session-cut-index'
|
|
14
|
+
|
|
15
|
+
function makeEntry(overrides: Partial<CutEntry> = {}): CutEntry {
|
|
16
|
+
return {
|
|
17
|
+
ts: new Date().toISOString(),
|
|
18
|
+
sessionId: SESSION_ID,
|
|
19
|
+
strategy: 'small-knife',
|
|
20
|
+
component: 'fresh',
|
|
21
|
+
eventSeqs: [42],
|
|
22
|
+
tokensBefore: 5000,
|
|
23
|
+
tokensAfter: 1200,
|
|
24
|
+
netGain: 3720,
|
|
25
|
+
cacheRecomputeEst: 500,
|
|
26
|
+
cardRef: 'session://test/event/42',
|
|
27
|
+
profile: 'balanced',
|
|
28
|
+
...overrides,
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
beforeAll(async () => {
|
|
33
|
+
testDir = await mkdtemp(join(tmpdir(), 'cci-cut-test-'))
|
|
34
|
+
// Point DSH_HOME to our test directory
|
|
35
|
+
process.env.DSH_HOME = testDir
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
afterAll(async () => {
|
|
39
|
+
delete process.env.DSH_HOME
|
|
40
|
+
await rm(testDir, { recursive: true, force: true })
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
describe('F2: appendCut + readCuts roundtrip', () => {
|
|
44
|
+
it('appends one entry and reads it back', () => {
|
|
45
|
+
const entry = makeEntry()
|
|
46
|
+
appendCut(entry)
|
|
47
|
+
const result = readCuts(SESSION_ID, { limit: 10 })
|
|
48
|
+
expect(result.length).toBeGreaterThanOrEqual(1)
|
|
49
|
+
expect(result[0]!.sessionId).toBe(SESSION_ID)
|
|
50
|
+
expect(result[0]!.strategy).toBe('small-knife')
|
|
51
|
+
expect(result[0]!.netGain).toBe(3720)
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
it('reads most recent first (reverse order)', () => {
|
|
55
|
+
appendCut(makeEntry({ netGain: 100 }))
|
|
56
|
+
appendCut(makeEntry({ netGain: 999 }))
|
|
57
|
+
const result = readCuts(SESSION_ID, { limit: 2 })
|
|
58
|
+
expect(result[0]!.netGain).toBe(999) // newest first
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
it('filters by strategy', () => {
|
|
62
|
+
appendCut(makeEntry({ strategy: 'big-knife', netGain: 5000 }))
|
|
63
|
+
const big = readCuts(SESSION_ID, { strategy: 'big-knife', limit: 10 })
|
|
64
|
+
expect(big.every(e => e.strategy === 'big-knife')).toBe(true)
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
it('limit caps returned entries', () => {
|
|
68
|
+
for (let i = 0; i < 5; i++) appendCut(makeEntry({ netGain: i }))
|
|
69
|
+
const limited = readCuts(SESSION_ID, { limit: 3 })
|
|
70
|
+
expect(limited).toHaveLength(3)
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
it('readCuts on nonexistent session returns empty', () => {
|
|
74
|
+
const result = readCuts('nonexistent-session-xyz')
|
|
75
|
+
expect(result).toHaveLength(0)
|
|
76
|
+
})
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
describe('F2: fire-and-forget safety', () => {
|
|
80
|
+
it('appendCut does not throw on bad entry (catches internally)', () => {
|
|
81
|
+
// Should not throw even with weird data
|
|
82
|
+
expect(() => {
|
|
83
|
+
appendCut(makeEntry({ eventSeqs: [] as unknown as number[] }))
|
|
84
|
+
}).not.toThrow()
|
|
85
|
+
})
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
describe('F2: MAX_LINES_PER_SESSION', () => {
|
|
89
|
+
it('is 2000', () => {
|
|
90
|
+
expect(MAX_LINES_PER_SESSION).toBe(2000)
|
|
91
|
+
})
|
|
92
|
+
})
|