dsh-context-compression-improved 0.4.0 → 0.5.0

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.
Files changed (31) hide show
  1. package/CHANGELOG.ja.md +19 -0
  2. package/CHANGELOG.ko.md +19 -0
  3. package/CHANGELOG.md +21 -0
  4. package/CHANGELOG.zh.md +17 -0
  5. package/docs/installation.md +25 -1
  6. package/docs/installation.zh.md +24 -1
  7. package/package.json +1 -1
  8. package/packages/selector/lib/{review-registry.js → advisor-state.js} +105 -4
  9. package/packages/selector/lib/client.d.ts +7 -0
  10. package/packages/selector/lib/client.js +32 -2
  11. package/packages/selector/lib/index.d.ts +7 -0
  12. package/packages/selector/lib/index.js +101 -2
  13. package/packages/selector/lib/pruner.d.ts +82 -0
  14. package/packages/selector/lib/pruner.js +545 -11
  15. package/packages/selector/src/client/preset-options.ts +2 -0
  16. package/packages/selector/src/index.ts +108 -0
  17. package/packages/selector/src/profiles.ts +48 -0
  18. package/packages/selector/src/pruner/state.ts +3 -0
  19. package/packages/selector/src/pruner.ts +113 -0
  20. package/packages/selector/src/runtime/audit.ts +22 -0
  21. package/packages/selector/src/runtime/config.ts +58 -0
  22. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +188 -0
  23. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +133 -0
  24. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -0
  25. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +24 -9
  26. package/packages/selector/src/runtime/types.ts +21 -0
  27. package/packages/selector/tests/advisor-report.host.spec.ts +223 -0
  28. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -0
  29. package/packages/selector/tests/runtime/advisor.spec.ts +226 -0
  30. package/packages/selector/tests/runtime/audit.spec.ts +44 -0
  31. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +12 -0
