dsh-context-compression-improved 0.2.3 → 0.2.4

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 (52) hide show
  1. package/.github/workflows/ci.yml +39 -39
  2. package/CHANGELOG.md +137 -135
  3. package/README.md +112 -112
  4. package/package.json +142 -142
  5. package/packages/selector/README.md +31 -31
  6. package/packages/selector/README.zh.md +31 -31
  7. package/packages/selector/dsh.plugin.json +16 -16
  8. package/packages/selector/lib/client.d.ts +228 -228
  9. package/packages/selector/lib/client.js +1462 -1462
  10. package/packages/selector/lib/config.js +856 -842
  11. package/packages/selector/lib/index.d.ts +37 -37
  12. package/packages/selector/lib/index.js +693 -645
  13. package/packages/selector/lib/invariant.js +70 -70
  14. package/packages/selector/lib/pruner.d.ts +728 -683
  15. package/packages/selector/lib/pruner.js +4765 -3807
  16. package/packages/selector/lib/style.css +46 -46
  17. package/packages/selector/lib/tail-trim.js +136 -136
  18. package/packages/selector/package.json +9 -1
  19. package/packages/selector/src/client/index.ts +111 -111
  20. package/packages/selector/src/preset-overlay.ts +60 -1
  21. package/packages/selector/src/pruner/content.ts +18 -5
  22. package/packages/selector/src/pruner/types.ts +23 -5
  23. package/packages/selector/src/pruner.ts +164 -154
  24. package/packages/selector/src/runtime/adaptive-cost.ts +23 -12
  25. package/packages/selector/src/runtime/audit.ts +18 -2
  26. package/packages/selector/src/runtime/config.ts +30 -1
  27. package/packages/selector/src/runtime/measurement.ts +31 -2
  28. package/packages/selector/src/runtime/reducers.ts +1115 -97
  29. package/packages/selector/src/runtime/tokenpilot/dedup.ts +1 -1
  30. package/packages/selector/src/runtime/tokenpilot/locator.ts +1 -1
  31. package/packages/selector/src/runtime/tokenpilot/read-state.ts +23 -2
  32. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +275 -0
  33. package/packages/selector/src/runtime/toolclass.ts +103 -0
  34. package/packages/selector/src/runtime/types.ts +16 -0
  35. package/packages/selector/tests/preset-overlay.host.spec.ts +256 -243
  36. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +7 -7
  37. package/packages/selector/tests/runtime/audit.spec.ts +44 -1
  38. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -0
  39. package/packages/selector/tests/runtime/code-skeleton.spec.ts +14 -3
  40. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -0
  41. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -0
  42. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -0
  43. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -0
  44. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +198 -27
  45. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -0
  46. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -0
  47. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -0
  48. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -0
  49. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +24 -0
  50. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -0
  51. package/packages/selector/tests/standing-generation.host.spec.ts +642 -631
  52. package/scripts/toolclass-corpus-replay.mjs +273 -0
@@ -44,6 +44,7 @@ import ToolResultPruner, {
44
44
  resolvePolicy,
45
45
  } from '../../../src/pruner.ts'
46
46
  import type { CustomCompressionPolicy } from '../../../src/pruner.ts'
47
+ import { CHARS_PER_TOKEN } from '../../../src/runtime/config.ts'
47
48
  import { DEEPSEEK_V4_TOKENIZER_ARTIFACT, deepSeekV4TokenizerForModel } from '../../../src/deepseek-v4-tokenizer.ts'
