dsh-context-compression-improved 0.9.8 → 0.9.9-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (239) hide show
  1. package/README.md +15 -98
  2. package/README.zh.md +14 -92
  3. package/THIRD_PARTY_NOTICES.md +25 -7
  4. package/{packages/selector/dsh.plugin.json → dsh.plugin.json} +1 -1
  5. package/{packages/selector/lib → lib}/client.d.ts +16 -0
  6. package/{packages/selector/lib → lib}/client.js +393 -116
  7. package/{packages/selector/lib → lib}/index.js +829 -10
  8. package/{packages/selector/lib → lib}/invariant.js +2 -1
  9. package/{packages/selector/lib → lib}/pruner.d.ts +1 -1
  10. package/{packages/selector/lib → lib}/pruner.js +77 -983
  11. package/lib/savings-integral.js +4515 -0
  12. package/{packages/selector/lib → lib}/tail-trim.js +2 -90
  13. package/lib/tool-result.js +150 -0
  14. package/package.json +125 -112
  15. package/screenshots.json +3 -6
  16. package/.gitattributes +0 -2
  17. package/.githooks/pre-push +0 -37
  18. package/.github/workflows/ci.yml +0 -39
  19. package/CHANGELOG.de.md +0 -580
  20. package/CHANGELOG.es.md +0 -588
  21. package/CHANGELOG.fr.md +0 -576
  22. package/CHANGELOG.it.md +0 -577
  23. package/CHANGELOG.ja.md +0 -261
  24. package/CHANGELOG.ko.md +0 -254
  25. package/CHANGELOG.md +0 -536
  26. package/CHANGELOG.ru.md +0 -554
  27. package/CHANGELOG.zh.md +0 -236
  28. package/CONTRIBUTING.md +0 -22
  29. package/README.de.md +0 -96
  30. package/README.es.md +0 -96
  31. package/README.fr.md +0 -96
  32. package/README.it.md +0 -96
  33. package/README.ja.md +0 -102
  34. package/README.ko.md +0 -102
  35. package/README.ru.md +0 -96
  36. package/SECURITY.md +0 -18
  37. package/assets/board.png +0 -0
  38. package/assets/context.png +0 -0
  39. package/docs/assets/context-compression-selector-profiles.jpg +0 -0
  40. package/docs/assets/context-compression-selector-settings.png +0 -0
  41. package/docs/compat-0.1.5-report.md +0 -77
  42. package/docs/installation.de.md +0 -104
  43. package/docs/installation.es.md +0 -104
  44. package/docs/installation.fr.md +0 -104
  45. package/docs/installation.it.md +0 -104
  46. package/docs/installation.ja.md +0 -78
  47. package/docs/installation.ko.md +0 -78
  48. package/docs/installation.md +0 -103
  49. package/docs/installation.ru.md +0 -104
  50. package/docs/installation.zh.md +0 -100
  51. package/docs/repair-log.md +0 -657
  52. package/eslint.config.js +0 -30
  53. package/packages/selector/LICENSE +0 -21
  54. package/packages/selector/README.md +0 -26
  55. package/packages/selector/README.zh.md +0 -24
  56. package/packages/selector/THIRD_PARTY_NOTICES.md +0 -32
  57. package/packages/selector/docs/history-tool-call-working-set-spec.md +0 -112
  58. package/packages/selector/docs/native-tool-result-selector-spec.md +0 -34
  59. package/packages/selector/docs/subagent-cache-reuse-spec.md +0 -46
  60. package/packages/selector/lib/config.js +0 -1777
  61. package/packages/selector/lib/host-generation.js +0 -62
  62. package/packages/selector/lib/style.css +0 -350
  63. package/packages/selector/package.json +0 -174
  64. package/packages/selector/screenshots.json +0 -3
  65. package/packages/selector/src/client/CompressionProfileControls.tsx +0 -293
  66. package/packages/selector/src/client/CompressionProfileSelector.module.css +0 -199
  67. package/packages/selector/src/client/CompressionProfileSelector.tsx +0 -85
  68. package/packages/selector/src/client/CustomPolicyEditor.tsx +0 -216
  69. package/packages/selector/src/client/EstimatorControls.tsx +0 -277
  70. package/packages/selector/src/client/bridge-scope.ts +0 -125
  71. package/packages/selector/src/client/decode.ts +0 -57
  72. package/packages/selector/src/client/index.ts +0 -421
  73. package/packages/selector/src/client/locales/de.ts +0 -142
  74. package/packages/selector/src/client/locales/es.ts +0 -142
  75. package/packages/selector/src/client/locales/fr.ts +0 -142
  76. package/packages/selector/src/client/locales/it.ts +0 -142
  77. package/packages/selector/src/client/locales/ja.ts +0 -142
  78. package/packages/selector/src/client/locales/ko.ts +0 -142
  79. package/packages/selector/src/client/locales/ru.ts +0 -142
  80. package/packages/selector/src/client/locales.ts +0 -284
  81. package/packages/selector/src/client/monitor-fab.ts +0 -349
  82. package/packages/selector/src/client/preset-options.ts +0 -88
  83. package/packages/selector/src/client/savings-card.tsx +0 -150
  84. package/packages/selector/src/client/scope-face.ts +0 -24
  85. package/packages/selector/src/client/settings-section.tsx +0 -140
  86. package/packages/selector/src/compat/host-generation.ts +0 -96
  87. package/packages/selector/src/compat/llm-messages.ts +0 -50
  88. package/packages/selector/src/compat/settings-lease.ts +0 -108
  89. package/packages/selector/src/compat/tool-result.ts +0 -91
  90. package/packages/selector/src/css-modules.d.ts +0 -6
  91. package/packages/selector/src/deepseek-v4-tokenizer.ts +0 -205
  92. package/packages/selector/src/estimator-catalog.ts +0 -104
  93. package/packages/selector/src/index.ts +0 -655
  94. package/packages/selector/src/invariant.ts +0 -113
  95. package/packages/selector/src/preset-overlay.ts +0 -749
  96. package/packages/selector/src/profiles.ts +0 -431
  97. package/packages/selector/src/pruner/content.ts +0 -198
  98. package/packages/selector/src/pruner/session.ts +0 -97
  99. package/packages/selector/src/pruner/state.ts +0 -61
  100. package/packages/selector/src/pruner/tuning.ts +0 -23
  101. package/packages/selector/src/pruner/types.ts +0 -78
  102. package/packages/selector/src/pruner.ts +0 -2868
  103. package/packages/selector/src/runtime/adaptive-cost.ts +0 -205
  104. package/packages/selector/src/runtime/audit.ts +0 -303
  105. package/packages/selector/src/runtime/config.ts +0 -756
  106. package/packages/selector/src/runtime/custom-policy.ts +0 -278
  107. package/packages/selector/src/runtime/deepseek-official-pricing.ts +0 -298
  108. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +0 -254
  109. package/packages/selector/src/runtime/measurement.ts +0 -444
  110. package/packages/selector/src/runtime/monitor.ts +0 -235
  111. package/packages/selector/src/runtime/reducers.ts +0 -1754
  112. package/packages/selector/src/runtime/retrieve.ts +0 -484
  113. package/packages/selector/src/runtime/savings-projection.ts +0 -226
  114. package/packages/selector/src/runtime/savings.ts +0 -417
  115. package/packages/selector/src/runtime/session-events.ts +0 -30
  116. package/packages/selector/src/runtime/summary-command.ts +0 -127
  117. package/packages/selector/src/runtime/tail-trim.ts +0 -176
  118. package/packages/selector/src/runtime/token-count.ts +0 -72
  119. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +0 -233
  120. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +0 -204
  121. package/packages/selector/src/runtime/tokenpilot/advisor.ts +0 -419
  122. package/packages/selector/src/runtime/tokenpilot/benefit.ts +0 -200
  123. package/packages/selector/src/runtime/tokenpilot/dedup.ts +0 -81
  124. package/packages/selector/src/runtime/tokenpilot/estimator.ts +0 -151
  125. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +0 -53
  126. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +0 -65
  127. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +0 -125
  128. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +0 -37
  129. package/packages/selector/src/runtime/tokenpilot/locator.ts +0 -128
  130. package/packages/selector/src/runtime/tokenpilot/read-state.ts +0 -98
  131. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +0 -303
  132. package/packages/selector/src/runtime/toolclass.ts +0 -103
  133. package/packages/selector/src/runtime/types.ts +0 -365
  134. package/packages/selector/src/runtime/value.ts +0 -48
  135. package/packages/selector/src/settings-bridge.ts +0 -175
  136. package/packages/selector/tests/advisor-report.host.spec.ts +0 -223
  137. package/packages/selector/tests/auto-compact.client.spec.tsx +0 -214
  138. package/packages/selector/tests/built/client-artifact.spec.ts +0 -56
  139. package/packages/selector/tests/cache-prefix-audit.spec.ts +0 -123
  140. package/packages/selector/tests/code-skeleton.client.spec.ts +0 -98
  141. package/packages/selector/tests/compat/compat-narrow-waist.spec.ts +0 -150
  142. package/packages/selector/tests/custom-contract.client.spec.ts +0 -226
  143. package/packages/selector/tests/estimator-catalog.spec.ts +0 -70
  144. package/packages/selector/tests/estimator-channel.client.spec.tsx +0 -253
  145. package/packages/selector/tests/estimator-route-registration.host.spec.ts +0 -199
  146. package/packages/selector/tests/helpers/legacy-namespace.ts +0 -35
  147. package/packages/selector/tests/helpers/legacy-settings/index.ts +0 -15
  148. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +0 -41
  149. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +0 -647
  150. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +0 -78
  151. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +0 -234
  152. package/packages/selector/tests/host-preset-overlay.host.spec.ts +0 -204
  153. package/packages/selector/tests/monitor-fab.client.spec.ts +0 -138
  154. package/packages/selector/tests/preset-options-write.client.spec.ts +0 -192
  155. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +0 -200
  156. package/packages/selector/tests/preset-overlay.host.spec.ts +0 -246
  157. package/packages/selector/tests/profiles.client.spec.tsx +0 -436
  158. package/packages/selector/tests/public/package-contract.client.spec.ts +0 -86
  159. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +0 -167
  160. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +0 -230
  161. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +0 -272
  162. package/packages/selector/tests/runtime/advisor.spec.ts +0 -226
  163. package/packages/selector/tests/runtime/audit.spec.ts +0 -275
  164. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +0 -523
  165. package/packages/selector/tests/runtime/char-basis.spec.ts +0 -30
  166. package/packages/selector/tests/runtime/code-skeleton.spec.ts +0 -152
  167. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +0 -186
  168. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +0 -122
  169. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +0 -122
  170. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +0 -96
  171. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +0 -273
  172. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +0 -106
  173. package/packages/selector/tests/runtime/fixtures/vision-golden.json +0 -459
  174. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +0 -74
  175. package/packages/selector/tests/runtime/fresh-gate.spec.ts +0 -43
  176. package/packages/selector/tests/runtime/html-reducer.spec.ts +0 -212
  177. package/packages/selector/tests/runtime/intent-gate.spec.ts +0 -62
  178. package/packages/selector/tests/runtime/intent-summary.spec.ts +0 -156
  179. package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +0 -79
  180. package/packages/selector/tests/runtime/line-mapping.spec.ts +0 -153
  181. package/packages/selector/tests/runtime/monitor.spec.ts +0 -301
  182. package/packages/selector/tests/runtime/prose-reducers.spec.ts +0 -133
  183. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +0 -2782
  184. package/packages/selector/tests/runtime/read-input-cap.spec.ts +0 -33
  185. package/packages/selector/tests/runtime/savings-projection.spec.ts +0 -89
  186. package/packages/selector/tests/runtime/savings.spec.ts +0 -139
  187. package/packages/selector/tests/runtime/search-reducer.spec.ts +0 -110
  188. package/packages/selector/tests/runtime/session-events.spec.ts +0 -27
  189. package/packages/selector/tests/runtime/settings-unwrap.spec.ts +0 -58
  190. package/packages/selector/tests/runtime/sidechannel.spec.ts +0 -241
  191. package/packages/selector/tests/runtime/summary-command.spec.ts +0 -154
  192. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +0 -159
  193. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +0 -53
  194. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +0 -217
  195. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +0 -52
  196. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +0 -79
  197. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +0 -76
  198. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +0 -119
  199. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +0 -82
  200. package/packages/selector/tests/runtime/toolclass.spec.ts +0 -156
  201. package/packages/selector/tests/runtime/value.spec.ts +0 -23
  202. package/packages/selector/tests/settings-seat.client.spec.ts +0 -215
  203. package/packages/selector/tests/standing-generation.host.spec.ts +0 -724
  204. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +0 -269
  205. package/packages/selector/tests/support/cache-prefix-audit.ts +0 -105
  206. package/packages/selector/tests/support/mock-adapter.ts +0 -37
  207. package/packages/selector/tests/support/ui-primitives.tsx +0 -34
  208. package/packages/selector/tsconfig.json +0 -11
  209. package/packages/selector/tsdown.client.config.ts +0 -102
  210. package/packages/selector/tsdown.config.ts +0 -20
  211. package/pnpm-workspace.yaml +0 -72
  212. package/scripts/capture-profile-baseline.mjs +0 -42
  213. package/scripts/cell-browser-e2e.mjs +0 -354
  214. package/scripts/generate-tokenizer-fixtures.py +0 -81
  215. package/scripts/generate-vision-fixtures.py +0 -208
  216. package/scripts/hosts.mjs +0 -78
  217. package/scripts/packed-components-smoke.mjs +0 -763
  218. package/scripts/packed-install-e2e.mjs +0 -1346
  219. package/scripts/sync-hosts.mjs +0 -174
  220. package/scripts/toolclass-corpus-replay.mjs +0 -281
  221. package/scripts/verify-release.mjs +0 -335
  222. package/tests/TEST_INVENTORY.md +0 -41
  223. package/tsconfig.base.json +0 -18
  224. package/tsconfig.json +0 -7
  225. package/tsconfig.tests.json +0 -15
  226. package/vitest.built.config.ts +0 -9
  227. package/vitest.config.ts +0 -46
  228. /package/{packages/selector/assets → assets}/deepseek-v4/LICENSE.DeepSeek-V4-Pro.txt +0 -0
  229. /package/{packages/selector/assets → assets}/deepseek-v4/manifest.json +0 -0
  230. /package/{packages/selector/assets → assets}/deepseek-v4/tokenizer.json +0 -0
  231. /package/{packages/selector/assets → assets}/deepseek-v4/tokenizer_config.json +0 -0
  232. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/LICENSE.DeepSeek-V4-Flash-Vision-Exp.txt +0 -0
  233. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/manifest.json +0 -0
  234. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/tokenizer.json +0 -0
  235. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/tokenizer_config.json +0 -0
  236. /package/{packages/selector/cordis.patch.yml → cordis.patch.yml} +0 -0
  237. /package/{packages/selector/lib → lib}/index.d.ts +0 -0
  238. /package/{packages/selector/lib → lib}/invariant.d.ts +0 -0
  239. /package/{packages/selector/lib → lib}/profiles.d.ts +0 -0
