dsh-context-compression-improved 0.5.2 → 0.5.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.
Files changed (28) hide show
  1. package/.gitattributes +1 -0
  2. package/CHANGELOG.ja.md +144 -119
  3. package/CHANGELOG.ko.md +143 -118
  4. package/CHANGELOG.md +278 -250
  5. package/CHANGELOG.zh.md +131 -109
  6. package/docs/installation.md +103 -103
  7. package/docs/installation.zh.md +100 -100
  8. package/package.json +1 -1
  9. package/packages/selector/cordis.patch.yml +5 -6
  10. package/packages/selector/src/client/EstimatorControls.tsx +277 -277
  11. package/packages/selector/src/client/locales.ts +196 -196
  12. package/packages/selector/src/index.ts +463 -463
  13. package/packages/selector/src/pruner/state.ts +50 -50
  14. package/packages/selector/src/pruner.ts +2402 -2402
  15. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +188 -188
  16. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +149 -149
  17. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -419
  18. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -200
  19. package/packages/selector/tests/advisor-report.host.spec.ts +223 -223
  20. package/packages/selector/tests/public/package-contract.client.spec.ts +20 -0
  21. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -232
  22. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -272
  23. package/packages/selector/tests/runtime/advisor.spec.ts +226 -226
  24. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -30
  25. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -96
  26. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -217
  27. package/packages/selector/tests/settings-seat.client.spec.ts +29 -4
  28. package/scripts/toolclass-corpus-replay.mjs +281 -281