@@ -0,0 +1,226 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import type { SessionEvent } from '@deepseek-ai/dsh-session'
3
+ import {
4
+ collectTaskSemantics,
5
+ prefixDecay,
6
+ selectScoringCandidates,
7
+ type AdvisorCandidate,
8
+ } from '../../src/runtime/tokenpilot/advisor.ts'
9
+ import {
10
+ ADVISOR_RECERTIFIED_LIMIT,
11
+ ADVISOR_SCORES_LIMIT,
12
+ getAdvisorState,
13
+ invalidateOnTaskChange,
14
+ recordRecertified,
15
+ recordScore,
16
+ } from '../../src/runtime/tokenpilot/advisor-state.ts'
17
+ import {
18
+ buildAdvisorScoringUserPrompt,
19
+ parseAdvisorScores,
20
+ parseAdvisorSummary,
21
+ } from '../../src/runtime/tokenpilot/advisor-prompt.ts'
22
+
23
+ function todoWriteEvent(data: unknown): SessionEvent {
24
+ return { type: 'todo/write', seq: 1, time: 0, data } as unknown as SessionEvent
25
+ }
26
+
27
+ function userMessageEvent(text: string): SessionEvent {
28
+ return {
29
+ type: 'user/message',
30
+ seq: 2,
31
+ time: 0,
32
+ data: { content: [{ type: 'text', text }] },
33
+ } as unknown as SessionEvent
34
+ }
35
+
36
+ describe('collectTaskSemantics (K5)', () => {
37
+ it('parses a structured todo/write payload', () => {
38
+ const semantics = collectTaskSemantics([
39
+ todoWriteEvent({ todos: [{ content: 'migrate gates', status: 'in_progress' }, 'write tests'] }),
40
+ ])
41
+ expect(semantics).toBeDefined()
42
+ expect(semantics?.source).toBe('todos')
43
+ expect(semantics?.taskText).toContain('migrate gates')
44
+ expect(semantics?.taskText).toContain('write tests')
45
+ // Same content ⇒ same version token (deterministic).
46
+ const again = collectTaskSemantics([todoWriteEvent({ todos: [{ content: 'migrate gates', status: 'in_progress' }, 'write tests'] })])
47
+ expect(again?.todoVersion).toBe(semantics?.todoVersion)
48
+ })
49
+
50
+ it('degrades a malformed todo payload to its raw JSON string', () => {
51
+ const semantics = collectTaskSemantics([todoWriteEvent({ todos: 'not-an-array' })])
52
+ expect(semantics).toBeDefined()
53
+ expect(semantics?.source).toBe('raw-todo')
54
+ expect(semantics?.taskText).toContain('not-an-array')
55
+ })
56
+
57
+ it('falls back to recent user/message text when no todo/write exists', () => {
58
+ const semantics = collectTaskSemantics([
59
+ userMessageEvent('earlier request'),
60
+ userMessageEvent('please refactor the pruner gates'),
61
+ ])
62
+ expect(semantics).toBeDefined()
63
+ expect(semantics?.source).toBe('messages')
64
+ expect(semantics?.taskText).toContain('refactor the pruner gates')
65
+ })
66
+
67
+ it('picks the most recent todo/write event', () => {
68
+ const semantics = collectTaskSemantics([
69
+ todoWriteEvent({ todos: ['old task'] }),
70
+ userMessageEvent('something else'),
71
+ todoWriteEvent({ todos: ['new task'] }),
72
+ ])
73
+ expect(semantics?.taskText).toBe('new task')
74
+ })
75
+
76
+ it('returns undefined for an empty log', () => {
77
+ expect(collectTaskSemantics([])).toBeUndefined()
78
+ })
79
+ })
80
+
81
+ describe('prefixDecay (K6)', () => {
82
+ const candidates: AdvisorCandidate[] = [
83
+ { seq: 1, characterPressure: 3_000, preview: 'a' },
84
+ { seq: 2, characterPressure: 1_000, preview: 'b' },
85
+ ]
86
+ // prefixDecay takes the weight face only; previews are scoring-prompt inputs.
87
+ const weights = candidates.map(({ seq, characterPressure }) => ({ seq, characterPressure }))
88
+
89
+ it('is deterministic and weights by character pressure', () => {
90
+ const scores = new Map([[1, { score: 0 }], [2, { score: 1 }]])
91
+ const first = prefixDecay(weights, scores)
92
+ const second = prefixDecay(weights, scores)
93
+ expect(first).toEqual(second)
94
+ // weight 3000×0 + 1000×1 over 4000 ⇒ relevance 0.25 ⇒ decay 0.75.
95
+ expect(first.decay).toBeCloseTo(0.75, 12)
96
+ expect(first.weightedChars).toBe(4_000)
97
+ })
98
+
99
+ it('counts unscored candidates as neutral 0.5', () => {
100
+ const decay = prefixDecay(weights, new Map())
101
+ expect(decay.decay).toBeCloseTo(0.5, 12)
102
+ })
103
+
104
+ it('is 0 with no candidates and ignores zero-pressure candidates', () => {
105
+ expect(prefixDecay([], new Map()).decay).toBe(0)
106
+ expect(prefixDecay([{ seq: 9, characterPressure: 0 }], new Map()).decay).toBe(0)
107
+ })
108
+ })
109
+
110
+ describe('selectScoringCandidates', () => {
111
+ const candidates: AdvisorCandidate[] = [
112
+ { seq: 1, characterPressure: 8_000, preview: 'auth module login handling' },
113
+ { seq: 2, characterPressure: 2_000, preview: 'tiny fragment' },
114
+ { seq: 3, characterPressure: 9_000, preview: 'login auth token refresh' },
115
+ { seq: 4, characterPressure: 12_000, preview: 'unrelated weather report' },
116
+ ]
117
+
118
+ it('applies the watermark, the character floor, and the sample limit', () => {
119
+ const state = { watermarkSeq: 1 }
120
+ const picked = selectScoringCandidates(candidates, state, {
121
+ taskKeywords: new Set(['login', 'auth', 'token']),
122
+ minChars: 4_000,
123
+ sampleLimit: 1,
124
+ taskChanged: false,
125
+ })
126
+ // seq 2 below floor, seq 1 at/below watermark; overlap ranks seq 3 first.
127
+ expect(picked.map(item => item.seq)).toEqual([3])
128
+ })
129
+
130
+ it('ignores the watermark when the task semantics changed', () => {
131
+ const picked = selectScoringCandidates(candidates, { watermarkSeq: 4 }, {
132
+ taskKeywords: new Set(['login']),
133
+ minChars: 4_000,
134
+ sampleLimit: 16,
135
+ taskChanged: true,
136
+ })
137
+ // Overlap ties (seq 1 and 3 both match "login") break by character pressure.
138
+ expect(picked.map(item => item.seq)).toEqual([3, 1, 4])
139
+ })
140
+ })
141
+
142
+ describe('advisor-state bounds (K8)', () => {
143
+ it('evicts the oldest score beyond the LRU limit', () => {
144
+ const session = {} as Parameters<typeof getAdvisorState>[0]
145
+ const state = getAdvisorState(session)
146
+ for (let seq = 0; seq < ADVISOR_SCORES_LIMIT + 10; seq += 1) {
147
+ recordScore(state, seq, { score: 0.5, turn: seq })
148
+ }
149
+ expect(state.scores.size).toBe(ADVISOR_SCORES_LIMIT)
150
+ expect(state.scores.has(0)).toBe(false)
151
+ expect(state.scores.has(ADVISOR_SCORES_LIMIT + 9)).toBe(true)
152
+ // Re-touching a seq moves it to the newest position.
153
+ recordScore(state, 10, { score: 0.9, turn: 999 })
154
+ recordScore(state, ADVISOR_SCORES_LIMIT + 10, { score: 0.1, turn: 1_000 })
155
+ expect(state.scores.has(10)).toBe(true)
156
+ expect(state.scores.size).toBe(ADVISOR_SCORES_LIMIT)
157
+ })
158
+
159
+ it('bounds recertified marks the same way', () => {
160
+ const session = {} as Parameters<typeof getAdvisorState>[0]
161
+ const state = getAdvisorState(session)
162
+ for (let seq = 0; seq < ADVISOR_RECERTIFIED_LIMIT + 5; seq += 1) {
163
+ recordRecertified(state, seq, seq)
164
+ }
165
+ expect(state.recertified.size).toBe(ADVISOR_RECERTIFIED_LIMIT)
166
+ expect(state.recertified.has(0)).toBe(false)
167
+ })
168
+
169
+ it('invalidates the summary when the task version changes', () => {
170
+ const session = {} as Parameters<typeof getAdvisorState>[0]
171
+ const state = getAdvisorState(session)
172
+ state.summary = { overallTask: 'x', activeSubtasks: [], keywords: [], todoVersion: 'aaa', turn: 1 }
173
+ state.lastSummaryTurn = 1
174
+ expect(invalidateOnTaskChange(state, 'bbb')).toBe(true)
175
+ expect(state.summary).toBeUndefined()
176
+ expect(state.lastSummaryTurn).toBe(-1)
177
+ expect(invalidateOnTaskChange(state, 'bbb')).toBe(false)
178
+ })
179
+ })
180
+
181
+ describe('advisor prompts (K7)', () => {
182
+ it('parses a well-formed summary answer', () => {
183
+ const parsed = parseAdvisorSummary(
184
+ 'Sure! {"overallTask":"migrate gates","activeSubtasks":["port fresh gate"],"keywords":["gates","pruner"]}',
185
+ )
186
+ expect(parsed?.overallTask).toBe('migrate gates')
187
+ expect(parsed?.keywords).toEqual(['gates', 'pruner'])
188
+ })
189
+
190
+ it('fails open on a malformed summary answer', () => {
191
+ expect(parseAdvisorSummary(undefined)).toBeUndefined()
192
+ expect(parseAdvisorSummary('')).toBeUndefined()
193
+ expect(parseAdvisorSummary('not json at all')).toBeUndefined()
194
+ expect(parseAdvisorSummary('{"overallTask":""}')).toBeUndefined()
195
+ expect(parseAdvisorSummary('{"overallTask":"x"}')).toBeUndefined()
196
+ })
197
+
198
+ it('parses JSON-lines scoring answers and drops invalid rows', () => {
199
+ const parsed = parseAdvisorScores(
200
+ '{"seq":1,"score":0.9,"reason":"current task"}\n'
201
+ + 'noise line {"seq":2,"score":1.5}\n'
202
+ + '{"seq":99,"score":0.5}\n'
203
+ + '{"seq":3,"score":0.1}\n',
204
+ new Set([1, 2, 3]),
205
+ )
206
+ expect(parsed?.size).toBe(2)
207
+ expect(parsed?.get(1)?.score).toBe(0.9)
208
+ expect(parsed?.get(3)?.score).toBe(0.1)
209
+ expect(parsed?.has(2)).toBe(false)
210
+ expect(parsed?.has(99)).toBe(false)
211
+ })
212
+
213
+ it('fails open on empty or all-garbage scoring answers', () => {
214
+ expect(parseAdvisorScores(undefined, new Set([1]))).toBeUndefined()
215
+ expect(parseAdvisorScores('', new Set([1]))).toBeUndefined()
216
+ expect(parseAdvisorScores('garbage only', new Set([1]))).toBeUndefined()
217
+ })
218
+
219
+ it('builds a scoring prompt that keeps previews one-per-line', () => {
220
+ const prompt = buildAdvisorScoringUserPrompt('task text', ['sub'], [
221
+ { seq: 7, preview: 'some\npreview' },
222
+ ])
223
+ expect(prompt).toContain('task: task text')
224
+ expect(prompt).toContain('seq=7 | some preview')
225
+ })
226
+ })
@@ -213,4 +213,48 @@ describe('context-compression audit records', () => {
213
213
  ) as CompressionAuditRecord
214
214
  expect(parsed).toEqual(record)
215
215
  })