@@ -1,724 +0,0 @@
1
- /** Real-AgentPresets standing-generation behavior for the overlay threshold. */
2
-
3
- import { createHash } from 'node:crypto'
4
- import { mkdir, mkdtemp, readdir, readFile, rm, stat, utimes, writeFile } from 'node:fs/promises'
5
- import { tmpdir } from 'node:os'
6
- import { dirname, join } from 'node:path'
7
- import { Context } from '@deepseek-ai/cordis'
8
- import Group from '@deepseek-ai/cordis-plugin-group'
9
- import Include from '@deepseek-ai/cordis-plugin-include'
10
- import Loader from '@deepseek-ai/cordis-plugin-loader'
11
- import AgentRegistry from '@deepseek-ai/dsh-agent'
12
- import AgentLoop from '@deepseek-ai/dsh-agent-loop'
13
- import AgentPresets from '@deepseek-ai/dsh-agent-presets'
14
- import CommandRuntime from '@deepseek-ai/dsh-commands'
15
- import LlmRuntime from '@deepseek-ai/dsh-llm'
16
- import SessionStore from '@deepseek-ai/dsh-session'
17
- import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
18
- import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
19
- import TokenMeter from '@deepseek-ai/dsh-token-meter'
20
- import ToolRuntime from '@deepseek-ai/dsh-tools'
21
- import { type SettingsNamespace } from '@deepseek-ai/dsh-settings'
22
- import { LegacySettingsProvider } from './helpers/legacy-settings/index.ts'
23
- import { pathToFileURL } from 'node:url'
24
- import { afterEach, describe, expect, it } from 'vitest'
25
- import { apply } from '../src/index.ts'
26
- import {
27
- decorateAgentPresets,
28
- resolveCompressionModulePaths,
29
- standingStampMs,
30
- standingStampMsAtWindow,
31
- } from '../src/preset-overlay.ts'
32
- import { LegacyNamespaceRegistrar } from './helpers/legacy-namespace.ts'
33
- import type {
34
- CompressionModulePaths,
35
- OverlayableAgentPresets,
36
- PresetOverlayMetadataIo,
37
- } from '../src/preset-overlay.ts'
38
-
39
- // 0.1.5 removed the settingsNamespace() wrapper; namespaces are validated at runtime.
40
- const nsBrand = (value: string): SettingsNamespace => value as unknown as SettingsNamespace
41
-
42
- let root: string | undefined
43
- let ctx: Context | undefined
44
-
45
- afterEach(async () => {
46
- await ctx?.fiber.dispose()
47
- ctx = undefined
48
- if (root !== undefined) await rm(root, { recursive: true, force: true })
49
- root = undefined
50
- })
51
-
52
- class MemorySettings extends LegacySettingsProvider {
53
- readonly writable = true
54
- private readonly stored: Record<string, unknown> = {}
55
-
56
- protected load(): Promise<Record<string, unknown>> {
57
- return Promise.resolve(structuredClone(this.stored))
58
- }
59
-
60
- protected persist(ns: SettingsNamespace, section: Record<string, unknown>): Promise<void> {
61
- this.stored[ns] = structuredClone(section)
62
- return Promise.resolve()
63
- }
64
- }
65
-
66
- async function presetsRoot(): Promise<string> {
67
- root = await mkdtemp(join(tmpdir(), 'dsh-selector-standing-'))
68
- const marker = join(root, 'marker-aaaaaaaaaa.mjs')
69
- await writeFile(marker, 'export function apply() {}\n')
70
- const path = join(root, 'standard', 'agent.cordis.yml')
71
- await mkdir(dirname(path), { recursive: true })
72
- await writeFile(path, `- id: source-marker\n name: ${JSON.stringify(marker)}\n`)
73
- return root
74
- }
75
-
76
- /**
77
- * Read the overlay compositions generated from THIS test's source preset.
78
- * Concurrent spec files write their own stores; the embedded marker path
79
- * distinguishes ours without depending on directory discovery timing.
80
- */
81
- async function overlayFiles(sourceMarker: string): Promise<{ path: string, rendered: string }[]> {
82
- const parent = await readdir(tmpdir(), { withFileTypes: true })
83
- const files: { path: string, rendered: string }[] = []
84
- for (const entry of parent) {
85
- if (!entry.isDirectory() || !entry.name.startsWith('dsh-context-compression-presets-')) continue
86
- const directory = join(tmpdir(), entry.name)
87
- let children
88
- try {
89
- children = await readdir(directory)
90
- } catch {
91
- continue // a concurrent spec disposed its store mid-scan
92
- }
93
- for (const child of children) {
94
- if (!child.startsWith('standard-') || !child.endsWith('.agent.cordis.yml')) continue
95
- const path = join(directory, child)
96
- const rendered = await readFile(path, 'utf8')
97
- if (rendered.includes(sourceMarker)) files.push({ path, rendered })
98
- }
99
- }
100
- return files
101
- }
102
-
103
- /**
104
- * The mtime this platform actually persists for one given stamp.
105
- *
106
- * `node:fs` `utimes` writes the seconds component through a 32-bit field on
107
- * Windows: on node v22 win32, `utimes(file, 4677832452 s)` reads back as
108
- * `382865156 s` — exactly `seconds >>> 0` — while sub-second precision
109
- * survives. The standing stamp deliberately parks identities around year 2162
110
- * (`STANDING_MTIME_EPOCH_SECONDS + 0xffffffff`, src/preset-overlay.ts), so its
111
- * seconds component sits past that 2^32-second horizon (max year 2106) and the
112
- * persisted literal differs on that platform. Deterministically so: the wrap is
113
- * a pure function of the identity stamp, which is why identity → mtime stays
114
- * stable and the collision escalation still absorbs any merge.
115
- *
116
- * Instead of hardcoding the platform or weakening the assertion, calibrate:
117
- * ask the filesystem what it stores for exactly this stamp, then require the
118
- * overlay to persist that same value. On a platform with a full-width seconds
119
- * field this collapses to the stamp itself, so the assertion stays strict.
120
- */
121
- async function platformPersistedMs(stampMs: number): Promise<number> {
122
- const directory = await mkdtemp(join(tmpdir(), 'dsh-selector-mtime-probe-'))
123
- const probe = join(directory, 'probe')
124
- try {
125
- await writeFile(probe, 'probe')
126
- const stamp = new Date(stampMs)
127
- await utimes(probe, stamp, stamp)
128
- return (await stat(probe)).mtimeMs
129
- } finally {
130
- await rm(directory, { recursive: true, force: true })
131
- }
132
- }
133
-
134
- let sourceRoot: string | undefined
135
-
136
- /** Rewrite the source preset to an equal-length marker module. */
137
- async function rewriteSourceMarker(name: string): Promise<void> {
138
- if (sourceRoot === undefined) throw new Error('source root not prepared')
139
- const marker = join(sourceRoot, name)
140
- await writeFile(marker, 'export function apply() {}\n')
141
- await writeFile(join(sourceRoot, 'standard', 'agent.cordis.yml'), `- id: source-marker\n name: ${JSON.stringify(marker)}\n`)
142
- }
143
-
144
- /** Create an importable marker module with an exact-length directory name. */
145
- async function sameLengthModule(label: string): Promise<string> {
146
- if (sourceRoot === undefined) throw new Error('source root not prepared')
147
- const directory = join(sourceRoot, label)
148
- await mkdir(directory, { recursive: true })
149
- const file = join(directory, 'index.mjs')
150
- await writeFile(file, 'export function apply() {}\n')
151
- return file
152
- }
153
-
154
- /** Reproduce the production content identity without replacing it in the store. */
155
- function overlayIdentity(
156
- source: string,
157
- modules: CompressionModulePaths,
158
- thresholdPercent: number,
159
- ): string {
160
- return createHash('sha256')
161
- .update('standard').update('\0')
162
- .update(source).update('\0')
163
- .update(JSON.stringify({ modules, autoCompactThresholdPercent: thresholdPercent }))
164
- .digest('hex')
165
- .slice(0, 24)
166
- }
167
-
168
- /** Find equal-length valid presets whose production identities share window 0. */
169
- function coarseCollisionFixture(
170
- marker: string,
171
- modules: CompressionModulePaths,
172
- ): Readonly<{ first: string, second: string, firstIdentity: string, secondIdentity: string }> {
173
- const seen = new Map<string, Readonly<{ source: string, identity: string }>>()
174
- for (let index = 0; index < 300_000; index += 1) {
175
- const label = index.toString(16).padStart(8, '0')
176
- const source = [
177
- '- id: source-marker',
178
- ` name: ${JSON.stringify(marker)}`,
179
- `- id: collision-${label}`,
180
- ' name: cordis:group',
181
- ' group: true',
182
- ' config: []',
183
- '',
184
- ].join('\n')
185
- const identity = overlayIdentity(source, modules, 80)
186
- const prefix = identity.slice(0, 8)
187
- const prior = seen.get(prefix)
188
- if (prior !== undefined && prior.identity !== identity) {
189
- return {
190
- first: prior.source,
191
- second: source,
192
- firstIdentity: prior.identity,
193
- secondIdentity: identity,
194
- }
195
- }
196
- seen.set(prefix, { source, identity })
197
- }
198
- throw new Error('failed to find a deterministic 32-bit standing-stamp collision')
199
- }
200
-
201
- /**
202
- * Mount the full real stack, run `arrange`, capture the standing key and
203
- * generated file, run `act`, and assert the generation moved.
204
- */
205
- async function assertStandingSwitch(
206
- arrange: () => Promise<() => Promise<void>>,
207
- ): Promise<void> {
208
- const rootPath = await presetsRoot()
209
- sourceRoot = rootPath
210
- ctx = new Context()
211
- ctx.baseUrl = `${pathToFileURL(rootPath).href}/`
212
- await ctx.plugin(Loader).await()
213
- ctx.loader.builtins.include = Include
214
- ctx.loader.builtins.group = Group
215
- await ctx.plugin(LlmRuntime).await()
216
- await ctx.plugin(SessionStore).await()
217
- await ctx.plugin(SystemPrompt).await()
218
- await ctx.plugin(ToolRuntime).await()
219
- await ctx.plugin(AgentRegistry).await()
220
- await ctx.plugin(AgentLoop).await()
221
- await ctx.plugin(CommandRuntime).await()
222
- await ctx.plugin(SessionProjectionRegistry).await()
223
- await ctx.plugin(TokenMeter).await()
224
- await ctx.plugin(MemorySettings).await()
225
- await ctx.plugin(LegacyNamespaceRegistrar).await()
226
- await ctx.plugin({ apply }).await()
227
- await ctx.plugin(AgentPresets, {
228
- default: 'standard',
229
- roots: [{ path: rootPath, trust: 'system' }],
230
- includeShippedRoot: false,
231
- includeUserRoot: false,
232
- }).await()
233
- const act = await arrange()
234
- const bundle = ctx.plugin({ apply: (child) => {
235
- apply(child, { presetOverlay: true })
236
- } })
237
- await bundle.await()
238
- const presets = ctx.agentPresets as unknown as OverlayableAgentPresets
239
- const first = await presets.standingKeyFor()
240
- const firstFiles = await overlayFiles(rootPath)
241
- expect(firstFiles).toHaveLength(1)
242
-
243
- await act()
244
- const second = await presets.standingKeyFor()
245
- const secondFiles = await overlayFiles(rootPath)
246
- expect(secondFiles).toHaveLength(2)
247
- expect(second).not.toBe(first)
248
- const stamps = await Promise.all(secondFiles.map(async file => (await stat(file.path)).mtimeMs))
249
- expect(new Set(stamps).size).toBe(2)
250
- }
251
-
252
- describe('deterministic standing stamps', () => {
253
- // The reviewer's reproduced 1-second-granularity collision: under the old
254
- // millisecond-prefix mapping these two identities stamped 280ms apart, and
255
- // floor(stamp/1000) collapsed both onto second 586129064.
256
- const COLLISION_A = '887803c2b6c57357206d271e'
257
- const COLLISION_B = '887803c3ceb119ac3cfb7d32'
258
-
259
- it('never shares a one-second bucket between distinct identities', () => {
260
- const stampA = standingStampMs(COLLISION_A)
261
- const stampB = standingStampMs(COLLISION_B)
262
- expect(Math.floor(stampA / 1000)).not.toBe(Math.floor(stampB / 1000))
263
- })
264
-
265
- it('stays inside the nanosecond range every filesystem can store', () => {
266
- const maxIdentity = 'ffffffffffffffffffffffff'
267
- const stamp = standingStampMs(maxIdentity)
268
- expect(Number.isFinite(stamp)).toBe(true)
269
- expect(stamp).toBeLessThan(Date.UTC(2260, 0, 1))
270
- expect(stamp).toBeGreaterThan(Date.UTC(2026, 0, 1))
271
- })
272
-
273
- it('is deterministic per identity and separable across hash windows', () => {
274
- expect(standingStampMs(COLLISION_A)).toBe(standingStampMs(COLLISION_A))
275
- // Equal 8-hex prefixes share the second bucket at window 0 but the
276
- // escalated window reads later hash digits into distinct seconds.
277
- const sharedPrefix = '887803c2'
278
- const first = `${sharedPrefix}aaaaaaaaaaaaaaaa`
279
- const second = `${sharedPrefix}bbbbbbbbbbbbbbbb`
280
- expect(Math.floor(standingStampMsAtWindow(first, 0) / 1000))
281
- .toBe(Math.floor(standingStampMsAtWindow(second, 0) / 1000))
282
- expect(standingStampMsAtWindow(first, 0)).not.toBe(standingStampMsAtWindow(second, 0))
283
- expect(Math.floor(standingStampMsAtWindow(first, 1) / 1000))
284
- .not.toBe(Math.floor(standingStampMsAtWindow(second, 1) / 1000))
285
- })
286
- })
287
-
288
- describe('real AgentPresets standing generations with the overlay threshold', () => {
289
- it('separates colliding equal-size generations on a whole-second metadata surface before publish', async () => {
290
- const rootPath = await presetsRoot()
291
- sourceRoot = rootPath
292
- const sourcePath = join(rootPath, 'standard', 'agent.cordis.yml')
293
- const marker = join(rootPath, 'marker-aaaaaaaaaa.mjs')
294
- const modules = resolveCompressionModulePaths()
295
- const collision = coarseCollisionFixture(marker, modules)
296
- expect(collision.first).toHaveLength(collision.second.length)
297
- expect(collision.firstIdentity.slice(0, 8)).toBe(collision.secondIdentity.slice(0, 8))
298
- await writeFile(sourcePath, collision.first)
299
-
300
- ctx = new Context()
301
- ctx.baseUrl = `${pathToFileURL(rootPath).href}/`
302
- await ctx.plugin(Loader).await()
303
- ctx.loader.builtins.include = Include
304
- ctx.loader.builtins.group = Group
305
- await ctx.plugin(LlmRuntime).await()
306
- await ctx.plugin(SessionStore).await()
307
- await ctx.plugin(SystemPrompt).await()
308
- await ctx.plugin(ToolRuntime).await()
309
- await ctx.plugin(AgentRegistry).await()
310
- await ctx.plugin(AgentLoop).await()
311
- await ctx.plugin(CommandRuntime).await()
312
- await ctx.plugin(SessionProjectionRegistry).await()
313
- await ctx.plugin(TokenMeter).await()
314
- await ctx.plugin(AgentPresets, {
315
- default: 'standard',
316
- roots: [{ path: rootPath, trust: 'system' }],
317
- includeShippedRoot: false,
318
- includeUserRoot: false,
319
- }).await()
320
-
321
- const coarseMetadataIo: PresetOverlayMetadataIo = {
322
- async setTimes(path, stamp) {
323
- const wholeSecond = new Date(Math.floor(stamp.getTime() / 1000) * 1000)
324
- await utimes(path, wholeSecond, wholeSecond)
325
- },
326
- async read(path) {
327
- const observed = await stat(path)
328
- return { mtimeMs: observed.mtimeMs, size: observed.size }
329
- },
330
- }
331
- const presets = ctx.agentPresets as unknown as OverlayableAgentPresets
332
- const installation = decorateAgentPresets(presets, {
333
- modules,
334
- autoCompactThresholdPercent: () => 80,
335
- metadataIo: coarseMetadataIo,
336
- })
337
-
338
- const firstKey = await presets.standingKeyFor()
339
- await writeFile(sourcePath, collision.second)
340
- const changedSourceStamp = new Date(Date.now() + 2_000)
341
- await utimes(sourcePath, changedSourceStamp, changedSourceStamp)
342
- const secondKey = await presets.standingKeyFor()
343
- // Scope keys are structurally `{ agentPreset: id }`; a new object identity
344
- // proves real AgentPresets observed a different composition stamp and
345
- // created a new standing generation.
346
- expect(secondKey).not.toBe(firstKey)
347
-
348
- const files = await overlayFiles(rootPath)
349
- expect(files).toHaveLength(2)
350
- const byIdentity = new Map(files.map(file => [
351
- /standard-([0-9a-f]+)\.agent\.cordis\.yml$/u.exec(file.path)?.[1],
352
- file.path,
353
- ]))
354
- const firstFile = byIdentity.get(collision.firstIdentity)
355
- const secondFile = byIdentity.get(collision.secondIdentity)
356
- expect(firstFile).toBeDefined()
357
- expect(secondFile).toBeDefined()
358
- const firstStat = await stat(firstFile as string)
359
- const secondStat = await stat(secondFile as string)
360
- expect(firstStat.size).toBe(secondStat.size)
361
- expect(firstStat.mtimeMs % 1000).toBe(0)
362
- expect(secondStat.mtimeMs % 1000).toBe(0)
363
- // The coarse metadata surface floors both stamps to a whole second, and the
364
- // platform may additionally wrap the seconds field (platformPersistedMs),
365
- // so require exactly what the filesystem stores for those identity stamps.
366
- const firstStamp = await platformPersistedMs(
367
- Math.floor(standingStampMsAtWindow(collision.firstIdentity, 0) / 1000) * 1000,
368
- )
369
- const secondStamp = await platformPersistedMs(
370
- Math.floor(standingStampMsAtWindow(collision.secondIdentity, 1) / 1000) * 1000,
371
- )
372
- expect(Math.floor(firstStat.mtimeMs / 1000)).toBe(Math.floor(firstStamp / 1000))
373
- expect(Math.floor(secondStat.mtimeMs / 1000)).toBe(Math.floor(secondStamp / 1000))
374
-
375
- await installation.dispose()
376
- })
377
-
378
- it('publishes distinct second buckets for equal-length colliding sources on the real filesystem', async () => {
379
- const rootPath = await presetsRoot()
380
- sourceRoot = rootPath
381
- ctx = new Context()
382
- ctx.baseUrl = `${pathToFileURL(rootPath).href}/`
383
- await ctx.plugin(Loader).await()
384
- ctx.loader.builtins.include = Include
385
- ctx.loader.builtins.group = Group
386
- await ctx.plugin(LlmRuntime).await()
387
- await ctx.plugin(SessionStore).await()
388
- await ctx.plugin(SystemPrompt).await()
389
- await ctx.plugin(ToolRuntime).await()
390
- await ctx.plugin(AgentRegistry).await()
391
- await ctx.plugin(AgentLoop).await()
392
- await ctx.plugin(CommandRuntime).await()
393
- await ctx.plugin(SessionProjectionRegistry).await()
394
- await ctx.plugin(TokenMeter).await()
395
- await ctx.plugin(MemorySettings).await()
396
- await ctx.plugin(LegacyNamespaceRegistrar).await()
397
- await ctx.plugin({ apply }).await()
398
- await ctx.plugin(AgentPresets, {
399
- default: 'standard',
400
- roots: [{ path: rootPath, trust: 'system' }],
401
- includeShippedRoot: false,
402
- includeUserRoot: false,
403
- }).await()
404
- const namespace = nsBrand('context-compression')
405
- await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 80 } })
406
- const bundle = ctx.plugin({ apply: (child) => {
407
- apply(child, { presetOverlay: true })
408
- } })
409
- await bundle.await()
410
-
411
- const presets = ctx.agentPresets as unknown as OverlayableAgentPresets
412
- await presets.standingKeyFor()
413
- // Two equal-length sources (55 bytes each, matching the collision
414
- // fixture's shape): distinct identities whose stamps must never collapse
415
- // onto the same whole second even if the filesystem truncates mtimes.
416
- await rewriteSourceMarker('marker-00000aa9.mjs')
417
- await presets.standingKeyFor()
418
- await rewriteSourceMarker('marker-00000wil.mjs')
419
- const third = await presets.standingKeyFor()
420
- expect(third).toBeDefined()
421
-
422
- const files = await overlayFiles(rootPath)
423
- expect(files.length).toBeGreaterThanOrEqual(3)
424
- const buckets = await Promise.all(files.map(async file => Math.floor((await stat(file.path)).mtimeMs / 1000)))
425
- expect(new Set(buckets).size).toBe(buckets.length)
426
- // No staging leftovers survive a publish. A spec file running in parallel
427
- // disposes its own store while this scan runs, so a vanished directory means
428
- // "no leftovers to find" rather than a failure (mirrors overlayFiles).
429
- // No staging leftovers survive a publish. Scan only this test's own store,
430
- // identified by its latest source marker: a concurrently running spec's
431
- // store may legitimately hold .tmp staging while this scan runs, and a
432
- // vanished directory means "no leftovers to find" (mirrors overlayFiles).
433
- const storeDirs = await Promise.all(
434
- (await readdir(tmpdir(), { withFileTypes: true }))
435
- .filter(entry => entry.isDirectory() && entry.name.startsWith('dsh-context-compression-presets-'))
436
- .map(async entry => {
437
- const directory = join(tmpdir(), entry.name)
438
- try {
439
- return { directory, entries: await readdir(directory) }
440
- } catch {
441
- return { directory: '', entries: [] as string[] }
442
- }
443
- }),
444
- )
445
- const ownStores: string[] = []
446
- await Promise.all(storeDirs.map(async ({ directory, entries }) => {
447
- if (directory === '') return
448
- for (const name of entries) {
449
- if (!name.startsWith('standard-') || !name.endsWith('.agent.cordis.yml')) continue
450
- try {
451
- const rendered = await readFile(join(directory, name), 'utf8')
452
- if (rendered.includes('marker-00000wil.mjs')) {
453
- ownStores.push(directory)
454
- return
455
- }
456
- } catch { /* a concurrent spec disposed its store mid-scan */ }
457
- }
458
- }))
459
- const leftovers = (await Promise.all(ownStores.map(directory => readdir(directory))))
460
- .flat()
461
- .filter(name => name.endsWith('.tmp'))
462
- expect(leftovers).toEqual([])
463
-
464
- await bundle.dispose()
465
- })
466
-
467
- it('keeps one fully-identical generation under concurrent composition of the same identity', async () => {
468
- const rootPath = await presetsRoot()
469
- ctx = new Context()
470
- ctx.baseUrl = `${pathToFileURL(rootPath).href}/`
471
- await ctx.plugin(Loader).await()
472
- ctx.loader.builtins.include = Include
473
- ctx.loader.builtins.group = Group
474
- await ctx.plugin(LlmRuntime).await()
475
- await ctx.plugin(SessionStore).await()
476
- await ctx.plugin(SystemPrompt).await()
477
- await ctx.plugin(ToolRuntime).await()
478
- await ctx.plugin(AgentRegistry).await()
479
- await ctx.plugin(AgentLoop).await()
480
- await ctx.plugin(CommandRuntime).await()
481
- await ctx.plugin(SessionProjectionRegistry).await()
482
- await ctx.plugin(TokenMeter).await()
483
- await ctx.plugin(MemorySettings).await()
484
- await ctx.plugin(LegacyNamespaceRegistrar).await()
485
- await ctx.plugin({ apply }).await()
486
- await ctx.plugin(AgentPresets, {
487
- default: 'standard',
488
- roots: [{ path: rootPath, trust: 'system' }],
489
- includeShippedRoot: false,
490
- includeUserRoot: false,
491
- }).await()
492
- const namespace = nsBrand('context-compression')
493
- await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 73 } })
494
- const bundle = ctx.plugin({ apply: (child) => {
495
- apply(child, { presetOverlay: true })
496
- } })
497
- await bundle.await()
498
-
499
- const presets = ctx.agentPresets as unknown as OverlayableAgentPresets
500
- // Every concurrent composer must hand out the SAME path, and the file's
501
- // persisted stamp must be the deterministic identity stamp — never a
502
- // wall-clock mtime from a metadata window.
503
- const concurrent = await Promise.all([
504
- presets.standingKeyFor(),
505
- presets.standingKeyFor(),
506
- presets.standingKeyFor(),
507
- presets.standingKeyFor(),
508
- presets.standingKeyFor(),
509
- presets.standingKeyFor(),
510
- ])
511
- expect(new Set(concurrent.map(key => JSON.stringify(key)))).toHaveLength(1)
512
- const files = await overlayFiles(rootPath)
513
- expect(files).toHaveLength(1)
514
- const details = await stat(files[0]!.path)
515
- const now = Date.now()
516
- expect(Math.abs(details.mtimeMs - now)).toBeGreaterThan(60 * 60 * 1000)
517
- // The persisted whole-second bucket matches the identity-derived stamp's
518
- // bucket regardless of filesystem mtime granularity, and the persisted
519
- // sub-second component is the identity-derived one (or its zero-truncated
520
- // form on a coarse filesystem).
521
- const rendered = files[0]!.rendered
522
- const identity = rendered.length > 0
523
- ? /standard-([0-9a-f]+)\.agent\.cordis\.yml$/u.exec(files[0]!.path)?.[1]
524
- : undefined
525
- expect(identity).toBeDefined()
526
- const persistedStamp = await platformPersistedMs(standingStampMs(identity as string))
527
- expect(Math.floor(details.mtimeMs / 1000))
528
- .toBe(Math.floor(persistedStamp / 1000))
529
- const observedSubSecond = details.mtimeMs % 1000
530
- const expectedSubSecond = standingStampMs(identity as string) % 1000
531
- expect(observedSubSecond === 0 || Math.abs(observedSubSecond - expectedSubSecond) < 1).toBe(true)
532
-
533
- await bundle.dispose()
534
- })
535
-
536
- it('switches the standing generation for an equal-length threshold change', async () => {
537
- await assertStandingSwitch(async () => {
538
- const namespace = nsBrand('context-compression')
539
- await ctx!.settings.update(namespace, { autoCompact: { thresholdPercent: 70 } })
540
- return async () => ctx!.settings.update(namespace, { autoCompact: { thresholdPercent: 80 } })
541
- })
542
- })
543
-
544
- it('switches the standing generation for an equal-length source change at a fixed threshold', async () => {
545
- await assertStandingSwitch(async () => {
546
- const namespace = nsBrand('context-compression')
547
- await ctx!.settings.update(namespace, { autoCompact: { thresholdPercent: 80 } })
548
- return async () => {
549
- await rewriteSourceMarker('marker-bbbbbbbbbb.mjs')
550
- }
551
- })
552
- })
553
-
554
- it('switches the standing generation for an equal-length module identity change', async () => {
555
- const rootPath = await presetsRoot()
556
- sourceRoot = rootPath
557
- ctx = new Context()
558
- ctx.baseUrl = `${pathToFileURL(rootPath).href}/`
559
- await ctx.plugin(Loader).await()
560
- ctx.loader.builtins.include = Include
561
- ctx.loader.builtins.group = Group
562
- await ctx.plugin(LlmRuntime).await()
563
- await ctx.plugin(SessionStore).await()
564
- await ctx.plugin(SystemPrompt).await()
565
- await ctx.plugin(ToolRuntime).await()
566
- await ctx.plugin(AgentRegistry).await()
567
- await ctx.plugin(AgentLoop).await()
568
- await ctx.plugin(CommandRuntime).await()
569
- await ctx.plugin(SessionProjectionRegistry).await()
570
- await ctx.plugin(TokenMeter).await()
571
- await ctx.plugin(MemorySettings).await()
572
- await ctx.plugin(LegacyNamespaceRegistrar).await()
573
- await ctx.plugin({ apply }).await()
574
- await ctx.plugin(AgentPresets, {
575
- default: 'standard',
576
- roots: [{ path: rootPath, trust: 'system' }],
577
- includeShippedRoot: false,
578
- includeUserRoot: false,
579
- }).await()
580
- const namespace = nsBrand('context-compression')
581
- await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 80 } })
582
-
583
- const presets = ctx.agentPresets as unknown as OverlayableAgentPresets
584
- // Two module sets whose entry paths differ in content but not length.
585
- const moduleA = await sameLengthModule('module-aaaaaaaaaa')
586
- const moduleB = await sameLengthModule('module-bbbbbbbbbb')
587
- const paths = (m: string) => ({
588
- compactionBasic: m,
589
- commandCompact: m,
590
- toolResultPruner: m,
591
- })
592
- let installation = decorateAgentPresets(presets, {
593
- modules: paths(moduleA),
594
- excludedPresetIds: ['minimal'],
595
- autoCompactThresholdPercent: () => 80,
596
- })
597
- const first = await presets.standingKeyFor()
598
- const firstFiles = await overlayFiles(rootPath)
599
- expect(firstFiles).toHaveLength(1)
600
- const firstPath = firstFiles[0]!.path
601
- const firstStamp = (await stat(firstPath)).mtimeMs
602
- expect(firstFiles[0]!.rendered).toContain(moduleA)
603
-
604
- // Disposing the old decoration also removes its generated store, so the
605
- // swap is proven by the new composition's path, content, and stamp.
606
- await installation.dispose()
607
- installation = decorateAgentPresets(presets, {
608
- modules: paths(moduleB),
609
- excludedPresetIds: ['minimal'],
610
- autoCompactThresholdPercent: () => 80,
611
- })
612
- const second = await presets.standingKeyFor()
613
- const secondFiles = await overlayFiles(rootPath)
614
- expect(secondFiles).toHaveLength(1)
615
- expect(second).not.toBe(first)
616
- expect(secondFiles[0]!.path).not.toBe(firstPath)
617
- expect(secondFiles[0]!.rendered).toContain(moduleB)
618
- expect((await stat(secondFiles[0]!.path)).mtimeMs).not.toBe(firstStamp)
619
- await installation.dispose()
620
- })
621
-
622
- it('keeps one generation under concurrent and repeated composition of the same identity', async () => {
623
- const rootPath = await presetsRoot()
624
- ctx = new Context()
625
- ctx.baseUrl = `${pathToFileURL(rootPath).href}/`
626
- await ctx.plugin(Loader).await()
627
- ctx.loader.builtins.include = Include
628
- ctx.loader.builtins.group = Group
629
- await ctx.plugin(LlmRuntime).await()
630
- await ctx.plugin(SessionStore).await()
631
- await ctx.plugin(SystemPrompt).await()
632
- await ctx.plugin(ToolRuntime).await()
633
- await ctx.plugin(AgentRegistry).await()
634
- await ctx.plugin(AgentLoop).await()
635
- await ctx.plugin(CommandRuntime).await()
636
- await ctx.plugin(SessionProjectionRegistry).await()
637
- await ctx.plugin(TokenMeter).await()
638
- await ctx.plugin(MemorySettings).await()
639
- await ctx.plugin(LegacyNamespaceRegistrar).await()
640
- await ctx.plugin({ apply }).await()
641
- await ctx.plugin(AgentPresets, {
642
- default: 'standard',
643
- roots: [{ path: rootPath, trust: 'system' }],
644
- includeShippedRoot: false,
645
- includeUserRoot: false,
646
- }).await()
647
- const namespace = nsBrand('context-compression')
648
- await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 73 } })
649
- const bundle = ctx.plugin({ apply: (child) => {
650
- apply(child, { presetOverlay: true })
651
- } })
652
- await bundle.await()
653
-
654
- const presets = ctx.agentPresets as unknown as OverlayableAgentPresets
655
- const concurrent = await Promise.all([
656
- presets.standingKeyFor(),
657
- presets.standingKeyFor(),
658
- presets.standingKeyFor(),
659
- ])
660
- expect(new Set(concurrent.map(key => JSON.stringify(key)))).toHaveLength(1)
661
- const files = await overlayFiles(rootPath)
662
- expect(files).toHaveLength(1)
663
- const stampFirst = (await stat(files[0]!.path)).mtimeMs
664
- const repeated = await presets.standingKeyFor()
665
- expect(JSON.stringify(repeated)).toBe(JSON.stringify(concurrent[0]))
666
- expect(await overlayFiles(rootPath)).toHaveLength(1)
667
- expect((await stat(files[0]!.path)).mtimeMs).toBe(stampFirst)
668
- })
669
-
670
- it('switches the standing generation for an equal-length threshold change (legacy body)', async () => {
671
- const rootPath = await presetsRoot()
672
- ctx = new Context()
673
- ctx.baseUrl = `${pathToFileURL(rootPath).href}/`
674
- await ctx.plugin(Loader).await()
675
- ctx.loader.builtins.include = Include
676
- ctx.loader.builtins.group = Group
677
- await ctx.plugin(LlmRuntime).await()
678
- await ctx.plugin(SessionStore).await()
679
- await ctx.plugin(SystemPrompt).await()
680
- await ctx.plugin(ToolRuntime).await()
681
- await ctx.plugin(AgentRegistry).await()
682
- await ctx.plugin(AgentLoop).await()
683
- await ctx.plugin(CommandRuntime).await()
684
- await ctx.plugin(SessionProjectionRegistry).await()
685
- await ctx.plugin(TokenMeter).await()
686
- await ctx.plugin(MemorySettings).await()
687
- await ctx.plugin(LegacyNamespaceRegistrar).await()
688
- await ctx.plugin({ apply }).await()
689
- await ctx.plugin(AgentPresets, {
690
- default: 'standard',
691
- roots: [{ path: rootPath, trust: 'system' }],
692
- includeShippedRoot: false,
693
- includeUserRoot: false,
694
- }).await()
695
- const namespace = nsBrand('context-compression')
696
- await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 70 } })
697
- const bundle = ctx.plugin({ apply: (child) => {
698
- apply(child, { presetOverlay: true })
699
- } })
700
- await bundle.await()
701
-
702
- const presets = ctx.agentPresets as unknown as OverlayableAgentPresets
703
- const first = await presets.standingKeyFor()
704
- const firstFiles = await overlayFiles(rootPath)
705
- expect(firstFiles).toHaveLength(1)
706
- expect(firstFiles[0]?.rendered).toContain('thresholdRatio: 0.7')
707
- expect(firstFiles[0]?.rendered).toContain('autoCompactThresholdPercent: 70')
708
-
709
- // Equal-length change: identical rendered sizes, and without the
710
- // deterministic threshold mtime a same-millisecond switch could have
711
- // reused the superseded generation.
712
- await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 80 } })
713
- const second = await presets.standingKeyFor()
714
- const secondFiles = await overlayFiles(rootPath)
715
- expect(secondFiles).toHaveLength(2)
716
- expect(secondFiles.some(file => file.rendered.includes('thresholdRatio: 0.8')
717
- && file.rendered.includes('autoCompactThresholdPercent: 80'))).toBe(true)
718
- expect(second).not.toBe(first)
719
- const stamps = await Promise.all(secondFiles.map(async file => (await stat(file.path)).mtimeMs))
720
- expect(new Set(stamps).size).toBe(2)
721
-
722
- await bundle.dispose()
723
- })
724
- })