dsh-context-compression-improved 0.13.0 → 0.13.2

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-context-compression-improved",
3
- "version": "0.13.0",
3
+ "version": "0.13.2",
4
4
  "publishConfig": {
5
5
  "registry": "https://registry.npmjs.org",
6
6
  "tag": "latest"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "dsh-external/dsh-context-compression-improved",
3
- "version": "0.13.0",
3
+ "version": "0.13.2",
4
4
  "main": "./lib/index.js",
5
5
  "description": "Token-saving, auditable tool-result context-compression selector with code-skeleton gate for DeepSeek Harness — fewer tokens on every turn",
6
6
  "engines": {
@@ -171,7 +171,7 @@ window.__ModuleLoader__.load({
171
171
  * never silently coerced.
172
172
  */
173
173
  function decodeCodeSkeletonSettings(value) {
174
- if (value === void 0) return { enabled: false };
174
+ if (value === void 0) return { enabled: true };
175
175
  if (!isPlainRecord(value)) return void 0;
176
176
  const keys = Object.keys(value);
177
177
  if (keys.length !== 1 || keys[0] !== "enabled") return void 0;
@@ -151,6 +151,12 @@ interface ContextCompressionSettings {
151
151
  sediment?: SedimentSettings;
152
152
  /** Optional tokenpilot-inspired sub-capability overrides (presence-validated only). */
153
153
  presetOptions?: PresetOptionsSettings;
154
+ /**
155
+ * F1 (v0.13.2): Minimum net-gain threshold in tokens for small-knife cuts.
156
+ * A candidate is skipped if (tokensBefore - tokensAfter - cardOverhead) < minNetGain.
157
+ * 0 disables the check. Default 1000.
158
+ */
159
+ minNetGain?: number;
154
160
  }
155
161
  //#endregion
156
162
  export { PresetOptionsSettings as i, ContextCompressionSettings as n, CustomCompressionPolicy as r, CompressionProfile as t };
@@ -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: false };
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: false },
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.0",
3
+ "version": "0.13.2",
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: false }
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
@@ -451,6 +451,12 @@ export interface ContextCompressionSettings {
451
451
  sediment?: SedimentSettings
452
452
  /** Optional tokenpilot-inspired sub-capability overrides (presence-validated only). */
453
453
  presetOptions?: PresetOptionsSettings
454
+ /**
455
+ * F1 (v0.13.2): Minimum net-gain threshold in tokens for small-knife cuts.
456
+ * A candidate is skipped if (tokensBefore - tokensAfter - cardOverhead) < minNetGain.
457
+ * 0 disables the check. Default 1000.
458
+ */
459
+ minNetGain?: number
454
460
  }
455
461
 
456
462
  /**
@@ -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: false }
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: false },
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 }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Injected-source whitelist: identifies host-injected messages that must NOT
3
+ * be treated as real user boundaries when determining turns, spans, or
4
+ * working-set protection.
5
+ *
6
+ * Plan: cci-longterm-refactor v0.13.2 (F13 — live-compact #69 lesson)
7
+ *
8
+ * DSH host injects user/message events with a specific source.kind for
9
+ * time-context, tool-jobs, skill-catalog, etc. These are NOT user turns and
10
+ * must not affect span boundary decisions.
11
+ *
12
+ * @module dsh-context-compression-improved/runtime/injected-kinds
13
+ */
14
+
15
+ /**
16
+ * Source kinds that represent host-injected content, NOT real user messages.
17
+ * Any event whose data.source.kind is in this set is an injection and must
18
+ * be skipped by all boundary/turn detection logic.
19
+ */
20
+ export const INJECTED_SOURCE_KINDS: ReadonlySet<string> = new Set([
21
+ 'time-context',
22
+ 'tool-jobs',
23
+ 'skill-catalog',
24
+ 'dsh-context-compression',
25
+ 'dsh-ops-ptc',
26
+ 'compaction-basic',
27
+ 'dsh-agent-presets',
28
+ ])
29
+
30
+ /**
31
+ * Determine whether an event represents a real user message (not injected).
32
+ *
33
+ * An event is a "real user boundary" if:
34
+ * - type is 'user/message', AND
35
+ * - its source.kind (if present) is NOT in INJECTED_SOURCE_KINDS
36
+ *
37
+ * Events without a source field are treated as real user messages
38
+ * (backward-compatible with older hosts that don't tag sources).
39
+ */
40
+ export function isRealUserBoundary(event: {
41
+ type?: unknown
42
+ data?: { source?: { kind?: unknown } }
43
+ }): boolean {
44
+ if (event.type !== 'user/message') return false
45
+ const kind = event.data?.source?.kind
46
+ if (typeof kind !== 'string') return true // no source = real user (old host compat)
47
+ return !INJECTED_SOURCE_KINDS.has(kind)
48
+ }
49
+
50
+ /**
51
+ * Check if a message event is a plugin injection (non-user boundary).
52
+ * Returns true for injected messages that should be skipped.
53
+ */
54
+ export function isInjectedMessage(event: {
55
+ type?: unknown
56
+ data?: { source?: { kind?: unknown } }
57
+ }): boolean {
58
+ if (event.type !== 'user/message') return false
59
+ const kind = event.data?.source?.kind
60
+ if (typeof kind !== 'string') return false // no source = not injected
61
+ return INJECTED_SOURCE_KINDS.has(kind)
62
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Net-gain threshold check (F1).
3
+ *
4
+ * Plan: cci-longterm-refactor v0.13.2
5
+ *
6
+ * A cut is only worthwhile if the tokens saved (minus the cost of the
7
+ * replacement card/pointer) exceed a configurable minimum. This prevents
8
+ * the "切了个寂寞" degeneration where small outputs are cut into cards
9
+ * that cost almost as much as the original.
10
+ *
11
+ * @module dsh-context-compression-improved/runtime/netgain
12
+ */
13
+
14
+ /** Fixed card overhead estimate: sourceRef + header + retrieve hint ≈ 80 tokens. */
15
+ const CARD_OVERHEAD_TOKENS = 80
16
+
17
+ /**
18
+ * Check whether a candidate cut has sufficient net gain to be published.
19
+ *
20
+ * @param tokensBefore - tokens of the original content
21
+ * @param tokensAfter - tokens of the replacement card/pointer
22
+ * @param minNetGain - minimum required net savings (0 = disabled)
23
+ * @returns true if the cut should proceed, false if it should be skipped
24
+ */
25
+ export function checkNetGain(
26
+ tokensBefore: number,
27
+ tokensAfter: number,
28
+ minNetGain: number,
29
+ ): boolean {
30
+ // Feature disabled
31
+ if (minNetGain <= 0) return true
32
+ const netGain = tokensBefore - tokensAfter - CARD_OVERHEAD_TOKENS
33
+ return netGain >= minNetGain
34
+ }
35
+
36
+ /**
37
+ * Compute the effective net gain of a proposed cut.
38
+ * Useful for logging/audit even when the cut is allowed.
39
+ */
40
+ export function computeNetGain(
41
+ tokensBefore: number,
42
+ tokensAfter: number,
43
+ ): number {
44
+ return tokensBefore - tokensAfter - CARD_OVERHEAD_TOKENS
45
+ }
46
+
47
+ /** The card overhead constant (exported for tests). */
48
+ export { CARD_OVERHEAD_TOKENS }
@@ -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 off', () => {
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: false })
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.12.1 baseline)', () => {
56
- it('decode(undefined) returns enabled=false', () => {
57
- expect(decodeCodeSkeletonSettings(undefined)).toEqual({ enabled: false })
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 NOT default-enabled under any profile', () => {
60
- // In v0.12.1, no profile auto-enables codeSkeleton
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,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
+ })
@@ -0,0 +1,86 @@
1
+ /**
2
+ * F13: Injected-source whitelist filtering tests.
3
+ *
4
+ * @module dsh-context-compression-improved/tests/runtime/injected-kinds
5
+ */
6
+ import { describe, expect, it } from 'vitest'
7
+ import { isInjectedMessage, isRealUserBoundary, INJECTED_SOURCE_KINDS } from '../../src/runtime/injected-kinds.ts'
8
+
9
+ describe('F13: INJECTED_SOURCE_KINDS whitelist', () => {
10
+ it('contains at least 5 known injection kinds', () => {
11
+ expect(INJECTED_SOURCE_KINDS.size).toBeGreaterThanOrEqual(5)
12
+ expect(INJECTED_SOURCE_KINDS.has('time-context')).toBe(true)
13
+ expect(INJECTED_SOURCE_KINDS.has('tool-jobs')).toBe(true)
14
+ expect(INJECTED_SOURCE_KINDS.has('skill-catalog')).toBe(true)
15
+ expect(INJECTED_SOURCE_KINDS.has('dsh-context-compression')).toBe(true)
16
+ expect(INJECTED_SOURCE_KINDS.has('dsh-ops-ptc')).toBe(true)
17
+ })
18
+ })
19
+
20
+ describe('F13: isInjectedMessage', () => {
21
+ it('returns true for injected user/message events', () => {
22
+ expect(isInjectedMessage({ type: 'user/message', data: { source: { kind: 'time-context' } } })).toBe(true)
23
+ expect(isInjectedMessage({ type: 'user/message', data: { source: { kind: 'dsh-ops-ptc' } } })).toBe(true)
24
+ })
25
+
26
+ it('returns false for real user messages (no source)', () => {
27
+ expect(isInjectedMessage({ type: 'user/message', data: {} })).toBe(false)
28
+ })
29
+
30
+ it('returns false for non-user events', () => {
31
+ expect(isInjectedMessage({ type: 'tool/result', data: { source: { kind: 'time-context' } } })).toBe(false)
32
+ expect(isInjectedMessage({ type: 'agent/step' })).toBe(false)
33
+ })
34
+
35
+ it('returns false for user/message with unknown source kind', () => {
36
+ expect(isInjectedMessage({ type: 'user/message', data: { source: { kind: 'something-new' } } })).toBe(false)
37
+ })
38
+ })
39
+
40
+ describe('F13: isRealUserBoundary', () => {
41
+ it('returns true for user/message without source (old host compat)', () => {
42
+ expect(isRealUserBoundary({ type: 'user/message', data: {} })).toBe(true)
43
+ })
44
+
45
+ it('returns true for user/message with non-injected source', () => {
46
+ expect(isRealUserBoundary({ type: 'user/message', data: { source: { kind: 'user-typed' } } })).toBe(true)
47
+ })
48
+
49
+ it('returns false for injected user/message', () => {
50
+ expect(isRealUserBoundary({ type: 'user/message', data: { source: { kind: 'skill-catalog' } } })).toBe(false)
51
+ })
52
+
53
+ it('returns false for non-user events', () => {
54
+ expect(isRealUserBoundary({ type: 'tool/result' })).toBe(false)
55
+ })
56
+ })
57
+
58
+ describe('F13: mixed event stream simulation', () => {
59
+ const events = [
60
+ { type: 'user/message', data: { source: { kind: 'time-context' } } },
61
+ { type: 'user/message', data: {} }, // real user
62
+ { type: 'tool/result', data: {} },
63
+ { type: 'user/message', data: { source: { kind: 'dsh-context-compression' } } },
64
+ { type: 'tool/result', data: {} },
65
+ { type: 'user/message', data: { source: { kind: 'tool-jobs' } } },
66
+ { type: 'user/message', data: {} }, // real user
67
+ { type: 'tool/result', data: {} },
68
+ ]
69
+
70
+ it('correctly identifies 2 real user boundaries out of 8 events', () => {
71
+ const real = events.filter(isRealUserBoundary)
72
+ expect(real).toHaveLength(2)
73
+ })
74
+
75
+ it('correctly identifies 3 injected messages out of 8 events', () => {
76
+ const injected = events.filter(isInjectedMessage)
77
+ expect(injected).toHaveLength(3)
78
+ })
79
+
80
+ it('injected + real = total user/message count (no double-counting)', () => {
81
+ const allUser = events.filter(e => e.type === 'user/message')
82
+ const injected = events.filter(isInjectedMessage)
83
+ const real = events.filter(isRealUserBoundary)
84
+ expect(injected.length + real.length).toBe(allUser.length)
85
+ })
86
+ })
@@ -0,0 +1,61 @@
1
+ /**
2
+ * F1: Net-gain threshold tests.
3
+ *
4
+ * @module dsh-context-compression-improved/tests/runtime/netgain
5
+ */
6
+ import { describe, expect, it } from 'vitest'
7
+ import { checkNetGain, computeNetGain, CARD_OVERHEAD_TOKENS } from '../../src/runtime/netgain.ts'
8
+
9
+ describe('F1: checkNetGain boundary cases', () => {
10
+ it('disabled when minNetGain = 0 (always allows)', () => {
11
+ expect(checkNetGain(100, 90, 0)).toBe(true)
12
+ expect(checkNetGain(200, 190, 0)).toBe(true)
13
+ })
14
+
15
+ it('disabled when minNetGain negative (always allows)', () => {
16
+ expect(checkNetGain(100, 90, -1)).toBe(true)
17
+ })
18
+
19
+ it('skips tiny gain: 500→400 tokens with overhead 80 = gain 20 < 1000', () => {
20
+ expect(checkNetGain(500, 400, 1000)).toBe(false)
21
+ })
22
+
23
+ it('allows good gain: 5000→1000 tokens with overhead 80 = gain 3920 > 1000', () => {
24
+ expect(checkNetGain(5000, 1000, 1000)).toBe(true)
25
+ })
26
+
27
+ it('boundary exact: gain = minNetGain → allows (>=)', () => {
28
+ // 1000 - 0 - 80 = 920 → need exactly 920 threshold
29
+ expect(checkNetGain(1000, 0, 920)).toBe(true)
30
+ expect(checkNetGain(1000, 0, 921)).toBe(false)
31
+ })
32
+
33
+ it('negative gain (card bigger than original) → always skip', () => {
34
+ expect(checkNetGain(100, 200, 1000)).toBe(false)
35
+ expect(checkNetGain(100, 200, 0)).toBe(true) // disabled = allows even bad cuts
36
+ })
37
+
38
+ it('zero tokens before → skip', () => {
39
+ expect(checkNetGain(0, 0, 1000)).toBe(false)
40
+ })
41
+
42
+ it('huge output: 50000→5000, gain = 44920 >> 1000', () => {
43
+ expect(checkNetGain(50000, 5000, 1000)).toBe(true)
44
+ })
45
+ })
46
+
47
+ describe('F1: computeNetGain', () => {
48
+ it('returns tokensBefore - tokensAfter - overhead', () => {
49
+ expect(computeNetGain(5000, 1000)).toBe(5000 - 1000 - CARD_OVERHEAD_TOKENS)
50
+ })
51
+
52
+ it('can be negative when card > original', () => {
53
+ expect(computeNetGain(100, 200)).toBeLessThan(0)
54
+ })
55
+ })
56
+
57
+ describe('F1: CARD_OVERHEAD_TOKENS is reasonable', () => {
58
+ it('overhead is 80 tokens (sourceRef + header + hint)', () => {
59
+ expect(CARD_OVERHEAD_TOKENS).toBe(80)
60
+ })
61
+ })