@@ -1,272 +1,272 @@
1
- /**
2
- * Advisor integration and the advisory-only invariant.
3
- *
4
- * The invariant this spec exists to pin (K13): the advisor is statistics and
5
- * suggestions only. Whatever its channel returns — extreme scores, a hostile
6
- * summary, garbage, or nothing at all — `pruneSession` must land exactly the
7
- * same reductions it lands with the advisor off and the state empty.
8
- */
9
- import { describe, expect, it } from 'vitest'
10
- import { Context } from '@deepseek-ai/cordis'
11
- import {
12
- ToolCallId as CallId,
13
- createMessage,
14
- createUserMessage,
15
- createToolResultMessage,
16
- } from '@deepseek-ai/dsh-llm'
17
- import { canonicalHeader, Session, SessionId } from '@deepseek-ai/dsh-session'
18
- import type { SessionEvent } from '@deepseek-ai/dsh-session'
19
- import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
20
- import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
21
- import TokenMeter from '@deepseek-ai/dsh-token-meter'
22
- import ToolRuntime from '@deepseek-ai/dsh-tools'
23
- import SessionStore from '@deepseek-ai/dsh-session'
24
- import ToolResultPruner from '../../src/pruner.ts'
25
- import {
26
- collectTaskSemantics,
27
- runSessionAdvisorPass,
28
- type AdvisorCandidate,
29
- } from '../../src/runtime/tokenpilot/advisor.ts'
30
- import { getAdvisorState, recordScore } from '../../src/runtime/tokenpilot/advisor-state.ts'
31
- import type { AdvisorOutcomeAuditRecord } from '../../src/runtime/audit.ts'
32
- import type { AdvisorChannel } from '../../src/runtime/tokenpilot/advisor.ts'
33
-
34
- // ── Orchestration against a scripted channel ───────────────────────────────
35
-
36
- const CANDIDATES: AdvisorCandidate[] = [
37
- { seq: 3, characterPressure: 4_000, preview: 'auth module login flow' },
38
- { seq: 5, characterPressure: 6_000, preview: 'database migration notes' },
39
- ]
40
-
41
- const TASK = {
42
- source: 'todos' as const,
43
- todoVersion: 'aaaa1111',
44
- taskText: 'migrate the auth module',
45
- }
46
-
47
- function advisorInput(turn: number, signal: AbortSignal): Parameters<typeof runSessionAdvisorPass>[3] {
48
- return {
49
- profile: 'tokenpilot-inspired',
50
- turn,
51
- candidates: CANDIDATES,
52
- task: TASK,
53
- advisor: { refreshTurns: 8, scoreThreshold: 0.35, sampleLimit: 16, minTokens: 250 },
54
- tailText: 'working on the migration',
55
- signal,
56
- }
57
- }
58
-
59
- function scriptedChannel(responses: (string | undefined)[]): { channel: AdvisorChannel, calls: { system: string, user: string }[] } {
60
- const calls: { system: string, user: string }[] = []
61
- return {
62
- calls,
63
- channel: {
64
- identity: () => 'host:mock/model',
65
- ask: async request => {
66
- calls.push({ system: request.system, user: request.user })
67
- return responses.shift()
68
- },
69
- },
70
- }
71
- }
72
-
73
- describe('runSessionAdvisorPass orchestration (K11)', () => {
74
- it('writes summary, scores, recertification marks, and emits three audits on success', async () => {
75
- const session = Session.create(SessionId('advisor-ok'))
76
- const { channel, calls } = scriptedChannel([
77
- '{"overallTask":"migrate the auth module","activeSubtasks":["port login flow"],"keywords":["auth","login"]}',
78
- '{"seq":3,"score":0.95,"reason":"current task"}\n{"seq":5,"score":0.10,"reason":"stale"}',
79
- ])
80
- const audits: AdvisorOutcomeAuditRecord[] = []
81
- const outcome = await runSessionAdvisorPass(session, channel, record => audits.push(record), advisorInput(4, new AbortController().signal))
82
-
83
- expect(calls).toHaveLength(2)
84
- expect(outcome).toBeDefined()
85
- const state = getAdvisorState(session)
86
- expect(state.summary?.overallTask).toBe('migrate the auth module')
87
- expect(state.scores.get(3)?.score).toBe(0.95)
88
- expect(state.scores.get(5)?.score).toBe(0.10)
89
- // Below-threshold segment recertified as a suggestion only.
90
- expect(state.recertified.get(5)).toBe(4)
91
- expect(state.recertified.has(3)).toBe(false)
92
- expect(state.watermarkSeq).toBe(5)
93
- expect(audits.map(record => record.phase)).toEqual(['summary', 'scoring', 'decay'])
94
- expect(audits.every(record => record.ok)).toBe(true)
95
- expect(audits.find(record => record.phase === 'decay')?.decay).toBeDefined()
96
- })
97
-
98
- it('leaves state untouched and audits ok:false when the channel answers nothing', async () => {
99
- const session = Session.create(SessionId('advisor-fail'))
100
- const { channel, calls } = scriptedChannel([undefined, undefined])
101
- const audits: AdvisorOutcomeAuditRecord[] = []
102
- const outcome = await runSessionAdvisorPass(session, channel, record => audits.push(record), advisorInput(2, new AbortController().signal))
103
-
104
- expect(outcome).toBeUndefined()
105
- expect(calls).toHaveLength(1) // summary failed; scoring never ran
106
- const state = getAdvisorState(session)
107
- expect(state.summary).toBeUndefined()
108
- expect(state.scores.size).toBe(0)
109
- expect(audits).toHaveLength(1)
110
- expect(audits[0]?.ok).toBe(false)
111
- expect(audits[0]?.reason).toBe('channel-empty')
112
- expect(state.inFlight).toBe(false)
113
- })
114
-
115
- it('skips entirely while a pass is in flight (re-entry guard)', async () => {
116
- const session = Session.create(SessionId('advisor-reentry'))
117
- const { channel, calls } = scriptedChannel([])
118
- const state = getAdvisorState(session)
119
- state.inFlight = true
120
- const outcome = await runSessionAdvisorPass(session, channel, () => undefined, advisorInput(1, new AbortController().signal))
121
- expect(outcome).toBeUndefined()
122
- expect(calls).toHaveLength(0)
123
- state.inFlight = false
124
- })
125
-
126
- it('does not advance the watermark on failure, so candidates rescore later', async () => {
127
- const session = Session.create(SessionId('advisor-watermark'))
128
- const failing = scriptedChannel([undefined])
129
- await runSessionAdvisorPass(session, failing.channel, () => undefined, advisorInput(1, new AbortController().signal))
130
- expect(getAdvisorState(session).watermarkSeq).toBe(0)
131
-
132
- const succeeding = scriptedChannel([
133
- '{"overallTask":"t","activeSubtasks":[],"keywords":["auth"]}',
134
- '{"seq":3,"score":0.9}',
135
- ])
136
- const audits: AdvisorOutcomeAuditRecord[] = []
137
- const outcome = await runSessionAdvisorPass(session, succeeding.channel, record => audits.push(record), advisorInput(2, new AbortController().signal))
138
- expect(outcome).toBeDefined()
139
- expect(getAdvisorState(session).watermarkSeq).toBe(3)
140
- })
141
-
142
- it('returns undefined without any channel call when the session has no task semantics', async () => {
143
- const session = Session.create(SessionId('advisor-notask'))
144
- const { channel, calls } = scriptedChannel(['{"overallTask":"x","keywords":["k"]}'])
145
- const outcome = await runSessionAdvisorPass(session, channel, () => undefined, {
146
- ...advisorInput(1, new AbortController().signal),
147
- task: undefined,
148
- })
149
- expect(outcome).toBeUndefined()
150
- expect(calls).toHaveLength(0)
151
- })
152
- })
153
-
154
- describe('collectTaskSemantics over real event shapes', () => {
155
- it('reads a todo/write event appended alongside message events', () => {
156
- const events = [
157
- {
158
- type: 'user/message',
159
- seq: 1,
160
- time: 0,
161
- data: { content: [{ type: 'text', text: 'start the migration' }] },
162
- },
163
- {
164
- type: 'todo/write',
165
- seq: 2,
166
- time: 0,
167
- data: { todos: ['migrate the auth module', { content: 'write tests', status: 'pending' }] },
168
- },
169
- ] as unknown as readonly SessionEvent[]
170
- const task = collectTaskSemantics(events)
171
- expect(task?.source).toBe('todos')
172
- expect(task?.taskText).toContain('write tests')
173
- })
174
- })
175
-
176
- // ── K13: the advisory-only invariant, against the real pruner ──────────────
177
-
178
- describe('advisory-only invariant (K13): advisor outputs never change landings', () => {
179
- async function prunedResult(session: Session): Promise<unknown> {
180
- const ctx = new Context()
181
- try {
182
- await ctx.plugin(SessionStore).await()
183
- await ctx.plugin(SystemPrompt).await()
184
- await ctx.plugin(ToolRuntime).await()
185
- await ctx.plugin(SessionProjectionRegistry).await()
186
- await ctx.plugin(TokenMeter).await()
187
- await ctx.plugin(ToolResultPruner, {
188
- profile: 'native',
189
- nativeTriggerTokens: 100,
190
- nativeTargetTokens: 64,
191
- headChars: 8,
192
- tailChars: 8,
193
- }).await()
194
- return ctx.toolResultPruner.pruneSession(session, { stage: 'pressure' })
195
- } finally {
196
- await ctx.fiber.dispose()
197
- }
198
- }
199
-
200
- function buildSession(id: string): Session {
201
- const session = Session.create(SessionId(id))
202
- const callId = CallId('call-1')
203
- session.append('turn/start', { turn: 1 })
204
- session.append('request/header', {
205
- reason: 'initial',
206
- header: canonicalHeader({ config: { provider: 'deepseek', model: 'deepseek-v4-flash' } }),
207
- })
208
- session.append('user/message', createUserMessage({
209
- content: [{ type: 'text', text: 'please inspect the failing module' }],
210
- source: { kind: 'user' },
211
- }), { surfaceOp: 'append' })
212
- session.append('step/start', { turn: 1, step: 1 })
213
- session.append('assistant/message', {
214
- stream: [],
215
- turn: 1,
216
- step: 1,
217
- message: createMessage({
218
- role: 'assistant',
219
- content: [{ type: 'tool-call', id: callId, name: 'bash', arguments: '{}' }],
220
- source: { kind: 'model', provider: 'deepseek', model: 'deepseek-v4-flash' },
221
- }),
222
- }, { surfaceOp: 'append' })
223
- session.append('tool/call', { turn: 1, step: 1, callId, name: 'bash', arguments: '{}' })
224
- session.append('tool/result', {
225
- turn: 1,
226
- step: 1,
227
- message: createToolResultMessage({
228
- callId,
229
- content: [{ type: 'text', text: 'gate evidence '.repeat(800) }],
230
- isError: false,
231
- }),
232
- }, { surfaceOp: 'append' })
233
- session.append('step/end', { turn: 1, step: 1 })
234
- // No turn/end: pruning lands its replacement inside the still-open turn.
235
- return session
236
- }
237
-
238
- it('lands identically with the advisor off, and with extreme scores or a failed pass', async () => {
239
- const scenarios: string[] = ['off', 'extreme-scores', 'failed-pass']
240
- const shapes: unknown[] = []
241
- for (const scenario of scenarios) {
242
- // One shared session id: replacement markers embed it, and the advisor
243
- // state is keyed by Session object identity, so this cannot cross-talk.
244
- const session = buildSession('advisor-invariant')
245
- if (scenario !== 'off') {
246
- const state = getAdvisorState(session)
247
- if (scenario === 'extreme-scores') {
248
- state.summary = {
249
- overallTask: 'ALL MUST BE KEPT',
250
- activeSubtasks: ['keep everything forever'],
251
- keywords: ['evidence'],
252
- todoVersion: 'deadbeef',
253
- turn: 1,
254
- }
255
- // Zero relevance everywhere: the most hostile score a channel could
256
- // return must still not delete, delay, or rewrite anything.
257
- recordScore(state, 2, { score: 0, turn: 1 })
258
- }
259
- if (scenario === 'failed-pass') {
260
- state.failures = { failures: 9, cooldownUntil: Date.now() + 600_000 }
261
- }
262
- }
263
- shapes.push(structuredClone(await prunedResult(session)))
264
- }
265
- for (const shape of shapes.slice(1)) {
266
- expect(shape).toEqual(shapes[0])
267
- }
268
- // And the baseline scenario actually reduced something (the test is real).
269
- const baseline = shapes[0] as { pruned: unknown[] }
270
- expect(baseline.pruned).toHaveLength(1)
271
- })
272
- })
1
+ /**
2
+ * Advisor integration and the advisory-only invariant.
3
+ *
4
+ * The invariant this spec exists to pin (K13): the advisor is statistics and
5
+ * suggestions only. Whatever its channel returns — extreme scores, a hostile
6
+ * summary, garbage, or nothing at all — `pruneSession` must land exactly the
7
+ * same reductions it lands with the advisor off and the state empty.
8
+ */
9
+ import { describe, expect, it } from 'vitest'
10
+ import { Context } from '@deepseek-ai/cordis'
11
+ import {
12
+ ToolCallId as CallId,
13
+ createMessage,
14
+ createUserMessage,
15
+ createToolResultMessage,
16
+ } from '@deepseek-ai/dsh-llm'
17
+ import { canonicalHeader, Session, SessionId } from '@deepseek-ai/dsh-session'
18
+ import type { SessionEvent } from '@deepseek-ai/dsh-session'
19
+ import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
20
+ import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
21
+ import TokenMeter from '@deepseek-ai/dsh-token-meter'
22
+ import ToolRuntime from '@deepseek-ai/dsh-tools'
23
+ import SessionStore from '@deepseek-ai/dsh-session'
24
+ import ToolResultPruner from '../../src/pruner.ts'
25
+ import {
26
+ collectTaskSemantics,
27
+ runSessionAdvisorPass,
28
+ type AdvisorCandidate,
29
+ } from '../../src/runtime/tokenpilot/advisor.ts'
30
+ import { getAdvisorState, recordScore } from '../../src/runtime/tokenpilot/advisor-state.ts'
31
+ import type { AdvisorOutcomeAuditRecord } from '../../src/runtime/audit.ts'
32
+ import type { AdvisorChannel } from '../../src/runtime/tokenpilot/advisor.ts'
33
+
34
+ // ── Orchestration against a scripted channel ───────────────────────────────
35
+
36
+ const CANDIDATES: AdvisorCandidate[] = [
37
+ { seq: 3, characterPressure: 4_000, preview: 'auth module login flow' },
38
+ { seq: 5, characterPressure: 6_000, preview: 'database migration notes' },
39
+ ]
40
+
41
+ const TASK = {
42
+ source: 'todos' as const,
43
+ todoVersion: 'aaaa1111',
44
+ taskText: 'migrate the auth module',
45
+ }
46
+
47
+ function advisorInput(turn: number, signal: AbortSignal): Parameters<typeof runSessionAdvisorPass>[3] {
48
+ return {
49
+ profile: 'tokenpilot-inspired',
50
+ turn,
51
+ candidates: CANDIDATES,
52
+ task: TASK,
53
+ advisor: { refreshTurns: 8, scoreThreshold: 0.35, sampleLimit: 16, minTokens: 250 },
54
+ tailText: 'working on the migration',
55
+ signal,
56
+ }
57
+ }
58
+
59
+ function scriptedChannel(responses: (string | undefined)[]): { channel: AdvisorChannel, calls: { system: string, user: string }[] } {
60
+ const calls: { system: string, user: string }[] = []
61
+ return {
62
+ calls,
63
+ channel: {
64
+ identity: () => 'host:mock/model',
65
+ ask: async request => {
66
+ calls.push({ system: request.system, user: request.user })
67
+ return responses.shift()
68
+ },
69
+ },
70
+ }
71
+ }
72
+
73
+ describe('runSessionAdvisorPass orchestration (K11)', () => {
74
+ it('writes summary, scores, recertification marks, and emits three audits on success', async () => {
75
+ const session = Session.create(SessionId('advisor-ok'))
76
+ const { channel, calls } = scriptedChannel([
77
+ '{"overallTask":"migrate the auth module","activeSubtasks":["port login flow"],"keywords":["auth","login"]}',
78
+ '{"seq":3,"score":0.95,"reason":"current task"}\n{"seq":5,"score":0.10,"reason":"stale"}',
79
+ ])
80
+ const audits: AdvisorOutcomeAuditRecord[] = []
81
+ const outcome = await runSessionAdvisorPass(session, channel, record => audits.push(record), advisorInput(4, new AbortController().signal))
82
+
83
+ expect(calls).toHaveLength(2)
84
+ expect(outcome).toBeDefined()
85
+ const state = getAdvisorState(session)
86
+ expect(state.summary?.overallTask).toBe('migrate the auth module')
87
+ expect(state.scores.get(3)?.score).toBe(0.95)
88
+ expect(state.scores.get(5)?.score).toBe(0.10)
89
+ // Below-threshold segment recertified as a suggestion only.
90
+ expect(state.recertified.get(5)).toBe(4)
91
+ expect(state.recertified.has(3)).toBe(false)
92
+ expect(state.watermarkSeq).toBe(5)
93
+ expect(audits.map(record => record.phase)).toEqual(['summary', 'scoring', 'decay'])
94
+ expect(audits.every(record => record.ok)).toBe(true)
95
+ expect(audits.find(record => record.phase === 'decay')?.decay).toBeDefined()
96
+ })
97
+
98
+ it('leaves state untouched and audits ok:false when the channel answers nothing', async () => {
99
+ const session = Session.create(SessionId('advisor-fail'))
100
+ const { channel, calls } = scriptedChannel([undefined, undefined])
101
+ const audits: AdvisorOutcomeAuditRecord[] = []
102
+ const outcome = await runSessionAdvisorPass(session, channel, record => audits.push(record), advisorInput(2, new AbortController().signal))
103
+
104
+ expect(outcome).toBeUndefined()
105
+ expect(calls).toHaveLength(1) // summary failed; scoring never ran
106
+ const state = getAdvisorState(session)
107
+ expect(state.summary).toBeUndefined()
108
+ expect(state.scores.size).toBe(0)
109
+ expect(audits).toHaveLength(1)
110
+ expect(audits[0]?.ok).toBe(false)
111
+ expect(audits[0]?.reason).toBe('channel-empty')
112
+ expect(state.inFlight).toBe(false)
113
+ })
114
+
115
+ it('skips entirely while a pass is in flight (re-entry guard)', async () => {
116
+ const session = Session.create(SessionId('advisor-reentry'))
117
+ const { channel, calls } = scriptedChannel([])
118
+ const state = getAdvisorState(session)
119
+ state.inFlight = true
120
+ const outcome = await runSessionAdvisorPass(session, channel, () => undefined, advisorInput(1, new AbortController().signal))
121
+ expect(outcome).toBeUndefined()
122
+ expect(calls).toHaveLength(0)
123
+ state.inFlight = false
124
+ })
125
+
126
+ it('does not advance the watermark on failure, so candidates rescore later', async () => {
127
+ const session = Session.create(SessionId('advisor-watermark'))
128
+ const failing = scriptedChannel([undefined])
129
+ await runSessionAdvisorPass(session, failing.channel, () => undefined, advisorInput(1, new AbortController().signal))
130
+ expect(getAdvisorState(session).watermarkSeq).toBe(0)
131
+
132
+ const succeeding = scriptedChannel([
133
+ '{"overallTask":"t","activeSubtasks":[],"keywords":["auth"]}',
134
+ '{"seq":3,"score":0.9}',
135
+ ])
136
+ const audits: AdvisorOutcomeAuditRecord[] = []
137
+ const outcome = await runSessionAdvisorPass(session, succeeding.channel, record => audits.push(record), advisorInput(2, new AbortController().signal))
138
+ expect(outcome).toBeDefined()
139
+ expect(getAdvisorState(session).watermarkSeq).toBe(3)
140
+ })
141
+
142
+ it('returns undefined without any channel call when the session has no task semantics', async () => {
143
+ const session = Session.create(SessionId('advisor-notask'))
144
+ const { channel, calls } = scriptedChannel(['{"overallTask":"x","keywords":["k"]}'])
145
+ const outcome = await runSessionAdvisorPass(session, channel, () => undefined, {
146
+ ...advisorInput(1, new AbortController().signal),
147
+ task: undefined,
148
+ })
149
+ expect(outcome).toBeUndefined()
150
+ expect(calls).toHaveLength(0)
151
+ })
152
+ })
153
+
154
+ describe('collectTaskSemantics over real event shapes', () => {
155
+ it('reads a todo/write event appended alongside message events', () => {
156
+ const events = [
157
+ {
158
+ type: 'user/message',
159
+ seq: 1,
160
+ time: 0,
161
+ data: { content: [{ type: 'text', text: 'start the migration' }] },
162
+ },
163
+ {
164
+ type: 'todo/write',
165
+ seq: 2,
166
+ time: 0,
167
+ data: { todos: ['migrate the auth module', { content: 'write tests', status: 'pending' }] },
168
+ },
169
+ ] as unknown as readonly SessionEvent[]
170
+ const task = collectTaskSemantics(events)
171
+ expect(task?.source).toBe('todos')
172
+ expect(task?.taskText).toContain('write tests')
173
+ })
174
+ })
175
+
176
+ // ── K13: the advisory-only invariant, against the real pruner ──────────────
177
+
178
+ describe('advisory-only invariant (K13): advisor outputs never change landings', () => {
179
+ async function prunedResult(session: Session): Promise<unknown> {
180
+ const ctx = new Context()
181
+ try {
182
+ await ctx.plugin(SessionStore).await()
183
+ await ctx.plugin(SystemPrompt).await()
184
+ await ctx.plugin(ToolRuntime).await()
185
+ await ctx.plugin(SessionProjectionRegistry).await()
186
+ await ctx.plugin(TokenMeter).await()
187
+ await ctx.plugin(ToolResultPruner, {
188
+ profile: 'native',
189
+ nativeTriggerTokens: 100,
190
+ nativeTargetTokens: 64,
191
+ headChars: 8,
192
+ tailChars: 8,
193
+ }).await()
194
+ return ctx.toolResultPruner.pruneSession(session, { stage: 'pressure' })
195
+ } finally {
196
+ await ctx.fiber.dispose()
197
+ }
198
+ }
199
+
200
+ function buildSession(id: string): Session {
201
+ const session = Session.create(SessionId(id))
202
+ const callId = CallId('call-1')
203
+ session.append('turn/start', { turn: 1 })
204
+ session.append('request/header', {
205
+ reason: 'initial',
206
+ header: canonicalHeader({ config: { provider: 'deepseek', model: 'deepseek-v4-flash' } }),
207
+ })
208
+ session.append('user/message', createUserMessage({
209
+ content: [{ type: 'text', text: 'please inspect the failing module' }],
210
+ source: { kind: 'user' },
211
+ }), { surfaceOp: 'append' })
212
+ session.append('step/start', { turn: 1, step: 1 })
213
+ session.append('assistant/message', {
214
+ stream: [],
215
+ turn: 1,
216
+ step: 1,
217
+ message: createMessage({
218
+ role: 'assistant',
219
+ content: [{ type: 'tool-call', id: callId, name: 'bash', arguments: '{}' }],
220
+ source: { kind: 'model', provider: 'deepseek', model: 'deepseek-v4-flash' },
221
+ }),
222
+ }, { surfaceOp: 'append' })
223
+ session.append('tool/call', { turn: 1, step: 1, callId, name: 'bash', arguments: '{}' })
224
+ session.append('tool/result', {
225
+ turn: 1,
226
+ step: 1,
227
+ message: createToolResultMessage({
228
+ callId,
229
+ content: [{ type: 'text', text: 'gate evidence '.repeat(800) }],
230
+ isError: false,
231
+ }),
232
+ }, { surfaceOp: 'append' })
233
+ session.append('step/end', { turn: 1, step: 1 })
234
+ // No turn/end: pruning lands its replacement inside the still-open turn.
235
+ return session
236
+ }
237
+
238
+ it('lands identically with the advisor off, and with extreme scores or a failed pass', async () => {
239
+ const scenarios: string[] = ['off', 'extreme-scores', 'failed-pass']
240
+ const shapes: unknown[] = []
241
+ for (const scenario of scenarios) {
242
+ // One shared session id: replacement markers embed it, and the advisor
243
+ // state is keyed by Session object identity, so this cannot cross-talk.
244
+ const session = buildSession('advisor-invariant')
245
+ if (scenario !== 'off') {
246
+ const state = getAdvisorState(session)
247
+ if (scenario === 'extreme-scores') {
248
+ state.summary = {
249
+ overallTask: 'ALL MUST BE KEPT',
250
+ activeSubtasks: ['keep everything forever'],
251
+ keywords: ['evidence'],
252
+ todoVersion: 'deadbeef',
253
+ turn: 1,
254
+ }
255
+ // Zero relevance everywhere: the most hostile score a channel could
256
+ // return must still not delete, delay, or rewrite anything.
257
+ recordScore(state, 2, { score: 0, turn: 1 })
258
+ }
259
+ if (scenario === 'failed-pass') {
260
+ state.failures = { failures: 9, cooldownUntil: Date.now() + 600_000 }
261
+ }
262
+ }
263
+ shapes.push(structuredClone(await prunedResult(session)))
264
+ }
265
+ for (const shape of shapes.slice(1)) {
266
+ expect(shape).toEqual(shapes[0])
267
+ }
268
+ // And the baseline scenario actually reduced something (the test is real).
269
+ const baseline = shapes[0] as { pruned: unknown[] }
270
+ expect(baseline.pruned).toHaveLength(1)
271
+ })
272
+ })