216
+
217
+ it('keeps advisor-outcome records free of prompts, keys, and content', () => {
218
+ const record: CompressionAuditRecord = {
219
+ schemaVersion: 1,
220
+ kind: 'advisor-outcome',
221
+ sessionId: 'advisor-session',
222
+ phase: 'decay',
223
+ ok: true,
224
+ sampledCount: 16,
225
+ decay: 0.42,
226
+ weightedChars: 57_688,
227
+ turnIndex: 12,
228
+ latencyMs: 0,
229
+ }
230
+
231
+ const line = formatCompressionAudit(record)
232
+ const parsed = JSON.parse(line.slice(COMPRESSION_AUDIT_PREFIX.length)) as CompressionAuditRecord
233
+ expect(parsed).toEqual(record)
234
+ // Only enums and numbers: never the todo snapshot, assistant text, prompts, or keys.
235
+ expect(line).not.toContain('prompt')
236
+ expect(line).not.toContain('"content"')
237
+ expect(line).not.toContain('"text"')
238
+ expect(line).not.toContain('apiKey')
239
+ expect(line).not.toContain('todo')
240
+ })
241
+
242
+ it('carries failure reason codes and the LLM channel on advisor-outcome records', () => {
243
+ const record: CompressionAuditRecord = {
244
+ schemaVersion: 1,
245
+ kind: 'advisor-outcome',
246
+ sessionId: 'advisor-session',
247
+ phase: 'scoring',
248
+ channel: 'direct',
249
+ ok: false,
250
+ sampledCount: 0,
251
+ turnIndex: 3,
252
+ reason: 'no-direct-endpoint',
253
+ latencyMs: 4,
254
+ }
255
+ const parsed = JSON.parse(
256
+ formatCompressionAudit(record).slice(COMPRESSION_AUDIT_PREFIX.length),
257
+ ) as CompressionAuditRecord
258
+ expect(parsed).toEqual(record)
259
+ })
216
260
  })
@@ -66,6 +66,18 @@ describe('tokenpilot-inspired preset', () => {
66
66
  reviewTimeoutTurns: 6,
67
67
  cacheHitDiscountAlpha: 0.1,
68
68
  reviewHighImpactTokens: 4000,
69
+ // Advisory advisor ships off with its documented defaults. The
70
+ // resolved matrix intentionally gains this group so it follows the
71
+ // estimator's resolved-consumption pattern; see
72
+ // .agents/plans/ctx-relevance-advisor/spec.md decision record.
73
+ advisor: {
74
+ mode: '',
75
+ timeoutMs: 8000,
76
+ refreshTurns: 8,
77
+ scoreThreshold: 0.35,
78
+ sampleLimit: 16,
79
+ minTokens: 250,
80
+ },
69
81
  })
70
82
  // Other profiles never carry the capability matrix.
71
83
  expect(resolvePolicy(config, 'balanced').presetOptions).toBeUndefined()