Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import {
3 applyCompactionEvent,
4 clearCompactionRegistry,
5 compactionEventsForHook,
6 createCompactionRegistryState,
7} from '../src/store/compaction-registry'
8import type { CompactionLifecycleInput } from '../src/store/compaction-registry'
9
10function input(
11 overrides: Partial<CompactionLifecycleInput> & { timestamp?: number },
12): CompactionLifecycleInput {
13 return {
14 timestamp: 1,
15 messagesBefore: 8,
16 messagesAfter: 3,
17 reusedCheckpoint: false,
18 ...overrides,
19 }
20}
21
22describe('compaction registry', () => {
23 it('accumulates started, state, and ended events', () => {
24 const state = createCompactionRegistryState()
25 applyCompactionEvent(
26 state,
27 'started',
28 input({
29 before: 400,
30 messagesBefore: 8,
31 timestamp: 10,
32 hookId: 'hook-1',
33 }),
34 )
35 applyCompactionEvent(
36 state,
37 'state',
38 input({
39 before: 400,
40 after: 180,
41 hookId: 'hook-1',
42 timestamp: 11,
43 strategyKey: 'evict-oldest:half:maxTokens=400',
44 maxTokens: 400,
45 dropped: [{ role: 'user', tokens: 40, text: 'old' }],
46 result: [{ role: 'user', tokens: 10, text: 'omitted' }],
47 }),
48 )
49 applyCompactionEvent(
50 state,
51 'ended',
52 input({
53 after: 180,
54 messagesAfter: 3,
55 durationMs: 12,
56 hookId: 'hook-1',
57 timestamp: 12,
58 }),
59 )
60 expect(state.events.map((event) => event.kind)).toEqual([
61 'started',
62 'state',
63 'ended',
64 ])
65 expect(state.events[1]).toMatchObject({
66 kind: 'state',
67 before: 400,
68 after: 180,
69 strategyKey: 'evict-oldest:half:maxTokens=400',
70 })
71 expect(state.events[1]?.dropped?.[0]?.text).toBe('old')
72 expect(state.events[2]?.durationMs).toBe(12)
73 })
74
75 it('filters events for a hook and falls back to all', () => {
76 const state = createCompactionRegistryState()
77 applyCompactionEvent(
78 state,
79 'state',
80 input({ before: 1, after: 1, hookId: 'a', timestamp: 1 }),
81 )
82 applyCompactionEvent(
83 state,
84 'state',
85 input({ before: 2, after: 1, hookId: 'b', timestamp: 2 }),
86 )
87 expect(
88 compactionEventsForHook(state, { id: 'b' }).map((event) => event.hookId),
89 ).toEqual(['b'])
90 expect(
91 compactionEventsForHook(state, { id: 'missing' }).map(
92 (event) => event.hookId,
93 ),
94 ).toEqual(['a', 'b'])
95 })
96
97 it('clears the registry', () => {
98 const state = createCompactionRegistryState()
99 applyCompactionEvent(state, 'started', input({ before: 1 }))
100 clearCompactionRegistry(state)
101 expect(state.events).toEqual([])
102 })
103})