dsh-context-compression-improved 0.10.2 → 0.10.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.
- package/.agents/plans/improve/checklist.md +32 -0
- package/.agents/plans/improve/findings.md +102 -0
- package/.agents/plans/improve/spec.md +53 -0
- package/.agents/plans/improve/tasks.md +70 -0
- package/.gitattributes +2 -0
- package/.githooks/pre-push +37 -0
- package/.github/workflows/ci.yml +39 -0
- package/CHANGELOG.de.md +580 -0
- package/CHANGELOG.es.md +588 -0
- package/CHANGELOG.fr.md +576 -0
- package/CHANGELOG.it.md +577 -0
- package/CHANGELOG.ja.md +261 -0
- package/CHANGELOG.ko.md +254 -0
- package/CHANGELOG.md +549 -0
- package/CHANGELOG.ru.md +554 -0
- package/CHANGELOG.zh.md +238 -0
- package/CONTRIBUTING.md +22 -0
- package/README.de.md +96 -0
- package/README.es.md +96 -0
- package/README.fr.md +96 -0
- package/README.it.md +96 -0
- package/README.ja.md +102 -0
- package/README.ko.md +102 -0
- package/README.md +110 -15
- package/README.ru.md +96 -0
- package/README.zh.md +104 -14
- package/SECURITY.md +18 -0
- package/THIRD_PARTY_NOTICES.md +7 -25
- package/assets/board.png +0 -0
- package/assets/context.png +0 -0
- package/docs/assets/context-compression-selector-profiles.jpg +0 -0
- package/docs/assets/context-compression-selector-settings.png +0 -0
- package/docs/compat-0.1.5-report.md +77 -0
- package/docs/installation.de.md +104 -0
- package/docs/installation.es.md +104 -0
- package/docs/installation.fr.md +104 -0
- package/docs/installation.it.md +104 -0
- package/docs/installation.ja.md +78 -0
- package/docs/installation.ko.md +78 -0
- package/docs/installation.md +103 -0
- package/docs/installation.ru.md +104 -0
- package/docs/installation.zh.md +100 -0
- package/docs/repair-log.md +657 -0
- package/eslint.config.js +30 -0
- package/package.json +116 -129
- package/packages/selector/LICENSE +21 -0
- package/packages/selector/README.md +26 -0
- package/packages/selector/README.zh.md +24 -0
- package/packages/selector/THIRD_PARTY_NOTICES.md +32 -0
- package/packages/selector/docs/history-tool-call-working-set-spec.md +112 -0
- package/packages/selector/docs/native-tool-result-selector-spec.md +34 -0
- package/packages/selector/docs/subagent-cache-reuse-spec.md +46 -0
- package/{dsh.plugin.json → packages/selector/dsh.plugin.json} +2 -2
- package/packages/selector/lib/style.css +350 -0
- package/packages/selector/package.json +178 -0
- package/packages/selector/screenshots.json +3 -0
- package/packages/selector/src/client/CompressionProfileControls.tsx +293 -0
- package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -0
- package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -0
- package/packages/selector/src/client/CustomPolicyEditor.tsx +216 -0
- package/packages/selector/src/client/EstimatorControls.tsx +277 -0
- package/packages/selector/src/client/bridge-scope.ts +125 -0
- package/packages/selector/src/client/decode.ts +57 -0
- package/packages/selector/src/client/fab-pos.ts +71 -0
- package/packages/selector/src/client/index.ts +424 -0
- package/packages/selector/src/client/locales/de.ts +158 -0
- package/packages/selector/src/client/locales/es.ts +158 -0
- package/packages/selector/src/client/locales/fr.ts +158 -0
- package/packages/selector/src/client/locales/it.ts +158 -0
- package/packages/selector/src/client/locales/ja.ts +158 -0
- package/packages/selector/src/client/locales/ko.ts +158 -0
- package/packages/selector/src/client/locales/ru.ts +158 -0
- package/packages/selector/src/client/locales.ts +316 -0
- package/packages/selector/src/client/monitor-fab.ts +431 -0
- package/packages/selector/src/client/preset-options.ts +88 -0
- package/packages/selector/src/client/savings-card.tsx +269 -0
- package/packages/selector/src/client/scope-face.ts +24 -0
- package/packages/selector/src/client/settings-section.tsx +140 -0
- package/packages/selector/src/compat/host-generation.ts +96 -0
- package/packages/selector/src/compat/llm-messages.ts +50 -0
- package/packages/selector/src/compat/settings-lease.ts +108 -0
- package/packages/selector/src/compat/tool-result.ts +91 -0
- package/packages/selector/src/css-modules.d.ts +6 -0
- package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -0
- package/packages/selector/src/estimator-catalog.ts +104 -0
- package/packages/selector/src/index.ts +890 -0
- package/packages/selector/src/invariant.ts +113 -0
- package/packages/selector/src/preset-overlay.ts +749 -0
- package/packages/selector/src/profiles.ts +431 -0
- package/packages/selector/src/pruner/content.ts +198 -0
- package/packages/selector/src/pruner/session.ts +97 -0
- package/packages/selector/src/pruner/state.ts +61 -0
- package/packages/selector/src/pruner/tuning.ts +23 -0
- package/packages/selector/src/pruner/types.ts +78 -0
- package/packages/selector/src/pruner.ts +2914 -0
- package/packages/selector/src/runtime/adaptive-cost.ts +205 -0
- package/packages/selector/src/runtime/audit.ts +320 -0
- package/packages/selector/src/runtime/config.ts +756 -0
- package/packages/selector/src/runtime/custom-policy.ts +278 -0
- package/packages/selector/src/runtime/deepseek-official-pricing.ts +298 -0
- package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +254 -0
- package/packages/selector/src/runtime/display-prefs.ts +98 -0
- package/packages/selector/src/runtime/measurement.ts +444 -0
- package/packages/selector/src/runtime/monitor.ts +310 -0
- package/packages/selector/src/runtime/panel-command.ts +213 -0
- package/packages/selector/src/runtime/reducers.ts +1754 -0
- package/packages/selector/src/runtime/retrieve.ts +503 -0
- package/packages/selector/src/runtime/savings-integral.ts +117 -0
- package/packages/selector/src/runtime/savings-projection.ts +229 -0
- package/packages/selector/src/runtime/savings-verify.ts +446 -0
- package/packages/selector/src/runtime/savings.ts +526 -0
- package/packages/selector/src/runtime/session-events.ts +30 -0
- package/packages/selector/src/runtime/session-file-decode.ts +523 -0
- package/packages/selector/src/runtime/stats-backfill.ts +541 -0
- package/packages/selector/src/runtime/stats-db.ts +492 -0
- package/packages/selector/src/runtime/stats-schema.ts +123 -0
- package/packages/selector/src/runtime/stats-sync.ts +307 -0
- package/packages/selector/src/runtime/summary-command.ts +127 -0
- package/packages/selector/src/runtime/tail-trim.ts +176 -0
- package/packages/selector/src/runtime/token-count.ts +72 -0
- package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -0
- package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -0
- package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -0
- package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -0
- package/packages/selector/src/runtime/tokenpilot/dedup.ts +81 -0
- package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -0
- package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
- package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
- package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
- package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
- package/packages/selector/src/runtime/tokenpilot/locator.ts +128 -0
- package/packages/selector/src/runtime/tokenpilot/read-state.ts +98 -0
- package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -0
- package/packages/selector/src/runtime/toolclass.ts +103 -0
- package/packages/selector/src/runtime/types.ts +365 -0
- package/packages/selector/src/runtime/value.ts +48 -0
- package/packages/selector/src/settings-bridge.ts +175 -0
- package/packages/selector/tests/advisor-report.host.spec.ts +223 -0
- package/packages/selector/tests/auto-compact.client.spec.tsx +214 -0
- package/packages/selector/tests/built/client-artifact.spec.ts +56 -0
- package/packages/selector/tests/cache-prefix-audit.spec.ts +123 -0
- package/packages/selector/tests/code-skeleton.client.spec.ts +98 -0
- package/packages/selector/tests/compat/compat-narrow-waist.spec.ts +150 -0
- package/packages/selector/tests/custom-contract.client.spec.ts +226 -0
- package/packages/selector/tests/estimator-catalog.spec.ts +70 -0
- package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -0
- package/packages/selector/tests/estimator-route-registration.host.spec.ts +202 -0
- package/packages/selector/tests/fab-pos.client.spec.ts +47 -0
- package/packages/selector/tests/helpers/legacy-namespace.ts +35 -0
- package/packages/selector/tests/helpers/legacy-settings/index.ts +15 -0
- package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +41 -0
- package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +647 -0
- package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +78 -0
- package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +234 -0
- package/packages/selector/tests/host-preset-overlay.host.spec.ts +204 -0
- package/packages/selector/tests/monitor-fab.client.spec.ts +240 -0
- package/packages/selector/tests/preset-options-write.client.spec.ts +192 -0
- package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +200 -0
- package/packages/selector/tests/preset-overlay.host.spec.ts +246 -0
- package/packages/selector/tests/profiles.client.spec.tsx +436 -0
- package/packages/selector/tests/public/package-contract.client.spec.ts +86 -0
- package/packages/selector/tests/runtime/adaptive-cost.spec.ts +167 -0
- package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +230 -0
- package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -0
- package/packages/selector/tests/runtime/advisor.spec.ts +226 -0
- package/packages/selector/tests/runtime/audit.spec.ts +275 -0
- package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -0
- package/packages/selector/tests/runtime/char-basis.spec.ts +30 -0
- package/packages/selector/tests/runtime/code-skeleton.spec.ts +152 -0
- package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +186 -0
- package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -0
- package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +122 -0
- package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -0
- package/packages/selector/tests/runtime/fixtures/profile-baseline.json +273 -0
- package/packages/selector/tests/runtime/fixtures/session-v4-dump.jsonl +46 -0
- package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +106 -0
- package/packages/selector/tests/runtime/fixtures/vision-golden.json +459 -0
- package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -0
- package/packages/selector/tests/runtime/fresh-gate.spec.ts +43 -0
- package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -0
- package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
- package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
- package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +79 -0
- package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -0
- package/packages/selector/tests/runtime/monitor.spec.ts +354 -0
- package/packages/selector/tests/runtime/panel-command.spec.ts +101 -0
- package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -0
- package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2781 -0
- package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -0
- package/packages/selector/tests/runtime/savings-accounting.spec.ts +291 -0
- package/packages/selector/tests/runtime/savings-integral.spec.ts +169 -0
- package/packages/selector/tests/runtime/savings-projection.spec.ts +89 -0
- package/packages/selector/tests/runtime/savings-verify.spec.ts +226 -0
- package/packages/selector/tests/runtime/savings.spec.ts +139 -0
- package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -0
- package/packages/selector/tests/runtime/session-events.spec.ts +27 -0
- package/packages/selector/tests/runtime/session-file-decode.spec.ts +281 -0
- package/packages/selector/tests/runtime/settings-unwrap.spec.ts +58 -0
- package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -0
- package/packages/selector/tests/runtime/stats-backfill-scheduler.spec.ts +167 -0
- package/packages/selector/tests/runtime/stats-backfill.spec.ts +348 -0
- package/packages/selector/tests/runtime/stats-db.spec.ts +361 -0
- package/packages/selector/tests/runtime/stats-privacy.spec.ts +55 -0
- package/packages/selector/tests/runtime/stats-sync.spec.ts +278 -0
- package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
- package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -0
- package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +53 -0
- package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -0
- package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +52 -0
- package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -0
- package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +76 -0
- package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +119 -0
- package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +82 -0
- package/packages/selector/tests/runtime/toolclass.spec.ts +156 -0
- package/packages/selector/tests/runtime/value.spec.ts +23 -0
- package/packages/selector/tests/savings-sessions.client.spec.tsx +140 -0
- package/packages/selector/tests/settings-seat.client.spec.ts +215 -0
- package/packages/selector/tests/standing-generation.host.spec.ts +724 -0
- package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +269 -0
- package/packages/selector/tests/support/cache-prefix-audit.ts +105 -0
- package/packages/selector/tests/support/mock-adapter.ts +37 -0
- package/packages/selector/tests/support/ui-primitives.tsx +34 -0
- package/packages/selector/tsconfig.json +11 -0
- package/packages/selector/tsdown.client.config.ts +102 -0
- package/packages/selector/tsdown.config.ts +20 -0
- package/pnpm-workspace.yaml +76 -0
- package/screenshots.json +6 -3
- package/scripts/capture-profile-baseline.mjs +42 -0
- package/scripts/cell-browser-e2e.mjs +354 -0
- package/scripts/generate-tokenizer-fixtures.py +81 -0
- package/scripts/generate-vision-fixtures.py +208 -0
- package/scripts/hosts.mjs +78 -0
- package/scripts/packed-components-smoke.mjs +763 -0
- package/scripts/packed-install-e2e.mjs +1346 -0
- package/scripts/sync-hosts.mjs +174 -0
- package/scripts/toolclass-corpus-replay.mjs +281 -0
- package/scripts/verify-release.mjs +338 -0
- package/tests/TEST_INVENTORY.md +41 -0
- package/tsconfig.base.json +18 -0
- package/tsconfig.json +7 -0
- package/tsconfig.tests.json +15 -0
- package/vitest.built.config.ts +9 -0
- package/vitest.config.ts +54 -0
- /package/{assets → packages/selector/assets}/deepseek-v4/LICENSE.DeepSeek-V4-Pro.txt +0 -0
- /package/{assets → packages/selector/assets}/deepseek-v4/manifest.json +0 -0
- /package/{assets → packages/selector/assets}/deepseek-v4/tokenizer.json +0 -0
- /package/{assets → packages/selector/assets}/deepseek-v4/tokenizer_config.json +0 -0
- /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/LICENSE.DeepSeek-V4-Flash-Vision-Exp.txt +0 -0
- /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/manifest.json +0 -0
- /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/tokenizer.json +0 -0
- /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/tokenizer_config.json +0 -0
- /package/{cordis.patch.yml → packages/selector/cordis.patch.yml} +0 -0
- /package/{lib → packages/selector/lib}/client.d.ts +0 -0
- /package/{lib → packages/selector/lib}/client.js +0 -0
- /package/{lib → packages/selector/lib}/index.d.ts +0 -0
- /package/{lib → packages/selector/lib}/index.js +0 -0
- /package/{lib → packages/selector/lib}/invariant.d.ts +0 -0
- /package/{lib → packages/selector/lib}/invariant.js +0 -0
- /package/{lib → packages/selector/lib}/profiles.d.ts +0 -0
- /package/{lib → packages/selector/lib}/pruner.d.ts +0 -0
- /package/{lib → packages/selector/lib}/pruner.js +0 -0
- /package/{lib → packages/selector/lib}/savings-integral.js +0 -0
- /package/{lib → packages/selector/lib}/tail-trim.js +0 -0
- /package/{lib → packages/selector/lib}/tool-result.js +0 -0
|
@@ -0,0 +1,2781 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from 'vitest'
|
|
2
|
+
import { Context } from '@deepseek-ai/cordis'
|
|
3
|
+
import {
|
|
4
|
+
ToolCallId as CallId,
|
|
5
|
+
createMessage,
|
|
6
|
+
createUserMessage,
|
|
7
|
+
createToolResultMessage,
|
|
8
|
+
LlmAdapter,
|
|
9
|
+
type ContentBlock,
|
|
10
|
+
type GenerateOptions,
|
|
11
|
+
type LlmResolvedModelInfo,
|
|
12
|
+
type StreamChunk,
|
|
13
|
+
} from '@deepseek-ai/dsh-llm'
|
|
14
|
+
import LlmRuntime from '@deepseek-ai/dsh-llm'
|
|
15
|
+
import AgentLoop from '@deepseek-ai/dsh-agent-loop'
|
|
16
|
+
import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
|
|
17
|
+
import BasicCompactionEngine from '@deepseek-ai/dsh-compaction-basic'
|
|
18
|
+
import SessionStore, {
|
|
19
|
+
Session,
|
|
20
|
+
SessionId,
|
|
21
|
+
SessionSeq,
|
|
22
|
+
canonicalHeader,
|
|
23
|
+
} from '@deepseek-ai/dsh-session'
|
|
24
|
+
import {
|
|
25
|
+
agentEvents,
|
|
26
|
+
type Agent,
|
|
27
|
+
} from '@deepseek-ai/dsh-agent'
|
|
28
|
+
import { type SettingsNamespace } from '@deepseek-ai/dsh-settings'
|
|
29
|
+
import { LegacySettingsProvider } from '../../helpers/legacy-settings/index.ts'
|
|
30
|
+
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
|
|
31
|
+
import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
|
|
32
|
+
import TokenMeter from '@deepseek-ai/dsh-token-meter'
|
|
33
|
+
import ToolRuntime from '@deepseek-ai/dsh-tools'
|
|
34
|
+
import { CompactionId } from '@deepseek-ai/dsh-compaction'
|
|
35
|
+
import InvariantRegistry from '@deepseek-ai/dsh-invariants'
|
|
36
|
+
import * as SelectorHost from '../../../src/index.ts'
|
|
37
|
+
import { LegacyNamespaceRegistrar } from '../../helpers/legacy-namespace.ts'
|
|
38
|
+
import * as RuntimeInvariant from '../../../src/invariant.ts'
|
|
39
|
+
import { sessionEvents } from '../../../src/runtime/session-events.ts'
|
|
40
|
+
import ToolResultPruner, {
|
|
41
|
+
CONTEXT_COMPRESSION_SETTINGS_NAMESPACE,
|
|
42
|
+
DEFAULT_CUSTOM_COMPRESSION_POLICY,
|
|
43
|
+
resolveConfig,
|
|
44
|
+
resolvePolicy,
|
|
45
|
+
} from '../../../src/pruner.ts'
|
|
46
|
+
import type { CustomCompressionPolicy } from '../../../src/pruner.ts'
|
|
47
|
+
import { CHARS_PER_TOKEN } from '../../../src/runtime/config.ts'
|
|
48
|
+
import { DEEPSEEK_V4_TOKENIZER_ARTIFACT, deepSeekV4TokenizerForModel } from '../../../src/deepseek-v4-tokenizer.ts'
|
|
49
|
+
import {
|
|
50
|
+
DEEPSEEK_VISION_DEFAULT_IMAGE_TOKENS,
|
|
51
|
+
DEEPSEEK_VISION_IMAGE_ESTIMATOR,
|
|
52
|
+
DEEPSEEK_VISION_PROJECTION,
|
|
53
|
+
deepSeekVisionImageBlockTokens,
|
|
54
|
+
deepSeekVisionImageGrid,
|
|
55
|
+
} from '../../../src/runtime/deepseek-v4-vision-tokens.ts'
|
|
56
|
+
import { validatePublishedTailTrim } from '../../../src/runtime/tail-trim.ts'
|
|
57
|
+
import { measureForCompaction } from '../../../src/runtime/measurement.ts'
|
|
58
|
+
import {
|
|
59
|
+
COMPRESSION_AUDIT_PREFIX,
|
|
60
|
+
type CompressionAuditRecord,
|
|
61
|
+
type CompressionRewriteAuditRecord,
|
|
62
|
+
} from '../../../src/runtime/audit.ts'
|
|
63
|
+
|
|
64
|
+
const MODEL = 'deepseek-v4-flash'
|
|
65
|
+
const VISION_MODEL = 'deepseek-v4-flash-vision-exp'
|
|
66
|
+
const activeContexts: Context[] = []
|
|
67
|
+
|
|
68
|
+
/** Metadata-only raster image block; never carries image bytes. */
|
|
69
|
+
function imageBlock(width: number, height: number): ContentBlock {
|
|
70
|
+
// AttachmentId is an opaque brand over string; tests construct the durable
|
|
71
|
+
// reference structurally without importing the attachment package.
|
|
72
|
+
return {
|
|
73
|
+
type: 'image',
|
|
74
|
+
attachment: {
|
|
75
|
+
attachmentId: `test-image-${String(width)}x${String(height)}`,
|
|
76
|
+
mediaType: 'image/png',
|
|
77
|
+
bytes: 1_024,
|
|
78
|
+
width,
|
|
79
|
+
height,
|
|
80
|
+
},
|
|
81
|
+
} as ContentBlock
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
afterEach(async () => {
|
|
85
|
+
for (const ctx of activeContexts.splice(0)) await ctx.fiber.dispose()
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
class TestSettings extends LegacySettingsProvider {
|
|
89
|
+
readonly writable = true
|
|
90
|
+
private readonly stored: Record<string, unknown> = {}
|
|
91
|
+
|
|
92
|
+
protected override load(): Promise<Record<string, unknown>> {
|
|
93
|
+
return Promise.resolve(structuredClone(this.stored))
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
protected override persist(namespace: SettingsNamespace, section: Record<string, unknown>): Promise<void> {
|
|
97
|
+
this.stored[namespace] = structuredClone(section)
|
|
98
|
+
return Promise.resolve()
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
class NativeSummaryAdapter extends LlmAdapter {
|
|
103
|
+
constructor(
|
|
104
|
+
private readonly responses: string[],
|
|
105
|
+
private readonly contextWindow: number,
|
|
106
|
+
) {
|
|
107
|
+
super()
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
override resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo> {
|
|
111
|
+
return Promise.resolve({
|
|
112
|
+
provider,
|
|
113
|
+
id: model,
|
|
114
|
+
name: model,
|
|
115
|
+
context: { contextWindow: this.contextWindow },
|
|
116
|
+
})
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
override async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
|
|
120
|
+
options.signal?.throwIfAborted()
|
|
121
|
+
const text = this.responses.shift()
|
|
122
|
+
if (text === undefined) throw new Error('NativeSummaryAdapter: response script exhausted')
|
|
123
|
+
yield { type: 'block-start', index: 0, blockType: 'text' }
|
|
124
|
+
yield { type: 'text-delta', index: 0, text }
|
|
125
|
+
yield { type: 'block-end', index: 0, block: { type: 'text', text } }
|
|
126
|
+
yield { type: 'usage', usage: { inputTokens: 10, outputTokens: text.length } }
|
|
127
|
+
yield { type: 'finish', reason: { kind: 'stop' } }
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async function runtimeContext(): Promise<Context> {
|
|
132
|
+
const ctx = new Context()
|
|
133
|
+
activeContexts.push(ctx)
|
|
134
|
+
await ctx.plugin(SessionStore).await()
|
|
135
|
+
await ctx.plugin(SystemPrompt).await()
|
|
136
|
+
await ctx.plugin(ToolRuntime).await()
|
|
137
|
+
await ctx.plugin(SessionProjectionRegistry).await()
|
|
138
|
+
await ctx.plugin(TokenMeter).await()
|
|
139
|
+
return ctx
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function captureAudit(ctx: Context): {
|
|
143
|
+
records(): CompressionAuditRecord[]
|
|
144
|
+
} {
|
|
145
|
+
const info = vi.spyOn(ctx.logger, 'info').mockImplementation(() => ctx.logger)
|
|
146
|
+
return {
|
|
147
|
+
records: () => info.mock.calls.flatMap((call) => {
|
|
148
|
+
const line = String(call[0])
|
|
149
|
+
return line.startsWith(COMPRESSION_AUDIT_PREFIX)
|
|
150
|
+
? [JSON.parse(line.slice(COMPRESSION_AUDIT_PREFIX.length)) as CompressionAuditRecord]
|
|
151
|
+
: []
|
|
152
|
+
}),
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function rewrites(records: readonly CompressionAuditRecord[]): CompressionRewriteAuditRecord[] {
|
|
157
|
+
return records.filter((record): record is CompressionRewriteAuditRecord => record.kind === 'rewrite')
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function appendToolTurn(
|
|
161
|
+
session: Session,
|
|
162
|
+
turn: number,
|
|
163
|
+
text: string,
|
|
164
|
+
closeTurn: boolean,
|
|
165
|
+
userText?: string,
|
|
166
|
+
provider = 'deepseek',
|
|
167
|
+
model: string = MODEL,
|
|
168
|
+
toolName = 'bash',
|
|
169
|
+
): { readonly assistantSeq: number; readonly resultSeq: number } {
|
|
170
|
+
const callId = CallId(`call-${String(turn)}`)
|
|
171
|
+
session.append('turn/start', { turn })
|
|
172
|
+
if (session.requestHeader() === undefined) {
|
|
173
|
+
session.append('request/header', {
|
|
174
|
+
reason: 'initial',
|
|
175
|
+
header: canonicalHeader({ config: { provider, model } }),
|
|
176
|
+
})
|
|
177
|
+
}
|
|
178
|
+
if (userText !== undefined) {
|
|
179
|
+
session.append('user/message', createUserMessage({
|
|
180
|
+
content: [{ type: 'text', text: userText }],
|
|
181
|
+
source: { kind: 'user' },
|
|
182
|
+
}), { surfaceOp: 'append' })
|
|
183
|
+
}
|
|
184
|
+
session.append('step/start', { turn, step: 1 })
|
|
185
|
+
const assistant = session.append('assistant/message', {
|
|
186
|
+
stream: [],
|
|
187
|
+
turn,
|
|
188
|
+
step: 1,
|
|
189
|
+
message: createMessage({
|
|
190
|
+
role: 'assistant',
|
|
191
|
+
content: [{ type: 'tool-call', id: callId, name: toolName, arguments: '{}' }],
|
|
192
|
+
source: { kind: 'model', provider, model },
|
|
193
|
+
}),
|
|
194
|
+
}, { surfaceOp: 'append' })
|
|
195
|
+
session.append('tool/call', { turn, step: 1, callId, name: toolName, arguments: '{}' })
|
|
196
|
+
const result = session.append('tool/result', {
|
|
197
|
+
turn,
|
|
198
|
+
step: 1,
|
|
199
|
+
message: createToolResultMessage({
|
|
200
|
+
callId,
|
|
201
|
+
content: [{ type: 'text', text }],
|
|
202
|
+
isError: false,
|
|
203
|
+
}),
|
|
204
|
+
}, { surfaceOp: 'append' })
|
|
205
|
+
session.append('step/end', { turn, step: 1 })
|
|
206
|
+
if (closeTurn) session.append('turn/end', { turn, reason: { kind: 'completed' } })
|
|
207
|
+
return { assistantSeq: assistant.seq, resultSeq: result.seq }
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function appendToolBatchTurn(
|
|
211
|
+
session: Session,
|
|
212
|
+
turn: number,
|
|
213
|
+
texts: readonly string[],
|
|
214
|
+
closeTurn: boolean,
|
|
215
|
+
userText?: string,
|
|
216
|
+
): { readonly assistantSeq: number; readonly resultSeqs: readonly number[] } {
|
|
217
|
+
const calls = texts.map((_, index) => ({
|
|
218
|
+
id: CallId(`call-${String(turn)}-${String(index + 1)}`),
|
|
219
|
+
name: 'bash',
|
|
220
|
+
}))
|
|
221
|
+
session.append('turn/start', { turn })
|
|
222
|
+
if (session.requestHeader() === undefined) {
|
|
223
|
+
session.append('request/header', {
|
|
224
|
+
reason: 'initial',
|
|
225
|
+
header: canonicalHeader({ config: { provider: 'deepseek', model: MODEL } }),
|
|
226
|
+
})
|
|
227
|
+
}
|
|
228
|
+
if (userText !== undefined) {
|
|
229
|
+
session.append('user/message', createUserMessage({
|
|
230
|
+
content: [{ type: 'text', text: userText }],
|
|
231
|
+
source: { kind: 'user' },
|
|
232
|
+
}), { surfaceOp: 'append' })
|
|
233
|
+
}
|
|
234
|
+
session.append('step/start', { turn, step: 1 })
|
|
235
|
+
const assistant = session.append('assistant/message', {
|
|
236
|
+
stream: [],
|
|
237
|
+
turn,
|
|
238
|
+
step: 1,
|
|
239
|
+
message: createMessage({
|
|
240
|
+
role: 'assistant',
|
|
241
|
+
content: calls.map(call => ({
|
|
242
|
+
type: 'tool-call' as const,
|
|
243
|
+
id: call.id,
|
|
244
|
+
name: call.name,
|
|
245
|
+
arguments: '{}',
|
|
246
|
+
})),
|
|
247
|
+
source: { kind: 'model', provider: 'deepseek', model: MODEL },
|
|
248
|
+
}),
|
|
249
|
+
}, { surfaceOp: 'append' })
|
|
250
|
+
const resultSeqs: number[] = []
|
|
251
|
+
for (const [index, call] of calls.entries()) {
|
|
252
|
+
session.append('tool/call', {
|
|
253
|
+
turn,
|
|
254
|
+
step: 1,
|
|
255
|
+
callId: call.id,
|
|
256
|
+
name: call.name,
|
|
257
|
+
arguments: '{}',
|
|
258
|
+
})
|
|
259
|
+
const result = session.append('tool/result', {
|
|
260
|
+
turn,
|
|
261
|
+
step: 1,
|
|
262
|
+
message: createToolResultMessage({
|
|
263
|
+
callId: call.id,
|
|
264
|
+
content: [{ type: 'text', text: texts[index] ?? '' }],
|
|
265
|
+
isError: false,
|
|
266
|
+
}),
|
|
267
|
+
}, { surfaceOp: 'append' })
|
|
268
|
+
resultSeqs.push(result.seq)
|
|
269
|
+
}
|
|
270
|
+
session.append('step/end', { turn, step: 1 })
|
|
271
|
+
if (closeTurn) session.append('turn/end', { turn, reason: { kind: 'completed' } })
|
|
272
|
+
return { assistantSeq: assistant.seq, resultSeqs }
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// 0.1.5 removed the settingsNamespace() wrapper; namespaces are branded
|
|
276
|
+
// strings validated at runtime by SettingsProvider.parse.
|
|
277
|
+
const nsBrand = (value: string): SettingsNamespace => value as unknown as SettingsNamespace
|
|
278
|
+
|
|
279
|
+
function stubAgent(ctx: Context, session: Session): Agent {
|
|
280
|
+
return {
|
|
281
|
+
id: session.id,
|
|
282
|
+
options: {},
|
|
283
|
+
session,
|
|
284
|
+
// 0.1.5 moved the durable Inbox behind the loop driver; the pruner only
|
|
285
|
+
// reads id/session, so an inert face is enough for the stub.
|
|
286
|
+
inbox: undefined as unknown as Agent['inbox'],
|
|
287
|
+
status: 'idle',
|
|
288
|
+
ctx,
|
|
289
|
+
send: () => {},
|
|
290
|
+
followup: () => {},
|
|
291
|
+
steer: () => ({ outcome: Promise.resolve({ status: 'rejected' as const }) }),
|
|
292
|
+
inject: () => {},
|
|
293
|
+
cancel() {},
|
|
294
|
+
runMaintenance: task => task(new AbortController().signal),
|
|
295
|
+
whenIdle: () => Promise.resolve(),
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
describe('standalone runtime on published Harness APIs', () => {
|
|
300
|
+
it('loads the pinned official tokenizers and refuses unverified model ids', () => {
|
|
301
|
+
const tokenizer = deepSeekV4TokenizerForModel(MODEL)
|
|
302
|
+
expect(tokenizer?.countText('DeepSeek Harness').tokens).toBeGreaterThan(0)
|
|
303
|
+
expect(deepSeekV4TokenizerForModel('deepseek-v4-flash-vision-exp')?.countText('DeepSeek Harness')).toMatchObject({
|
|
304
|
+
kind: 'exact-tokenizer',
|
|
305
|
+
tokenizerId: 'deepseek-ai/DeepSeek-V4-Flash-Vision-Exp',
|
|
306
|
+
tokenizerRevision: '6821d6ad3681a4b137b066b76094fa82ebd0a380',
|
|
307
|
+
})
|
|
308
|
+
expect(deepSeekV4TokenizerForModel('deepseek-v4-flash-vision')).toBeUndefined()
|
|
309
|
+
})
|
|
310
|
+
|
|
311
|
+
it.each([
|
|
312
|
+
['off', Number.MAX_SAFE_INTEGER],
|
|
313
|
+
['native', Number.MAX_SAFE_INTEGER],
|
|
314
|
+
['balanced', 500_000],
|
|
315
|
+
['cache-strict', 600_000],
|
|
316
|
+
['savings', 400_000],
|
|
317
|
+
['adaptive', 500_000],
|
|
318
|
+
] as const)('resolves %s with the shared 10-call and 64k token-tail History working set', (profile, trigger) => {
|
|
319
|
+
const policy = resolvePolicy(resolveConfig(), profile)
|
|
320
|
+
|
|
321
|
+
expect(policy.historyTriggerTokens).toBe(trigger)
|
|
322
|
+
expect(policy.historyKeepRecentToolCalls).toBe(10)
|
|
323
|
+
expect(policy.historyKeepRecentTokens).toBe(64_000)
|
|
324
|
+
})
|
|
325
|
+
|
|
326
|
+
it.each([
|
|
327
|
+
'balanced',
|
|
328
|
+
'cache-strict',
|
|
329
|
+
'savings',
|
|
330
|
+
'adaptive',
|
|
331
|
+
'custom',
|
|
332
|
+
] as const)('disables native head/middle/tail pruning for %s', (profile) => {
|
|
333
|
+
expect(resolvePolicy(resolveConfig(), profile).nativeToolResultEnabled).toBe(false)
|
|
334
|
+
})
|
|
335
|
+
|
|
336
|
+
it('enables native head/middle/tail pruning only for the Native profile', () => {
|
|
337
|
+
expect(resolvePolicy(resolveConfig(), 'native').nativeToolResultEnabled).toBe(true)
|
|
338
|
+
expect(resolvePolicy(resolveConfig(), 'off').nativeToolResultEnabled).toBe(false)
|
|
339
|
+
})
|
|
340
|
+
|
|
341
|
+
it('lands a standard compaction/prune plus tool-result replacement without custom events', async () => {
|
|
342
|
+
const ctx = await runtimeContext()
|
|
343
|
+
const audit = captureAudit(ctx)
|
|
344
|
+
await ctx.plugin(ToolResultPruner, {
|
|
345
|
+
profile: 'native',
|
|
346
|
+
nativeTriggerTokens: 100,
|
|
347
|
+
nativeTargetTokens: 64,
|
|
348
|
+
headChars: 8,
|
|
349
|
+
tailChars: 8,
|
|
350
|
+
}).await()
|
|
351
|
+
const pruner = ctx.toolResultPruner
|
|
352
|
+
const session = Session.create(SessionId('public-native-prune'))
|
|
353
|
+
const source = appendToolTurn(session, 1, 'x'.repeat(8_000), false)
|
|
354
|
+
const view = measureForCompaction(ctx, session)
|
|
355
|
+
expect(ctx.tools.get('context_compression_retrieve')).toBeDefined()
|
|
356
|
+
expect(view.currentSurface.kind).toBe('exact-tokenizer')
|
|
357
|
+
if (view.currentSurface.kind === 'exact-tokenizer') {
|
|
358
|
+
expect(view.currentSurface.tokens).toBeGreaterThan(100)
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
const result = pruner.pruneSession(session, { stage: 'pressure' })
|
|
362
|
+
|
|
363
|
+
expect(result.pruned).toHaveLength(1)
|
|
364
|
+
const manifest = sessionEvents(session).at(-2)
|
|
365
|
+
const replacement = sessionEvents(session).at(-1)
|
|
366
|
+
expect(manifest?.type).toBe('compaction/prune')
|
|
367
|
+
expect(sessionEvents(session).some(event => event.type === ('compaction/group-trim' as string))).toBe(false)
|
|
368
|
+
expect(replacement?.type).toBe('tool/result')
|
|
369
|
+
if (replacement?.type !== 'tool/result') throw new Error('Native prune did not append a tool result replacement')
|
|
370
|
+
expect(replacement.surfaceOp).toEqual({
|
|
371
|
+
op: 'replace',
|
|
372
|
+
startSeq: source.resultSeq,
|
|
373
|
+
endSeq: source.resultSeq,
|
|
374
|
+
})
|
|
375
|
+
expect(replacement.sourceEventSeqs).toContain(source.resultSeq)
|
|
376
|
+
expect(rewrites(audit.records())).toContainEqual(expect.objectContaining({
|
|
377
|
+
component: 'native-tool-result',
|
|
378
|
+
stage: 'pressure',
|
|
379
|
+
manifestSeq: manifest?.seq,
|
|
380
|
+
replacementSeq: replacement?.seq,
|
|
381
|
+
tokensBefore: expect.any(Number),
|
|
382
|
+
tokensAfter: expect.any(Number),
|
|
383
|
+
}))
|
|
384
|
+
})
|
|
385
|
+
|
|
386
|
+
it('proves isolated Fresh with exact before/after audit evidence', async () => {
|
|
387
|
+
const ctx = await runtimeContext()
|
|
388
|
+
const audit = captureAudit(ctx)
|
|
389
|
+
await ctx.plugin(ToolResultPruner, {
|
|
390
|
+
profile: 'balanced',
|
|
391
|
+
freshTriggerTokens: 100,
|
|
392
|
+
freshTargetTokens: 64,
|
|
393
|
+
aggregateTriggerTokens: 100_000,
|
|
394
|
+
aggregateTargetTokens: 90_000,
|
|
395
|
+
historyTriggerTokens: 100_000,
|
|
396
|
+
}).await()
|
|
397
|
+
const session = Session.create(SessionId('public-fresh-e2e'))
|
|
398
|
+
appendToolTurn(session, 1, 'fresh evidence '.repeat(1_000), false, undefined, 'deepseek-official')
|
|
399
|
+
|
|
400
|
+
const result = ctx.toolResultPruner.pruneSession(session, {
|
|
401
|
+
stage: 'fresh',
|
|
402
|
+
freshTurn: 1,
|
|
403
|
+
freshStep: 1,
|
|
404
|
+
})
|
|
405
|
+
|
|
406
|
+
expect(result.pruned).toHaveLength(1)
|
|
407
|
+
const record = rewrites(audit.records()).find(entry => entry.component === 'fresh')
|
|
408
|
+
expect(record).toMatchObject({
|
|
409
|
+
stage: 'fresh',
|
|
410
|
+
reducer: expect.any(String),
|
|
411
|
+
manifestEventType: 'compaction/prune',
|
|
412
|
+
tokenizerId: expect.any(String),
|
|
413
|
+
tokenizerRevision: expect.any(String),
|
|
414
|
+
})
|
|
415
|
+
expect(record?.tokensBefore).toBeGreaterThan(100)
|
|
416
|
+
expect(record?.tokensAfter).toBeLessThanOrEqual(64)
|
|
417
|
+
expect(record?.tokensRemoved).toBe((record?.tokensBefore ?? 0) - (record?.tokensAfter ?? 0))
|
|
418
|
+
})
|
|
419
|
+
|
|
420
|
+
it('tokenpilot-inspired default threshold lands a fresh replace end-to-end (no explicit override)', async () => {
|
|
421
|
+
const ctx = await runtimeContext()
|
|
422
|
+
const audit = captureAudit(ctx)
|
|
423
|
+
// No freshTriggerTokens passed → the profile default governs. The lowered
|
|
424
|
+
// default (4096) must reduce a large fresh result through the real cordis
|
|
425
|
+
// path, mirroring what the desktop panel observes at turn tail.
|
|
426
|
+
await ctx.plugin(ToolResultPruner, { profile: 'tokenpilot-inspired' }).await()
|
|
427
|
+
const session = Session.create(SessionId('public-tokenpilot-default-fresh'))
|
|
428
|
+
const fixture = Array.from({ length: 1_200 }, (_, index) =>
|
|
429
|
+
`row ${String(index)} :: ${['alpha', 'bravo', 'charlie', 'delta', 'echo'][index % 5]}-${String((index * 7) % 997)} payload ${String(index)}`).join('\n')
|
|
430
|
+
appendToolTurn(session, 1, fixture, false, undefined, 'deepseek-official')
|
|
431
|
+
|
|
432
|
+
const result = ctx.toolResultPruner.pruneSession(session, {
|
|
433
|
+
stage: 'fresh',
|
|
434
|
+
freshTurn: 1,
|
|
435
|
+
freshStep: 1,
|
|
436
|
+
})
|
|
437
|
+
|
|
438
|
+
expect(result.pruned.length).toBeGreaterThanOrEqual(1)
|
|
439
|
+
const record = rewrites(audit.records()).find(entry => entry.component === 'fresh')
|
|
440
|
+
expect(record).toBeDefined()
|
|
441
|
+
expect(record?.reducer).toEqual(expect.any(String))
|
|
442
|
+
})
|
|
443
|
+
|
|
444
|
+
it('tokenpilot-inspired lands a fresh replace on an UNAVAILABLE-tokenizer route (local Qwen)', async () => {
|
|
445
|
+
const ctx = await runtimeContext()
|
|
446
|
+
const audit = captureAudit(ctx)
|
|
447
|
+
await ctx.plugin(ToolResultPruner, { profile: 'tokenpilot-inspired' }).await()
|
|
448
|
+
const session = Session.create(SessionId('public-tokenpilot-qwen-fresh'))
|
|
449
|
+
// A ~40KB JSONL result — the exact shape the desktop test feeds. local-35 has
|
|
450
|
+
// no bundled tokenizer, so every node count is 'unavailable' and the fresh
|
|
451
|
+
// gate + land must run entirely on the character basis.
|
|
452
|
+
const jsonl = Array.from({ length: 150 }, (_, index) =>
|
|
453
|
+
JSON.stringify({ qid: index, question: `Janet's ducks lay ${index} eggs. How many remain after ${index + 3}?`, answer: `step ${index} ... #### ${index * 2}` })).join('\n')
|
|
454
|
+
appendToolTurn(session, 1, jsonl, false, undefined, 'local-35', 'Qwen3.6-35B-A3B')
|
|
455
|
+
|
|
456
|
+
const result = ctx.toolResultPruner.pruneSession(session, {
|
|
457
|
+
stage: 'fresh',
|
|
458
|
+
freshTurn: 1,
|
|
459
|
+
freshStep: 1,
|
|
460
|
+
})
|
|
461
|
+
|
|
462
|
+
const record = rewrites(audit.records()).find(entry => entry.component === 'fresh')
|
|
463
|
+
console.log('QWEN_FRESH pruned=', result.pruned.length, 'reducer=', record?.reducer ?? 'none', 'basis=', record?.measurementBasis ?? 'none')
|
|
464
|
+
expect(result.pruned.length).toBeGreaterThanOrEqual(1)
|
|
465
|
+
})
|
|
466
|
+
|
|
467
|
+
it('threads the reducer elided-line count from a fresh plan into the rewrite audit', async () => {
|
|
468
|
+
// The skeleton reducer counts the lines it hid behind elision markers; that
|
|
469
|
+
// count must survive the whole planning middle (plan options → planned
|
|
470
|
+
// replacement → audit record) without ever touching the replacement text.
|
|
471
|
+
const ctx = await runtimeContext()
|
|
472
|
+
await ctx.plugin(TestSettings).await()
|
|
473
|
+
await ctx.plugin(LegacyNamespaceRegistrar).await()
|
|
474
|
+
await ctx.settings.update(nsBrand(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE), {
|
|
475
|
+
profile: 'balanced',
|
|
476
|
+
codeSkeleton: { enabled: true },
|
|
477
|
+
})
|
|
478
|
+
const audit = captureAudit(ctx)
|
|
479
|
+
await ctx.plugin(ToolResultPruner, {
|
|
480
|
+
profile: 'balanced',
|
|
481
|
+
freshTriggerTokens: 1_000,
|
|
482
|
+
freshTargetTokens: 800,
|
|
483
|
+
aggregateTriggerTokens: 500_000,
|
|
484
|
+
aggregateTargetTokens: 450_000,
|
|
485
|
+
historyTriggerTokens: 500_000,
|
|
486
|
+
}).await()
|
|
487
|
+
const session = Session.create(SessionId('public-fresh-elided-lines'))
|
|
488
|
+
const fixture = [
|
|
489
|
+
"import { readFile } from 'node:fs/promises'",
|
|
490
|
+
'',
|
|
491
|
+
...Array.from({ length: 40 }, (_, index) => [
|
|
492
|
+
`export function handler${String(index)}(input: string): string {`,
|
|
493
|
+
` const normalized = input.trim().toLowerCase()`,
|
|
494
|
+
` if (normalized.length === 0) return 'empty-${String(index)}'`,
|
|
495
|
+
` return normalized.split('-').join('+')`,
|
|
496
|
+
'}',
|
|
497
|
+
'',
|
|
498
|
+
]).flat(),
|
|
499
|
+
].join('\n')
|
|
500
|
+
appendToolTurn(session, 1, fixture, false, undefined, 'deepseek-official', MODEL, 'read')
|
|
501
|
+
|
|
502
|
+
const result = ctx.toolResultPruner.pruneSession(session, {
|
|
503
|
+
stage: 'fresh',
|
|
504
|
+
freshTurn: 1,
|
|
505
|
+
freshStep: 1,
|
|
506
|
+
})
|
|
507
|
+
|
|
508
|
+
expect(result.pruned).toHaveLength(1)
|
|
509
|
+
expect(result.pruned[0]?.reducer).toBe('hypa-code-skeleton')
|
|
510
|
+
const record = rewrites(audit.records()).find(entry => entry.component === 'fresh')
|
|
511
|
+
expect(record?.reducer).toBe('hypa-code-skeleton')
|
|
512
|
+
expect(record?.elidedLines).toEqual(expect.any(Number))
|
|
513
|
+
expect(record?.elidedLines).toBeGreaterThan(0)
|
|
514
|
+
expect(Number.isInteger(record?.elidedLines)).toBe(true)
|
|
515
|
+
expect(record?.tokensBefore).toBeGreaterThan(1_000)
|
|
516
|
+
expect(record?.tokensAfter).toBeLessThanOrEqual(800)
|
|
517
|
+
})
|
|
518
|
+
|
|
519
|
+
it('proves isolated Aggregate while Fresh and History remain below their gates', async () => {
|
|
520
|
+
const ctx = await runtimeContext()
|
|
521
|
+
const audit = captureAudit(ctx)
|
|
522
|
+
await ctx.plugin(ToolResultPruner, {
|
|
523
|
+
profile: 'balanced',
|
|
524
|
+
freshTriggerTokens: 100_000,
|
|
525
|
+
freshTargetTokens: 90_000,
|
|
526
|
+
aggregateTriggerTokens: 100,
|
|
527
|
+
aggregateTargetTokens: 64,
|
|
528
|
+
historyTriggerTokens: 100_000,
|
|
529
|
+
}).await()
|
|
530
|
+
const session = Session.create(SessionId('public-aggregate-e2e'))
|
|
531
|
+
appendToolTurn(session, 1, 'aggregate evidence '.repeat(1_000), false, undefined, 'deepseek-official')
|
|
532
|
+
|
|
533
|
+
const result = ctx.toolResultPruner.pruneSession(session, {
|
|
534
|
+
stage: 'fresh',
|
|
535
|
+
freshTurn: 1,
|
|
536
|
+
freshStep: 1,
|
|
537
|
+
})
|
|
538
|
+
|
|
539
|
+
expect(result.pruned).toHaveLength(1)
|
|
540
|
+
const record = rewrites(audit.records()).find(entry => entry.component === 'aggregate')
|
|
541
|
+
expect(record).toMatchObject({
|
|
542
|
+
stage: 'fresh',
|
|
543
|
+
reducer: 'fresh-step-aggregate',
|
|
544
|
+
manifestEventType: 'compaction/prune',
|
|
545
|
+
})
|
|
546
|
+
expect(record?.tokensBefore).toBeGreaterThan(100)
|
|
547
|
+
expect(record?.tokensAfter).toBeLessThanOrEqual(64)
|
|
548
|
+
expect(rewrites(audit.records()).some(entry => entry.component === 'fresh')).toBe(false)
|
|
549
|
+
expect(rewrites(audit.records()).some(entry => entry.component === 'history')).toBe(false)
|
|
550
|
+
})
|
|
551
|
+
|
|
552
|
+
it('ages only results outside the recent tool-call and token-tail working set', async () => {
|
|
553
|
+
const ctx = await runtimeContext()
|
|
554
|
+
const session = Session.create(SessionId('public-history-tool-call-working-set'))
|
|
555
|
+
const batch = appendToolBatchTurn(
|
|
556
|
+
session,
|
|
557
|
+
1,
|
|
558
|
+
Array.from({ length: 5 }, () => 'working-set evidence '.repeat(1_000)),
|
|
559
|
+
true,
|
|
560
|
+
)
|
|
561
|
+
session.append('turn/start', { turn: 2 })
|
|
562
|
+
const view = measureForCompaction(ctx, session)
|
|
563
|
+
// Decision gates run on the character basis, so the thresholds below are
|
|
564
|
+
// derived from per-result character pressure and expressed in the
|
|
565
|
+
// token-named settings keys via CHARS_PER_TOKEN.
|
|
566
|
+
const counts = batch.resultSeqs.map((seq) => {
|
|
567
|
+
const entry = view.measuredNodes.find(node => node.seq === seq)
|
|
568
|
+
if (entry === undefined) throw new Error('working-set test needs measured results')
|
|
569
|
+
return entry.characterPressure
|
|
570
|
+
})
|
|
571
|
+
const recentTailChars = counts.slice(-3).reduce((sum, chars) => sum + chars, 0) - 1
|
|
572
|
+
const totalToolChars = counts.reduce((sum, chars) => sum + chars, 0)
|
|
573
|
+
|
|
574
|
+
await ctx.plugin(ToolResultPruner, {
|
|
575
|
+
profile: 'balanced',
|
|
576
|
+
freshTriggerTokens: 100_000,
|
|
577
|
+
freshTargetTokens: 90_000,
|
|
578
|
+
aggregateTriggerTokens: 100_000,
|
|
579
|
+
aggregateTargetTokens: 90_000,
|
|
580
|
+
// The strict required-reclaim gate demands one batch pull tool chars
|
|
581
|
+
// back below the trigger; 72% leaves exactly the two oldest results as
|
|
582
|
+
// the reclaimable margin above the placeholder residue.
|
|
583
|
+
historyTriggerTokens: Math.floor(totalToolChars * 0.72 / CHARS_PER_TOKEN),
|
|
584
|
+
historyKeepRecentToolCalls: 2,
|
|
585
|
+
// 4 x floor(recentTailChars / 4) sits above the two-newest char total
|
|
586
|
+
// and at or below the three-newest total, so the tail protects exactly
|
|
587
|
+
// the three newest results.
|
|
588
|
+
historyKeepRecentTokens: Math.floor(recentTailChars / CHARS_PER_TOKEN),
|
|
589
|
+
historyMinReclaimTokens: 1,
|
|
590
|
+
}).await()
|
|
591
|
+
|
|
592
|
+
const result = ctx.toolResultPruner.pruneSession(session, { stage: 'pressure' })
|
|
593
|
+
|
|
594
|
+
expect(result.pruned).toHaveLength(2)
|
|
595
|
+
expect(result.pruned.map(entry => entry.originalSeq)).toEqual(batch.resultSeqs.slice(0, 2))
|
|
596
|
+
expect(result.pruned.map(entry => entry.originalSeq)).not.toContain(batch.resultSeqs.at(-1))
|
|
597
|
+
expect(result.pruned.map(entry => entry.originalSeq)).not.toContain(batch.resultSeqs.at(-2))
|
|
598
|
+
expect(result.pruned.map(entry => entry.originalSeq)).not.toContain(batch.resultSeqs.at(-3))
|
|
599
|
+
})
|
|
600
|
+
|
|
601
|
+
it('proves isolated routine History against completed old turns', async () => {
|
|
602
|
+
const ctx = await runtimeContext()
|
|
603
|
+
const audit = captureAudit(ctx)
|
|
604
|
+
await ctx.plugin(ToolResultPruner, {
|
|
605
|
+
profile: 'savings',
|
|
606
|
+
freshTriggerTokens: 100_000,
|
|
607
|
+
freshTargetTokens: 90_000,
|
|
608
|
+
aggregateTriggerTokens: 100_000,
|
|
609
|
+
aggregateTargetTokens: 90_000,
|
|
610
|
+
historyTriggerTokens: 1_200,
|
|
611
|
+
historyKeepRecentToolCalls: 0,
|
|
612
|
+
historyKeepRecentTokens: 1,
|
|
613
|
+
historyMinReclaimTokens: 1,
|
|
614
|
+
}).await()
|
|
615
|
+
const session = Session.create(SessionId('public-history-e2e'))
|
|
616
|
+
appendToolTurn(session, 1, 'old historical evidence '.repeat(1_000), true)
|
|
617
|
+
// The one-token recent working-set budget protects at least the newest
|
|
618
|
+
// completed result, so provide a second completed turn and age the oldest.
|
|
619
|
+
appendToolTurn(session, 2, 'newer protected evidence', true)
|
|
620
|
+
session.append('turn/start', { turn: 3 })
|
|
621
|
+
|
|
622
|
+
const result = ctx.toolResultPruner.pruneSession(session, { stage: 'pressure' })
|
|
623
|
+
|
|
624
|
+
expect(result.pruned).toHaveLength(1)
|
|
625
|
+
const record = rewrites(audit.records()).find(entry => entry.component === 'history')
|
|
626
|
+
expect(record).toMatchObject({
|
|
627
|
+
stage: 'pressure',
|
|
628
|
+
historyMode: 'routine',
|
|
629
|
+
manifestEventType: 'compaction/prune',
|
|
630
|
+
})
|
|
631
|
+
expect(record?.tokensBefore).toBeGreaterThan(100)
|
|
632
|
+
expect(record?.tokensAfter).toBeLessThan(record?.tokensBefore ?? 0)
|
|
633
|
+
})
|
|
634
|
+
|
|
635
|
+
it('moves the capacity-pressure gate with the frozen Auto Compact threshold', async () => {
|
|
636
|
+
const ctx = await runtimeContext()
|
|
637
|
+
await ctx.plugin(TestSettings).await()
|
|
638
|
+
await ctx.plugin(LegacyNamespaceRegistrar).await()
|
|
639
|
+
const audit = captureAudit(ctx)
|
|
640
|
+
const namespace = nsBrand(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE)
|
|
641
|
+
|
|
642
|
+
// A high threshold delays the micro-compact last-chance gate past the old
|
|
643
|
+
// fixed 0.7 ratio: pressure between 0.7*C and D must NOT age history.
|
|
644
|
+
await ctx.settings.update(namespace, { profile: 'cache-strict', autoCompact: { thresholdPercent: 90 } })
|
|
645
|
+
await ctx.plugin(ToolResultPruner, {
|
|
646
|
+
profile: 'cache-strict',
|
|
647
|
+
freshTriggerTokens: 100_000,
|
|
648
|
+
freshTargetTokens: 90_000,
|
|
649
|
+
aggregateTriggerTokens: 100_000,
|
|
650
|
+
aggregateTargetTokens: 90_000,
|
|
651
|
+
}).await()
|
|
652
|
+
const delayed = Session.create(SessionId('public-autocompact-90-delayed'))
|
|
653
|
+
appendToolTurn(delayed, 1, 'delayed gate evidence '.repeat(600), true)
|
|
654
|
+
appendToolTurn(delayed, 2, 'newest protected result', true)
|
|
655
|
+
const delayedTotal = measureForCompaction(ctx, delayed).totalTokens
|
|
656
|
+
const delayedWindow = Math.floor(delayedTotal / 0.72)
|
|
657
|
+
delayed.append('request/context', { provider: 'deepseek', model: MODEL, contextWindow: delayedWindow })
|
|
658
|
+
delayed.append('turn/start', { turn: 3 })
|
|
659
|
+
ctx.toolResultPruner.pruneSession(delayed, { stage: 'pressure' })
|
|
660
|
+
expect(rewrites(audit.records()).some(record =>
|
|
661
|
+
record.sessionId === String(delayed.id) && record.component === 'history')).toBe(false)
|
|
662
|
+
expect(audit.records()).toContainEqual(expect.objectContaining({
|
|
663
|
+
kind: 'component-evaluation',
|
|
664
|
+
sessionId: String(delayed.id),
|
|
665
|
+
component: 'history',
|
|
666
|
+
reason: 'below-micro-deadline',
|
|
667
|
+
triggerTokens: Math.floor(Math.floor(delayedWindow * 90 / 100) * 0.875),
|
|
668
|
+
}))
|
|
669
|
+
})
|
|
670
|
+
|
|
671
|
+
it('ages History earlier when the frozen Auto Compact threshold is low', async () => {
|
|
672
|
+
const ctx = await runtimeContext()
|
|
673
|
+
await ctx.plugin(TestSettings).await()
|
|
674
|
+
await ctx.plugin(LegacyNamespaceRegistrar).await()
|
|
675
|
+
const audit = captureAudit(ctx)
|
|
676
|
+
const namespace = nsBrand(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE)
|
|
677
|
+
|
|
678
|
+
// A low threshold pulls the micro-compact deadline below the old fixed
|
|
679
|
+
// 0.7 ratio: pressure between D and 0.7*C must age history now.
|
|
680
|
+
await ctx.settings.update(namespace, { profile: 'cache-strict', autoCompact: { thresholdPercent: 50 } })
|
|
681
|
+
await ctx.plugin(ToolResultPruner, {
|
|
682
|
+
profile: 'cache-strict',
|
|
683
|
+
freshTriggerTokens: 100_000,
|
|
684
|
+
freshTargetTokens: 90_000,
|
|
685
|
+
aggregateTriggerTokens: 100_000,
|
|
686
|
+
aggregateTargetTokens: 90_000,
|
|
687
|
+
historyTriggerTokens: 400,
|
|
688
|
+
historyKeepRecentToolCalls: 0,
|
|
689
|
+
historyKeepRecentTokens: 1,
|
|
690
|
+
historyMinReclaimTokens: 1,
|
|
691
|
+
}).await()
|
|
692
|
+
const early = Session.create(SessionId('public-autocompact-50-early'))
|
|
693
|
+
appendToolTurn(early, 1, 'early gate evidence '.repeat(600), true)
|
|
694
|
+
appendToolTurn(early, 2, 'newest protected result', true)
|
|
695
|
+
const earlyTotal = measureForCompaction(ctx, early).totalTokens
|
|
696
|
+
const earlyWindow = Math.floor(earlyTotal / 0.6)
|
|
697
|
+
early.append('request/context', { provider: 'deepseek', model: MODEL, contextWindow: earlyWindow })
|
|
698
|
+
early.append('turn/start', { turn: 3 })
|
|
699
|
+
ctx.toolResultPruner.pruneSession(early, { stage: 'pressure' })
|
|
700
|
+
|
|
701
|
+
expect(rewrites(audit.records()).some(record =>
|
|
702
|
+
record.sessionId === String(early.id) && record.component === 'history')).toBe(true)
|
|
703
|
+
})
|
|
704
|
+
|
|
705
|
+
it('freezes the generation-owned threshold over later global settings changes', async () => {
|
|
706
|
+
const ctx = await runtimeContext()
|
|
707
|
+
await ctx.plugin(TestSettings).await()
|
|
708
|
+
await ctx.plugin(LegacyNamespaceRegistrar).await()
|
|
709
|
+
const audit = captureAudit(ctx)
|
|
710
|
+
const namespace = nsBrand(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE)
|
|
711
|
+
// The preset overlay captured 70% into this generation's deployment
|
|
712
|
+
// config; the user then moved the global setting to 90 before the first
|
|
713
|
+
// prune. Auto Compact and micro compact must both stay on 70%.
|
|
714
|
+
await ctx.plugin(ToolResultPruner, {
|
|
715
|
+
profile: 'balanced',
|
|
716
|
+
autoCompactThresholdPercent: 70,
|
|
717
|
+
}).await()
|
|
718
|
+
const session = Session.create(SessionId('public-generation-owned-threshold'))
|
|
719
|
+
appendToolTurn(session, 1, 'generation-owned threshold evidence', false)
|
|
720
|
+
session.append('request/context', { provider: 'deepseek', model: MODEL, contextWindow: 1_000_000 })
|
|
721
|
+
await ctx.settings.update(namespace, { profile: 'balanced', autoCompact: { thresholdPercent: 90 } })
|
|
722
|
+
ctx.toolResultPruner.pruneSession(session, { stage: 'fresh', freshTurn: 1, freshStep: 1 })
|
|
723
|
+
|
|
724
|
+
const resolved = audit.records().find(record =>
|
|
725
|
+
record.kind === 'policy-resolved' && record.sessionId === String(session.id))
|
|
726
|
+
expect(resolved).toMatchObject({
|
|
727
|
+
coordination: {
|
|
728
|
+
thresholdPercent: 70,
|
|
729
|
+
autoCompactTokens: 700_000,
|
|
730
|
+
microDeadlineTokens: 612_500,
|
|
731
|
+
},
|
|
732
|
+
})
|
|
733
|
+
const frozen = audit.records().find(record =>
|
|
734
|
+
record.kind === 'policy-frozen' && record.sessionId === String(session.id))
|
|
735
|
+
expect(frozen).toMatchObject({
|
|
736
|
+
autoCompactThresholdSource: 'generation-config',
|
|
737
|
+
settings: { autoCompact: { thresholdPercent: 70 } },
|
|
738
|
+
})
|
|
739
|
+
})
|
|
740
|
+
|
|
741
|
+
it('fails open to a lossless frozen policy when stored settings are malformed', async () => {
|
|
742
|
+
const ctx = await runtimeContext()
|
|
743
|
+
await ctx.plugin(TestSettings).await()
|
|
744
|
+
await ctx.plugin(LegacyNamespaceRegistrar).await()
|
|
745
|
+
const audit = captureAudit(ctx)
|
|
746
|
+
const namespace = nsBrand(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE)
|
|
747
|
+
// A hand-edited store can surface a document the schema rejects (unknown
|
|
748
|
+
// top-level key). The runtime must not fall back to a lossy-capable
|
|
749
|
+
// profile: the session freezes effectively off and keeps every original
|
|
750
|
+
// tool result.
|
|
751
|
+
const malformed = {
|
|
752
|
+
profile: 'off',
|
|
753
|
+
custom: structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY),
|
|
754
|
+
unrelated: true,
|
|
755
|
+
}
|
|
756
|
+
const legacySettings = ctx.settings as unknown as LegacySettingsProvider
|
|
757
|
+
const originalGet = legacySettings.get.bind(legacySettings)
|
|
758
|
+
vi.spyOn(legacySettings, 'get').mockImplementation((ns: unknown) =>
|
|
759
|
+
|
|
760
|
+
ns === undefined || String(ns) === String(namespace) ? structuredClone(malformed) : originalGet(ns as never))
|
|
761
|
+
await ctx.plugin(ToolResultPruner, {
|
|
762
|
+
profile: 'balanced',
|
|
763
|
+
freshTriggerTokens: 10,
|
|
764
|
+
freshTargetTokens: 8,
|
|
765
|
+
}).await()
|
|
766
|
+
const session = Session.create(SessionId('public-malformed-settings-fail-open'))
|
|
767
|
+
appendToolTurn(session, 1, 'malformed settings must not compress '.repeat(300), true)
|
|
768
|
+
session.append('turn/start', { turn: 2 })
|
|
769
|
+
|
|
770
|
+
const result = ctx.toolResultPruner.pruneSession(session, { stage: 'pressure' })
|
|
771
|
+
|
|
772
|
+
expect(result.pruned).toHaveLength(0)
|
|
773
|
+
expect(rewrites(audit.records())).toHaveLength(0)
|
|
774
|
+
const frozen = audit.records().find(record =>
|
|
775
|
+
record.kind === 'policy-frozen' && record.sessionId === String(session.id))
|
|
776
|
+
expect(frozen).toMatchObject({
|
|
777
|
+
settingsInvalidFallback: 'lossless-off',
|
|
778
|
+
settings: { profile: 'off' },
|
|
779
|
+
})
|
|
780
|
+
})
|
|
781
|
+
|
|
782
|
+
it.each([
|
|
783
|
+
['null profile', { profile: null, custom: structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY) }],
|
|
784
|
+
['null custom', { profile: 'balanced', custom: null }],
|
|
785
|
+
['both sections null', { profile: null, custom: null }],
|
|
786
|
+
['own-property undefined profile', { profile: undefined, custom: structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY) }],
|
|
787
|
+
['own-property undefined custom', { profile: 'off', custom: undefined }],
|
|
788
|
+
['profile off plus malformed autoCompact', {
|
|
789
|
+
profile: 'off',
|
|
790
|
+
custom: structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY),
|
|
791
|
+
autoCompact: { thresholdPercent: 400 },
|
|
792
|
+
}],
|
|
793
|
+
])('fails open to a lossless frozen policy when the stored document carries %s', async (label, malformed) => {
|
|
794
|
+
const ctx = await runtimeContext()
|
|
795
|
+
await ctx.plugin(TestSettings).await()
|
|
796
|
+
await ctx.plugin(LegacyNamespaceRegistrar).await()
|
|
797
|
+
const audit = captureAudit(ctx)
|
|
798
|
+
const namespace = nsBrand(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE)
|
|
799
|
+
// Schemastery `.default(...)` would silently replace these present-but-null
|
|
800
|
+
// sections with the balanced/default-v3 policy; the runtime must reject the
|
|
801
|
+
// document and freeze the session losslessly instead.
|
|
802
|
+
const legacySettings = ctx.settings as unknown as LegacySettingsProvider
|
|
803
|
+
const originalGet = legacySettings.get.bind(legacySettings)
|
|
804
|
+
vi.spyOn(legacySettings, 'get').mockImplementation((ns: unknown) =>
|
|
805
|
+
|
|
806
|
+
ns === undefined || String(ns) === String(namespace) ? structuredClone(malformed) : originalGet(ns as never))
|
|
807
|
+
await ctx.plugin(ToolResultPruner, {
|
|
808
|
+
profile: 'balanced',
|
|
809
|
+
freshTriggerTokens: 10,
|
|
810
|
+
freshTargetTokens: 8,
|
|
811
|
+
}).await()
|
|
812
|
+
const session = Session.create(SessionId(`public-null-settings-${label.replace(/\s+/gu, '-')}`))
|
|
813
|
+
appendToolTurn(session, 1, 'null settings must not compress '.repeat(300), true)
|
|
814
|
+
session.append('turn/start', { turn: 2 })
|
|
815
|
+
|
|
816
|
+
const result = ctx.toolResultPruner.pruneSession(session, { stage: 'pressure' })
|
|
817
|
+
|
|
818
|
+
expect(result.pruned).toHaveLength(0)
|
|
819
|
+
expect(rewrites(audit.records())).toHaveLength(0)
|
|
820
|
+
const frozen = audit.records().find(record =>
|
|
821
|
+
record.kind === 'policy-frozen' && record.sessionId === String(session.id))
|
|
822
|
+
expect(frozen).toMatchObject({
|
|
823
|
+
settingsInvalidFallback: 'lossless-off',
|
|
824
|
+
settings: { profile: 'off' },
|
|
825
|
+
})
|
|
826
|
+
})
|
|
827
|
+
|
|
828
|
+
it('validates exotic Host settings before any clone can erase their prototype', async () => {
|
|
829
|
+
class AutoCompactDocument {
|
|
830
|
+
thresholdPercent = 73
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
const ctx = await runtimeContext()
|
|
834
|
+
await ctx.plugin(TestSettings).await()
|
|
835
|
+
await ctx.plugin(LegacyNamespaceRegistrar).await()
|
|
836
|
+
const audit = captureAudit(ctx)
|
|
837
|
+
const namespace = nsBrand(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE)
|
|
838
|
+
const malformed = {
|
|
839
|
+
profile: 'balanced' as const,
|
|
840
|
+
custom: structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY),
|
|
841
|
+
autoCompact: new AutoCompactDocument(),
|
|
842
|
+
}
|
|
843
|
+
const legacySettings = ctx.settings as unknown as LegacySettingsProvider
|
|
844
|
+
const originalGet = legacySettings.get.bind(legacySettings)
|
|
845
|
+
vi.spyOn(legacySettings, 'get').mockImplementation((ns: unknown) =>
|
|
846
|
+
|
|
847
|
+
ns === undefined || String(ns) === String(namespace) ? malformed : originalGet(ns as never))
|
|
848
|
+
await ctx.plugin(ToolResultPruner, {
|
|
849
|
+
profile: 'balanced',
|
|
850
|
+
freshTriggerTokens: 10,
|
|
851
|
+
freshTargetTokens: 8,
|
|
852
|
+
}).await()
|
|
853
|
+
const session = Session.create(SessionId('public-exotic-settings-before-clone'))
|
|
854
|
+
appendToolTurn(session, 1, 'exotic settings must not compress '.repeat(300), false)
|
|
855
|
+
|
|
856
|
+
const result = ctx.toolResultPruner.pruneSession(session, {
|
|
857
|
+
stage: 'fresh',
|
|
858
|
+
freshTurn: 1,
|
|
859
|
+
freshStep: 1,
|
|
860
|
+
})
|
|
861
|
+
|
|
862
|
+
expect(result.pruned).toHaveLength(0)
|
|
863
|
+
expect(rewrites(audit.records())).toHaveLength(0)
|
|
864
|
+
expect(audit.records()).toContainEqual(expect.objectContaining({
|
|
865
|
+
kind: 'policy-frozen',
|
|
866
|
+
sessionId: String(session.id),
|
|
867
|
+
settingsInvalidFallback: 'lossless-off',
|
|
868
|
+
settings: expect.objectContaining({ profile: 'off' }),
|
|
869
|
+
}))
|
|
870
|
+
})
|
|
871
|
+
|
|
872
|
+
it('emits a policy audit again when the route returns to a previous value', async () => {
|
|
873
|
+
const ctx = await runtimeContext()
|
|
874
|
+
const audit = captureAudit(ctx)
|
|
875
|
+
await ctx.plugin(ToolResultPruner, { profile: 'balanced' }).await()
|
|
876
|
+
const session = Session.create(SessionId('public-policy-audit-reroute-aba'))
|
|
877
|
+
const route = (model: string) => session.append('request/header', {
|
|
878
|
+
reason: 'change',
|
|
879
|
+
header: canonicalHeader({ config: { provider: 'deepseek', model } }),
|
|
880
|
+
})
|
|
881
|
+
const prune = (turn: number) => {
|
|
882
|
+
appendToolTurn(session, turn, `route evidence ${String(turn)}`, false)
|
|
883
|
+
ctx.toolResultPruner.pruneSession(session, { stage: 'fresh', freshTurn: turn, freshStep: 1 })
|
|
884
|
+
}
|
|
885
|
+
prune(1)
|
|
886
|
+
route('deepseek-v4-pro')
|
|
887
|
+
prune(2)
|
|
888
|
+
route(MODEL)
|
|
889
|
+
prune(3)
|
|
890
|
+
|
|
891
|
+
const resolved = audit.records().filter((record): record is Extract<CompressionAuditRecord, { kind: 'policy-resolved' }> =>
|
|
892
|
+
record.kind === 'policy-resolved' && record.sessionId === String(session.id))
|
|
893
|
+
expect(resolved).toHaveLength(3)
|
|
894
|
+
expect(resolved.map(record => record.route?.model)).toEqual([MODEL, 'deepseek-v4-pro', MODEL])
|
|
895
|
+
})
|
|
896
|
+
|
|
897
|
+
it('reports no bundled tokenizer for a DeepSeek model behind another provider', async () => {
|
|
898
|
+
const ctx = await runtimeContext()
|
|
899
|
+
const audit = captureAudit(ctx)
|
|
900
|
+
await ctx.plugin(ToolResultPruner, { profile: 'balanced' }).await()
|
|
901
|
+
const session = Session.create(SessionId('public-policy-audit-foreign-provider'))
|
|
902
|
+
appendToolTurn(session, 1, 'foreign provider evidence', false, undefined, 'openai', 'deepseek-v4-pro')
|
|
903
|
+
ctx.toolResultPruner.pruneSession(session, { stage: 'fresh', freshTurn: 1, freshStep: 1 })
|
|
904
|
+
|
|
905
|
+
expect(audit.records()).toContainEqual(expect.objectContaining({
|
|
906
|
+
kind: 'policy-resolved',
|
|
907
|
+
sessionId: String(session.id),
|
|
908
|
+
route: { provider: 'openai', model: 'deepseek-v4-pro' },
|
|
909
|
+
tokenizer: { repository: 'unavailable', revision: 'unavailable' },
|
|
910
|
+
}))
|
|
911
|
+
})
|
|
912
|
+
|
|
913
|
+
it('emits a fresh policy audit when the durable route changes mid-session', async () => {
|
|
914
|
+
const ctx = await runtimeContext()
|
|
915
|
+
const audit = captureAudit(ctx)
|
|
916
|
+
await ctx.plugin(ToolResultPruner, { profile: 'balanced' }).await()
|
|
917
|
+
const session = Session.create(SessionId('public-policy-audit-reroute'))
|
|
918
|
+
appendToolTurn(session, 1, 'first route evidence', false)
|
|
919
|
+
ctx.toolResultPruner.pruneSession(session, { stage: 'fresh', freshTurn: 1, freshStep: 1 })
|
|
920
|
+
session.append('request/header', {
|
|
921
|
+
reason: 'change',
|
|
922
|
+
header: canonicalHeader({ config: { provider: 'deepseek', model: 'deepseek-v4-pro' } }),
|
|
923
|
+
})
|
|
924
|
+
appendToolTurn(session, 2, 'second route evidence', false, undefined, 'deepseek', 'deepseek-v4-pro')
|
|
925
|
+
ctx.toolResultPruner.pruneSession(session, { stage: 'fresh', freshTurn: 2, freshStep: 1 })
|
|
926
|
+
|
|
927
|
+
const resolved = audit.records().filter(record =>
|
|
928
|
+
record.kind === 'policy-resolved' && record.sessionId === String(session.id))
|
|
929
|
+
expect(resolved).toHaveLength(2)
|
|
930
|
+
expect(resolved[0]).toMatchObject({ route: { model: MODEL } })
|
|
931
|
+
expect(resolved[1]).toMatchObject({ route: { model: 'deepseek-v4-pro' } })
|
|
932
|
+
})
|
|
933
|
+
|
|
934
|
+
it('audits the Auto Compact coordination block on policy resolution', async () => {
|
|
935
|
+
const ctx = await runtimeContext()
|
|
936
|
+
await ctx.plugin(TestSettings).await()
|
|
937
|
+
await ctx.plugin(LegacyNamespaceRegistrar).await()
|
|
938
|
+
const audit = captureAudit(ctx)
|
|
939
|
+
const namespace = nsBrand(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE)
|
|
940
|
+
await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 73 } })
|
|
941
|
+
await ctx.plugin(ToolResultPruner, { profile: 'balanced' }).await()
|
|
942
|
+
const session = Session.create(SessionId('public-autocompact-coordination'))
|
|
943
|
+
appendToolTurn(session, 1, 'coordination audit evidence', false)
|
|
944
|
+
session.append('request/context', { provider: 'deepseek', model: MODEL, contextWindow: 1_000_000 })
|
|
945
|
+
ctx.toolResultPruner.pruneSession(session, { stage: 'fresh', freshTurn: 1, freshStep: 1 })
|
|
946
|
+
|
|
947
|
+
const resolved = audit.records().find(record =>
|
|
948
|
+
record.kind === 'policy-resolved' && record.sessionId === String(session.id))
|
|
949
|
+
expect(resolved).toMatchObject({
|
|
950
|
+
policy: {
|
|
951
|
+
autoCompactTokens: 730_000,
|
|
952
|
+
microDeadlineTokens: 638_750,
|
|
953
|
+
historyTriggerTokens: 456_250,
|
|
954
|
+
},
|
|
955
|
+
contextWindowTokens: 1_000_000,
|
|
956
|
+
coordination: {
|
|
957
|
+
thresholdPercent: 73,
|
|
958
|
+
autoCompactTokens: 730_000,
|
|
959
|
+
microDeadlineTokens: 638_750,
|
|
960
|
+
paramSource: 'auto-compact-linked',
|
|
961
|
+
},
|
|
962
|
+
route: { provider: 'deepseek', model: MODEL },
|
|
963
|
+
tokenizer: {
|
|
964
|
+
repository: 'deepseek-ai/DeepSeek-V4-Pro',
|
|
965
|
+
revision: DEEPSEEK_V4_TOKENIZER_ARTIFACT.revision,
|
|
966
|
+
},
|
|
967
|
+
})
|
|
968
|
+
|
|
969
|
+
// Deployment config overriding every linked History watermark must audit
|
|
970
|
+
// itself as deployment-override, not as linkage-derived.
|
|
971
|
+
const overrideCtx = await runtimeContext()
|
|
972
|
+
await overrideCtx.plugin(TestSettings).await()
|
|
973
|
+
await overrideCtx.plugin(SelectorHost).await()
|
|
974
|
+
await overrideCtx.plugin(LegacyNamespaceRegistrar).await()
|
|
975
|
+
const overrideAudit = captureAudit(overrideCtx)
|
|
976
|
+
await overrideCtx.settings.update(namespace, { autoCompact: { thresholdPercent: 73 } })
|
|
977
|
+
await overrideCtx.plugin(ToolResultPruner, {
|
|
978
|
+
profile: 'balanced',
|
|
979
|
+
historyTriggerTokens: 123_456,
|
|
980
|
+
historyKeepRecentTokens: 12_345,
|
|
981
|
+
historyMinReclaimTokens: 1_234,
|
|
982
|
+
}).await()
|
|
983
|
+
const overrideSession = Session.create(SessionId('public-autocompact-deployment-override'))
|
|
984
|
+
appendToolTurn(overrideSession, 1, 'deployment override evidence', false)
|
|
985
|
+
overrideSession.append('request/context', { provider: 'deepseek', model: MODEL, contextWindow: 1_000_000 })
|
|
986
|
+
overrideCtx.toolResultPruner.pruneSession(overrideSession, { stage: 'fresh', freshTurn: 1, freshStep: 1 })
|
|
987
|
+
expect(overrideAudit.records()).toContainEqual(expect.objectContaining({
|
|
988
|
+
kind: 'policy-resolved',
|
|
989
|
+
sessionId: String(overrideSession.id),
|
|
990
|
+
coordination: expect.objectContaining({
|
|
991
|
+
microDeadlineTokens: 638_750,
|
|
992
|
+
paramSource: 'deployment-override',
|
|
993
|
+
}),
|
|
994
|
+
}))
|
|
995
|
+
|
|
996
|
+
// A partial override of the linked watermarks reads as mixed.
|
|
997
|
+
const mixedCtx = await runtimeContext()
|
|
998
|
+
await mixedCtx.plugin(TestSettings).await()
|
|
999
|
+
await mixedCtx.plugin(SelectorHost).await()
|
|
1000
|
+
await mixedCtx.plugin(LegacyNamespaceRegistrar).await()
|
|
1001
|
+
const mixedAudit = captureAudit(mixedCtx)
|
|
1002
|
+
await mixedCtx.settings.update(namespace, { autoCompact: { thresholdPercent: 73 } })
|
|
1003
|
+
await mixedCtx.plugin(ToolResultPruner, {
|
|
1004
|
+
profile: 'balanced',
|
|
1005
|
+
historyTriggerTokens: 123_456,
|
|
1006
|
+
}).await()
|
|
1007
|
+
const mixedSession = Session.create(SessionId('public-autocompact-mixed-source'))
|
|
1008
|
+
appendToolTurn(mixedSession, 1, 'mixed source evidence', false)
|
|
1009
|
+
mixedSession.append('request/context', { provider: 'deepseek', model: MODEL, contextWindow: 1_000_000 })
|
|
1010
|
+
mixedCtx.toolResultPruner.pruneSession(mixedSession, { stage: 'fresh', freshTurn: 1, freshStep: 1 })
|
|
1011
|
+
expect(mixedAudit.records()).toContainEqual(expect.objectContaining({
|
|
1012
|
+
kind: 'policy-resolved',
|
|
1013
|
+
sessionId: String(mixedSession.id),
|
|
1014
|
+
coordination: expect.objectContaining({
|
|
1015
|
+
microDeadlineTokens: 638_750,
|
|
1016
|
+
paramSource: 'mixed',
|
|
1017
|
+
}),
|
|
1018
|
+
}))
|
|
1019
|
+
|
|
1020
|
+
// A route without a verified bundled tokenizer reports the unavailable
|
|
1021
|
+
// identity instead of inventing one.
|
|
1022
|
+
const unknown = Session.create(SessionId('public-autocompact-unknown-route'))
|
|
1023
|
+
appendToolTurn(unknown, 1, 'unknown route evidence', false, undefined, 'deepseek', 'some-other-model')
|
|
1024
|
+
ctx.toolResultPruner.pruneSession(unknown, { stage: 'fresh', freshTurn: 1, freshStep: 1 })
|
|
1025
|
+
expect(audit.records()).toContainEqual(expect.objectContaining({
|
|
1026
|
+
kind: 'policy-resolved',
|
|
1027
|
+
sessionId: String(unknown.id),
|
|
1028
|
+
route: { provider: 'deepseek', model: 'some-other-model' },
|
|
1029
|
+
tokenizer: { repository: 'unavailable', revision: 'unavailable' },
|
|
1030
|
+
}))
|
|
1031
|
+
})
|
|
1032
|
+
|
|
1033
|
+
it('freezes the Auto Compact threshold per Session and applies new values only to new Sessions', async () => {
|
|
1034
|
+
const ctx = await runtimeContext()
|
|
1035
|
+
await ctx.plugin(TestSettings).await()
|
|
1036
|
+
await ctx.plugin(LegacyNamespaceRegistrar).await()
|
|
1037
|
+
const audit = captureAudit(ctx)
|
|
1038
|
+
const namespace = nsBrand(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE)
|
|
1039
|
+
await ctx.plugin(ToolResultPruner, { profile: 'balanced' }).await()
|
|
1040
|
+
|
|
1041
|
+
const first = Session.create(SessionId('public-autocompact-freeze-first'))
|
|
1042
|
+
appendToolTurn(first, 1, 'frozen threshold evidence', false)
|
|
1043
|
+
first.append('request/context', { provider: 'deepseek', model: MODEL, contextWindow: 1_000_000 })
|
|
1044
|
+
ctx.toolResultPruner.pruneSession(first, { stage: 'fresh', freshTurn: 1, freshStep: 1 })
|
|
1045
|
+
|
|
1046
|
+
await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 73 } })
|
|
1047
|
+
|
|
1048
|
+
const second = Session.create(SessionId('public-autocompact-freeze-second'))
|
|
1049
|
+
appendToolTurn(second, 1, 'new threshold evidence', false)
|
|
1050
|
+
second.append('request/context', { provider: 'deepseek', model: MODEL, contextWindow: 1_000_000 })
|
|
1051
|
+
ctx.toolResultPruner.pruneSession(second, { stage: 'fresh', freshTurn: 1, freshStep: 1 })
|
|
1052
|
+
|
|
1053
|
+
// The already-observed session keeps its frozen 80% policy even after
|
|
1054
|
+
// another prune; only the new session adopts 73%.
|
|
1055
|
+
first.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
|
|
1056
|
+
appendToolTurn(first, 2, 'post-change frozen evidence', false)
|
|
1057
|
+
first.append('request/context', { provider: 'deepseek', model: MODEL, contextWindow: 1_000_000 })
|
|
1058
|
+
ctx.toolResultPruner.pruneSession(first, { stage: 'fresh', freshTurn: 2, freshStep: 1 })
|
|
1059
|
+
|
|
1060
|
+
const resolvedFor = (sessionId: string) => audit.records().find(record =>
|
|
1061
|
+
record.kind === 'policy-resolved' && record.sessionId === sessionId)
|
|
1062
|
+
expect(resolvedFor(String(first.id))).toMatchObject({
|
|
1063
|
+
coordination: { thresholdPercent: 80, autoCompactTokens: 800_000, microDeadlineTokens: 700_000 },
|
|
1064
|
+
})
|
|
1065
|
+
expect(resolvedFor(String(second.id))).toMatchObject({
|
|
1066
|
+
coordination: { thresholdPercent: 73, autoCompactTokens: 730_000, microDeadlineTokens: 638_750 },
|
|
1067
|
+
})
|
|
1068
|
+
expect(audit.records().filter(record =>
|
|
1069
|
+
record.kind === 'policy-resolved'
|
|
1070
|
+
&& record.sessionId === String(first.id)
|
|
1071
|
+
&& record.coordination?.thresholdPercent === 73)).toHaveLength(0)
|
|
1072
|
+
})
|
|
1073
|
+
|
|
1074
|
+
it('ages History through the full-request last-chance gate even below the profile trigger', async () => {
|
|
1075
|
+
const ctx = await runtimeContext()
|
|
1076
|
+
const audit = captureAudit(ctx)
|
|
1077
|
+
await ctx.plugin(ToolResultPruner, {
|
|
1078
|
+
profile: 'balanced',
|
|
1079
|
+
freshTriggerTokens: 100_000,
|
|
1080
|
+
freshTargetTokens: 90_000,
|
|
1081
|
+
aggregateTriggerTokens: 100_000,
|
|
1082
|
+
aggregateTargetTokens: 90_000,
|
|
1083
|
+
historyTriggerTokens: 100_000,
|
|
1084
|
+
historyKeepRecentToolCalls: 0,
|
|
1085
|
+
historyKeepRecentTokens: 1,
|
|
1086
|
+
historyMinReclaimTokens: 1,
|
|
1087
|
+
}).await()
|
|
1088
|
+
const session = Session.create(SessionId('public-history-last-chance'))
|
|
1089
|
+
session.append('turn/start', { turn: 1 })
|
|
1090
|
+
session.append('request/header', {
|
|
1091
|
+
reason: 'initial',
|
|
1092
|
+
header: canonicalHeader({ config: { provider: 'deepseek', model: MODEL } }),
|
|
1093
|
+
})
|
|
1094
|
+
// Non-tool prose carries the full request past the deadline while the
|
|
1095
|
+
// tool results alone stay far below the linked profile trigger.
|
|
1096
|
+
session.append('user/message', createUserMessage({
|
|
1097
|
+
content: [{ type: 'text', text: 'pressure prose '.repeat(1_000) }],
|
|
1098
|
+
source: { kind: 'user' },
|
|
1099
|
+
}), { surfaceOp: 'append' })
|
|
1100
|
+
session.append('step/start', { turn: 1, step: 1 })
|
|
1101
|
+
session.append('assistant/message', {
|
|
1102
|
+
stream: [],
|
|
1103
|
+
turn: 1,
|
|
1104
|
+
step: 1,
|
|
1105
|
+
message: createMessage({
|
|
1106
|
+
role: 'assistant',
|
|
1107
|
+
content: [{ type: 'tool-call', id: CallId('last-chance-old'), name: 'bash', arguments: '{}' }],
|
|
1108
|
+
source: { kind: 'model', provider: 'deepseek', model: MODEL },
|
|
1109
|
+
}),
|
|
1110
|
+
}, { surfaceOp: 'append' })
|
|
1111
|
+
session.append('tool/call', { turn: 1, step: 1, callId: CallId('last-chance-old'), name: 'bash', arguments: '{}' })
|
|
1112
|
+
session.append('tool/result', {
|
|
1113
|
+
turn: 1,
|
|
1114
|
+
step: 1,
|
|
1115
|
+
message: createToolResultMessage({
|
|
1116
|
+
callId: CallId('last-chance-old'),
|
|
1117
|
+
content: [{ type: 'text', text: 'last-chance aging evidence '.repeat(700) }],
|
|
1118
|
+
isError: false,
|
|
1119
|
+
}),
|
|
1120
|
+
}, { surfaceOp: 'append' })
|
|
1121
|
+
session.append('step/end', { turn: 1, step: 1 })
|
|
1122
|
+
session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
|
|
1123
|
+
appendToolTurn(session, 2, 'newest protected result', true)
|
|
1124
|
+
// 80% default on a 10,000-token window: A = 8000, linked H = 5000, D = 7000.
|
|
1125
|
+
session.append('request/context', { provider: 'deepseek', model: MODEL, contextWindow: 10_000 })
|
|
1126
|
+
session.append('turn/start', { turn: 3 })
|
|
1127
|
+
|
|
1128
|
+
const before = measureForCompaction(ctx, session)
|
|
1129
|
+
const toolResultTokens = before.measuredNodes
|
|
1130
|
+
.filter(node => sessionEvents(session)[node.seq]?.type === 'tool/result')
|
|
1131
|
+
.reduce((sum, node) => sum + (node.count.kind === 'exact-tokenizer' ? node.count.tokens : 0), 0)
|
|
1132
|
+
// Deadline D = 7000 is reached by the complete request, not by the tool
|
|
1133
|
+
// results, which stay far below every trigger in force.
|
|
1134
|
+
expect(before.totalTokens).toBeGreaterThanOrEqual(7_000)
|
|
1135
|
+
expect(toolResultTokens).toBeLessThan(7_000)
|
|
1136
|
+
|
|
1137
|
+
const result = ctx.toolResultPruner.pruneSession(session, { stage: 'pressure' })
|
|
1138
|
+
|
|
1139
|
+
const aged = rewrites(audit.records()).filter(record =>
|
|
1140
|
+
record.sessionId === String(session.id) && record.component === 'history')
|
|
1141
|
+
expect(aged.length).toBeGreaterThanOrEqual(1)
|
|
1142
|
+
expect(result.pruned.length).toBeGreaterThanOrEqual(1)
|
|
1143
|
+
})
|
|
1144
|
+
|
|
1145
|
+
it.each(['balanced', 'adaptive'] as const)(
|
|
1146
|
+
'skips a linked History batch that cannot reach its reclaim target in %s mode',
|
|
1147
|
+
async (profile) => {
|
|
1148
|
+
const ctx = await runtimeContext()
|
|
1149
|
+
const audit = captureAudit(ctx)
|
|
1150
|
+
await ctx.plugin(ToolResultPruner, {
|
|
1151
|
+
profile,
|
|
1152
|
+
freshTriggerTokens: 100_000,
|
|
1153
|
+
freshTargetTokens: 90_000,
|
|
1154
|
+
aggregateTriggerTokens: 100_000,
|
|
1155
|
+
aggregateTargetTokens: 90_000,
|
|
1156
|
+
historyTriggerTokens: 100,
|
|
1157
|
+
historyKeepRecentToolCalls: 0,
|
|
1158
|
+
historyKeepRecentTokens: 1,
|
|
1159
|
+
historyMinReclaimTokens: 1,
|
|
1160
|
+
}).await()
|
|
1161
|
+
|
|
1162
|
+
// Below the deadline: the excess above the trigger sits mostly in the
|
|
1163
|
+
// protected newest result, so the only reclaimable batch is far too small.
|
|
1164
|
+
const below = Session.create(SessionId(`public-history-insufficient-reclaim-${profile}`))
|
|
1165
|
+
appendToolTurn(below, 1, 'unreachable reclaim evidence '.repeat(400), true)
|
|
1166
|
+
appendToolTurn(below, 2, 'newest protected bulk '.repeat(600), true)
|
|
1167
|
+
below.append('request/context', { provider: 'deepseek', model: MODEL, contextWindow: 10_000 })
|
|
1168
|
+
below.append('turn/start', { turn: 3 })
|
|
1169
|
+
const belowResult = ctx.toolResultPruner.pruneSession(below, { stage: 'pressure' })
|
|
1170
|
+
expect(belowResult.pruned).toHaveLength(0)
|
|
1171
|
+
expect(rewrites(audit.records()).some(record =>
|
|
1172
|
+
record.sessionId === String(below.id) && record.component === 'history')).toBe(false)
|
|
1173
|
+
expect(audit.records()).toContainEqual(expect.objectContaining({
|
|
1174
|
+
kind: 'component-evaluation',
|
|
1175
|
+
sessionId: String(below.id),
|
|
1176
|
+
component: 'history',
|
|
1177
|
+
status: 'skipped',
|
|
1178
|
+
reason: 'insufficient-reclaim',
|
|
1179
|
+
reclaimTokens: expect.any(Number),
|
|
1180
|
+
requiredTokens: expect.any(Number),
|
|
1181
|
+
}))
|
|
1182
|
+
|
|
1183
|
+
// Past the deadline with tool tokens below the trigger: the last-chance
|
|
1184
|
+
// gate engages planning, and the skip names the deadline target.
|
|
1185
|
+
const past = Session.create(SessionId(`public-history-deadline-unreachable-${profile}`))
|
|
1186
|
+
past.append('turn/start', { turn: 1 })
|
|
1187
|
+
past.append('request/header', {
|
|
1188
|
+
reason: 'initial',
|
|
1189
|
+
header: canonicalHeader({ config: { provider: 'deepseek', model: MODEL } }),
|
|
1190
|
+
})
|
|
1191
|
+
past.append('user/message', createUserMessage({
|
|
1192
|
+
content: [{ type: 'text', text: 'deadline pressure prose '.repeat(2_000) }],
|
|
1193
|
+
source: { kind: 'user' },
|
|
1194
|
+
}), { surfaceOp: 'append' })
|
|
1195
|
+
appendToolTurn(past, 1, 'deadline unreachable evidence '.repeat(400), true)
|
|
1196
|
+
appendToolTurn(past, 2, 'newest protected bulk '.repeat(600), true)
|
|
1197
|
+
past.append('request/context', { provider: 'deepseek', model: MODEL, contextWindow: 10_000 })
|
|
1198
|
+
past.append('turn/start', { turn: 2 })
|
|
1199
|
+
const pastResult = ctx.toolResultPruner.pruneSession(past, { stage: 'pressure' })
|
|
1200
|
+
expect(pastResult.pruned).toHaveLength(0)
|
|
1201
|
+
expect(rewrites(audit.records()).some(record =>
|
|
1202
|
+
record.sessionId === String(past.id) && record.component === 'history')).toBe(false)
|
|
1203
|
+
expect(audit.records()).toContainEqual(expect.objectContaining({
|
|
1204
|
+
kind: 'component-evaluation',
|
|
1205
|
+
sessionId: String(past.id),
|
|
1206
|
+
component: 'history',
|
|
1207
|
+
status: 'skipped',
|
|
1208
|
+
reason: 'cannot-reach-deadline-target',
|
|
1209
|
+
triggerTokens: 7_000,
|
|
1210
|
+
}))
|
|
1211
|
+
},
|
|
1212
|
+
)
|
|
1213
|
+
|
|
1214
|
+
it.each(['balanced', 'adaptive'] as const)(
|
|
1215
|
+
'audits below-profile-trigger in %s mode when the tool-result total sits under the History trigger',
|
|
1216
|
+
async (profile) => {
|
|
1217
|
+
const ctx = await runtimeContext()
|
|
1218
|
+
const audit = captureAudit(ctx)
|
|
1219
|
+
await ctx.plugin(ToolResultPruner, {
|
|
1220
|
+
profile,
|
|
1221
|
+
freshTriggerTokens: 100_000,
|
|
1222
|
+
freshTargetTokens: 90_000,
|
|
1223
|
+
aggregateTriggerTokens: 100_000,
|
|
1224
|
+
aggregateTargetTokens: 90_000,
|
|
1225
|
+
historyTriggerTokens: 100_000,
|
|
1226
|
+
historyKeepRecentToolCalls: 0,
|
|
1227
|
+
historyKeepRecentTokens: 1,
|
|
1228
|
+
historyMinReclaimTokens: 1,
|
|
1229
|
+
}).await()
|
|
1230
|
+
const session = Session.create(SessionId(`public-history-below-profile-trigger-${profile}`))
|
|
1231
|
+
appendToolTurn(session, 1, 'small routine evidence', true)
|
|
1232
|
+
session.append('turn/start', { turn: 2 })
|
|
1233
|
+
ctx.toolResultPruner.pruneSession(session, { stage: 'pressure' })
|
|
1234
|
+
expect(audit.records()).toContainEqual(expect.objectContaining({
|
|
1235
|
+
kind: 'component-evaluation',
|
|
1236
|
+
sessionId: String(session.id),
|
|
1237
|
+
component: 'history',
|
|
1238
|
+
status: 'skipped',
|
|
1239
|
+
reason: 'below-profile-trigger',
|
|
1240
|
+
triggerTokens: 100_000,
|
|
1241
|
+
}))
|
|
1242
|
+
},
|
|
1243
|
+
)
|
|
1244
|
+
|
|
1245
|
+
it.each(['balanced', 'adaptive'] as const)(
|
|
1246
|
+
'audits protected-working-set in %s mode when every safe candidate is inside the protected tail',
|
|
1247
|
+
async (profile) => {
|
|
1248
|
+
const ctx = await runtimeContext()
|
|
1249
|
+
const audit = captureAudit(ctx)
|
|
1250
|
+
await ctx.plugin(ToolResultPruner, {
|
|
1251
|
+
profile,
|
|
1252
|
+
freshTriggerTokens: 100_000,
|
|
1253
|
+
freshTargetTokens: 90_000,
|
|
1254
|
+
aggregateTriggerTokens: 100_000,
|
|
1255
|
+
aggregateTargetTokens: 90_000,
|
|
1256
|
+
historyTriggerTokens: 100,
|
|
1257
|
+
historyKeepRecentToolCalls: 10,
|
|
1258
|
+
historyKeepRecentTokens: 1_000_000,
|
|
1259
|
+
historyMinReclaimTokens: 1,
|
|
1260
|
+
}).await()
|
|
1261
|
+
const session = Session.create(SessionId(`public-history-protected-working-set-${profile}`))
|
|
1262
|
+
appendToolTurn(session, 1, 'protected working set evidence '.repeat(300), true)
|
|
1263
|
+
appendToolTurn(session, 2, 'newest protected result '.repeat(300), true)
|
|
1264
|
+
session.append('turn/start', { turn: 3 })
|
|
1265
|
+
const result = ctx.toolResultPruner.pruneSession(session, { stage: 'pressure' })
|
|
1266
|
+
expect(result.pruned).toHaveLength(0)
|
|
1267
|
+
expect(audit.records()).toContainEqual(expect.objectContaining({
|
|
1268
|
+
kind: 'component-evaluation',
|
|
1269
|
+
sessionId: String(session.id),
|
|
1270
|
+
component: 'history',
|
|
1271
|
+
status: 'skipped',
|
|
1272
|
+
reason: 'protected-working-set',
|
|
1273
|
+
}))
|
|
1274
|
+
},
|
|
1275
|
+
)
|
|
1276
|
+
|
|
1277
|
+
it.each(['balanced', 'adaptive'] as const)(
|
|
1278
|
+
'audits no-safe-candidates in %s mode when the only tool results are recovery-tool output',
|
|
1279
|
+
async (profile) => {
|
|
1280
|
+
const ctx = await runtimeContext()
|
|
1281
|
+
const audit = captureAudit(ctx)
|
|
1282
|
+
await ctx.plugin(ToolResultPruner, {
|
|
1283
|
+
profile,
|
|
1284
|
+
freshTriggerTokens: 100_000,
|
|
1285
|
+
freshTargetTokens: 90_000,
|
|
1286
|
+
aggregateTriggerTokens: 100_000,
|
|
1287
|
+
aggregateTargetTokens: 90_000,
|
|
1288
|
+
historyTriggerTokens: 100,
|
|
1289
|
+
historyKeepRecentToolCalls: 0,
|
|
1290
|
+
historyKeepRecentTokens: 1,
|
|
1291
|
+
historyMinReclaimTokens: 1,
|
|
1292
|
+
}).await()
|
|
1293
|
+
const session = Session.create(SessionId(`public-history-no-safe-candidates-${profile}`))
|
|
1294
|
+
// One ordinary turn (protected by nothing) plus one recovery-tool output:
|
|
1295
|
+
// filtering only unsafe candidates leaves the ordinary result, so this
|
|
1296
|
+
// first pass must NOT read as no-safe-candidates.
|
|
1297
|
+
appendToolTurn(session, 1, 'ordinary reclaimable evidence '.repeat(300), true)
|
|
1298
|
+
const turn = 2
|
|
1299
|
+
const callId = CallId('recovery-call')
|
|
1300
|
+
session.append('turn/start', { turn })
|
|
1301
|
+
session.append('step/start', { turn, step: 1 })
|
|
1302
|
+
session.append('assistant/message', {
|
|
1303
|
+
stream: [],
|
|
1304
|
+
turn,
|
|
1305
|
+
step: 1,
|
|
1306
|
+
message: createMessage({
|
|
1307
|
+
role: 'assistant',
|
|
1308
|
+
content: [{ type: 'tool-call', id: callId, name: 'context_compression_retrieve', arguments: '{}' }],
|
|
1309
|
+
source: { kind: 'model', provider: 'deepseek', model: MODEL },
|
|
1310
|
+
}),
|
|
1311
|
+
}, { surfaceOp: 'append' })
|
|
1312
|
+
session.append('tool/call', { turn, step: 1, callId, name: 'context_compression_retrieve', arguments: '{}' })
|
|
1313
|
+
session.append('tool/result', {
|
|
1314
|
+
turn,
|
|
1315
|
+
step: 1,
|
|
1316
|
+
message: createToolResultMessage({
|
|
1317
|
+
callId,
|
|
1318
|
+
content: [{ type: 'text', text: 'recovered original group '.repeat(300) }],
|
|
1319
|
+
isError: false,
|
|
1320
|
+
}),
|
|
1321
|
+
}, { surfaceOp: 'append' })
|
|
1322
|
+
session.append('step/end', { turn, step: 1 })
|
|
1323
|
+
session.append('turn/end', { turn, reason: { kind: 'completed' } })
|
|
1324
|
+
session.append('turn/start', { turn: 3 })
|
|
1325
|
+
ctx.toolResultPruner.pruneSession(session, { stage: 'pressure' })
|
|
1326
|
+
// The ordinary result remains a safe candidate. Balanced commits it;
|
|
1327
|
+
// Adaptive may reject its real plan on cost, but neither profile may
|
|
1328
|
+
// misreport this mixed set as no-safe-candidates.
|
|
1329
|
+
expect(audit.records().some(record => record.kind === 'component-evaluation'
|
|
1330
|
+
&& record.sessionId === String(session.id)
|
|
1331
|
+
&& record.component === 'history'
|
|
1332
|
+
&& record.reason === 'no-safe-candidates')).toBe(false)
|
|
1333
|
+
if (profile === 'balanced') {
|
|
1334
|
+
expect(rewrites(audit.records()).some(record =>
|
|
1335
|
+
record.sessionId === String(session.id) && record.component === 'history')).toBe(true)
|
|
1336
|
+
} else {
|
|
1337
|
+
expect(audit.records()).toContainEqual(expect.objectContaining({
|
|
1338
|
+
kind: 'component-evaluation',
|
|
1339
|
+
sessionId: String(session.id),
|
|
1340
|
+
component: 'history',
|
|
1341
|
+
reason: 'adaptive-cost-rejected',
|
|
1342
|
+
}))
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
const onlyUnsafe = Session.create(SessionId(`public-history-no-safe-candidates-only-${profile}`))
|
|
1346
|
+
onlyUnsafe.append('turn/start', { turn: 1 })
|
|
1347
|
+
onlyUnsafe.append('request/header', {
|
|
1348
|
+
reason: 'initial',
|
|
1349
|
+
header: canonicalHeader({ config: { provider: 'deepseek', model: MODEL } }),
|
|
1350
|
+
})
|
|
1351
|
+
onlyUnsafe.append('step/start', { turn: 1, step: 1 })
|
|
1352
|
+
onlyUnsafe.append('assistant/message', {
|
|
1353
|
+
stream: [],
|
|
1354
|
+
turn: 1,
|
|
1355
|
+
step: 1,
|
|
1356
|
+
message: createMessage({
|
|
1357
|
+
role: 'assistant',
|
|
1358
|
+
content: [{ type: 'tool-call', id: callId, name: 'context_compression_retrieve', arguments: '{}' }],
|
|
1359
|
+
source: { kind: 'model', provider: 'deepseek', model: MODEL },
|
|
1360
|
+
}),
|
|
1361
|
+
}, { surfaceOp: 'append' })
|
|
1362
|
+
onlyUnsafe.append('tool/call', { turn: 1, step: 1, callId, name: 'context_compression_retrieve', arguments: '{}' })
|
|
1363
|
+
onlyUnsafe.append('tool/result', {
|
|
1364
|
+
turn: 1,
|
|
1365
|
+
step: 1,
|
|
1366
|
+
message: createToolResultMessage({
|
|
1367
|
+
callId,
|
|
1368
|
+
content: [{ type: 'text', text: 'only recovery output lives here '.repeat(300) }],
|
|
1369
|
+
isError: false,
|
|
1370
|
+
}),
|
|
1371
|
+
}, { surfaceOp: 'append' })
|
|
1372
|
+
onlyUnsafe.append('step/end', { turn: 1, step: 1 })
|
|
1373
|
+
onlyUnsafe.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
|
|
1374
|
+
onlyUnsafe.append('turn/start', { turn: 2 })
|
|
1375
|
+
ctx.toolResultPruner.pruneSession(onlyUnsafe, { stage: 'pressure' })
|
|
1376
|
+
expect(audit.records()).toContainEqual(expect.objectContaining({
|
|
1377
|
+
kind: 'component-evaluation',
|
|
1378
|
+
sessionId: String(onlyUnsafe.id),
|
|
1379
|
+
component: 'history',
|
|
1380
|
+
status: 'skipped',
|
|
1381
|
+
reason: 'no-safe-candidates',
|
|
1382
|
+
}))
|
|
1383
|
+
},
|
|
1384
|
+
)
|
|
1385
|
+
|
|
1386
|
+
it('audits adaptive-cost-rejected when the adaptive estimate refuses the batch', async () => {
|
|
1387
|
+
const ctx = await runtimeContext()
|
|
1388
|
+
const audit = captureAudit(ctx)
|
|
1389
|
+
await ctx.plugin(ToolResultPruner, {
|
|
1390
|
+
profile: 'adaptive',
|
|
1391
|
+
freshTriggerTokens: 100_000,
|
|
1392
|
+
freshTargetTokens: 90_000,
|
|
1393
|
+
aggregateTriggerTokens: 100_000,
|
|
1394
|
+
aggregateTargetTokens: 90_000,
|
|
1395
|
+
historyTriggerTokens: 100,
|
|
1396
|
+
historyKeepRecentToolCalls: 0,
|
|
1397
|
+
historyKeepRecentTokens: 1,
|
|
1398
|
+
historyMinReclaimTokens: 1,
|
|
1399
|
+
}).await()
|
|
1400
|
+
const session = Session.create(SessionId('public-history-adaptive-cost-rejected'))
|
|
1401
|
+
appendToolTurn(session, 1, 'adaptive rejected evidence '.repeat(300), true)
|
|
1402
|
+
appendToolTurn(session, 2, 'newest adaptive working-set evidence', true)
|
|
1403
|
+
session.append('turn/start', { turn: 3 })
|
|
1404
|
+
ctx.toolResultPruner.pruneSession(session, { stage: 'pressure' })
|
|
1405
|
+
expect(audit.records()).toContainEqual(expect.objectContaining({
|
|
1406
|
+
kind: 'component-evaluation',
|
|
1407
|
+
sessionId: String(session.id),
|
|
1408
|
+
component: 'history',
|
|
1409
|
+
status: 'skipped',
|
|
1410
|
+
reason: 'adaptive-cost-rejected',
|
|
1411
|
+
historyMode: 'adaptive',
|
|
1412
|
+
}))
|
|
1413
|
+
})
|
|
1414
|
+
|
|
1415
|
+
it('preserves below-profile-trigger when Adaptive planning never forms a batch', async () => {
|
|
1416
|
+
const ctx = await runtimeContext()
|
|
1417
|
+
const audit = captureAudit(ctx)
|
|
1418
|
+
await ctx.plugin(ToolResultPruner, {
|
|
1419
|
+
profile: 'adaptive',
|
|
1420
|
+
freshTriggerTokens: 100_000,
|
|
1421
|
+
freshTargetTokens: 90_000,
|
|
1422
|
+
aggregateTriggerTokens: 100_000,
|
|
1423
|
+
aggregateTargetTokens: 90_000,
|
|
1424
|
+
historyTriggerTokens: 100_000,
|
|
1425
|
+
historyKeepRecentToolCalls: 0,
|
|
1426
|
+
historyKeepRecentTokens: 1,
|
|
1427
|
+
historyMinReclaimTokens: 1,
|
|
1428
|
+
}).await()
|
|
1429
|
+
const session = Session.create(SessionId('public-history-adaptive-below-trigger'))
|
|
1430
|
+
appendToolTurn(session, 1, 'small adaptive evidence', true)
|
|
1431
|
+
session.append('turn/start', { turn: 2 })
|
|
1432
|
+
ctx.toolResultPruner.pruneSession(session, { stage: 'pressure' })
|
|
1433
|
+
expect(audit.records()).toContainEqual(expect.objectContaining({
|
|
1434
|
+
kind: 'component-evaluation',
|
|
1435
|
+
sessionId: String(session.id),
|
|
1436
|
+
component: 'history',
|
|
1437
|
+
status: 'skipped',
|
|
1438
|
+
reason: 'below-profile-trigger',
|
|
1439
|
+
historyMode: 'adaptive',
|
|
1440
|
+
triggerTokens: 100_000,
|
|
1441
|
+
}))
|
|
1442
|
+
})
|
|
1443
|
+
|
|
1444
|
+
it('audits adaptive-cost-rejected on the character basis when the authority lacks request telemetry', async () => {
|
|
1445
|
+
const ctx = await runtimeContext()
|
|
1446
|
+
const audit = captureAudit(ctx)
|
|
1447
|
+
await ctx.plugin(ToolResultPruner, {
|
|
1448
|
+
profile: 'adaptive',
|
|
1449
|
+
freshTriggerTokens: 100_000,
|
|
1450
|
+
freshTargetTokens: 90_000,
|
|
1451
|
+
aggregateTriggerTokens: 100_000,
|
|
1452
|
+
aggregateTargetTokens: 90_000,
|
|
1453
|
+
historyTriggerTokens: 100,
|
|
1454
|
+
historyKeepRecentToolCalls: 0,
|
|
1455
|
+
// A zero tail budget keeps nothing in the char-basis protection loop
|
|
1456
|
+
// (0 < 0 is false), so the batch can actually form.
|
|
1457
|
+
historyKeepRecentTokens: 0,
|
|
1458
|
+
historyMinReclaimTokens: 1,
|
|
1459
|
+
}).await()
|
|
1460
|
+
const session = Session.create(SessionId('public-history-adaptive-exact-unavailable'))
|
|
1461
|
+
appendToolTurn(
|
|
1462
|
+
session,
|
|
1463
|
+
1,
|
|
1464
|
+
'unknown adaptive model evidence '.repeat(300),
|
|
1465
|
+
true,
|
|
1466
|
+
undefined,
|
|
1467
|
+
'deepseek',
|
|
1468
|
+
'unsupported-public-model',
|
|
1469
|
+
)
|
|
1470
|
+
session.append('turn/start', { turn: 2 })
|
|
1471
|
+
ctx.toolResultPruner.pruneSession(session, { stage: 'pressure' })
|
|
1472
|
+
// Planning now succeeds on the character basis; the batch is refused by
|
|
1473
|
+
// the adaptive cost authority (no adjacent request telemetry), not by a
|
|
1474
|
+
// missing exact count.
|
|
1475
|
+
expect(audit.records()).toContainEqual(expect.objectContaining({
|
|
1476
|
+
kind: 'component-evaluation',
|
|
1477
|
+
sessionId: String(session.id),
|
|
1478
|
+
component: 'history',
|
|
1479
|
+
status: 'skipped',
|
|
1480
|
+
reason: 'adaptive-cost-rejected',
|
|
1481
|
+
historyMode: 'adaptive',
|
|
1482
|
+
measurementKind: 'characters',
|
|
1483
|
+
}))
|
|
1484
|
+
})
|
|
1485
|
+
|
|
1486
|
+
it('plans and lands History on the character basis when counts are not exact', async () => {
|
|
1487
|
+
const ctx = await runtimeContext()
|
|
1488
|
+
const audit = captureAudit(ctx)
|
|
1489
|
+
await ctx.plugin(ToolResultPruner, {
|
|
1490
|
+
profile: 'balanced',
|
|
1491
|
+
freshTriggerTokens: 100_000,
|
|
1492
|
+
freshTargetTokens: 90_000,
|
|
1493
|
+
aggregateTriggerTokens: 100_000,
|
|
1494
|
+
aggregateTargetTokens: 90_000,
|
|
1495
|
+
historyTriggerTokens: 100,
|
|
1496
|
+
historyKeepRecentToolCalls: 0,
|
|
1497
|
+
historyKeepRecentTokens: 0,
|
|
1498
|
+
historyMinReclaimTokens: 1,
|
|
1499
|
+
}).await()
|
|
1500
|
+
const session = Session.create(SessionId('public-history-exact-unavailable'))
|
|
1501
|
+
appendToolTurn(session, 1, 'unknown model history evidence '.repeat(300), true, undefined, 'deepseek', 'unsupported-public-model')
|
|
1502
|
+
session.append('turn/start', { turn: 2 })
|
|
1503
|
+
ctx.toolResultPruner.pruneSession(session, { stage: 'pressure' })
|
|
1504
|
+
// A committed batch forms from character pressure alone and lands, because
|
|
1505
|
+
// this pruner registers its own recovery tool. The sibling case below drops
|
|
1506
|
+
// the tool registry to exercise the recovery-tool-unavailable path.
|
|
1507
|
+
expect(audit.records()).toContainEqual(expect.objectContaining({
|
|
1508
|
+
kind: 'rewrite',
|
|
1509
|
+
sessionId: String(session.id),
|
|
1510
|
+
component: 'history',
|
|
1511
|
+
reducer: 'historical-tool-result-aging',
|
|
1512
|
+
measurementBasis: 'characters',
|
|
1513
|
+
tokenizerId: 'characters',
|
|
1514
|
+
tokenizerRevision: 'chars-per-token-4.0',
|
|
1515
|
+
}))
|
|
1516
|
+
// The character basis never claims an exact tokenizer it does not have.
|
|
1517
|
+
expect(audit.records().some(record =>
|
|
1518
|
+
record.kind === 'rewrite' && record.measurementBasis === 'exact-tokenizer')).toBe(false)
|
|
1519
|
+
})
|
|
1520
|
+
|
|
1521
|
+
it('audits recovery-tool-unavailable when a committed batch cannot land without the recovery tool', async () => {
|
|
1522
|
+
const ctx = new Context()
|
|
1523
|
+
activeContexts.push(ctx)
|
|
1524
|
+
await ctx.plugin(SessionStore).await()
|
|
1525
|
+
await ctx.plugin(SystemPrompt).await()
|
|
1526
|
+
await ctx.plugin(SessionProjectionRegistry).await()
|
|
1527
|
+
await ctx.plugin(TokenMeter).await()
|
|
1528
|
+
const audit = captureAudit(ctx)
|
|
1529
|
+
await ctx.plugin(ToolResultPruner, {
|
|
1530
|
+
profile: 'balanced',
|
|
1531
|
+
freshTriggerTokens: 100_000,
|
|
1532
|
+
freshTargetTokens: 90_000,
|
|
1533
|
+
aggregateTriggerTokens: 100_000,
|
|
1534
|
+
aggregateTargetTokens: 90_000,
|
|
1535
|
+
historyTriggerTokens: 100,
|
|
1536
|
+
historyKeepRecentToolCalls: 0,
|
|
1537
|
+
historyKeepRecentTokens: 1,
|
|
1538
|
+
historyMinReclaimTokens: 1,
|
|
1539
|
+
}).await()
|
|
1540
|
+
const session = Session.create(SessionId('public-history-recovery-tool-unavailable'))
|
|
1541
|
+
// The newest result stays inside the protected tail; the older one plans a
|
|
1542
|
+
// committed batch that cannot land without the recovery tool.
|
|
1543
|
+
appendToolTurn(session, 1, 'committed batch without recovery tool '.repeat(300), true)
|
|
1544
|
+
appendToolTurn(session, 2, 'newest protected result', true)
|
|
1545
|
+
session.append('turn/start', { turn: 3 })
|
|
1546
|
+
const result = ctx.toolResultPruner.pruneSession(session, { stage: 'pressure' })
|
|
1547
|
+
expect(result.pruned).toHaveLength(0)
|
|
1548
|
+
expect(audit.records()).toContainEqual(expect.objectContaining({
|
|
1549
|
+
kind: 'component-evaluation',
|
|
1550
|
+
sessionId: String(session.id),
|
|
1551
|
+
component: 'history',
|
|
1552
|
+
status: 'skipped',
|
|
1553
|
+
reason: 'recovery-tool-unavailable',
|
|
1554
|
+
}))
|
|
1555
|
+
})
|
|
1556
|
+
|
|
1557
|
+
it('still commits unlinked Custom History batches at the minimum reclaim', async () => {
|
|
1558
|
+
const ctx = await runtimeContext()
|
|
1559
|
+
await ctx.plugin(TestSettings).await()
|
|
1560
|
+
await ctx.plugin(LegacyNamespaceRegistrar).await()
|
|
1561
|
+
const audit = captureAudit(ctx)
|
|
1562
|
+
// A protected token tail larger than the trigger leaves the linked-style
|
|
1563
|
+
// whole-excess demand unreachable; Custom stays manual and must still
|
|
1564
|
+
// commit once a batch passes its explicit minimum reclaim.
|
|
1565
|
+
const custom = structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY) as CustomCompressionPolicy
|
|
1566
|
+
if (custom.version !== 3) throw new Error('unlinked Custom fixture requires policy v3')
|
|
1567
|
+
custom.fresh = { enabled: true, trigger: 1_000_000, target: 900_000 }
|
|
1568
|
+
custom.aggregate = { enabled: true, trigger: 1_000_000, target: 900_000 }
|
|
1569
|
+
custom.history = {
|
|
1570
|
+
enabled: true,
|
|
1571
|
+
trigger: 20_000,
|
|
1572
|
+
keepRecentToolCalls: 2,
|
|
1573
|
+
keepRecentTokens: 30_000,
|
|
1574
|
+
minReclaim: 1_000,
|
|
1575
|
+
}
|
|
1576
|
+
custom.prefixPolicy = 'pressure-break'
|
|
1577
|
+
custom.tailTrim = { enabled: false, trigger: 700_000 }
|
|
1578
|
+
await ctx.settings.update(nsBrand(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE), {
|
|
1579
|
+
profile: 'custom',
|
|
1580
|
+
custom,
|
|
1581
|
+
})
|
|
1582
|
+
await ctx.plugin(ToolResultPruner, { profile: 'custom' }).await()
|
|
1583
|
+
|
|
1584
|
+
const session = Session.create(SessionId('public-custom-min-reclaim-commit'))
|
|
1585
|
+
// Five results of ~14k tokens: the 30k token tail plus 2 newest calls
|
|
1586
|
+
// protect the newest three, leaving two old results reclaimable.
|
|
1587
|
+
appendToolTurn(session, 1, 'custom old reclaimable evidence '.repeat(3_000), true)
|
|
1588
|
+
appendToolTurn(session, 2, 'custom old reclaimable evidence '.repeat(3_000), true)
|
|
1589
|
+
appendToolTurn(session, 3, 'custom newer reclaimable evidence '.repeat(3_000), true)
|
|
1590
|
+
appendToolTurn(session, 4, 'custom newer reclaimable evidence '.repeat(3_000), true)
|
|
1591
|
+
appendToolTurn(session, 5, 'custom newest protected evidence '.repeat(3_000), true)
|
|
1592
|
+
session.append('turn/start', { turn: 6 })
|
|
1593
|
+
|
|
1594
|
+
const result = ctx.toolResultPruner.pruneSession(session, { stage: 'pressure' })
|
|
1595
|
+
|
|
1596
|
+
expect(result.pruned.length).toBeGreaterThanOrEqual(1)
|
|
1597
|
+
expect(rewrites(audit.records()).some(record =>
|
|
1598
|
+
record.sessionId === String(session.id) && record.component === 'history')).toBe(true)
|
|
1599
|
+
})
|
|
1600
|
+
|
|
1601
|
+
it('distinguishes inactive and active History capacity-pressure from durable route capacity', async () => {
|
|
1602
|
+
const ctx = await runtimeContext()
|
|
1603
|
+
const audit = captureAudit(ctx)
|
|
1604
|
+
await ctx.plugin(ToolResultPruner, {
|
|
1605
|
+
profile: 'cache-strict',
|
|
1606
|
+
freshTriggerTokens: 100_000,
|
|
1607
|
+
freshTargetTokens: 90_000,
|
|
1608
|
+
aggregateTriggerTokens: 100_000,
|
|
1609
|
+
aggregateTargetTokens: 90_000,
|
|
1610
|
+
historyTriggerTokens: 400,
|
|
1611
|
+
historyKeepRecentToolCalls: 0,
|
|
1612
|
+
historyKeepRecentTokens: 1,
|
|
1613
|
+
historyMinReclaimTokens: 1,
|
|
1614
|
+
}).await()
|
|
1615
|
+
|
|
1616
|
+
const belowCapacityGate = Session.create(SessionId('public-history-capacity-inactive'))
|
|
1617
|
+
appendToolTurn(belowCapacityGate, 1, 'capacity inactive evidence '.repeat(600), true)
|
|
1618
|
+
appendToolTurn(belowCapacityGate, 2, 'newest protected result', true)
|
|
1619
|
+
belowCapacityGate.append('request/context', {
|
|
1620
|
+
provider: 'deepseek',
|
|
1621
|
+
model: MODEL,
|
|
1622
|
+
contextWindow: 1_000_000,
|
|
1623
|
+
})
|
|
1624
|
+
belowCapacityGate.append('turn/start', { turn: 3 })
|
|
1625
|
+
ctx.toolResultPruner.pruneSession(belowCapacityGate, { stage: 'pressure' })
|
|
1626
|
+
|
|
1627
|
+
expect(rewrites(audit.records()).some(record =>
|
|
1628
|
+
record.sessionId === String(belowCapacityGate.id) && record.component === 'history')).toBe(false)
|
|
1629
|
+
expect(audit.records()).toContainEqual(expect.objectContaining({
|
|
1630
|
+
kind: 'component-evaluation',
|
|
1631
|
+
sessionId: String(belowCapacityGate.id),
|
|
1632
|
+
component: 'history',
|
|
1633
|
+
status: 'skipped',
|
|
1634
|
+
reason: 'below-micro-deadline',
|
|
1635
|
+
historyMode: 'capacity-pressure',
|
|
1636
|
+
}))
|
|
1637
|
+
|
|
1638
|
+
const aboveCapacityGate = Session.create(SessionId('public-history-capacity-active'))
|
|
1639
|
+
appendToolTurn(aboveCapacityGate, 1, 'capacity active evidence '.repeat(600), true)
|
|
1640
|
+
appendToolTurn(aboveCapacityGate, 2, 'newest protected result', true)
|
|
1641
|
+
const capacityWindow = Math.floor(measureForCompaction(ctx, aboveCapacityGate).totalTokens / 0.75)
|
|
1642
|
+
aboveCapacityGate.append('request/context', {
|
|
1643
|
+
provider: 'deepseek',
|
|
1644
|
+
model: MODEL,
|
|
1645
|
+
contextWindow: capacityWindow,
|
|
1646
|
+
})
|
|
1647
|
+
aboveCapacityGate.append('turn/start', { turn: 3 })
|
|
1648
|
+
ctx.toolResultPruner.pruneSession(aboveCapacityGate, { stage: 'pressure' })
|
|
1649
|
+
|
|
1650
|
+
expect(rewrites(audit.records())).toContainEqual(expect.objectContaining({
|
|
1651
|
+
sessionId: String(aboveCapacityGate.id),
|
|
1652
|
+
component: 'history',
|
|
1653
|
+
stage: 'pressure',
|
|
1654
|
+
historyMode: 'capacity-pressure',
|
|
1655
|
+
}))
|
|
1656
|
+
})
|
|
1657
|
+
|
|
1658
|
+
it('runs Cache Strict capacity-pressure History through the real agent pre-step boundary', async () => {
|
|
1659
|
+
const ctx = new Context()
|
|
1660
|
+
activeContexts.push(ctx)
|
|
1661
|
+
await mountAgentLoopTestDependencies(ctx)
|
|
1662
|
+
await ctx.plugin(AgentLoop, { agents: [] })
|
|
1663
|
+
await ctx.plugin(TokenMeter).await()
|
|
1664
|
+
const audit = captureAudit(ctx)
|
|
1665
|
+
ctx.llm.registerAdapter(
|
|
1666
|
+
['deepseek'],
|
|
1667
|
+
new NativeSummaryAdapter(['Cache Strict pressure pass complete'], 100),
|
|
1668
|
+
)
|
|
1669
|
+
await ctx.plugin(ToolResultPruner, {
|
|
1670
|
+
profile: 'cache-strict',
|
|
1671
|
+
freshTriggerTokens: 100_000,
|
|
1672
|
+
freshTargetTokens: 90_000,
|
|
1673
|
+
aggregateTriggerTokens: 100_000,
|
|
1674
|
+
aggregateTargetTokens: 90_000,
|
|
1675
|
+
historyTriggerTokens: 400,
|
|
1676
|
+
historyKeepRecentToolCalls: 0,
|
|
1677
|
+
historyKeepRecentTokens: 1,
|
|
1678
|
+
historyMinReclaimTokens: 1,
|
|
1679
|
+
}).await()
|
|
1680
|
+
|
|
1681
|
+
const agent = await ctx.agentLoop.create(SessionId('public-history-capacity-request-boundary'), {
|
|
1682
|
+
provider: 'deepseek',
|
|
1683
|
+
model: MODEL,
|
|
1684
|
+
})
|
|
1685
|
+
const { session } = agent
|
|
1686
|
+
appendToolTurn(session, 1, 'old capacity-pressure evidence '.repeat(600), true)
|
|
1687
|
+
appendToolTurn(session, 2, 'newest protected result', true)
|
|
1688
|
+
const boundaryTotal = measureForCompaction(ctx, session).totalTokens
|
|
1689
|
+
session.append('request/context', {
|
|
1690
|
+
provider: 'deepseek',
|
|
1691
|
+
model: MODEL,
|
|
1692
|
+
// Just under the frozen 80% deadline D = 0.7 * window, so the gate is
|
|
1693
|
+
// active while the reclaim target stays reachable for one old result.
|
|
1694
|
+
contextWindow: Math.floor(boundaryTotal / 0.72),
|
|
1695
|
+
})
|
|
1696
|
+
|
|
1697
|
+
agent.followup(createUserMessage({
|
|
1698
|
+
content: [{ type: 'text', text: 'run Cache Strict pressure pass' }],
|
|
1699
|
+
source: { kind: 'user' },
|
|
1700
|
+
}))
|
|
1701
|
+
await agent.whenIdle()
|
|
1702
|
+
|
|
1703
|
+
expect(rewrites(audit.records())).toContainEqual(expect.objectContaining({
|
|
1704
|
+
sessionId: String(session.id),
|
|
1705
|
+
component: 'history',
|
|
1706
|
+
stage: 'pressure',
|
|
1707
|
+
historyMode: 'capacity-pressure',
|
|
1708
|
+
}))
|
|
1709
|
+
})
|
|
1710
|
+
|
|
1711
|
+
it('audits enabled-but-below-trigger without claiming a rewrite', async () => {
|
|
1712
|
+
const ctx = await runtimeContext()
|
|
1713
|
+
const audit = captureAudit(ctx)
|
|
1714
|
+
await ctx.plugin(ToolResultPruner, {
|
|
1715
|
+
profile: 'balanced',
|
|
1716
|
+
freshTriggerTokens: 100_000,
|
|
1717
|
+
freshTargetTokens: 90_000,
|
|
1718
|
+
aggregateTriggerTokens: 100_000,
|
|
1719
|
+
aggregateTargetTokens: 90_000,
|
|
1720
|
+
historyTriggerTokens: 100_000,
|
|
1721
|
+
}).await()
|
|
1722
|
+
const session = Session.create(SessionId('public-below-trigger-audit'))
|
|
1723
|
+
appendToolTurn(session, 1, 'small evidence', false)
|
|
1724
|
+
|
|
1725
|
+
ctx.toolResultPruner.pruneSession(session, {
|
|
1726
|
+
stage: 'fresh',
|
|
1727
|
+
freshTurn: 1,
|
|
1728
|
+
freshStep: 1,
|
|
1729
|
+
})
|
|
1730
|
+
|
|
1731
|
+
expect(rewrites(audit.records())).toHaveLength(0)
|
|
1732
|
+
expect(audit.records()).toContainEqual(expect.objectContaining({
|
|
1733
|
+
kind: 'component-evaluation',
|
|
1734
|
+
component: 'fresh',
|
|
1735
|
+
status: 'skipped',
|
|
1736
|
+
reason: 'at-or-below-trigger',
|
|
1737
|
+
currentTokens: expect.any(Number),
|
|
1738
|
+
triggerTokens: 100_000,
|
|
1739
|
+
}))
|
|
1740
|
+
})
|
|
1741
|
+
|
|
1742
|
+
it('freezes the complete settings and deployment snapshot on first Session observation', async () => {
|
|
1743
|
+
const ctx = new Context()
|
|
1744
|
+
activeContexts.push(ctx)
|
|
1745
|
+
await ctx.plugin(TestSettings).await()
|
|
1746
|
+
await ctx.plugin(LegacyNamespaceRegistrar).await()
|
|
1747
|
+
await ctx.plugin(SessionStore).await()
|
|
1748
|
+
await ctx.plugin(SystemPrompt).await()
|
|
1749
|
+
await ctx.plugin(ToolRuntime).await()
|
|
1750
|
+
await ctx.plugin(SessionProjectionRegistry).await()
|
|
1751
|
+
await ctx.plugin(TokenMeter).await()
|
|
1752
|
+
const audit = captureAudit(ctx)
|
|
1753
|
+
|
|
1754
|
+
const firstCustom = structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY) as CustomCompressionPolicy
|
|
1755
|
+
firstCustom.fresh = { enabled: true, trigger: 512, target: 256 }
|
|
1756
|
+
firstCustom.aggregate.enabled = false
|
|
1757
|
+
firstCustom.history.enabled = false
|
|
1758
|
+
if (firstCustom.version === 3) firstCustom.tailTrim.enabled = false
|
|
1759
|
+
const namespace = nsBrand(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE)
|
|
1760
|
+
await ctx.settings.update(namespace, { profile: 'custom', custom: firstCustom })
|
|
1761
|
+
await ctx.plugin(ToolResultPruner, {
|
|
1762
|
+
profile: 'off',
|
|
1763
|
+
headChars: 6,
|
|
1764
|
+
tailChars: 4,
|
|
1765
|
+
}).await()
|
|
1766
|
+
|
|
1767
|
+
const sessionA = Session.create(SessionId('public-policy-freeze-a'))
|
|
1768
|
+
appendToolTurn(sessionA, 1, 'first frozen policy result '.repeat(800), false)
|
|
1769
|
+
expect(ctx.toolResultPruner.pruneSession(sessionA, {
|
|
1770
|
+
stage: 'fresh', freshTurn: 1, freshStep: 1,
|
|
1771
|
+
}).pruned).toHaveLength(1)
|
|
1772
|
+
|
|
1773
|
+
const secondCustom = structuredClone(firstCustom)
|
|
1774
|
+
secondCustom.fresh.enabled = false
|
|
1775
|
+
secondCustom.history.trigger += 123
|
|
1776
|
+
await ctx.settings.update(namespace, { custom: secondCustom })
|
|
1777
|
+
sessionA.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
|
|
1778
|
+
appendToolTurn(sessionA, 2, 'second frozen policy result '.repeat(800), false)
|
|
1779
|
+
expect(ctx.toolResultPruner.pruneSession(sessionA, {
|
|
1780
|
+
stage: 'fresh', freshTurn: 2, freshStep: 1,
|
|
1781
|
+
}).pruned).toHaveLength(1)
|
|
1782
|
+
|
|
1783
|
+
const sessionB = Session.create(SessionId('public-policy-freeze-b'))
|
|
1784
|
+
const keptB = appendToolTurn(sessionB, 1, 'new Session disabled Fresh '.repeat(800), false)
|
|
1785
|
+
expect(ctx.toolResultPruner.pruneSession(sessionB, {
|
|
1786
|
+
stage: 'fresh', freshTurn: 1, freshStep: 1,
|
|
1787
|
+
})).toEqual({ pruned: [], charsRemoved: 0, tokensRemoved: 0 })
|
|
1788
|
+
expect(sessionB.surface.nodes).toContain(keptB.resultSeq)
|
|
1789
|
+
|
|
1790
|
+
const frozen = audit.records().filter(record => record.kind === 'policy-frozen')
|
|
1791
|
+
expect(frozen).toHaveLength(2)
|
|
1792
|
+
expect(frozen.find(record => record.sessionId === String(sessionA.id))).toMatchObject({
|
|
1793
|
+
settingsSource: 'host-settings',
|
|
1794
|
+
settings: { profile: 'custom', custom: firstCustom },
|
|
1795
|
+
deploymentConfig: { profile: 'off', headChars: 6, tailChars: 4 },
|
|
1796
|
+
})
|
|
1797
|
+
expect(frozen.find(record => record.sessionId === String(sessionB.id))).toMatchObject({
|
|
1798
|
+
settingsSource: 'host-settings',
|
|
1799
|
+
settings: { profile: 'custom', custom: secondCustom },
|
|
1800
|
+
deploymentConfig: { profile: 'off', headChars: 6, tailChars: 4 },
|
|
1801
|
+
})
|
|
1802
|
+
})
|
|
1803
|
+
|
|
1804
|
+
it('publishes TailTrim through standard prune + user replacement and validates append roots', async () => {
|
|
1805
|
+
const ctx = new Context()
|
|
1806
|
+
activeContexts.push(ctx)
|
|
1807
|
+
await ctx.plugin(TestSettings).await()
|
|
1808
|
+
await ctx.plugin(LegacyNamespaceRegistrar).await()
|
|
1809
|
+
await ctx.plugin(SessionStore).await()
|
|
1810
|
+
await ctx.plugin(SystemPrompt).await()
|
|
1811
|
+
await ctx.plugin(ToolRuntime).await()
|
|
1812
|
+
await ctx.plugin(SessionProjectionRegistry).await()
|
|
1813
|
+
await ctx.plugin(TokenMeter).await()
|
|
1814
|
+
const audit = captureAudit(ctx)
|
|
1815
|
+
|
|
1816
|
+
const policy = structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY) as CustomCompressionPolicy
|
|
1817
|
+
if (policy.version !== 3) throw new Error('TailTrim public protocol test requires policy v3')
|
|
1818
|
+
policy.fresh.enabled = false
|
|
1819
|
+
policy.aggregate.enabled = false
|
|
1820
|
+
policy.history.enabled = false
|
|
1821
|
+
// Isolate TailTrim: keep no History working set protected.
|
|
1822
|
+
policy.history.keepRecentToolCalls = 0
|
|
1823
|
+
policy.history.keepRecentTokens = 0
|
|
1824
|
+
policy.history.minReclaim = 1
|
|
1825
|
+
policy.tailTrim = { enabled: true, trigger: 8 }
|
|
1826
|
+
await ctx.settings.update(nsBrand(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE), {
|
|
1827
|
+
profile: 'custom',
|
|
1828
|
+
custom: policy,
|
|
1829
|
+
})
|
|
1830
|
+
await ctx.plugin(ToolResultPruner, { profile: 'off' }).await()
|
|
1831
|
+
const pruner = ctx.toolResultPruner
|
|
1832
|
+
const session = Session.create(SessionId('public-tailtrim'))
|
|
1833
|
+
appendToolTurn(session, 1, 'first completed group'.repeat(40), true)
|
|
1834
|
+
const candidate = appendToolTurn(session, 2, 'old candidate result'.repeat(400), true)
|
|
1835
|
+
session.append('turn/start', { turn: 3 })
|
|
1836
|
+
expect(ctx.tools.get('context_compression_retrieve')).toBeDefined()
|
|
1837
|
+
const before = measureForCompaction(ctx, session)
|
|
1838
|
+
expect(before.currentSurface.kind).toBe('exact-tokenizer')
|
|
1839
|
+
|
|
1840
|
+
pruner.pruneSession(session, { stage: 'pressure' })
|
|
1841
|
+
|
|
1842
|
+
const manifest = sessionEvents(session).findLast(event => event.type === 'compaction/prune')
|
|
1843
|
+
expect(manifest?.type).toBe('compaction/prune')
|
|
1844
|
+
if (manifest?.type !== 'compaction/prune') throw new Error('TailTrim did not publish a standard prune')
|
|
1845
|
+
const publication = validatePublishedTailTrim(session, manifest.seq)
|
|
1846
|
+
expect(publication).not.toBeNull()
|
|
1847
|
+
expect(publication?.manifest.data.shadowedSeqs).toEqual([
|
|
1848
|
+
candidate.assistantSeq,
|
|
1849
|
+
candidate.resultSeq,
|
|
1850
|
+
])
|
|
1851
|
+
expect(publication?.replacement.type).toBe('user/message')
|
|
1852
|
+
expect(publication?.ref).toBe(`session://${String(session.id)}/tailtrim/${String(manifest.seq)}`)
|
|
1853
|
+
expect(ctx.tools.get('context_compression_retrieve')).toBeDefined()
|
|
1854
|
+
expect(rewrites(audit.records())).toContainEqual(expect.objectContaining({
|
|
1855
|
+
component: 'tail-trim',
|
|
1856
|
+
stage: 'pressure',
|
|
1857
|
+
reducer: 'pair-preserving-tail-trim',
|
|
1858
|
+
manifestSeq: manifest.seq,
|
|
1859
|
+
tokensBefore: expect.any(Number),
|
|
1860
|
+
tokensAfter: expect.any(Number),
|
|
1861
|
+
}))
|
|
1862
|
+
|
|
1863
|
+
const recovered = await ctx.tools.execute({
|
|
1864
|
+
name: 'context_compression_retrieve',
|
|
1865
|
+
arguments: { ref: publication?.ref, max_lines: 20 },
|
|
1866
|
+
callId: CallId('tailtrim-retrieve-live'),
|
|
1867
|
+
signal: new AbortController().signal,
|
|
1868
|
+
agent: stubAgent(ctx, session),
|
|
1869
|
+
})
|
|
1870
|
+
expect(recovered.isError).toBe(false)
|
|
1871
|
+
const recoveredText = recovered.content
|
|
1872
|
+
.map(block => block.type === 'text' ? block.text : '')
|
|
1873
|
+
.join('\n')
|
|
1874
|
+
expect(recoveredText).toContain('kind: tailtrim-group')
|
|
1875
|
+
expect(recoveredText).toContain('old candidate result')
|
|
1876
|
+
|
|
1877
|
+
const persistedEvents = JSON.parse(JSON.stringify(sessionEvents(session)))
|
|
1878
|
+
const replay = Session.create(session.id, persistedEvents)
|
|
1879
|
+
const replayPublication = validatePublishedTailTrim(replay, manifest.seq)
|
|
1880
|
+
expect(replayPublication?.ref).toBe(publication?.ref)
|
|
1881
|
+
expect(replay.deriveMessages()).toEqual(session.deriveMessages())
|
|
1882
|
+
const replayRecovered = await ctx.tools.execute({
|
|
1883
|
+
name: 'context_compression_retrieve',
|
|
1884
|
+
arguments: { ref: replayPublication?.ref, max_lines: 20 },
|
|
1885
|
+
callId: CallId('tailtrim-retrieve-replay'),
|
|
1886
|
+
signal: new AbortController().signal,
|
|
1887
|
+
agent: stubAgent(ctx, replay),
|
|
1888
|
+
})
|
|
1889
|
+
expect(replayRecovered).toEqual(recovered)
|
|
1890
|
+
})
|
|
1891
|
+
|
|
1892
|
+
it('audits TailTrim threshold, safety-group, and min-reclaim skip paths and lands on the character basis for an unknown model', async () => {
|
|
1893
|
+
async function runScenario(options: {
|
|
1894
|
+
readonly id: string
|
|
1895
|
+
readonly expectedReason?: string
|
|
1896
|
+
readonly trigger: number
|
|
1897
|
+
readonly minReclaim: number
|
|
1898
|
+
readonly candidateTurns: number
|
|
1899
|
+
readonly model?: string
|
|
1900
|
+
readonly expectLanding?: boolean
|
|
1901
|
+
}): Promise<void> {
|
|
1902
|
+
const ctx = new Context()
|
|
1903
|
+
activeContexts.push(ctx)
|
|
1904
|
+
await ctx.plugin(TestSettings).await()
|
|
1905
|
+
await ctx.plugin(LegacyNamespaceRegistrar).await()
|
|
1906
|
+
await ctx.plugin(SessionStore).await()
|
|
1907
|
+
await ctx.plugin(SystemPrompt).await()
|
|
1908
|
+
await ctx.plugin(ToolRuntime).await()
|
|
1909
|
+
await ctx.plugin(SessionProjectionRegistry).await()
|
|
1910
|
+
await ctx.plugin(TokenMeter).await()
|
|
1911
|
+
const audit = captureAudit(ctx)
|
|
1912
|
+
|
|
1913
|
+
const policy = structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY) as CustomCompressionPolicy
|
|
1914
|
+
if (policy.version !== 3) throw new Error('TailTrim negative-path test requires policy v3')
|
|
1915
|
+
policy.fresh.enabled = false
|
|
1916
|
+
policy.aggregate.enabled = false
|
|
1917
|
+
policy.history.enabled = false
|
|
1918
|
+
policy.history.trigger = Math.max(policy.history.trigger, options.minReclaim)
|
|
1919
|
+
policy.history.keepRecentToolCalls = 0
|
|
1920
|
+
policy.history.keepRecentTokens = 0
|
|
1921
|
+
policy.history.minReclaim = options.minReclaim
|
|
1922
|
+
policy.tailTrim = { enabled: true, trigger: options.trigger }
|
|
1923
|
+
await ctx.settings.update(nsBrand(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE), {
|
|
1924
|
+
profile: 'custom',
|
|
1925
|
+
custom: policy,
|
|
1926
|
+
})
|
|
1927
|
+
await ctx.plugin(ToolResultPruner, { profile: 'off' }).await()
|
|
1928
|
+
|
|
1929
|
+
const session = Session.create(SessionId(options.id))
|
|
1930
|
+
if (options.model !== undefined) {
|
|
1931
|
+
session.append('request/header', {
|
|
1932
|
+
reason: 'initial',
|
|
1933
|
+
header: canonicalHeader({ config: { provider: 'deepseek', model: options.model } }),
|
|
1934
|
+
})
|
|
1935
|
+
}
|
|
1936
|
+
for (let turn = 1; turn <= options.candidateTurns; turn++) {
|
|
1937
|
+
appendToolTurn(session, turn, `tailtrim negative ${options.id} `.repeat(200), true)
|
|
1938
|
+
}
|
|
1939
|
+
session.append('turn/start', { turn: options.candidateTurns + 1 })
|
|
1940
|
+
|
|
1941
|
+
ctx.toolResultPruner.pruneSession(session, { stage: 'pressure' })
|
|
1942
|
+
|
|
1943
|
+
const tailTrimRewrites = rewrites(audit.records()).filter(record => record.component === 'tail-trim')
|
|
1944
|
+
if (options.expectLanding === true) {
|
|
1945
|
+
// An unknown model id no longer skips: the group lands and the record
|
|
1946
|
+
// must honestly report the character basis.
|
|
1947
|
+
expect(tailTrimRewrites).toHaveLength(1)
|
|
1948
|
+
expect(tailTrimRewrites[0]?.measurementBasis).toBe('characters')
|
|
1949
|
+
expect(tailTrimRewrites[0]?.tokenizerId).toBe('characters')
|
|
1950
|
+
expect(tailTrimRewrites[0]?.tokenizerRevision).toBe('chars-per-token-4.0')
|
|
1951
|
+
return
|
|
1952
|
+
}
|
|
1953
|
+
expect(tailTrimRewrites).toHaveLength(0)
|
|
1954
|
+
expect(audit.records()).toContainEqual(expect.objectContaining({
|
|
1955
|
+
kind: 'component-evaluation',
|
|
1956
|
+
sessionId: String(session.id),
|
|
1957
|
+
component: 'tail-trim',
|
|
1958
|
+
status: 'skipped',
|
|
1959
|
+
reason: options.expectedReason,
|
|
1960
|
+
}))
|
|
1961
|
+
}
|
|
1962
|
+
|
|
1963
|
+
await runScenario({
|
|
1964
|
+
id: 'public-tailtrim-below-trigger',
|
|
1965
|
+
expectedReason: 'at-or-below-trigger',
|
|
1966
|
+
trigger: 1_000_000,
|
|
1967
|
+
minReclaim: 1,
|
|
1968
|
+
candidateTurns: 2,
|
|
1969
|
+
})
|
|
1970
|
+
await runScenario({
|
|
1971
|
+
id: 'public-tailtrim-character-basis-landing',
|
|
1972
|
+
trigger: 1,
|
|
1973
|
+
minReclaim: 1,
|
|
1974
|
+
candidateTurns: 2,
|
|
1975
|
+
model: 'unsupported-public-model',
|
|
1976
|
+
expectLanding: true,
|
|
1977
|
+
})
|
|
1978
|
+
await runScenario({
|
|
1979
|
+
id: 'public-tailtrim-first-group-protected',
|
|
1980
|
+
expectedReason: 'no-safe-eligible-tool-group',
|
|
1981
|
+
trigger: 1,
|
|
1982
|
+
minReclaim: 1,
|
|
1983
|
+
candidateTurns: 1,
|
|
1984
|
+
})
|
|
1985
|
+
await runScenario({
|
|
1986
|
+
id: 'public-tailtrim-min-reclaim',
|
|
1987
|
+
expectedReason: 'no-safe-eligible-tool-group',
|
|
1988
|
+
trigger: 1,
|
|
1989
|
+
minReclaim: 1_000_000,
|
|
1990
|
+
candidateTurns: 2,
|
|
1991
|
+
})
|
|
1992
|
+
})
|
|
1993
|
+
|
|
1994
|
+
it('fails open after an orphan prune and remains appendable after JSON restart', async () => {
|
|
1995
|
+
const ctx = new Context()
|
|
1996
|
+
activeContexts.push(ctx)
|
|
1997
|
+
await ctx.plugin(TestSettings).await()
|
|
1998
|
+
await ctx.plugin(LegacyNamespaceRegistrar).await()
|
|
1999
|
+
await ctx.plugin(SessionStore).await()
|
|
2000
|
+
await ctx.plugin(InvariantRegistry).await()
|
|
2001
|
+
await ctx.plugin(RuntimeInvariant).await()
|
|
2002
|
+
await ctx.plugin(SystemPrompt).await()
|
|
2003
|
+
await ctx.plugin(ToolRuntime).await()
|
|
2004
|
+
await ctx.plugin(SessionProjectionRegistry).await()
|
|
2005
|
+
await ctx.plugin(TokenMeter).await()
|
|
2006
|
+
const audit = captureAudit(ctx)
|
|
2007
|
+
|
|
2008
|
+
const policy = structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY) as CustomCompressionPolicy
|
|
2009
|
+
if (policy.version !== 3) throw new Error('orphan recovery test requires policy v3')
|
|
2010
|
+
policy.fresh.enabled = false
|
|
2011
|
+
policy.aggregate.enabled = false
|
|
2012
|
+
policy.history.enabled = false
|
|
2013
|
+
policy.history.keepRecentToolCalls = 0
|
|
2014
|
+
policy.history.keepRecentTokens = 0
|
|
2015
|
+
policy.history.minReclaim = 1
|
|
2016
|
+
policy.tailTrim = { enabled: true, trigger: 8 }
|
|
2017
|
+
await ctx.settings.update(nsBrand(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE), {
|
|
2018
|
+
profile: 'custom',
|
|
2019
|
+
custom: policy,
|
|
2020
|
+
})
|
|
2021
|
+
await ctx.plugin(ToolResultPruner, { profile: 'off' }).await()
|
|
2022
|
+
const session = ctx.sessions.create(SessionId('public-tailtrim-orphan-recovery'))
|
|
2023
|
+
appendToolTurn(session, 1, 'first completed group'.repeat(40), true)
|
|
2024
|
+
appendToolTurn(session, 2, 'orphan source remains intact'.repeat(400), true)
|
|
2025
|
+
session.append('turn/start', { turn: 3 })
|
|
2026
|
+
const beforeSurface = [...session.surface.nodes]
|
|
2027
|
+
const originalAppend = session.append.bind(session)
|
|
2028
|
+
const append = vi.spyOn(session, 'append').mockImplementation((type: string, ...args: unknown[]) => {
|
|
2029
|
+
const options = args[1] as { surfaceOp?: unknown } | undefined
|
|
2030
|
+
if (type === 'user/message' && typeof options?.surfaceOp === 'object') {
|
|
2031
|
+
throw new Error('fixture replacement append failure')
|
|
2032
|
+
}
|
|
2033
|
+
return Reflect.apply(
|
|
2034
|
+
originalAppend as (...values: unknown[]) => unknown,
|
|
2035
|
+
undefined,
|
|
2036
|
+
[type, ...args],
|
|
2037
|
+
) as never
|
|
2038
|
+
})
|
|
2039
|
+
|
|
2040
|
+
expect(() => ctx.toolResultPruner.pruneSession(session, { stage: 'pressure' })).not.toThrow()
|
|
2041
|
+
append.mockRestore()
|
|
2042
|
+
expect(sessionEvents(session).at(-1)?.type).toBe('compaction/prune')
|
|
2043
|
+
expect(session.surface.nodes).toEqual(beforeSurface)
|
|
2044
|
+
expect(rewrites(audit.records())).toHaveLength(0)
|
|
2045
|
+
expect(audit.records()).toContainEqual(expect.objectContaining({
|
|
2046
|
+
kind: 'failure',
|
|
2047
|
+
operation: 'publication',
|
|
2048
|
+
component: 'tail-trim',
|
|
2049
|
+
manifestSeq: sessionEvents(session).length - 1,
|
|
2050
|
+
}))
|
|
2051
|
+
|
|
2052
|
+
expect(() => session.append('turn/end', {
|
|
2053
|
+
turn: 3,
|
|
2054
|
+
reason: { kind: 'completed' },
|
|
2055
|
+
})).not.toThrow()
|
|
2056
|
+
const persisted = JSON.parse(JSON.stringify(sessionEvents(session)))
|
|
2057
|
+
|
|
2058
|
+
const resumedCtx = new Context()
|
|
2059
|
+
activeContexts.push(resumedCtx)
|
|
2060
|
+
await resumedCtx.plugin(SessionStore).await()
|
|
2061
|
+
await resumedCtx.plugin(InvariantRegistry).await()
|
|
2062
|
+
await resumedCtx.plugin(RuntimeInvariant).await()
|
|
2063
|
+
const resumed = resumedCtx.sessions.create(session.id, { seed: persisted })
|
|
2064
|
+
expect(resumed.surface.nodes).toEqual(beforeSurface)
|
|
2065
|
+
expect(() => resumed.append('turn/start', { turn: 4 })).not.toThrow()
|
|
2066
|
+
})
|
|
2067
|
+
|
|
2068
|
+
it('still rejects a malformed adjacent replacement instead of treating it as an orphan', async () => {
|
|
2069
|
+
const ctx = new Context()
|
|
2070
|
+
activeContexts.push(ctx)
|
|
2071
|
+
await ctx.plugin(SessionStore).await()
|
|
2072
|
+
await ctx.plugin(InvariantRegistry).await()
|
|
2073
|
+
await ctx.plugin(RuntimeInvariant).await()
|
|
2074
|
+
const session = ctx.sessions.create(SessionId('public-malformed-companion'))
|
|
2075
|
+
const source = appendToolTurn(session, 1, 'source remains intact', false)
|
|
2076
|
+
session.append('compaction/prune', {
|
|
2077
|
+
shadowedRange: { start: SessionSeq(source.resultSeq), end: SessionSeq(source.resultSeq) },
|
|
2078
|
+
shadowedSeqs: [SessionSeq(source.resultSeq)],
|
|
2079
|
+
shadowedTokenCount: 1,
|
|
2080
|
+
})
|
|
2081
|
+
const result = sessionEvents(session)[source.resultSeq]
|
|
2082
|
+
if (result?.type !== 'tool/result') throw new Error('missing source result')
|
|
2083
|
+
const before = session.seq
|
|
2084
|
+
|
|
2085
|
+
expect(() => session.append('tool/result', result.data, {
|
|
2086
|
+
surfaceOp: { op: 'replace', startSeq: SessionSeq(source.assistantSeq), endSeq: SessionSeq(source.assistantSeq) },
|
|
2087
|
+
sourceEventSeqs: [SessionSeq(source.resultSeq)],
|
|
2088
|
+
})).toThrow(/sourceEventSeqs|does not replace compaction\/prune range/)
|
|
2089
|
+
expect(session.seq).toBe(before)
|
|
2090
|
+
})
|
|
2091
|
+
|
|
2092
|
+
it('observes committed Native auto-compact separately from plugin rewrites', async () => {
|
|
2093
|
+
const ctx = await runtimeContext()
|
|
2094
|
+
const audit = captureAudit(ctx)
|
|
2095
|
+
await ctx.plugin(ToolResultPruner, { profile: 'off' }).await()
|
|
2096
|
+
const session = Session.create(SessionId('public-native-auto-audit'))
|
|
2097
|
+
const summary = session.append('compaction/summary', {
|
|
2098
|
+
compactionId: CompactionId('public-native-auto'),
|
|
2099
|
+
summary: [{ type: 'text', text: 'summary' }],
|
|
2100
|
+
shadowedRange: { start: SessionSeq(0), end: SessionSeq(0) },
|
|
2101
|
+
shadowedSeqs: [],
|
|
2102
|
+
shadowedTokenCount: 321,
|
|
2103
|
+
provider: 'deepseek',
|
|
2104
|
+
model: MODEL,
|
|
2105
|
+
})
|
|
2106
|
+
|
|
2107
|
+
ctx.emit('session/event', session, summary)
|
|
2108
|
+
|
|
2109
|
+
expect(rewrites(audit.records())).toHaveLength(0)
|
|
2110
|
+
expect(audit.records()).toContainEqual(expect.objectContaining({
|
|
2111
|
+
kind: 'native-auto-compact',
|
|
2112
|
+
manifestEventType: 'compaction/summary',
|
|
2113
|
+
manifestSeq: summary.seq,
|
|
2114
|
+
provider: 'deepseek',
|
|
2115
|
+
model: MODEL,
|
|
2116
|
+
tokensBefore: 321,
|
|
2117
|
+
tokensAfter: null,
|
|
2118
|
+
}))
|
|
2119
|
+
})
|
|
2120
|
+
|
|
2121
|
+
it('triggers Native auto-compact through the real AgentLoop pre-step boundary', async () => {
|
|
2122
|
+
const ctx = new Context()
|
|
2123
|
+
activeContexts.push(ctx)
|
|
2124
|
+
await mountAgentLoopTestDependencies(ctx)
|
|
2125
|
+
await ctx.plugin(AgentLoop, { agents: [] })
|
|
2126
|
+
await ctx.plugin(TokenMeter).await()
|
|
2127
|
+
const audit = captureAudit(ctx)
|
|
2128
|
+
ctx.llm.registerAdapter(
|
|
2129
|
+
['deepseek'],
|
|
2130
|
+
new NativeSummaryAdapter([
|
|
2131
|
+
'first native turn complete',
|
|
2132
|
+
'native compact summary',
|
|
2133
|
+
'second native turn complete',
|
|
2134
|
+
], 1_000),
|
|
2135
|
+
)
|
|
2136
|
+
await ctx.plugin(ToolResultPruner, { profile: 'off' }).await()
|
|
2137
|
+
void new BasicCompactionEngine(ctx, {
|
|
2138
|
+
// 0.1.7-rc.2 defaults a 65536-token compaction headroom; the tiny probe windows here need it zeroed.
|
|
2139
|
+
headroomTokens: 0,
|
|
2140
|
+
auto: true,
|
|
2141
|
+
thresholdRatio: 0.3,
|
|
2142
|
+
retainTokens: 0,
|
|
2143
|
+
maxTokens: 100,
|
|
2144
|
+
compactionRetries: 0,
|
|
2145
|
+
})
|
|
2146
|
+
const agent = await ctx.agentLoop.create(SessionId('public-native-auto-real'), {
|
|
2147
|
+
provider: 'deepseek',
|
|
2148
|
+
model: MODEL,
|
|
2149
|
+
})
|
|
2150
|
+
|
|
2151
|
+
agent.followup(createUserMessage({
|
|
2152
|
+
content: [{ type: 'text', text: 'native pressure evidence '.repeat(500) }],
|
|
2153
|
+
source: { kind: 'user' },
|
|
2154
|
+
}))
|
|
2155
|
+
await agent.whenIdle()
|
|
2156
|
+
agent.followup(createUserMessage({
|
|
2157
|
+
content: [{ type: 'text', text: 'continue after native compaction' }],
|
|
2158
|
+
source: { kind: 'user' },
|
|
2159
|
+
}))
|
|
2160
|
+
await agent.whenIdle()
|
|
2161
|
+
|
|
2162
|
+
expect(rewrites(audit.records())).toHaveLength(0)
|
|
2163
|
+
const summary = sessionEvents(agent.session).findLast(event => event.type === 'compaction/summary')
|
|
2164
|
+
expect(summary?.type).toBe('compaction/summary')
|
|
2165
|
+
expect(audit.records()).toContainEqual(expect.objectContaining({
|
|
2166
|
+
kind: 'native-auto-compact',
|
|
2167
|
+
manifestEventType: 'compaction/summary',
|
|
2168
|
+
manifestSeq: summary?.seq,
|
|
2169
|
+
provider: 'deepseek',
|
|
2170
|
+
model: MODEL,
|
|
2171
|
+
tokensBefore: expect.any(Number),
|
|
2172
|
+
tokensAfter: null,
|
|
2173
|
+
}))
|
|
2174
|
+
})
|
|
2175
|
+
|
|
2176
|
+
it('runs Fresh, Aggregate, History, TailTrim and Native in one non-isolated audited session', async () => {
|
|
2177
|
+
const ctx = new Context()
|
|
2178
|
+
activeContexts.push(ctx)
|
|
2179
|
+
await ctx.plugin(TestSettings).await()
|
|
2180
|
+
await ctx.plugin(LegacyNamespaceRegistrar).await()
|
|
2181
|
+
await ctx.plugin(LlmRuntime).await()
|
|
2182
|
+
await ctx.plugin(SessionStore).await()
|
|
2183
|
+
await ctx.plugin(SystemPrompt).await()
|
|
2184
|
+
await ctx.plugin(ToolRuntime).await()
|
|
2185
|
+
await ctx.plugin(SessionProjectionRegistry).await()
|
|
2186
|
+
await ctx.plugin(TokenMeter).await()
|
|
2187
|
+
const audit = captureAudit(ctx)
|
|
2188
|
+
|
|
2189
|
+
const policy = structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY) as CustomCompressionPolicy
|
|
2190
|
+
if (policy.version !== 3) throw new Error('full-pipeline public E2E requires policy v3')
|
|
2191
|
+
policy.fresh = { enabled: true, trigger: 512, target: 256 }
|
|
2192
|
+
policy.aggregate = { enabled: true, trigger: 1_000, target: 400 }
|
|
2193
|
+
policy.history = {
|
|
2194
|
+
enabled: true,
|
|
2195
|
+
// The strict required-reclaim gate demands one batch pull tool tokens
|
|
2196
|
+
// back under this trigger: it must sit above the large protected tail
|
|
2197
|
+
// (so the batch is reachable) while the residual total stays far above
|
|
2198
|
+
// the auto-compact threshold (half the measured total) afterwards.
|
|
2199
|
+
trigger: 7_800,
|
|
2200
|
+
keepRecentToolCalls: 0,
|
|
2201
|
+
keepRecentTokens: 1,
|
|
2202
|
+
minReclaim: 1,
|
|
2203
|
+
}
|
|
2204
|
+
policy.prefixPolicy = 'pressure-break'
|
|
2205
|
+
policy.tailTrim = { enabled: true, trigger: 8 }
|
|
2206
|
+
await ctx.settings.update(nsBrand(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE), {
|
|
2207
|
+
profile: 'custom',
|
|
2208
|
+
custom: policy,
|
|
2209
|
+
})
|
|
2210
|
+
await ctx.plugin(ToolResultPruner, { profile: 'off' }).await()
|
|
2211
|
+
|
|
2212
|
+
const session = ctx.sessions.create(SessionId('public-full-pipeline-e2e'))
|
|
2213
|
+
appendToolTurn(session, 1, 'fresh full pipeline '.repeat(600), false, 'run Fresh')
|
|
2214
|
+
ctx.toolResultPruner.pruneSession(session, {
|
|
2215
|
+
stage: 'fresh',
|
|
2216
|
+
freshTurn: 1,
|
|
2217
|
+
freshStep: 1,
|
|
2218
|
+
})
|
|
2219
|
+
session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
|
|
2220
|
+
|
|
2221
|
+
appendToolBatchTurn(
|
|
2222
|
+
session,
|
|
2223
|
+
2,
|
|
2224
|
+
Array.from({ length: 30 }, (_, index) => `aggregate-${String(index)} `.repeat(20)),
|
|
2225
|
+
false,
|
|
2226
|
+
'run Aggregate',
|
|
2227
|
+
)
|
|
2228
|
+
ctx.toolResultPruner.pruneSession(session, {
|
|
2229
|
+
stage: 'fresh',
|
|
2230
|
+
freshTurn: 2,
|
|
2231
|
+
freshStep: 1,
|
|
2232
|
+
})
|
|
2233
|
+
session.append('turn/end', { turn: 2, reason: { kind: 'completed' } })
|
|
2234
|
+
// Leave one old, still-original result for the pressure-stage History
|
|
2235
|
+
// reducer, then add a newer working-set result that remains protected.
|
|
2236
|
+
appendToolTurn(session, 3, 'history full pipeline '.repeat(600), true, 'run History')
|
|
2237
|
+
appendToolTurn(session, 4, 'recent protected working-set context '.repeat(1200), true, 'retain recent context')
|
|
2238
|
+
session.append('turn/start', { turn: 5 })
|
|
2239
|
+
ctx.toolResultPruner.pruneSession(session, { stage: 'pressure' })
|
|
2240
|
+
|
|
2241
|
+
const beforeNative = ctx.tokenMeter.measure(session).totalTokens
|
|
2242
|
+
expect(beforeNative).toBeGreaterThan(2)
|
|
2243
|
+
ctx.llm.registerAdapter(
|
|
2244
|
+
['deepseek'],
|
|
2245
|
+
new NativeSummaryAdapter(['full-pipeline native summary'], beforeNative),
|
|
2246
|
+
)
|
|
2247
|
+
void new BasicCompactionEngine(ctx, {
|
|
2248
|
+
// 0.1.7-rc.2 defaults a 65536-token compaction headroom; the tiny probe windows here need it zeroed.
|
|
2249
|
+
headroomTokens: 0,
|
|
2250
|
+
auto: true,
|
|
2251
|
+
thresholdRatio: 0.5,
|
|
2252
|
+
retainTokens: 0,
|
|
2253
|
+
maxTokens: 100,
|
|
2254
|
+
compactionRetries: 0,
|
|
2255
|
+
})
|
|
2256
|
+
const signal = new AbortController().signal
|
|
2257
|
+
const decision = await agentEvents(ctx, stubAgent(ctx, session)).waterfall(
|
|
2258
|
+
'agent/pre-step',
|
|
2259
|
+
{ messages: [], turn: 5, step: 1, signal },
|
|
2260
|
+
() => Promise.resolve({ kind: 'enter' as const, messages: [] }),
|
|
2261
|
+
)
|
|
2262
|
+
expect(decision).toEqual({ kind: 'enter', messages: [] })
|
|
2263
|
+
const summary = sessionEvents(session).findLast(event => event.type === 'compaction/summary')
|
|
2264
|
+
expect(summary?.type).toBe('compaction/summary')
|
|
2265
|
+
|
|
2266
|
+
const records = audit.records()
|
|
2267
|
+
const rewriteRecords = rewrites(records)
|
|
2268
|
+
const components = rewriteRecords.map(record => record.component)
|
|
2269
|
+
expect(components).toContain('fresh')
|
|
2270
|
+
expect(components).toContain('aggregate')
|
|
2271
|
+
expect(components).toContain('history')
|
|
2272
|
+
expect(components).toContain('tail-trim')
|
|
2273
|
+
expect(records).toContainEqual(expect.objectContaining({
|
|
2274
|
+
kind: 'native-auto-compact',
|
|
2275
|
+
manifestSeq: summary?.seq,
|
|
2276
|
+
tokensBefore: expect.any(Number),
|
|
2277
|
+
}))
|
|
2278
|
+
|
|
2279
|
+
const firstIndex = (component: CompressionRewriteAuditRecord['component']) =>
|
|
2280
|
+
records.findIndex(record => record.kind === 'rewrite' && record.component === component)
|
|
2281
|
+
expect(firstIndex('fresh')).toBeLessThan(firstIndex('aggregate'))
|
|
2282
|
+
expect(firstIndex('aggregate')).toBeLessThan(firstIndex('history'))
|
|
2283
|
+
expect(firstIndex('history')).toBeLessThan(firstIndex('tail-trim'))
|
|
2284
|
+
expect(records.findIndex(record => record.kind === 'native-auto-compact'))
|
|
2285
|
+
.toBeGreaterThan(firstIndex('tail-trim'))
|
|
2286
|
+
expect(sessionEvents(session).some(event => event.type === ('compaction/group-trim' as string))).toBe(false)
|
|
2287
|
+
})
|
|
2288
|
+
|
|
2289
|
+
it('compresses text tool results exactly in a vision session that also carries a user image', async () => {
|
|
2290
|
+
const ctx = await runtimeContext()
|
|
2291
|
+
const audit = captureAudit(ctx)
|
|
2292
|
+
await ctx.plugin(ToolResultPruner, {
|
|
2293
|
+
profile: 'balanced',
|
|
2294
|
+
freshTriggerTokens: 1_000_000,
|
|
2295
|
+
freshTargetTokens: 900_000,
|
|
2296
|
+
aggregateTriggerTokens: 100,
|
|
2297
|
+
aggregateTargetTokens: 64,
|
|
2298
|
+
historyTriggerTokens: 600,
|
|
2299
|
+
historyKeepRecentToolCalls: 0,
|
|
2300
|
+
historyKeepRecentTokens: 1,
|
|
2301
|
+
historyMinReclaimTokens: 1,
|
|
2302
|
+
}).await()
|
|
2303
|
+
const session = Session.create(SessionId('public-vision-text-session'))
|
|
2304
|
+
session.append('turn/start', { turn: 1 })
|
|
2305
|
+
session.append('request/header', {
|
|
2306
|
+
reason: 'initial',
|
|
2307
|
+
header: canonicalHeader({ config: { provider: 'deepseek', model: VISION_MODEL } }),
|
|
2308
|
+
})
|
|
2309
|
+
session.append('user/message', createUserMessage({
|
|
2310
|
+
content: [
|
|
2311
|
+
imageBlock(640, 480),
|
|
2312
|
+
{ type: 'text', text: 'describe the attachment and run the tools' },
|
|
2313
|
+
],
|
|
2314
|
+
source: { kind: 'user' },
|
|
2315
|
+
}), { surfaceOp: 'append' })
|
|
2316
|
+
session.append('step/start', { turn: 1, step: 1 })
|
|
2317
|
+
session.append('assistant/message', {
|
|
2318
|
+
stream: [],
|
|
2319
|
+
turn: 1,
|
|
2320
|
+
step: 1,
|
|
2321
|
+
message: createMessage({
|
|
2322
|
+
role: 'assistant',
|
|
2323
|
+
content: [{ type: 'tool-call', id: CallId('vision-call-1'), name: 'bash', arguments: '{}' }],
|
|
2324
|
+
source: { kind: 'model', provider: 'deepseek', model: VISION_MODEL },
|
|
2325
|
+
}),
|
|
2326
|
+
}, { surfaceOp: 'append' })
|
|
2327
|
+
session.append('tool/call', { turn: 1, step: 1, callId: CallId('vision-call-1'), name: 'bash', arguments: '{}' })
|
|
2328
|
+
session.append('tool/result', {
|
|
2329
|
+
turn: 1,
|
|
2330
|
+
step: 1,
|
|
2331
|
+
message: createToolResultMessage({
|
|
2332
|
+
callId: CallId('vision-call-1'),
|
|
2333
|
+
content: [{ type: 'text', text: 'vision fresh evidence '.repeat(1_000) }],
|
|
2334
|
+
isError: false,
|
|
2335
|
+
}),
|
|
2336
|
+
}, { surfaceOp: 'append' })
|
|
2337
|
+
session.append('step/end', { turn: 1, step: 1 })
|
|
2338
|
+
session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
|
|
2339
|
+
// One older text result outside the fresh coordinates keeps History above
|
|
2340
|
+
// its trigger after Fresh has already shrunk the turn-1 result.
|
|
2341
|
+
appendToolTurn(session, 2, 'vision history evidence '.repeat(300), true, undefined, 'deepseek', VISION_MODEL)
|
|
2342
|
+
appendToolTurn(session, 3, 'recent protected result', true, undefined, 'deepseek', VISION_MODEL)
|
|
2343
|
+
session.append('turn/start', { turn: 4 })
|
|
2344
|
+
|
|
2345
|
+
const fresh = ctx.toolResultPruner.pruneSession(session, { stage: 'fresh', freshTurn: 1, freshStep: 1 })
|
|
2346
|
+
const pressure = ctx.toolResultPruner.pruneSession(session, { stage: 'pressure' })
|
|
2347
|
+
|
|
2348
|
+
expect(fresh.pruned).toHaveLength(1)
|
|
2349
|
+
expect(pressure.pruned.length).toBeGreaterThanOrEqual(1)
|
|
2350
|
+
const visionRewrites = rewrites(audit.records())
|
|
2351
|
+
.filter(record => record.sessionId === String(session.id))
|
|
2352
|
+
expect(visionRewrites.length).toBeGreaterThanOrEqual(2)
|
|
2353
|
+
for (const record of visionRewrites) {
|
|
2354
|
+
expect(record.tokenizerId).toBe('deepseek-ai/DeepSeek-V4-Flash-Vision-Exp')
|
|
2355
|
+
expect(record.tokenizerRevision).toBe('6821d6ad3681a4b137b066b76094fa82ebd0a380')
|
|
2356
|
+
}
|
|
2357
|
+
// Fresh is disabled by its trigger; Aggregate is the pre-compression stage
|
|
2358
|
+
// that lands on the vision route for the oversized new result.
|
|
2359
|
+
expect(visionRewrites.some(record => record.component === 'fresh')).toBe(false)
|
|
2360
|
+
expect(visionRewrites.some(record => record.component === 'aggregate')).toBe(true)
|
|
2361
|
+
expect(visionRewrites.some(record => record.component === 'history')).toBe(true)
|
|
2362
|
+
})
|
|
2363
|
+
|
|
2364
|
+
it('keeps an image-bearing tool result fail-open in a vision session', async () => {
|
|
2365
|
+
const ctx = await runtimeContext()
|
|
2366
|
+
const audit = captureAudit(ctx)
|
|
2367
|
+
await ctx.plugin(ToolResultPruner, {
|
|
2368
|
+
profile: 'balanced',
|
|
2369
|
+
freshTriggerTokens: 10,
|
|
2370
|
+
freshTargetTokens: 8,
|
|
2371
|
+
aggregateTriggerTokens: 10,
|
|
2372
|
+
aggregateTargetTokens: 8,
|
|
2373
|
+
historyTriggerTokens: 10,
|
|
2374
|
+
historyKeepRecentToolCalls: 0,
|
|
2375
|
+
historyKeepRecentTokens: 1,
|
|
2376
|
+
historyMinReclaimTokens: 1,
|
|
2377
|
+
}).await()
|
|
2378
|
+
const session = Session.create(SessionId('public-vision-image-tool-result'))
|
|
2379
|
+
session.append('turn/start', { turn: 1 })
|
|
2380
|
+
session.append('request/header', {
|
|
2381
|
+
reason: 'initial',
|
|
2382
|
+
header: canonicalHeader({ config: { provider: 'deepseek', model: VISION_MODEL } }),
|
|
2383
|
+
})
|
|
2384
|
+
session.append('step/start', { turn: 1, step: 1 })
|
|
2385
|
+
session.append('assistant/message', {
|
|
2386
|
+
stream: [],
|
|
2387
|
+
turn: 1,
|
|
2388
|
+
step: 1,
|
|
2389
|
+
message: createMessage({
|
|
2390
|
+
role: 'assistant',
|
|
2391
|
+
content: [{ type: 'tool-call', id: CallId('vision-image-call'), name: 'screenshot', arguments: '{}' }],
|
|
2392
|
+
source: { kind: 'model', provider: 'deepseek', model: VISION_MODEL },
|
|
2393
|
+
}),
|
|
2394
|
+
}, { surfaceOp: 'append' })
|
|
2395
|
+
session.append('tool/call', { turn: 1, step: 1, callId: CallId('vision-image-call'), name: 'screenshot', arguments: '{}' })
|
|
2396
|
+
const imageResult = session.append('tool/result', {
|
|
2397
|
+
turn: 1,
|
|
2398
|
+
step: 1,
|
|
2399
|
+
message: createToolResultMessage({
|
|
2400
|
+
callId: CallId('vision-image-call'),
|
|
2401
|
+
content: [
|
|
2402
|
+
{ type: 'text', text: 'screenshot captured' },
|
|
2403
|
+
imageBlock(800, 600),
|
|
2404
|
+
],
|
|
2405
|
+
isError: false,
|
|
2406
|
+
}),
|
|
2407
|
+
}, { surfaceOp: 'append' })
|
|
2408
|
+
session.append('step/end', { turn: 1, step: 1 })
|
|
2409
|
+
session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
|
|
2410
|
+
session.append('turn/start', { turn: 2 })
|
|
2411
|
+
|
|
2412
|
+
const fresh = ctx.toolResultPruner.pruneSession(session, { stage: 'fresh', freshTurn: 1, freshStep: 1 })
|
|
2413
|
+
const pressure = ctx.toolResultPruner.pruneSession(session, { stage: 'pressure' })
|
|
2414
|
+
|
|
2415
|
+
expect(fresh.pruned).toHaveLength(0)
|
|
2416
|
+
expect(pressure.pruned).toHaveLength(0)
|
|
2417
|
+
// The original image-bearing result stays on the surface untouched.
|
|
2418
|
+
const original = sessionEvents(session)[imageResult.seq]
|
|
2419
|
+
expect(original?.type).toBe('tool/result')
|
|
2420
|
+
// Character basis: the text-only guard rejects a rich node, so the fresh and
|
|
2421
|
+
// aggregate passes report no reducible candidate and the single candidate
|
|
2422
|
+
// stays inside the protected History tail. The image itself is never
|
|
2423
|
+
// rewritten, which is the behaviour this case exists to protect.
|
|
2424
|
+
expect(audit.records()).toContainEqual(expect.objectContaining({
|
|
2425
|
+
kind: 'component-evaluation',
|
|
2426
|
+
sessionId: String(session.id),
|
|
2427
|
+
component: 'fresh',
|
|
2428
|
+
status: 'skipped',
|
|
2429
|
+
reason: 'no-valid-reduction',
|
|
2430
|
+
measurementKind: 'characters',
|
|
2431
|
+
}))
|
|
2432
|
+
expect(audit.records()).toContainEqual(expect.objectContaining({
|
|
2433
|
+
kind: 'component-evaluation',
|
|
2434
|
+
sessionId: String(session.id),
|
|
2435
|
+
component: 'history',
|
|
2436
|
+
status: 'skipped',
|
|
2437
|
+
reason: 'protected-working-set',
|
|
2438
|
+
measurementKind: 'characters',
|
|
2439
|
+
}))
|
|
2440
|
+
})
|
|
2441
|
+
|
|
2442
|
+
it('counts image nodes as estimates while retaining exact text-only siblings', async () => {
|
|
2443
|
+
const ctx = await runtimeContext()
|
|
2444
|
+
const session = Session.create(SessionId('public-vision-image-surface'))
|
|
2445
|
+
session.append('turn/start', { turn: 1 })
|
|
2446
|
+
session.append('request/header', {
|
|
2447
|
+
reason: 'initial',
|
|
2448
|
+
header: canonicalHeader({ config: { provider: 'deepseek', model: VISION_MODEL } }),
|
|
2449
|
+
})
|
|
2450
|
+
const userMessage = session.append('user/message', createUserMessage({
|
|
2451
|
+
content: [
|
|
2452
|
+
{ type: 'text', text: 'look at this' },
|
|
2453
|
+
imageBlock(640, 480),
|
|
2454
|
+
{ type: 'text', text: 'and describe it' },
|
|
2455
|
+
],
|
|
2456
|
+
source: { kind: 'user' },
|
|
2457
|
+
}), { surfaceOp: 'append' })
|
|
2458
|
+
const textOnly = session.append('user/message', createUserMessage({
|
|
2459
|
+
content: [{ type: 'text', text: 'still exactly measurable' }],
|
|
2460
|
+
source: { kind: 'user' },
|
|
2461
|
+
}), { surfaceOp: 'append' })
|
|
2462
|
+
|
|
2463
|
+
const view = measureForCompaction(ctx, session)
|
|
2464
|
+
|
|
2465
|
+
// The exact request expansion is not publicly verifiable, so a mixed
|
|
2466
|
+
// text/image node carries a bounded estimate and cannot authorize an exact
|
|
2467
|
+
// rewrite proof.
|
|
2468
|
+
const node = view.measuredNodes.find(entry => entry.seq === userMessage.seq)
|
|
2469
|
+
expect(node?.count).toMatchObject({
|
|
2470
|
+
kind: 'tokenizer-estimate',
|
|
2471
|
+
estimatorId: DEEPSEEK_VISION_IMAGE_ESTIMATOR.id,
|
|
2472
|
+
estimatorRevision: DEEPSEEK_VISION_IMAGE_ESTIMATOR.revision,
|
|
2473
|
+
})
|
|
2474
|
+
if (node?.count.kind !== 'tokenizer-estimate') throw new Error('image node must carry an estimate')
|
|
2475
|
+
expect(node.count.upperBoundTokens).toBeGreaterThanOrEqual(node.count.tokens)
|
|
2476
|
+
expect(view.currentSurface.kind).toBe('tokenizer-estimate')
|
|
2477
|
+
// Text-only siblings keep their exact counts.
|
|
2478
|
+
expect(view.measuredNodes.find(entry => entry.seq === textOnly.seq)?.count).toMatchObject({
|
|
2479
|
+
kind: 'exact-tokenizer',
|
|
2480
|
+
tokenizerId: 'deepseek-ai/DeepSeek-V4-Flash-Vision-Exp',
|
|
2481
|
+
})
|
|
2482
|
+
// The official arithmetic is attached as an INTRINSIC diagnostic (the
|
|
2483
|
+
// padding extremes on intrinsic dimensions), explicitly not a request
|
|
2484
|
+
// bound: the adapter may still re-project the image.
|
|
2485
|
+
const grid = deepSeekVisionImageGrid(640, 480)
|
|
2486
|
+
expect(node.intrinsicImageBlockEstimate).toMatchObject({
|
|
2487
|
+
paddingMinimumTokens: deepSeekVisionImageBlockTokens(grid.nLlmH, grid.nLlmW, 3),
|
|
2488
|
+
paddingMaximumTokens: deepSeekVisionImageBlockTokens(grid.nLlmH, grid.nLlmW, 0),
|
|
2489
|
+
})
|
|
2490
|
+
expect(view.intrinsicImageBlockEstimateTokens).toBe(node.intrinsicImageBlockEstimate?.paddingMinimumTokens)
|
|
2491
|
+
})
|
|
2492
|
+
|
|
2493
|
+
it('estimates over-budget image metadata instead of making the surface unavailable', async () => {
|
|
2494
|
+
const ctx = await runtimeContext()
|
|
2495
|
+
const session = Session.create(SessionId('public-vision-image-over-budget'))
|
|
2496
|
+
session.append('turn/start', { turn: 1 })
|
|
2497
|
+
session.append('request/header', {
|
|
2498
|
+
reason: 'initial',
|
|
2499
|
+
header: canonicalHeader({ config: { provider: 'deepseek', model: VISION_MODEL } }),
|
|
2500
|
+
})
|
|
2501
|
+
const userMessage = session.append('user/message', createUserMessage({
|
|
2502
|
+
content: [imageBlock(4096, 4096)],
|
|
2503
|
+
source: { kind: 'user' },
|
|
2504
|
+
}), { surfaceOp: 'append' })
|
|
2505
|
+
|
|
2506
|
+
const view = measureForCompaction(ctx, session)
|
|
2507
|
+
|
|
2508
|
+
const node = view.measuredNodes.find(entry => entry.seq === userMessage.seq)
|
|
2509
|
+
expect(node?.count).toMatchObject({
|
|
2510
|
+
kind: 'tokenizer-estimate',
|
|
2511
|
+
upperBoundTokens: DEEPSEEK_VISION_PROJECTION.visionMaxNTokens,
|
|
2512
|
+
})
|
|
2513
|
+
expect(view.currentSurface.kind).toBe('tokenizer-estimate')
|
|
2514
|
+
})
|
|
2515
|
+
|
|
2516
|
+
it('keeps empty content nodes exact instead of fail-opening the surface', async () => {
|
|
2517
|
+
const ctx = await runtimeContext()
|
|
2518
|
+
const session = Session.create(SessionId('public-empty-content-node'))
|
|
2519
|
+
session.append('turn/start', { turn: 1 })
|
|
2520
|
+
session.append('request/header', {
|
|
2521
|
+
reason: 'initial',
|
|
2522
|
+
header: canonicalHeader({ config: { provider: 'deepseek', model: MODEL } }),
|
|
2523
|
+
})
|
|
2524
|
+
const empty = session.append('user/message', createUserMessage({
|
|
2525
|
+
content: [],
|
|
2526
|
+
source: { kind: 'user' },
|
|
2527
|
+
}), { surfaceOp: 'append' })
|
|
2528
|
+
const present = session.append('user/message', createUserMessage({
|
|
2529
|
+
content: [{ type: 'text', text: 'still measurable' }],
|
|
2530
|
+
source: { kind: 'user' },
|
|
2531
|
+
}), { surfaceOp: 'append' })
|
|
2532
|
+
|
|
2533
|
+
const view = measureForCompaction(ctx, session)
|
|
2534
|
+
|
|
2535
|
+
expect(view.measuredNodes.find(node => node.seq === empty.seq)?.count).toMatchObject({
|
|
2536
|
+
kind: 'exact-tokenizer',
|
|
2537
|
+
tokens: 0,
|
|
2538
|
+
})
|
|
2539
|
+
expect(view.measuredNodes.find(node => node.seq === present.seq)?.count).toMatchObject({
|
|
2540
|
+
kind: 'exact-tokenizer',
|
|
2541
|
+
})
|
|
2542
|
+
expect(view.currentSurface.kind).toBe('exact-tokenizer')
|
|
2543
|
+
})
|
|
2544
|
+
|
|
2545
|
+
it('uses the fixed image-token fallback for malformed metadata', async () => {
|
|
2546
|
+
const ctx = await runtimeContext()
|
|
2547
|
+
const session = Session.create(SessionId('public-vision-image-malformed-dims'))
|
|
2548
|
+
session.append('turn/start', { turn: 1 })
|
|
2549
|
+
session.append('request/header', {
|
|
2550
|
+
reason: 'initial',
|
|
2551
|
+
header: canonicalHeader({ config: { provider: 'deepseek', model: VISION_MODEL } }),
|
|
2552
|
+
})
|
|
2553
|
+
const userMessage = session.append('user/message', createUserMessage({
|
|
2554
|
+
content: [imageBlock(640.5, 480)],
|
|
2555
|
+
source: { kind: 'user' },
|
|
2556
|
+
}), { surfaceOp: 'append' })
|
|
2557
|
+
const zeroSize = session.append('user/message', createUserMessage({
|
|
2558
|
+
content: [imageBlock(0, 480)],
|
|
2559
|
+
source: { kind: 'user' },
|
|
2560
|
+
}), { surfaceOp: 'append' })
|
|
2561
|
+
|
|
2562
|
+
const view = measureForCompaction(ctx, session)
|
|
2563
|
+
|
|
2564
|
+
expect(view.measuredNodes.find(node => node.seq === userMessage.seq)?.count).toEqual({
|
|
2565
|
+
kind: 'tokenizer-estimate',
|
|
2566
|
+
tokens: DEEPSEEK_VISION_DEFAULT_IMAGE_TOKENS,
|
|
2567
|
+
upperBoundTokens: DEEPSEEK_VISION_PROJECTION.visionMaxNTokens,
|
|
2568
|
+
estimatorId: DEEPSEEK_VISION_IMAGE_ESTIMATOR.id,
|
|
2569
|
+
estimatorRevision: DEEPSEEK_VISION_IMAGE_ESTIMATOR.revision,
|
|
2570
|
+
})
|
|
2571
|
+
expect(view.measuredNodes.find(node => node.seq === zeroSize.seq)?.count).toEqual({
|
|
2572
|
+
kind: 'tokenizer-estimate',
|
|
2573
|
+
tokens: DEEPSEEK_VISION_DEFAULT_IMAGE_TOKENS,
|
|
2574
|
+
upperBoundTokens: DEEPSEEK_VISION_PROJECTION.visionMaxNTokens,
|
|
2575
|
+
estimatorId: DEEPSEEK_VISION_IMAGE_ESTIMATOR.id,
|
|
2576
|
+
estimatorRevision: DEEPSEEK_VISION_IMAGE_ESTIMATOR.revision,
|
|
2577
|
+
})
|
|
2578
|
+
expect(view.currentSurface).toMatchObject({
|
|
2579
|
+
kind: 'tokenizer-estimate',
|
|
2580
|
+
tokens: DEEPSEEK_VISION_DEFAULT_IMAGE_TOKENS * 2,
|
|
2581
|
+
upperBoundTokens: DEEPSEEK_VISION_PROJECTION.visionMaxNTokens * 2,
|
|
2582
|
+
})
|
|
2583
|
+
})
|
|
2584
|
+
|
|
2585
|
+
it('keeps image content unavailable for non-vision models', async () => {
|
|
2586
|
+
const ctx = await runtimeContext()
|
|
2587
|
+
const session = Session.create(SessionId('public-text-model-image-node'))
|
|
2588
|
+
session.append('turn/start', { turn: 1 })
|
|
2589
|
+
session.append('request/header', {
|
|
2590
|
+
reason: 'initial',
|
|
2591
|
+
header: canonicalHeader({ config: { provider: 'deepseek', model: MODEL } }),
|
|
2592
|
+
})
|
|
2593
|
+
const userMessage = session.append('user/message', createUserMessage({
|
|
2594
|
+
content: [imageBlock(640, 480)],
|
|
2595
|
+
source: { kind: 'user' },
|
|
2596
|
+
}), { surfaceOp: 'append' })
|
|
2597
|
+
|
|
2598
|
+
const view = measureForCompaction(ctx, session)
|
|
2599
|
+
|
|
2600
|
+
expect(view.measuredNodes.find(entry => entry.seq === userMessage.seq)?.count).toMatchObject({
|
|
2601
|
+
kind: 'unavailable',
|
|
2602
|
+
})
|
|
2603
|
+
})
|
|
2604
|
+
|
|
2605
|
+
it('keeps the vision image estimator unavailable behind a foreign provider', async () => {
|
|
2606
|
+
const ctx = await runtimeContext()
|
|
2607
|
+
const session = Session.create(SessionId('public-foreign-provider-vision-image-node'))
|
|
2608
|
+
session.append('turn/start', { turn: 1 })
|
|
2609
|
+
session.append('request/header', {
|
|
2610
|
+
reason: 'initial',
|
|
2611
|
+
header: canonicalHeader({ config: { provider: 'openai', model: VISION_MODEL } }),
|
|
2612
|
+
})
|
|
2613
|
+
const userMessage = session.append('user/message', createUserMessage({
|
|
2614
|
+
content: [imageBlock(640, 480)],
|
|
2615
|
+
source: { kind: 'user' },
|
|
2616
|
+
}), { surfaceOp: 'append' })
|
|
2617
|
+
|
|
2618
|
+
const view = measureForCompaction(ctx, session)
|
|
2619
|
+
|
|
2620
|
+
expect(view.measuredNodes.find(entry => entry.seq === userMessage.seq)?.count).toMatchObject({
|
|
2621
|
+
kind: 'unavailable',
|
|
2622
|
+
})
|
|
2623
|
+
expect(view.currentSurface).toMatchObject({ kind: 'unavailable' })
|
|
2624
|
+
})
|
|
2625
|
+
|
|
2626
|
+
it('never TailTrims a tool group whose results carry images', async () => {
|
|
2627
|
+
const ctx = await runtimeContext()
|
|
2628
|
+
await ctx.plugin(TestSettings).await()
|
|
2629
|
+
await ctx.plugin(LegacyNamespaceRegistrar).await()
|
|
2630
|
+
const audit = captureAudit(ctx)
|
|
2631
|
+
await ctx.settings.update(nsBrand(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE), {
|
|
2632
|
+
profile: 'custom',
|
|
2633
|
+
custom: {
|
|
2634
|
+
version: 3,
|
|
2635
|
+
unit: 'tokens',
|
|
2636
|
+
fresh: { enabled: true, trigger: 1_000_000, target: 900_000 },
|
|
2637
|
+
aggregate: { enabled: true, trigger: 1_000_000, target: 900_000 },
|
|
2638
|
+
history: { enabled: false, trigger: 900_000, keepRecentToolCalls: 0, keepRecentTokens: 0, minReclaim: 1 },
|
|
2639
|
+
prefixPolicy: 'preserve',
|
|
2640
|
+
tailTrim: { enabled: true, trigger: 10 },
|
|
2641
|
+
},
|
|
2642
|
+
})
|
|
2643
|
+
await ctx.plugin(ToolResultPruner, { profile: 'custom' }).await()
|
|
2644
|
+
const session = Session.create(SessionId('public-vision-tailtrim-image-group'))
|
|
2645
|
+
session.append('turn/start', { turn: 1 })
|
|
2646
|
+
session.append('request/header', {
|
|
2647
|
+
reason: 'initial',
|
|
2648
|
+
header: canonicalHeader({ config: { provider: 'deepseek', model: VISION_MODEL } }),
|
|
2649
|
+
})
|
|
2650
|
+
session.append('step/start', { turn: 1, step: 1 })
|
|
2651
|
+
session.append('assistant/message', {
|
|
2652
|
+
stream: [],
|
|
2653
|
+
turn: 1,
|
|
2654
|
+
step: 1,
|
|
2655
|
+
message: createMessage({
|
|
2656
|
+
role: 'assistant',
|
|
2657
|
+
content: [{ type: 'tool-call', id: CallId('vision-tailtrim-call'), name: 'screenshot', arguments: '{}' }],
|
|
2658
|
+
source: { kind: 'model', provider: 'deepseek', model: VISION_MODEL },
|
|
2659
|
+
}),
|
|
2660
|
+
}, { surfaceOp: 'append' })
|
|
2661
|
+
session.append('tool/call', { turn: 1, step: 1, callId: CallId('vision-tailtrim-call'), name: 'screenshot', arguments: '{}' })
|
|
2662
|
+
session.append('tool/result', {
|
|
2663
|
+
turn: 1,
|
|
2664
|
+
step: 1,
|
|
2665
|
+
message: createToolResultMessage({
|
|
2666
|
+
callId: CallId('vision-tailtrim-call'),
|
|
2667
|
+
content: [
|
|
2668
|
+
{ type: 'text', text: 'screenshot captured for tail trim' },
|
|
2669
|
+
imageBlock(320, 240),
|
|
2670
|
+
],
|
|
2671
|
+
isError: false,
|
|
2672
|
+
}),
|
|
2673
|
+
}, { surfaceOp: 'append' })
|
|
2674
|
+
session.append('step/end', { turn: 1, step: 1 })
|
|
2675
|
+
session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
|
|
2676
|
+
session.append('turn/start', { turn: 2 })
|
|
2677
|
+
|
|
2678
|
+
const result = ctx.toolResultPruner.pruneSession(session, { stage: 'pressure' })
|
|
2679
|
+
|
|
2680
|
+
expect(result.pruned).toHaveLength(0)
|
|
2681
|
+
expect(rewrites(audit.records()).some(record =>
|
|
2682
|
+
record.sessionId === String(session.id) && record.component === 'tail-trim')).toBe(false)
|
|
2683
|
+
expect(sessionEvents(session).some(event =>
|
|
2684
|
+
event.type === 'tool/result'
|
|
2685
|
+
&& event.data.message.content.some(block => block.type === 'image'))).toBe(true)
|
|
2686
|
+
// Either fail-open gate is acceptable: the protected-set scan refuses the
|
|
2687
|
+
// image-bearing candidate, and the group scan independently refuses it.
|
|
2688
|
+
const tailTrimSkips = audit.records().filter((record): record is Extract<CompressionAuditRecord, { kind: 'component-evaluation' }> =>
|
|
2689
|
+
record.kind === 'component-evaluation'
|
|
2690
|
+
&& record.sessionId === String(session.id)
|
|
2691
|
+
&& record.component === 'tail-trim'
|
|
2692
|
+
&& record.status === 'skipped')
|
|
2693
|
+
expect(tailTrimSkips.length).toBeGreaterThan(0)
|
|
2694
|
+
expect(tailTrimSkips.every(record =>
|
|
2695
|
+
record.reason === 'no-safe-eligible-tool-group'
|
|
2696
|
+
|| record.reason === 'exact-tokenizer-unavailable-in-protected-set'
|
|
2697
|
+
|| record.reason === 'exact-tokenizer-unavailable')).toBe(true)
|
|
2698
|
+
})
|
|
2699
|
+
})
|
|
2700
|
+
|
|
2701
|
+
describe('character basis / model-id independence', () => {
|
|
2702
|
+
// ~57,688 characters of read-type output on the decision surface, in the
|
|
2703
|
+
// code shape the hypa-code-skeleton reducer collapses.
|
|
2704
|
+
const readFixture = [
|
|
2705
|
+
"import { readFile } from 'node:fs/promises'",
|
|
2706
|
+
'',
|
|
2707
|
+
...Array.from({ length: 300 }, (_, index) => [
|
|
2708
|
+
`export function handler${String(index)}(input: string): string {`,
|
|
2709
|
+
` const normalized = input.trim().toLowerCase()`,
|
|
2710
|
+
` if (normalized.length === 0) return 'empty-${String(index)}'`,
|
|
2711
|
+
` return normalized.split('-').join('+')`,
|
|
2712
|
+
'}',
|
|
2713
|
+
'',
|
|
2714
|
+
]).flat(),
|
|
2715
|
+
].join('\n')
|
|
2716
|
+
|
|
2717
|
+
async function characterBasisContext(): Promise<Context> {
|
|
2718
|
+
const ctx = await runtimeContext()
|
|
2719
|
+
await ctx.plugin(TestSettings).await()
|
|
2720
|
+
await ctx.plugin(LegacyNamespaceRegistrar).await()
|
|
2721
|
+
await ctx.settings.update(nsBrand(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE), {
|
|
2722
|
+
profile: 'balanced',
|
|
2723
|
+
codeSkeleton: { enabled: true },
|
|
2724
|
+
})
|
|
2725
|
+
await ctx.plugin(ToolResultPruner, {
|
|
2726
|
+
profile: 'balanced',
|
|
2727
|
+
freshTriggerTokens: 1_000,
|
|
2728
|
+
freshTargetTokens: 800,
|
|
2729
|
+
aggregateTriggerTokens: 500_000,
|
|
2730
|
+
aggregateTargetTokens: 450_000,
|
|
2731
|
+
historyTriggerTokens: 500_000,
|
|
2732
|
+
}).await()
|
|
2733
|
+
return ctx
|
|
2734
|
+
}
|
|
2735
|
+
|
|
2736
|
+
for (const routedModel of ['deepseek-nonexistent-9', 'deepseek-flash']) {
|
|
2737
|
+
it(`lands a fresh reduction on the character basis for routed model ${routedModel}`, async () => {
|
|
2738
|
+
const ctx = await characterBasisContext()
|
|
2739
|
+
const audit = captureAudit(ctx)
|
|
2740
|
+
const session = Session.create(SessionId(`public-char-basis-${routedModel}`))
|
|
2741
|
+
appendToolTurn(session, 1, readFixture, false, undefined, 'deepseek-official', routedModel, 'read')
|
|
2742
|
+
|
|
2743
|
+
const result = ctx.toolResultPruner.pruneSession(session, {
|
|
2744
|
+
stage: 'fresh',
|
|
2745
|
+
freshTurn: 1,
|
|
2746
|
+
freshStep: 1,
|
|
2747
|
+
})
|
|
2748
|
+
|
|
2749
|
+
expect(result.pruned.length).toBe(1)
|
|
2750
|
+
expect(result.pruned[0]?.reducer).toBe('hypa-code-skeleton')
|
|
2751
|
+
// The decision ran on characters: the record must not claim an exact
|
|
2752
|
+
// tokenizer it never used.
|
|
2753
|
+
const record = rewrites(audit.records()).find(entry => entry.component === 'fresh')
|
|
2754
|
+
expect(record?.measurementBasis).toBe('characters')
|
|
2755
|
+
expect(record?.tokenizerId).toBe('characters')
|
|
2756
|
+
expect(record?.tokenizerRevision).toBe('chars-per-token-4.0')
|
|
2757
|
+
})
|
|
2758
|
+
}
|
|
2759
|
+
|
|
2760
|
+
it('keeps the exact-tokenizer basis and the same reducer for a whitelisted model', async () => {
|
|
2761
|
+
const ctx = await characterBasisContext()
|
|
2762
|
+
const audit = captureAudit(ctx)
|
|
2763
|
+
const session = Session.create(SessionId('public-char-basis-whitelisted'))
|
|
2764
|
+
appendToolTurn(session, 1, readFixture, false, undefined, 'deepseek-official', MODEL, 'read')
|
|
2765
|
+
|
|
2766
|
+
const result = ctx.toolResultPruner.pruneSession(session, {
|
|
2767
|
+
stage: 'fresh',
|
|
2768
|
+
freshTurn: 1,
|
|
2769
|
+
freshStep: 1,
|
|
2770
|
+
})
|
|
2771
|
+
|
|
2772
|
+
expect(result.pruned.length).toBe(1)
|
|
2773
|
+
expect(result.pruned[0]?.reducer).toBe('hypa-code-skeleton')
|
|
2774
|
+
const record = rewrites(audit.records()).find(entry => entry.component === 'fresh')
|
|
2775
|
+
expect(record?.measurementBasis).toBe('exact-tokenizer')
|
|
2776
|
+
expect(record?.tokenizerId).toEqual(expect.stringContaining('deepseek'))
|
|
2777
|
+
expect(record?.tokenizerRevision).toEqual(expect.any(String))
|
|
2778
|
+
expect(record?.tokensBefore).toBeGreaterThan(0)
|
|
2779
|
+
expect(record?.tokensAfter).toBeGreaterThan(0)
|
|
2780
|
+
})
|
|
2781
|
+
})
|