48
49
  import {
49
50
  DEEPSEEK_VISION_DEFAULT_IMAGE_TOKENS,
@@ -163,6 +164,7 @@ function appendToolTurn(
163
164
  userText?: string,
164
165
  provider = 'deepseek',
165
166
  model: string = MODEL,
167
+ toolName = 'bash',
166
168
  ): { readonly assistantSeq: number; readonly resultSeq: number } {
167
169
  const callId = CallId(`call-${String(turn)}`)
168
170
  session.append('turn/start', { turn })
@@ -184,11 +186,11 @@ function appendToolTurn(
184
186
  step: 1,
185
187
  message: createMessage({
186
188
  role: 'assistant',
187
- content: [{ type: 'tool-call', id: callId, name: 'bash', arguments: '{}' }],
189
+ content: [{ type: 'tool-call', id: callId, name: toolName, arguments: '{}' }],
188
190
  source: { kind: 'model', provider, model },
189
191
  }),
190
192
  }, { surfaceOp: 'append' })
191
- session.append('tool/call', { turn, step: 1, callId, name: 'bash', arguments: '{}' })
193
+ session.append('tool/call', { turn, step: 1, callId, name: toolName, arguments: '{}' })
192
194
  const result = session.append('tool/result', {
193
195
  turn,
194
196
  step: 1,
@@ -406,6 +408,58 @@ describe('standalone runtime on published Harness APIs', () => {
406
408
  expect(record?.tokensRemoved).toBe((record?.tokensBefore ?? 0) - (record?.tokensAfter ?? 0))
407
409
  })
408
410
 
411
+ it('threads the reducer elided-line count from a fresh plan into the rewrite audit', async () => {
412
+ // The skeleton reducer counts the lines it hid behind elision markers; that
413
+ // count must survive the whole planning middle (plan options → planned
414
+ // replacement → audit record) without ever touching the replacement text.
415
+ const ctx = await runtimeContext()
416
+ await ctx.plugin(TestSettings).await()
417
+ await ctx.plugin(SelectorHost).await()
418
+ await ctx.settings.update(settingsNamespace(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE), {
419
+ profile: 'balanced',
420
+ codeSkeleton: { enabled: true },
421
+ })
422
+ const audit = captureAudit(ctx)
423
+ await ctx.plugin(ToolResultPruner, {
424
+ profile: 'balanced',
425
+ freshTriggerTokens: 1_000,
426
+ freshTargetTokens: 800,
427
+ aggregateTriggerTokens: 500_000,
428
+ aggregateTargetTokens: 450_000,
429
+ historyTriggerTokens: 500_000,
430
+ }).await()
431
+ const session = Session.create(SessionId('public-fresh-elided-lines'))
432
+ const fixture = [
433
+ "import { readFile } from 'node:fs/promises'",
434
+ '',
435
+ ...Array.from({ length: 40 }, (_, index) => [
436
+ `export function handler${String(index)}(input: string): string {`,
437
+ ` const normalized = input.trim().toLowerCase()`,
438
+ ` if (normalized.length === 0) return 'empty-${String(index)}'`,
439
+ ` return normalized.split('-').join('+')`,
440
+ '}',
441
+ '',
442
+ ]).flat(),
443
+ ].join('\n')
444
+ appendToolTurn(session, 1, fixture, false, undefined, 'deepseek-official', MODEL, 'read')
445
+
446
+ const result = ctx.toolResultPruner.pruneSession(session, {
447
+ stage: 'fresh',
448
+ freshTurn: 1,
449
+ freshStep: 1,
450
+ })
451
+
452
+ expect(result.pruned).toHaveLength(1)
453
+ expect(result.pruned[0]?.reducer).toBe('hypa-code-skeleton')
454
+ const record = rewrites(audit.records()).find(entry => entry.component === 'fresh')
455
+ expect(record?.reducer).toBe('hypa-code-skeleton')
456
+ expect(record?.elidedLines).toEqual(expect.any(Number))
457
+ expect(record?.elidedLines).toBeGreaterThan(0)
458
+ expect(Number.isInteger(record?.elidedLines)).toBe(true)
459
+ expect(record?.tokensBefore).toBeGreaterThan(1_000)
460
+ expect(record?.tokensAfter).toBeLessThanOrEqual(800)
461
+ })
462
+
409
463
  it('proves isolated Aggregate while Fresh and History remain below their gates', async () => {
410
464
  const ctx = await runtimeContext()
411
465
  const audit = captureAudit(ctx)
@@ -450,13 +504,16 @@ describe('standalone runtime on published Harness APIs', () => {
450
504
  )
451
505
  session.append('turn/start', { turn: 2 })
452
506
  const view = measureForCompaction(ctx, session)
507
+ // Decision gates run on the character basis, so the thresholds below are
508
+ // derived from per-result character pressure and expressed in the
509
+ // token-named settings keys via CHARS_PER_TOKEN.
453
510
  const counts = batch.resultSeqs.map((seq) => {
454
- const entry = view.measuredNodes.find(node => node.seq === seq)?.count
455
- if (entry?.kind !== 'exact-tokenizer') throw new Error('working-set test needs exact result counts')
456
- return entry.tokens
511
+ const entry = view.measuredNodes.find(node => node.seq === seq)
512
+ if (entry === undefined) throw new Error('working-set test needs measured results')
513
+ return entry.characterPressure
457
514
  })
458
- const recentTailTokens = counts.slice(-3).reduce((sum, tokens) => sum + tokens, 0) - 1
459
- const totalToolTokens = counts.reduce((sum, tokens) => sum + tokens, 0)
515
+ const recentTailChars = counts.slice(-3).reduce((sum, chars) => sum + chars, 0) - 1
516
+ const totalToolChars = counts.reduce((sum, chars) => sum + chars, 0)
460
517
 
461
518
  await ctx.plugin(ToolResultPruner, {
462
519
  profile: 'balanced',
@@ -464,12 +521,15 @@ describe('standalone runtime on published Harness APIs', () => {
464
521
  freshTargetTokens: 90_000,
465
522
  aggregateTriggerTokens: 100_000,
466
523
  aggregateTargetTokens: 90_000,
467
- // The strict required-reclaim gate demands one batch pull tool tokens
524
+ // The strict required-reclaim gate demands one batch pull tool chars
468
525
  // back below the trigger; 72% leaves exactly the two oldest results as
469
526
  // the reclaimable margin above the placeholder residue.
470
- historyTriggerTokens: Math.floor(totalToolTokens * 0.72),
527
+ historyTriggerTokens: Math.floor(totalToolChars * 0.72 / CHARS_PER_TOKEN),
471
528
  historyKeepRecentToolCalls: 2,
472
- historyKeepRecentTokens: recentTailTokens,
529
+ // 4 x floor(recentTailChars / 4) sits above the two-newest char total
530
+ // and at or below the three-newest total, so the tail protects exactly
531
+ // the three newest results.
532
+ historyKeepRecentTokens: Math.floor(recentTailChars / CHARS_PER_TOKEN),
473
533
  historyMinReclaimTokens: 1,
474
534
  }).await()
475
535
 
@@ -1314,7 +1374,7 @@ describe('standalone runtime on published Harness APIs', () => {
1314
1374
  }))
1315
1375
  })
1316
1376
 
1317
- it('preserves exact-tokenizer-unavailable before Adaptive cost authority', async () => {
1377
+ it('audits adaptive-cost-rejected on the character basis when the authority lacks request telemetry', async () => {
1318
1378
  const ctx = await runtimeContext()
1319
1379
  const audit = captureAudit(ctx)
1320
1380
  await ctx.plugin(ToolResultPruner, {
@@ -1325,7 +1385,9 @@ describe('standalone runtime on published Harness APIs', () => {
1325
1385
  aggregateTargetTokens: 90_000,
1326
1386
  historyTriggerTokens: 100,
1327
1387
  historyKeepRecentToolCalls: 0,
1328
- historyKeepRecentTokens: 1,
1388
+ // A zero tail budget keeps nothing in the char-basis protection loop
1389
+ // (0 < 0 is false), so the batch can actually form.
1390
+ historyKeepRecentTokens: 0,
1329
1391
  historyMinReclaimTokens: 1,
1330
1392
  }).await()
1331
1393
  const session = Session.create(SessionId('public-history-adaptive-exact-unavailable'))
@@ -1340,18 +1402,21 @@ describe('standalone runtime on published Harness APIs', () => {
1340
1402
  )
1341
1403
  session.append('turn/start', { turn: 2 })
1342
1404
  ctx.toolResultPruner.pruneSession(session, { stage: 'pressure' })
1405
+ // Planning now succeeds on the character basis; the batch is refused by
1406
+ // the adaptive cost authority (no adjacent request telemetry), not by a
1407
+ // missing exact count.
1343
1408
  expect(audit.records()).toContainEqual(expect.objectContaining({
1344
1409
  kind: 'component-evaluation',
1345
1410
  sessionId: String(session.id),
1346
1411
  component: 'history',
1347
1412
  status: 'skipped',
1348
- reason: 'exact-tokenizer-unavailable',
1413
+ reason: 'adaptive-cost-rejected',
1349
1414
  historyMode: 'adaptive',
1350
- measurementKind: 'unavailable',
1415
+ measurementKind: 'characters',
1351
1416
  }))
1352
1417
  })
1353
1418
 
1354
- it('audits exact-tokenizer-unavailable for History when counts are not exact', async () => {
1419
+ it('plans and lands History on the character basis when counts are not exact', async () => {
1355
1420
  const ctx = await runtimeContext()
1356
1421
  const audit = captureAudit(ctx)
1357
1422
  await ctx.plugin(ToolResultPruner, {
@@ -1362,21 +1427,28 @@ describe('standalone runtime on published Harness APIs', () => {
1362
1427
  aggregateTargetTokens: 90_000,
1363
1428
  historyTriggerTokens: 100,
1364
1429
  historyKeepRecentToolCalls: 0,
1365
- historyKeepRecentTokens: 1,
1430
+ historyKeepRecentTokens: 0,
1366
1431
  historyMinReclaimTokens: 1,
1367
1432
  }).await()
1368
1433
  const session = Session.create(SessionId('public-history-exact-unavailable'))
1369
1434
  appendToolTurn(session, 1, 'unknown model history evidence '.repeat(300), true, undefined, 'deepseek', 'unsupported-public-model')
1370
1435
  session.append('turn/start', { turn: 2 })
1371
1436
  ctx.toolResultPruner.pruneSession(session, { stage: 'pressure' })
1437
+ // A committed batch forms from character pressure alone and lands, because
1438
+ // this pruner registers its own recovery tool. The sibling case below drops
1439
+ // the tool registry to exercise the recovery-tool-unavailable path.
1372
1440
  expect(audit.records()).toContainEqual(expect.objectContaining({
1373
- kind: 'component-evaluation',
1441
+ kind: 'rewrite',
1374
1442
  sessionId: String(session.id),
1375
1443
  component: 'history',
1376
- status: 'skipped',
1377
- reason: 'exact-tokenizer-unavailable',
1378
- measurementKind: 'unavailable',
1444
+ reducer: 'historical-tool-result-aging',
1445
+ measurementBasis: 'characters',
1446
+ tokenizerId: 'characters',
1447
+ tokenizerRevision: 'chars-per-token-4.0',
1379
1448
  }))
1449
+ // The character basis never claims an exact tokenizer it does not have.
1450
+ expect(audit.records().some(record =>
1451
+ record.kind === 'rewrite' && record.measurementBasis === 'exact-tokenizer')).toBe(false)
1380
1452
  })
1381
1453
 
1382
1454
  it('audits recovery-tool-unavailable when a committed batch cannot land without the recovery tool', async () => {
@@ -1747,14 +1819,15 @@ describe('standalone runtime on published Harness APIs', () => {
1747
1819
  expect(replayRecovered).toEqual(recovered)
1748
1820
  })
1749
1821
 
1750
- it('audits TailTrim threshold, tokenizer, safety-group, and min-reclaim skip paths', async () => {
1822
+ it('audits TailTrim threshold, safety-group, and min-reclaim skip paths and lands on the character basis for an unknown model', async () => {
1751
1823
  async function runScenario(options: {
1752
1824
  readonly id: string
1753
- readonly expectedReason: string
1825
+ readonly expectedReason?: string
1754
1826
  readonly trigger: number
1755
1827
  readonly minReclaim: number
1756
1828
  readonly candidateTurns: number
1757
1829
  readonly model?: string
1830
+ readonly expectLanding?: boolean
1758
1831
  }): Promise<void> {
1759
1832
  const ctx = new Context()
1760
1833
  activeContexts.push(ctx)
@@ -1796,7 +1869,17 @@ describe('standalone runtime on published Harness APIs', () => {
1796
1869
 
1797
1870
  ctx.toolResultPruner.pruneSession(session, { stage: 'pressure' })
1798
1871
 
1799
- expect(rewrites(audit.records()).filter(record => record.component === 'tail-trim')).toHaveLength(0)
1872
+ const tailTrimRewrites = rewrites(audit.records()).filter(record => record.component === 'tail-trim')
1873
+ if (options.expectLanding === true) {
1874
+ // An unknown model id no longer skips: the group lands and the record
1875
+ // must honestly report the character basis.
1876
+ expect(tailTrimRewrites).toHaveLength(1)
1877
+ expect(tailTrimRewrites[0]?.measurementBasis).toBe('characters')
1878
+ expect(tailTrimRewrites[0]?.tokenizerId).toBe('characters')
1879
+ expect(tailTrimRewrites[0]?.tokenizerRevision).toBe('chars-per-token-4.0')
1880
+ return
1881
+ }
1882
+ expect(tailTrimRewrites).toHaveLength(0)
1800
1883
  expect(audit.records()).toContainEqual(expect.objectContaining({
1801
1884
  kind: 'component-evaluation',
1802
1885
  sessionId: String(session.id),
@@ -1814,12 +1897,12 @@ describe('standalone runtime on published Harness APIs', () => {
1814
1897
  candidateTurns: 2,
1815
1898
  })
1816
1899
  await runScenario({
1817
- id: 'public-tailtrim-tokenizer-unavailable',
1818
- expectedReason: 'exact-tokenizer-unavailable',
1900
+ id: 'public-tailtrim-character-basis-landing',
1819
1901
  trigger: 1,
1820
1902
  minReclaim: 1,
1821
1903
  candidateTurns: 2,
1822
1904
  model: 'unsupported-public-model',
1905
+ expectLanding: true,
1823
1906
  })
1824
1907
  await runScenario({
1825
1908
  id: 'public-tailtrim-first-group-protected',
@@ -2255,19 +2338,25 @@ describe('standalone runtime on published Harness APIs', () => {
2255
2338
  // The original image-bearing result stays on the surface untouched.
2256
2339
  const original = session.events[imageResult.seq]
2257
2340
  expect(original?.type).toBe('tool/result')
2341
+ // Character basis: the text-only guard rejects a rich node, so the fresh and
2342
+ // aggregate passes report no reducible candidate and the single candidate
2343
+ // stays inside the protected History tail. The image itself is never
2344
+ // rewritten, which is the behaviour this case exists to protect.
2258
2345
  expect(audit.records()).toContainEqual(expect.objectContaining({
2259
2346
  kind: 'component-evaluation',
2260
2347
  sessionId: String(session.id),
2261
2348
  component: 'fresh',
2262
2349
  status: 'skipped',
2263
- reason: 'exact-tokenizer-unavailable',
2350
+ reason: 'no-valid-reduction',
2351
+ measurementKind: 'characters',
2264
2352
  }))
2265
2353
  expect(audit.records()).toContainEqual(expect.objectContaining({
2266
2354
  kind: 'component-evaluation',
2267
2355
  sessionId: String(session.id),
2268
2356
  component: 'history',
2269
2357
  status: 'skipped',
2270
- reason: 'exact-tokenizer-unavailable',
2358
+ reason: 'protected-working-set',
2359
+ measurementKind: 'characters',
2271
2360
  }))
2272
2361
  })
2273
2362
 
@@ -2529,3 +2618,85 @@ describe('standalone runtime on published Harness APIs', () => {
2529
2618
  || record.reason === 'exact-tokenizer-unavailable')).toBe(true)
2530
2619
  })
2531
2620
  })
2621
+
2622
+ describe('character basis / model-id independence', () => {
2623
+ // ~57,688 characters of read-type output on the decision surface, in the
2624
+ // code shape the hypa-code-skeleton reducer collapses.
2625
+ const readFixture = [
2626
+ "import { readFile } from 'node:fs/promises'",
2627
+ '',
2628
+ ...Array.from({ length: 300 }, (_, index) => [
2629
+ `export function handler${String(index)}(input: string): string {`,
2630
+ ` const normalized = input.trim().toLowerCase()`,
2631
+ ` if (normalized.length === 0) return 'empty-${String(index)}'`,
2632
+ ` return normalized.split('-').join('+')`,
2633
+ '}',
2634
+ '',
2635
+ ]).flat(),
2636
+ ].join('\n')
2637
+
2638
+ async function characterBasisContext(): Promise<Context> {
2639
+ const ctx = await runtimeContext()
2640
+ await ctx.plugin(TestSettings).await()
2641
+ await ctx.plugin(SelectorHost).await()
2642
+ await ctx.settings.update(settingsNamespace(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE), {
2643
+ profile: 'balanced',
2644
+ codeSkeleton: { enabled: true },
2645
+ })
2646
+ await ctx.plugin(ToolResultPruner, {
2647
+ profile: 'balanced',
2648
+ freshTriggerTokens: 1_000,
2649
+ freshTargetTokens: 800,
2650
+ aggregateTriggerTokens: 500_000,
2651
+ aggregateTargetTokens: 450_000,
2652
+ historyTriggerTokens: 500_000,
2653
+ }).await()
2654
+ return ctx
2655
+ }
2656
+
2657
+ for (const routedModel of ['deepseek-nonexistent-9', 'deepseek-flash']) {
2658
+ it(`lands a fresh reduction on the character basis for routed model ${routedModel}`, async () => {
2659
+ const ctx = await characterBasisContext()
2660
+ const audit = captureAudit(ctx)
2661
+ const session = Session.create(SessionId(`public-char-basis-${routedModel}`))
2662
+ appendToolTurn(session, 1, readFixture, false, undefined, 'deepseek-official', routedModel, 'read')
2663
+
2664
+ const result = ctx.toolResultPruner.pruneSession(session, {
2665
+ stage: 'fresh',
2666
+ freshTurn: 1,
2667
+ freshStep: 1,
2668
+ })
2669
+
2670
+ expect(result.pruned.length).toBe(1)
2671
+ expect(result.pruned[0]?.reducer).toBe('hypa-code-skeleton')
2672
+ // The decision ran on characters: the record must not claim an exact
2673
+ // tokenizer it never used.
2674
+ const record = rewrites(audit.records()).find(entry => entry.component === 'fresh')
2675
+ expect(record?.measurementBasis).toBe('characters')
2676
+ expect(record?.tokenizerId).toBe('characters')
2677
+ expect(record?.tokenizerRevision).toBe('chars-per-token-4.0')
2678
+ })
2679
+ }
2680
+
2681
+ it('keeps the exact-tokenizer basis and the same reducer for a whitelisted model', async () => {
2682
+ const ctx = await characterBasisContext()
2683
+ const audit = captureAudit(ctx)
2684
+ const session = Session.create(SessionId('public-char-basis-whitelisted'))
2685
+ appendToolTurn(session, 1, readFixture, false, undefined, 'deepseek-official', MODEL, 'read')
2686
+
2687
+ const result = ctx.toolResultPruner.pruneSession(session, {
2688
+ stage: 'fresh',
2689
+ freshTurn: 1,
2690
+ freshStep: 1,
2691
+ })
2692
+
2693
+ expect(result.pruned.length).toBe(1)
2694
+ expect(result.pruned[0]?.reducer).toBe('hypa-code-skeleton')
2695
+ const record = rewrites(audit.records()).find(entry => entry.component === 'fresh')
2696
+ expect(record?.measurementBasis).toBe('exact-tokenizer')
2697
+ expect(record?.tokenizerId).toEqual(expect.stringContaining('deepseek'))
2698
+ expect(record?.tokenizerRevision).toEqual(expect.any(String))
2699
+ expect(record?.tokensBefore).toBeGreaterThan(0)
2700
+ expect(record?.tokensAfter).toBeGreaterThan(0)
2701
+ })
2702
+ })
@@ -0,0 +1,33 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { resolveConfig, resolvePolicy } from '../../src/pruner.ts'
3
+
4
+ /** task_4 (G2): the read input cap is in CHARACTERS while the fresh trigger is
5
+ * in TOKENS. At the conservative 4.0 chars/token upper bound, a cap at or
6
+ * below `freshTriggerTokens × 4.0` truncates every read result below the
7
+ * trigger and silently silences the fresh path — so `resolvePolicy` must
8
+ * reject that combination at startup. 32k fails (32,000 < 8192×4.0 = 32,768);
9
+ * the deployed 50k cap passes; unset stays untouched. */
10
+ describe('readInputCapChars invariant', () => {
11
+ it('throws when the cap would sit below the fresh trigger (32k vs 8192×4.0)', () => {
12
+ const config = resolveConfig({ readInputCapChars: 32_000 })
13
+ expect(() => resolvePolicy(config, 'balanced')).toThrow(
14
+ 'context compression policy: read input cap would silence the fresh path',
15
+ )
16
+ })
17
+
18
+ it('accepts the deployed 50k cap', () => {
19
+ const config = resolveConfig({ readInputCapChars: 50_000 })
20
+ const policy = resolvePolicy(config, 'balanced')
21
+ expect(policy.readInputCapChars).toBe(50_000)
22
+ })
23
+
24
+ it('leaves the policy untouched when the cap is not set', () => {
25
+ const policy = resolvePolicy(resolveConfig({}), 'balanced')
26
+ expect(policy.readInputCapChars).toBeUndefined()
27
+ })
28
+
29
+ it('keeps profiles without a configured cap byte-identical (no field on the resolved object)', () => {
30
+ const policy = resolvePolicy(resolveConfig({}), 'balanced')
31
+ expect(Object.hasOwn(policy, 'readInputCapChars')).toBe(false)
32
+ })
33
+ })
@@ -0,0 +1,110 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { reduceFreshToolResult } from '../../src/runtime/reducers.ts'
3
+
4
+ const SOURCE_REF = 'session://s1/event/7'
5
+
6
+ function searchInput(text: string, budgetChars = 16_000): Parameters<typeof reduceFreshToolResult>[0] {
7
+ return {
8
+ toolName: 'grep_search',
9
+ argumentsText: '{"pattern":"config"}',
10
+ text,
11
+ budgetChars,
12
+ sourceRef: SOURCE_REF,
13
+ isError: false,
14
+ }
15
+ }
16
+
17
+ describe('search L1 locator (R10)', () => {
18
+ it('reports the complete line-number set for a 592-hit file (count == hits)', () => {
19
+ // 实测 upper bound: one real session had a 592-hit file; the old reducer
20
+ // reported only "(592 matches)" and dropped every line number (21.2% of
21
+ // all hits across sessions were silently unlocatable).
22
+ const lines = Array.from({ length: 592 }, (_, i) =>
23
+ `src/deep/module.ts:${String(i + 1)}: export const config${String(i)} = configure(${String(i)})`)
24
+ const output = reduceFreshToolResult(searchInput(lines.join('\n')))
25
+ expect(output).not.toBeNull()
26
+ const locator = output!.text.split('\n').find(line => line.startsWith('## src/deep/module.ts'))
27
+ expect(locator).toBeDefined()
28
+ const numbers = [...locator!.matchAll(/L(\d+)/g)].map(match => Number(match[1]))
29
+ expect(numbers).toHaveLength(592)
30
+ expect(numbers[0]).toBe(1)
31
+ expect(numbers[591]).toBe(592)
32
+ })
33
+
34
+ it('keeps L1 free of content rows (pure locator)', () => {
35
+ const lines = Array.from({ length: 40 }, (_, i) => `a.ts:${String(i + 1)}: content row ${String(i)}`)
36
+ const output = reduceFreshToolResult(searchInput(lines.join('\n'), 700))
37
+ expect(output).not.toBeNull()
38
+ const locatorLine = output!.text.split('\n').find(line => line.startsWith('## a.ts'))
39
+ expect(locatorLine).toBeDefined()
40
+ expect(locatorLine).not.toContain('content row')
41
+ })
42
+
43
+ it('announces withheld locators visibly instead of silently truncating', () => {
44
+ // Budget too small for the full L1 set: the header must state how much
45
+ // was withheld rather than quietly shrinking the list.
46
+ const lines = [
47
+ ...Array.from({ length: 300 }, (_, i) => `big.ts:${String(i + 1)}: hit ${String(i)}`),
48
+ ...Array.from({ length: 5 }, (_, i) => `small.ts:${String(i + 1)}: hit ${String(i)}`),
49
+ ].join('\n')
50
+ const output = reduceFreshToolResult(searchInput(lines, 900))
51
+ expect(output).not.toBeNull()
52
+ expect(output!.text).toMatch(/withheld|more (?:files|matches)/i)
53
+ })
54
+ })
55
+
56
+ describe('search L2 water-filling (R10)', () => {
57
+ it('serves every file one round before any file takes a second row', () => {
58
+ const fat = Array.from({ length: 500 }, (_, i) => `fat.ts:${String(i + 1)}: fat file row ${String(i)}`)
59
+ const mid = Array.from({ length: 10 }, (_, i) => `mid.ts:${String(i + 1)}: mid file row ${String(i)}`)
60
+ const thin = Array.from({ length: 5 }, (_, i) => `thin.ts:${String(i + 1)}: thin file row ${String(i)}`)
61
+ // Tight content quota: only ~15 rows fit after L1. Round-robin must give
62
+ // each file a row per round — the old "fill from index 0" let the first
63
+ // file eat the whole quota.
64
+ const output = reduceFreshToolResult(searchInput([...fat, ...mid, ...thin].join('\n'), 1_600))
65
+ expect(output).not.toBeNull()
66
+ const counts = new Map<string, number>()
67
+ for (const line of output!.text.split('\n')) {
68
+ const match = /^(fat|mid|thin)\.ts:\d+:/.exec(line)
69
+ if (match !== null) counts.set(match[1]!, (counts.get(match[1]!) ?? 0) + 1)
70
+ }
71
+ expect(counts.get('fat')!).toBeGreaterThan(0)
72
+ expect(counts.get('mid')!).toBeGreaterThan(0)
73
+ expect(counts.get('thin')!).toBeGreaterThan(0)
74
+ })
75
+
76
+ it('exhausts small files before the big file takes the remaining quota', () => {
77
+ const fat = Array.from({ length: 500 }, (_, i) => `fat.ts:${String(i + 1)}: fat file row ${String(i)}`)
78
+ const mid = Array.from({ length: 10 }, (_, i) => `mid.ts:${String(i + 1)}: mid file row ${String(i)}`)
79
+ const thin = Array.from({ length: 5 }, (_, i) => `thin.ts:${String(i + 1)}: thin file row ${String(i)}`)
80
+ // Generous quota after L1: mid and thin end up FULLY covered (100% of
81
+ // their rows) while fat takes only what is left.
82
+ const output = reduceFreshToolResult(searchInput([...fat, ...mid, ...thin].join('\n'), 6_000))
83
+ const counts = new Map<string, number>()
84
+ for (const line of output!.text.split('\n')) {
85
+ const match = /^(fat|mid|thin)\.ts:\d+:/.exec(line)
86
+ if (match !== null) counts.set(match[1]!, (counts.get(match[1]!) ?? 0) + 1)
87
+ }
88
+ expect(counts.get('thin')).toBe(5)
89
+ expect(counts.get('mid')).toBe(10)
90
+ expect(counts.get('fat')!).toBeGreaterThan(0)
91
+ })
92
+
93
+ it('keeps error rows available to the quota', () => {
94
+ const rows = Array.from({ length: 40 }, (_, i) => `app.ts:${String(i + 1)}: ordinary row ${String(i)}`)
95
+ rows.push('app.ts:99: FATAL: unhandled rejection in loader')
96
+ // Tight quota: round 0 must reach the important row (offered first within
97
+ // the file) even though 40 ordinary rows outrank it by line number.
98
+ const output = reduceFreshToolResult(searchInput(rows.join('\n'), 900))
99
+ expect(output).not.toBeNull()
100
+ expect(output!.text).toContain('FATAL: unhandled rejection in loader')
101
+ })
102
+
103
+ it('falls back to salience when no path:line form exists', () => {
104
+ const output = reduceFreshToolResult(searchInput([
105
+ ...Array.from({ length: 60 }, (_, i) => `ordinary output line ${String(i)} without any locators at all`),
106
+ 'FATAL: something exploded without a path prefix',
107
+ ].join('\n'), 1_200))
108
+ expect(output?.reducer).toBe('search-salience')
109
+ })
110
+ })