dsh-context-compression-improved 0.5.6 → 0.5.7

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 (162) hide show
  1. package/.gitattributes +2 -2
  2. package/.githooks/pre-push +37 -37
  3. package/.github/workflows/ci.yml +39 -39
  4. package/CHANGELOG.ja.md +169 -169
  5. package/CHANGELOG.ko.md +167 -167
  6. package/CHANGELOG.md +314 -304
  7. package/CHANGELOG.zh.md +152 -152
  8. package/CONTRIBUTING.md +22 -22
  9. package/LICENSE +21 -21
  10. package/README.ja.md +85 -85
  11. package/README.ko.md +85 -85
  12. package/README.md +94 -94
  13. package/README.zh.md +85 -85
  14. package/SECURITY.md +18 -18
  15. package/THIRD_PARTY_NOTICES.md +14 -14
  16. package/docs/compat-0.1.5-report.md +77 -77
  17. package/docs/installation.ja.md +78 -78
  18. package/docs/installation.ko.md +78 -78
  19. package/docs/installation.md +103 -103
  20. package/docs/installation.zh.md +100 -100
  21. package/docs/repair-log.md +657 -657
  22. package/eslint.config.js +30 -30
  23. package/package.json +164 -164
  24. package/packages/selector/LICENSE +21 -21
  25. package/packages/selector/README.md +26 -26
  26. package/packages/selector/README.zh.md +24 -24
  27. package/packages/selector/THIRD_PARTY_NOTICES.md +32 -32
  28. package/packages/selector/cordis.patch.yml +27 -27
  29. package/packages/selector/docs/history-tool-call-working-set-spec.md +112 -112
  30. package/packages/selector/docs/native-tool-result-selector-spec.md +34 -34
  31. package/packages/selector/docs/subagent-cache-reuse-spec.md +46 -46
  32. package/packages/selector/dsh.plugin.json +16 -16
  33. package/packages/selector/lib/client.js +733 -0
  34. package/packages/selector/lib/style.css +46 -46
  35. package/packages/selector/package.json +114 -114
  36. package/packages/selector/screenshots.json +3 -3
  37. package/packages/selector/src/client/CompressionProfileControls.tsx +226 -226
  38. package/packages/selector/src/client/CompressionProfileSelector.module.css +170 -170
  39. package/packages/selector/src/client/CompressionProfileSelector.tsx +83 -83
  40. package/packages/selector/src/client/CustomPolicyEditor.tsx +216 -216
  41. package/packages/selector/src/client/EstimatorControls.tsx +277 -277
  42. package/packages/selector/src/client/decode.ts +49 -49
  43. package/packages/selector/src/client/index.ts +178 -149
  44. package/packages/selector/src/client/locales/de.ts +98 -0
  45. package/packages/selector/src/client/locales/es.ts +98 -0
  46. package/packages/selector/src/client/locales/fr.ts +98 -0
  47. package/packages/selector/src/client/locales/it.ts +98 -0
  48. package/packages/selector/src/client/locales/ja.ts +98 -0
  49. package/packages/selector/src/client/locales/ko.ts +98 -0
  50. package/packages/selector/src/client/locales/ru.ts +98 -0
  51. package/packages/selector/src/client/locales.ts +196 -196
  52. package/packages/selector/src/client/preset-options.ts +88 -88
  53. package/packages/selector/src/client/settings-section.tsx +124 -124
  54. package/packages/selector/src/css-modules.d.ts +6 -6
  55. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -205
  56. package/packages/selector/src/estimator-catalog.ts +104 -104
  57. package/packages/selector/src/index.ts +463 -463
  58. package/packages/selector/src/invariant.ts +113 -113
  59. package/packages/selector/src/preset-overlay.ts +626 -626
  60. package/packages/selector/src/profiles.ts +394 -394
  61. package/packages/selector/src/pruner/content.ts +201 -201
  62. package/packages/selector/src/pruner/session.ts +94 -94
  63. package/packages/selector/src/pruner/state.ts +50 -50
  64. package/packages/selector/src/pruner/tuning.ts +23 -23
  65. package/packages/selector/src/pruner/types.ts +78 -78
  66. package/packages/selector/src/pruner.ts +2402 -2402
  67. package/packages/selector/src/runtime/adaptive-cost.ts +205 -205
  68. package/packages/selector/src/runtime/audit.ts +286 -286
  69. package/packages/selector/src/runtime/config.ts +706 -706
  70. package/packages/selector/src/runtime/custom-policy.ts +278 -278
  71. package/packages/selector/src/runtime/deepseek-official-pricing.ts +298 -298
  72. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +254 -254
  73. package/packages/selector/src/runtime/measurement.ts +436 -436
  74. package/packages/selector/src/runtime/reducers.ts +1674 -1674
  75. package/packages/selector/src/runtime/retrieve.ts +457 -457
  76. package/packages/selector/src/runtime/session-events.ts +30 -30
  77. package/packages/selector/src/runtime/tail-trim.ts +166 -166
  78. package/packages/selector/src/runtime/token-count.ts +72 -72
  79. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +188 -188
  80. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +149 -149
  81. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -419
  82. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -200
  83. package/packages/selector/src/runtime/tokenpilot/dedup.ts +81 -81
  84. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -151
  85. package/packages/selector/src/runtime/tokenpilot/locator.ts +128 -128
  86. package/packages/selector/src/runtime/tokenpilot/read-state.ts +98 -98
  87. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -303
  88. package/packages/selector/src/runtime/toolclass.ts +103 -103
  89. package/packages/selector/src/runtime/types.ts +346 -346
  90. package/packages/selector/src/runtime/value.ts +48 -48
  91. package/packages/selector/tests/advisor-report.host.spec.ts +223 -223
  92. package/packages/selector/tests/auto-compact.client.spec.tsx +213 -213
  93. package/packages/selector/tests/built/client-artifact.spec.ts +59 -59
  94. package/packages/selector/tests/cache-prefix-audit.spec.ts +123 -123
  95. package/packages/selector/tests/code-skeleton.client.spec.ts +90 -90
  96. package/packages/selector/tests/custom-contract.client.spec.ts +204 -204
  97. package/packages/selector/tests/estimator-catalog.spec.ts +70 -70
  98. package/packages/selector/tests/estimator-channel.client.spec.tsx +252 -252
  99. package/packages/selector/tests/estimator-route-registration.host.spec.ts +188 -188
  100. package/packages/selector/tests/host-preset-overlay.host.spec.ts +206 -206
  101. package/packages/selector/tests/preset-options-write.client.spec.ts +206 -206
  102. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +201 -201
  103. package/packages/selector/tests/preset-overlay.host.spec.ts +246 -246
  104. package/packages/selector/tests/profiles.client.spec.tsx +434 -434
  105. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -78
  106. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +167 -167
  107. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -232
  108. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -272
  109. package/packages/selector/tests/runtime/advisor.spec.ts +226 -226
  110. package/packages/selector/tests/runtime/audit.spec.ts +274 -274
  111. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -523
  112. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -30
  113. package/packages/selector/tests/runtime/code-skeleton.spec.ts +152 -152
  114. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +186 -186
  115. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -122
  116. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +122 -122
  117. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -96
  118. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +273 -273
  119. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +106 -106
  120. package/packages/selector/tests/runtime/fixtures/vision-golden.json +459 -459
  121. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -74
  122. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -212
  123. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -153
  124. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -133
  125. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2724 -2724
  126. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -33
  127. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -110
  128. package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
  129. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -241
  130. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -159
  131. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +53 -53
  132. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -217
  133. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +52 -52
  134. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -79
  135. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +76 -76
  136. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -116
  137. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +82 -82
  138. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -156
  139. package/packages/selector/tests/runtime/value.spec.ts +23 -23
  140. package/packages/selector/tests/settings-seat.client.spec.ts +118 -118
  141. package/packages/selector/tests/standing-generation.host.spec.ts +697 -697
  142. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +253 -253
  143. package/packages/selector/tests/support/cache-prefix-audit.ts +105 -105
  144. package/packages/selector/tests/support/mock-adapter.ts +37 -37
  145. package/packages/selector/tests/support/ui-primitives.tsx +34 -34
  146. package/packages/selector/tsconfig.json +11 -11
  147. package/packages/selector/tsdown.client.config.ts +102 -102
  148. package/packages/selector/tsdown.config.ts +20 -20
  149. package/pnpm-workspace.yaml +66 -66
  150. package/scripts/capture-profile-baseline.mjs +42 -42
  151. package/scripts/generate-tokenizer-fixtures.py +81 -81
  152. package/scripts/generate-vision-fixtures.py +208 -208
  153. package/scripts/packed-components-smoke.mjs +732 -732
  154. package/scripts/packed-install-e2e.mjs +1273 -1273
  155. package/scripts/toolclass-corpus-replay.mjs +281 -281
  156. package/scripts/verify-release.mjs +317 -317
  157. package/tests/TEST_INVENTORY.md +41 -41
  158. package/tsconfig.base.json +18 -18
  159. package/tsconfig.json +7 -7
  160. package/tsconfig.tests.json +15 -15
  161. package/vitest.built.config.ts +9 -9
  162. package/vitest.config.ts +43 -43
@@ -1,697 +1,697 @@
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 {
22
- SettingsProvider,
23
- type SettingsNamespace,
24
- } from '@deepseek-ai/dsh-settings'
25
- import { pathToFileURL } from 'node:url'
26
- import { afterEach, describe, expect, it } from 'vitest'
27
- import { apply } from '../src/index.ts'
28
- import {
29
- decorateAgentPresets,
30
- resolveCompressionModulePaths,
31
- standingStampMs,
32
- standingStampMsAtWindow,
33
- } from '../src/preset-overlay.ts'
34
- import type {
35
- CompressionModulePaths,
36
- OverlayableAgentPresets,
37
- PresetOverlayMetadataIo,
38
- } from '../src/preset-overlay.ts'
39
-
40
- // 0.1.5 removed the settingsNamespace() wrapper; namespaces are validated at runtime.
41
- const nsBrand = (value: string): SettingsNamespace => value as unknown as SettingsNamespace
42
-
43
- let root: string | undefined
44
- let ctx: Context | undefined
45
-
46
- afterEach(async () => {
47
- await ctx?.fiber.dispose()
48
- ctx = undefined
49
- if (root !== undefined) await rm(root, { recursive: true, force: true })
50
- root = undefined
51
- })
52
-
53
- class MemorySettings extends SettingsProvider {
54
- readonly writable = true
55
- private readonly stored: Record<string, unknown> = {}
56
-
57
- protected load(): Promise<Record<string, unknown>> {
58
- return Promise.resolve(structuredClone(this.stored))
59
- }
60
-
61
- protected persist(ns: SettingsNamespace, section: Record<string, unknown>): Promise<void> {
62
- this.stored[ns] = structuredClone(section)
63
- return Promise.resolve()
64
- }
65
- }
66
-
67
- async function presetsRoot(): Promise<string> {
68
- root = await mkdtemp(join(tmpdir(), 'dsh-selector-standing-'))
69
- const marker = join(root, 'marker-aaaaaaaaaa.mjs')
70
- await writeFile(marker, 'export function apply() {}\n')
71
- const path = join(root, 'standard', 'agent.cordis.yml')
72
- await mkdir(dirname(path), { recursive: true })
73
- await writeFile(path, `- id: source-marker\n name: ${JSON.stringify(marker)}\n`)
74
- return root
75
- }
76
-
77
- /**
78
- * Read the overlay compositions generated from THIS test's source preset.
79
- * Concurrent spec files write their own stores; the embedded marker path
80
- * distinguishes ours without depending on directory discovery timing.
81
- */
82
- async function overlayFiles(sourceMarker: string): Promise<{ path: string, rendered: string }[]> {
83
- const parent = await readdir(tmpdir(), { withFileTypes: true })
84
- const files: { path: string, rendered: string }[] = []
85
- for (const entry of parent) {
86
- if (!entry.isDirectory() || !entry.name.startsWith('dsh-context-compression-presets-')) continue
87
- const directory = join(tmpdir(), entry.name)
88
- let children
89
- try {
90
- children = await readdir(directory)
91
- } catch {
92
- continue // a concurrent spec disposed its store mid-scan
93
- }
94
- for (const child of children) {
95
- if (!child.startsWith('standard-') || !child.endsWith('.agent.cordis.yml')) continue
96
- const path = join(directory, child)
97
- const rendered = await readFile(path, 'utf8')
98
- if (rendered.includes(sourceMarker)) files.push({ path, rendered })
99
- }
100
- }
101
- return files
102
- }
103
-
104
- /**
105
- * The mtime this platform actually persists for one given stamp.
106
- *
107
- * `node:fs` `utimes` writes the seconds component through a 32-bit field on
108
- * Windows: on node v22 win32, `utimes(file, 4677832452 s)` reads back as
109
- * `382865156 s` — exactly `seconds >>> 0` — while sub-second precision
110
- * survives. The standing stamp deliberately parks identities around year 2162
111
- * (`STANDING_MTIME_EPOCH_SECONDS + 0xffffffff`, src/preset-overlay.ts), so its
112
- * seconds component sits past that 2^32-second horizon (max year 2106) and the
113
- * persisted literal differs on that platform. Deterministically so: the wrap is
114
- * a pure function of the identity stamp, which is why identity → mtime stays
115
- * stable and the collision escalation still absorbs any merge.
116
- *
117
- * Instead of hardcoding the platform or weakening the assertion, calibrate:
118
- * ask the filesystem what it stores for exactly this stamp, then require the
119
- * overlay to persist that same value. On a platform with a full-width seconds
120
- * field this collapses to the stamp itself, so the assertion stays strict.
121
- */
122
- async function platformPersistedMs(stampMs: number): Promise<number> {
123
- const directory = await mkdtemp(join(tmpdir(), 'dsh-selector-mtime-probe-'))
124
- const probe = join(directory, 'probe')
125
- try {
126
- await writeFile(probe, 'probe')
127
- const stamp = new Date(stampMs)
128
- await utimes(probe, stamp, stamp)
129
- return (await stat(probe)).mtimeMs
130
- } finally {
131
- await rm(directory, { recursive: true, force: true })
132
- }
133
- }
134
-
135
- let sourceRoot: string | undefined
136
-
137
- /** Rewrite the source preset to an equal-length marker module. */
138
- async function rewriteSourceMarker(name: string): Promise<void> {
139
- if (sourceRoot === undefined) throw new Error('source root not prepared')
140
- const marker = join(sourceRoot, name)
141
- await writeFile(marker, 'export function apply() {}\n')
142
- await writeFile(join(sourceRoot, 'standard', 'agent.cordis.yml'), `- id: source-marker\n name: ${JSON.stringify(marker)}\n`)
143
- }
144
-
145
- /** Create an importable marker module with an exact-length directory name. */
146
- async function sameLengthModule(label: string): Promise<string> {
147
- if (sourceRoot === undefined) throw new Error('source root not prepared')
148
- const directory = join(sourceRoot, label)
149
- await mkdir(directory, { recursive: true })
150
- const file = join(directory, 'index.mjs')
151
- await writeFile(file, 'export function apply() {}\n')
152
- return file
153
- }
154
-
155
- /** Reproduce the production content identity without replacing it in the store. */
156
- function overlayIdentity(
157
- source: string,
158
- modules: CompressionModulePaths,
159
- thresholdPercent: number,
160
- ): string {
161
- return createHash('sha256')
162
- .update('standard').update('\0')
163
- .update(source).update('\0')
164
- .update(JSON.stringify({ modules, autoCompactThresholdPercent: thresholdPercent }))
165
- .digest('hex')
166
- .slice(0, 24)
167
- }
168
-
169
- /** Find equal-length valid presets whose production identities share window 0. */
170
- function coarseCollisionFixture(
171
- marker: string,
172
- modules: CompressionModulePaths,
173
- ): Readonly<{ first: string, second: string, firstIdentity: string, secondIdentity: string }> {
174
- const seen = new Map<string, Readonly<{ source: string, identity: string }>>()
175
- for (let index = 0; index < 300_000; index += 1) {
176
- const label = index.toString(16).padStart(8, '0')
177
- const source = [
178
- '- id: source-marker',
179
- ` name: ${JSON.stringify(marker)}`,
180
- `- id: collision-${label}`,
181
- ' name: cordis:group',
182
- ' group: true',
183
- ' config: []',
184
- '',
185
- ].join('\n')
186
- const identity = overlayIdentity(source, modules, 80)
187
- const prefix = identity.slice(0, 8)
188
- const prior = seen.get(prefix)
189
- if (prior !== undefined && prior.identity !== identity) {
190
- return {
191
- first: prior.source,
192
- second: source,
193
- firstIdentity: prior.identity,
194
- secondIdentity: identity,
195
- }
196
- }
197
- seen.set(prefix, { source, identity })
198
- }
199
- throw new Error('failed to find a deterministic 32-bit standing-stamp collision')
200
- }
201
-
202
- /**
203
- * Mount the full real stack, run `arrange`, capture the standing key and
204
- * generated file, run `act`, and assert the generation moved.
205
- */
206
- async function assertStandingSwitch(
207
- arrange: () => Promise<() => Promise<void>>,
208
- ): Promise<void> {
209
- const rootPath = await presetsRoot()
210
- sourceRoot = rootPath
211
- ctx = new Context()
212
- ctx.baseUrl = `${pathToFileURL(rootPath).href}/`
213
- await ctx.plugin(Loader).await()
214
- ctx.loader.builtins.include = Include
215
- ctx.loader.builtins.group = Group
216
- await ctx.plugin(LlmRuntime).await()
217
- await ctx.plugin(SessionStore).await()
218
- await ctx.plugin(SystemPrompt).await()
219
- await ctx.plugin(ToolRuntime).await()
220
- await ctx.plugin(AgentRegistry).await()
221
- await ctx.plugin(AgentLoop).await()
222
- await ctx.plugin(CommandRuntime).await()
223
- await ctx.plugin(SessionProjectionRegistry).await()
224
- await ctx.plugin(TokenMeter).await()
225
- await ctx.plugin(MemorySettings).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({ apply }).await()
397
- await ctx.plugin(AgentPresets, {
398
- default: 'standard',
399
- roots: [{ path: rootPath, trust: 'system' }],
400
- includeShippedRoot: false,
401
- includeUserRoot: false,
402
- }).await()
403
- const namespace = nsBrand('context-compression')
404
- await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 80 } })
405
- const bundle = ctx.plugin({ apply: (child) => {
406
- apply(child, { presetOverlay: true })
407
- } })
408
- await bundle.await()
409
-
410
- const presets = ctx.agentPresets as unknown as OverlayableAgentPresets
411
- await presets.standingKeyFor()
412
- // Two equal-length sources (55 bytes each, matching the collision
413
- // fixture's shape): distinct identities whose stamps must never collapse
414
- // onto the same whole second even if the filesystem truncates mtimes.
415
- await rewriteSourceMarker('marker-00000aa9.mjs')
416
- await presets.standingKeyFor()
417
- await rewriteSourceMarker('marker-00000wil.mjs')
418
- const third = await presets.standingKeyFor()
419
- expect(third).toBeDefined()
420
-
421
- const files = await overlayFiles(rootPath)
422
- expect(files.length).toBeGreaterThanOrEqual(3)
423
- const buckets = await Promise.all(files.map(async file => Math.floor((await stat(file.path)).mtimeMs / 1000)))
424
- expect(new Set(buckets).size).toBe(buckets.length)
425
- // No staging leftovers survive a publish. A spec file running in parallel
426
- // disposes its own store while this scan runs, so a vanished directory means
427
- // "no leftovers to find" rather than a failure (mirrors overlayFiles).
428
- const storeDirs = await Promise.all(
429
- (await readdir(tmpdir(), { withFileTypes: true }))
430
- .filter(entry => entry.isDirectory() && entry.name.startsWith('dsh-context-compression-presets-'))
431
- .map(async entry => {
432
- try {
433
- return await readdir(join(tmpdir(), entry.name))
434
- } catch {
435
- return []
436
- }
437
- }),
438
- )
439
- expect(storeDirs.flat().some(name => name.endsWith('.tmp'))).toBe(false)
440
-
441
- await bundle.dispose()
442
- })
443
-
444
- it('keeps one fully-identical generation under concurrent composition of the same identity', async () => {
445
- const rootPath = await presetsRoot()
446
- ctx = new Context()
447
- ctx.baseUrl = `${pathToFileURL(rootPath).href}/`
448
- await ctx.plugin(Loader).await()
449
- ctx.loader.builtins.include = Include
450
- ctx.loader.builtins.group = Group
451
- await ctx.plugin(LlmRuntime).await()
452
- await ctx.plugin(SessionStore).await()
453
- await ctx.plugin(SystemPrompt).await()
454
- await ctx.plugin(ToolRuntime).await()
455
- await ctx.plugin(AgentRegistry).await()
456
- await ctx.plugin(AgentLoop).await()
457
- await ctx.plugin(CommandRuntime).await()
458
- await ctx.plugin(SessionProjectionRegistry).await()
459
- await ctx.plugin(TokenMeter).await()
460
- await ctx.plugin(MemorySettings).await()
461
- await ctx.plugin({ apply }).await()
462
- await ctx.plugin(AgentPresets, {
463
- default: 'standard',
464
- roots: [{ path: rootPath, trust: 'system' }],
465
- includeShippedRoot: false,
466
- includeUserRoot: false,
467
- }).await()
468
- const namespace = nsBrand('context-compression')
469
- await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 73 } })
470
- const bundle = ctx.plugin({ apply: (child) => {
471
- apply(child, { presetOverlay: true })
472
- } })
473
- await bundle.await()
474
-
475
- const presets = ctx.agentPresets as unknown as OverlayableAgentPresets
476
- // Every concurrent composer must hand out the SAME path, and the file's
477
- // persisted stamp must be the deterministic identity stamp — never a
478
- // wall-clock mtime from a metadata window.
479
- const concurrent = await Promise.all([
480
- presets.standingKeyFor(),
481
- presets.standingKeyFor(),
482
- presets.standingKeyFor(),
483
- presets.standingKeyFor(),
484
- presets.standingKeyFor(),
485
- presets.standingKeyFor(),
486
- ])
487
- expect(new Set(concurrent.map(key => JSON.stringify(key)))).toHaveLength(1)
488
- const files = await overlayFiles(rootPath)
489
- expect(files).toHaveLength(1)
490
- const details = await stat(files[0]!.path)
491
- const now = Date.now()
492
- expect(Math.abs(details.mtimeMs - now)).toBeGreaterThan(60 * 60 * 1000)
493
- // The persisted whole-second bucket matches the identity-derived stamp's
494
- // bucket regardless of filesystem mtime granularity, and the persisted
495
- // sub-second component is the identity-derived one (or its zero-truncated
496
- // form on a coarse filesystem).
497
- const rendered = files[0]!.rendered
498
- const identity = rendered.length > 0
499
- ? /standard-([0-9a-f]+)\.agent\.cordis\.yml$/u.exec(files[0]!.path)?.[1]
500
- : undefined
501
- expect(identity).toBeDefined()
502
- const persistedStamp = await platformPersistedMs(standingStampMs(identity as string))
503
- expect(Math.floor(details.mtimeMs / 1000))
504
- .toBe(Math.floor(persistedStamp / 1000))
505
- const observedSubSecond = details.mtimeMs % 1000
506
- const expectedSubSecond = standingStampMs(identity as string) % 1000
507
- expect(observedSubSecond === 0 || Math.abs(observedSubSecond - expectedSubSecond) < 1).toBe(true)
508
-
509
- await bundle.dispose()
510
- })
511
-
512
- it('switches the standing generation for an equal-length threshold change', async () => {
513
- await assertStandingSwitch(async () => {
514
- const namespace = nsBrand('context-compression')
515
- await ctx!.settings.update(namespace, { autoCompact: { thresholdPercent: 70 } })
516
- return async () => ctx!.settings.update(namespace, { autoCompact: { thresholdPercent: 80 } })
517
- })
518
- })
519
-
520
- it('switches the standing generation for an equal-length source change at a fixed threshold', async () => {
521
- await assertStandingSwitch(async () => {
522
- const namespace = nsBrand('context-compression')
523
- await ctx!.settings.update(namespace, { autoCompact: { thresholdPercent: 80 } })
524
- return async () => {
525
- await rewriteSourceMarker('marker-bbbbbbbbbb.mjs')
526
- }
527
- })
528
- })
529
-
530
- it('switches the standing generation for an equal-length module identity change', async () => {
531
- const rootPath = await presetsRoot()
532
- sourceRoot = rootPath
533
- ctx = new Context()
534
- ctx.baseUrl = `${pathToFileURL(rootPath).href}/`
535
- await ctx.plugin(Loader).await()
536
- ctx.loader.builtins.include = Include
537
- ctx.loader.builtins.group = Group
538
- await ctx.plugin(LlmRuntime).await()
539
- await ctx.plugin(SessionStore).await()
540
- await ctx.plugin(SystemPrompt).await()
541
- await ctx.plugin(ToolRuntime).await()
542
- await ctx.plugin(AgentRegistry).await()
543
- await ctx.plugin(AgentLoop).await()
544
- await ctx.plugin(CommandRuntime).await()
545
- await ctx.plugin(SessionProjectionRegistry).await()
546
- await ctx.plugin(TokenMeter).await()
547
- await ctx.plugin(MemorySettings).await()
548
- await ctx.plugin({ apply }).await()
549
- await ctx.plugin(AgentPresets, {
550
- default: 'standard',
551
- roots: [{ path: rootPath, trust: 'system' }],
552
- includeShippedRoot: false,
553
- includeUserRoot: false,
554
- }).await()
555
- const namespace = nsBrand('context-compression')
556
- await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 80 } })
557
-
558
- const presets = ctx.agentPresets as unknown as OverlayableAgentPresets
559
- // Two module sets whose entry paths differ in content but not length.
560
- const moduleA = await sameLengthModule('module-aaaaaaaaaa')
561
- const moduleB = await sameLengthModule('module-bbbbbbbbbb')
562
- const paths = (m: string) => ({
563
- compactionBasic: m,
564
- commandCompact: m,
565
- toolResultPruner: m,
566
- })
567
- let installation = decorateAgentPresets(presets, {
568
- modules: paths(moduleA),
569
- excludedPresetIds: ['minimal'],
570
- autoCompactThresholdPercent: () => 80,
571
- })
572
- const first = await presets.standingKeyFor()
573
- const firstFiles = await overlayFiles(rootPath)
574
- expect(firstFiles).toHaveLength(1)
575
- const firstPath = firstFiles[0]!.path
576
- const firstStamp = (await stat(firstPath)).mtimeMs
577
- expect(firstFiles[0]!.rendered).toContain(moduleA)
578
-
579
- // Disposing the old decoration also removes its generated store, so the
580
- // swap is proven by the new composition's path, content, and stamp.
581
- await installation.dispose()
582
- installation = decorateAgentPresets(presets, {
583
- modules: paths(moduleB),
584
- excludedPresetIds: ['minimal'],
585
- autoCompactThresholdPercent: () => 80,
586
- })
587
- const second = await presets.standingKeyFor()
588
- const secondFiles = await overlayFiles(rootPath)
589
- expect(secondFiles).toHaveLength(1)
590
- expect(second).not.toBe(first)
591
- expect(secondFiles[0]!.path).not.toBe(firstPath)
592
- expect(secondFiles[0]!.rendered).toContain(moduleB)
593
- expect((await stat(secondFiles[0]!.path)).mtimeMs).not.toBe(firstStamp)
594
- await installation.dispose()
595
- })
596
-
597
- it('keeps one generation under concurrent and repeated composition of the same identity', async () => {
598
- const rootPath = await presetsRoot()
599
- ctx = new Context()
600
- ctx.baseUrl = `${pathToFileURL(rootPath).href}/`
601
- await ctx.plugin(Loader).await()
602
- ctx.loader.builtins.include = Include
603
- ctx.loader.builtins.group = Group
604
- await ctx.plugin(LlmRuntime).await()
605
- await ctx.plugin(SessionStore).await()
606
- await ctx.plugin(SystemPrompt).await()
607
- await ctx.plugin(ToolRuntime).await()
608
- await ctx.plugin(AgentRegistry).await()
609
- await ctx.plugin(AgentLoop).await()
610
- await ctx.plugin(CommandRuntime).await()
611
- await ctx.plugin(SessionProjectionRegistry).await()
612
- await ctx.plugin(TokenMeter).await()
613
- await ctx.plugin(MemorySettings).await()
614
- await ctx.plugin({ apply }).await()
615
- await ctx.plugin(AgentPresets, {
616
- default: 'standard',
617
- roots: [{ path: rootPath, trust: 'system' }],
618
- includeShippedRoot: false,
619
- includeUserRoot: false,
620
- }).await()
621
- const namespace = nsBrand('context-compression')
622
- await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 73 } })
623
- const bundle = ctx.plugin({ apply: (child) => {
624
- apply(child, { presetOverlay: true })
625
- } })
626
- await bundle.await()
627
-
628
- const presets = ctx.agentPresets as unknown as OverlayableAgentPresets
629
- const concurrent = await Promise.all([
630
- presets.standingKeyFor(),
631
- presets.standingKeyFor(),
632
- presets.standingKeyFor(),
633
- ])
634
- expect(new Set(concurrent.map(key => JSON.stringify(key)))).toHaveLength(1)
635
- const files = await overlayFiles(rootPath)
636
- expect(files).toHaveLength(1)
637
- const stampFirst = (await stat(files[0]!.path)).mtimeMs
638
- const repeated = await presets.standingKeyFor()
639
- expect(JSON.stringify(repeated)).toBe(JSON.stringify(concurrent[0]))
640
- expect(await overlayFiles(rootPath)).toHaveLength(1)
641
- expect((await stat(files[0]!.path)).mtimeMs).toBe(stampFirst)
642
- })
643
-
644
- it('switches the standing generation for an equal-length threshold change (legacy body)', async () => {
645
- const rootPath = await presetsRoot()
646
- ctx = new Context()
647
- ctx.baseUrl = `${pathToFileURL(rootPath).href}/`
648
- await ctx.plugin(Loader).await()
649
- ctx.loader.builtins.include = Include
650
- ctx.loader.builtins.group = Group
651
- await ctx.plugin(LlmRuntime).await()
652
- await ctx.plugin(SessionStore).await()
653
- await ctx.plugin(SystemPrompt).await()
654
- await ctx.plugin(ToolRuntime).await()
655
- await ctx.plugin(AgentRegistry).await()
656
- await ctx.plugin(AgentLoop).await()
657
- await ctx.plugin(CommandRuntime).await()
658
- await ctx.plugin(SessionProjectionRegistry).await()
659
- await ctx.plugin(TokenMeter).await()
660
- await ctx.plugin(MemorySettings).await()
661
- await ctx.plugin({ apply }).await()
662
- await ctx.plugin(AgentPresets, {
663
- default: 'standard',
664
- roots: [{ path: rootPath, trust: 'system' }],
665
- includeShippedRoot: false,
666
- includeUserRoot: false,
667
- }).await()
668
- const namespace = nsBrand('context-compression')
669
- await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 70 } })
670
- const bundle = ctx.plugin({ apply: (child) => {
671
- apply(child, { presetOverlay: true })
672
- } })
673
- await bundle.await()
674
-
675
- const presets = ctx.agentPresets as unknown as OverlayableAgentPresets
676
- const first = await presets.standingKeyFor()
677
- const firstFiles = await overlayFiles(rootPath)
678
- expect(firstFiles).toHaveLength(1)
679
- expect(firstFiles[0]?.rendered).toContain('thresholdRatio: 0.7')
680
- expect(firstFiles[0]?.rendered).toContain('autoCompactThresholdPercent: 70')
681
-
682
- // Equal-length change: identical rendered sizes, and without the
683
- // deterministic threshold mtime a same-millisecond switch could have
684
- // reused the superseded generation.
685
- await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 80 } })
686
- const second = await presets.standingKeyFor()
687
- const secondFiles = await overlayFiles(rootPath)
688
- expect(secondFiles).toHaveLength(2)
689
- expect(secondFiles.some(file => file.rendered.includes('thresholdRatio: 0.8')
690
- && file.rendered.includes('autoCompactThresholdPercent: 80'))).toBe(true)
691
- expect(second).not.toBe(first)
692
- const stamps = await Promise.all(secondFiles.map(async file => (await stat(file.path)).mtimeMs))
693
- expect(new Set(stamps).size).toBe(2)
694
-
695
- await bundle.dispose()
696
- })
697
- })
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 {
22
+ SettingsProvider,
23
+ type SettingsNamespace,
24
+ } from '@deepseek-ai/dsh-settings'
25
+ import { pathToFileURL } from 'node:url'
26
+ import { afterEach, describe, expect, it } from 'vitest'
27
+ import { apply } from '../src/index.ts'
28
+ import {
29
+ decorateAgentPresets,
30
+ resolveCompressionModulePaths,
31
+ standingStampMs,
32
+ standingStampMsAtWindow,
33
+ } from '../src/preset-overlay.ts'
34
+ import type {
35
+ CompressionModulePaths,
36
+ OverlayableAgentPresets,
37
+ PresetOverlayMetadataIo,
38
+ } from '../src/preset-overlay.ts'
39
+
40
+ // 0.1.5 removed the settingsNamespace() wrapper; namespaces are validated at runtime.
41
+ const nsBrand = (value: string): SettingsNamespace => value as unknown as SettingsNamespace
42
+
43
+ let root: string | undefined
44
+ let ctx: Context | undefined
45
+
46
+ afterEach(async () => {
47
+ await ctx?.fiber.dispose()
48
+ ctx = undefined
49
+ if (root !== undefined) await rm(root, { recursive: true, force: true })
50
+ root = undefined
51
+ })
52
+
53
+ class MemorySettings extends SettingsProvider {
54
+ readonly writable = true
55
+ private readonly stored: Record<string, unknown> = {}
56
+
57
+ protected load(): Promise<Record<string, unknown>> {
58
+ return Promise.resolve(structuredClone(this.stored))
59
+ }
60
+
61
+ protected persist(ns: SettingsNamespace, section: Record<string, unknown>): Promise<void> {
62
+ this.stored[ns] = structuredClone(section)
63
+ return Promise.resolve()
64
+ }
65
+ }
66
+
67
+ async function presetsRoot(): Promise<string> {
68
+ root = await mkdtemp(join(tmpdir(), 'dsh-selector-standing-'))
69
+ const marker = join(root, 'marker-aaaaaaaaaa.mjs')
70
+ await writeFile(marker, 'export function apply() {}\n')
71
+ const path = join(root, 'standard', 'agent.cordis.yml')
72
+ await mkdir(dirname(path), { recursive: true })
73
+ await writeFile(path, `- id: source-marker\n name: ${JSON.stringify(marker)}\n`)
74
+ return root
75
+ }
76
+
77
+ /**
78
+ * Read the overlay compositions generated from THIS test's source preset.
79
+ * Concurrent spec files write their own stores; the embedded marker path
80
+ * distinguishes ours without depending on directory discovery timing.
81
+ */
82
+ async function overlayFiles(sourceMarker: string): Promise<{ path: string, rendered: string }[]> {
83
+ const parent = await readdir(tmpdir(), { withFileTypes: true })
84
+ const files: { path: string, rendered: string }[] = []
85
+ for (const entry of parent) {
86
+ if (!entry.isDirectory() || !entry.name.startsWith('dsh-context-compression-presets-')) continue
87
+ const directory = join(tmpdir(), entry.name)
88
+ let children
89
+ try {
90
+ children = await readdir(directory)
91
+ } catch {
92
+ continue // a concurrent spec disposed its store mid-scan
93
+ }
94
+ for (const child of children) {
95
+ if (!child.startsWith('standard-') || !child.endsWith('.agent.cordis.yml')) continue
96
+ const path = join(directory, child)
97
+ const rendered = await readFile(path, 'utf8')
98
+ if (rendered.includes(sourceMarker)) files.push({ path, rendered })
99
+ }
100
+ }
101
+ return files
102
+ }
103
+
104
+ /**
105
+ * The mtime this platform actually persists for one given stamp.
106
+ *
107
+ * `node:fs` `utimes` writes the seconds component through a 32-bit field on
108
+ * Windows: on node v22 win32, `utimes(file, 4677832452 s)` reads back as
109
+ * `382865156 s` — exactly `seconds >>> 0` — while sub-second precision
110
+ * survives. The standing stamp deliberately parks identities around year 2162
111
+ * (`STANDING_MTIME_EPOCH_SECONDS + 0xffffffff`, src/preset-overlay.ts), so its
112
+ * seconds component sits past that 2^32-second horizon (max year 2106) and the
113
+ * persisted literal differs on that platform. Deterministically so: the wrap is
114
+ * a pure function of the identity stamp, which is why identity → mtime stays
115
+ * stable and the collision escalation still absorbs any merge.
116
+ *
117
+ * Instead of hardcoding the platform or weakening the assertion, calibrate:
118
+ * ask the filesystem what it stores for exactly this stamp, then require the
119
+ * overlay to persist that same value. On a platform with a full-width seconds
120
+ * field this collapses to the stamp itself, so the assertion stays strict.
121
+ */
122
+ async function platformPersistedMs(stampMs: number): Promise<number> {
123
+ const directory = await mkdtemp(join(tmpdir(), 'dsh-selector-mtime-probe-'))
124
+ const probe = join(directory, 'probe')
125
+ try {
126
+ await writeFile(probe, 'probe')
127
+ const stamp = new Date(stampMs)
128
+ await utimes(probe, stamp, stamp)
129
+ return (await stat(probe)).mtimeMs
130
+ } finally {
131
+ await rm(directory, { recursive: true, force: true })
132
+ }
133
+ }
134
+
135
+ let sourceRoot: string | undefined
136
+
137
+ /** Rewrite the source preset to an equal-length marker module. */
138
+ async function rewriteSourceMarker(name: string): Promise<void> {
139
+ if (sourceRoot === undefined) throw new Error('source root not prepared')
140
+ const marker = join(sourceRoot, name)
141
+ await writeFile(marker, 'export function apply() {}\n')
142
+ await writeFile(join(sourceRoot, 'standard', 'agent.cordis.yml'), `- id: source-marker\n name: ${JSON.stringify(marker)}\n`)
143
+ }
144
+
145
+ /** Create an importable marker module with an exact-length directory name. */
146
+ async function sameLengthModule(label: string): Promise<string> {
147
+ if (sourceRoot === undefined) throw new Error('source root not prepared')
148
+ const directory = join(sourceRoot, label)
149
+ await mkdir(directory, { recursive: true })
150
+ const file = join(directory, 'index.mjs')
151
+ await writeFile(file, 'export function apply() {}\n')
152
+ return file
153
+ }
154
+
155
+ /** Reproduce the production content identity without replacing it in the store. */
156
+ function overlayIdentity(
157
+ source: string,
158
+ modules: CompressionModulePaths,
159
+ thresholdPercent: number,
160
+ ): string {
161
+ return createHash('sha256')
162
+ .update('standard').update('\0')
163
+ .update(source).update('\0')
164
+ .update(JSON.stringify({ modules, autoCompactThresholdPercent: thresholdPercent }))
165
+ .digest('hex')
166
+ .slice(0, 24)
167
+ }
168
+
169
+ /** Find equal-length valid presets whose production identities share window 0. */
170
+ function coarseCollisionFixture(
171
+ marker: string,
172
+ modules: CompressionModulePaths,
173
+ ): Readonly<{ first: string, second: string, firstIdentity: string, secondIdentity: string }> {
174
+ const seen = new Map<string, Readonly<{ source: string, identity: string }>>()
175
+ for (let index = 0; index < 300_000; index += 1) {
176
+ const label = index.toString(16).padStart(8, '0')
177
+ const source = [
178
+ '- id: source-marker',
179
+ ` name: ${JSON.stringify(marker)}`,
180
+ `- id: collision-${label}`,
181
+ ' name: cordis:group',
182
+ ' group: true',
183
+ ' config: []',
184
+ '',
185
+ ].join('\n')
186
+ const identity = overlayIdentity(source, modules, 80)
187
+ const prefix = identity.slice(0, 8)
188
+ const prior = seen.get(prefix)
189
+ if (prior !== undefined && prior.identity !== identity) {
190
+ return {
191
+ first: prior.source,
192
+ second: source,
193
+ firstIdentity: prior.identity,
194
+ secondIdentity: identity,
195
+ }
196
+ }
197
+ seen.set(prefix, { source, identity })
198
+ }
199
+ throw new Error('failed to find a deterministic 32-bit standing-stamp collision')
200
+ }
201
+
202
+ /**
203
+ * Mount the full real stack, run `arrange`, capture the standing key and
204
+ * generated file, run `act`, and assert the generation moved.
205
+ */
206
+ async function assertStandingSwitch(
207
+ arrange: () => Promise<() => Promise<void>>,
208
+ ): Promise<void> {
209
+ const rootPath = await presetsRoot()
210
+ sourceRoot = rootPath
211
+ ctx = new Context()
212
+ ctx.baseUrl = `${pathToFileURL(rootPath).href}/`
213
+ await ctx.plugin(Loader).await()
214
+ ctx.loader.builtins.include = Include
215
+ ctx.loader.builtins.group = Group
216
+ await ctx.plugin(LlmRuntime).await()
217
+ await ctx.plugin(SessionStore).await()
218
+ await ctx.plugin(SystemPrompt).await()
219
+ await ctx.plugin(ToolRuntime).await()
220
+ await ctx.plugin(AgentRegistry).await()
221
+ await ctx.plugin(AgentLoop).await()
222
+ await ctx.plugin(CommandRuntime).await()
223
+ await ctx.plugin(SessionProjectionRegistry).await()
224
+ await ctx.plugin(TokenMeter).await()
225
+ await ctx.plugin(MemorySettings).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({ apply }).await()
397
+ await ctx.plugin(AgentPresets, {
398
+ default: 'standard',
399
+ roots: [{ path: rootPath, trust: 'system' }],
400
+ includeShippedRoot: false,
401
+ includeUserRoot: false,
402
+ }).await()
403
+ const namespace = nsBrand('context-compression')
404
+ await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 80 } })
405
+ const bundle = ctx.plugin({ apply: (child) => {
406
+ apply(child, { presetOverlay: true })
407
+ } })
408
+ await bundle.await()
409
+
410
+ const presets = ctx.agentPresets as unknown as OverlayableAgentPresets
411
+ await presets.standingKeyFor()
412
+ // Two equal-length sources (55 bytes each, matching the collision
413
+ // fixture's shape): distinct identities whose stamps must never collapse
414
+ // onto the same whole second even if the filesystem truncates mtimes.
415
+ await rewriteSourceMarker('marker-00000aa9.mjs')
416
+ await presets.standingKeyFor()
417
+ await rewriteSourceMarker('marker-00000wil.mjs')
418
+ const third = await presets.standingKeyFor()
419
+ expect(third).toBeDefined()
420
+
421
+ const files = await overlayFiles(rootPath)
422
+ expect(files.length).toBeGreaterThanOrEqual(3)
423
+ const buckets = await Promise.all(files.map(async file => Math.floor((await stat(file.path)).mtimeMs / 1000)))
424
+ expect(new Set(buckets).size).toBe(buckets.length)
425
+ // No staging leftovers survive a publish. A spec file running in parallel
426
+ // disposes its own store while this scan runs, so a vanished directory means
427
+ // "no leftovers to find" rather than a failure (mirrors overlayFiles).
428
+ const storeDirs = await Promise.all(
429
+ (await readdir(tmpdir(), { withFileTypes: true }))
430
+ .filter(entry => entry.isDirectory() && entry.name.startsWith('dsh-context-compression-presets-'))
431
+ .map(async entry => {
432
+ try {
433
+ return await readdir(join(tmpdir(), entry.name))
434
+ } catch {
435
+ return []
436
+ }
437
+ }),
438
+ )
439
+ expect(storeDirs.flat().some(name => name.endsWith('.tmp'))).toBe(false)
440
+
441
+ await bundle.dispose()
442
+ })
443
+
444
+ it('keeps one fully-identical generation under concurrent composition of the same identity', async () => {
445
+ const rootPath = await presetsRoot()
446
+ ctx = new Context()
447
+ ctx.baseUrl = `${pathToFileURL(rootPath).href}/`
448
+ await ctx.plugin(Loader).await()
449
+ ctx.loader.builtins.include = Include
450
+ ctx.loader.builtins.group = Group
451
+ await ctx.plugin(LlmRuntime).await()
452
+ await ctx.plugin(SessionStore).await()
453
+ await ctx.plugin(SystemPrompt).await()
454
+ await ctx.plugin(ToolRuntime).await()
455
+ await ctx.plugin(AgentRegistry).await()
456
+ await ctx.plugin(AgentLoop).await()
457
+ await ctx.plugin(CommandRuntime).await()
458
+ await ctx.plugin(SessionProjectionRegistry).await()
459
+ await ctx.plugin(TokenMeter).await()
460
+ await ctx.plugin(MemorySettings).await()
461
+ await ctx.plugin({ apply }).await()
462
+ await ctx.plugin(AgentPresets, {
463
+ default: 'standard',
464
+ roots: [{ path: rootPath, trust: 'system' }],
465
+ includeShippedRoot: false,
466
+ includeUserRoot: false,
467
+ }).await()
468
+ const namespace = nsBrand('context-compression')
469
+ await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 73 } })
470
+ const bundle = ctx.plugin({ apply: (child) => {
471
+ apply(child, { presetOverlay: true })
472
+ } })
473
+ await bundle.await()
474
+
475
+ const presets = ctx.agentPresets as unknown as OverlayableAgentPresets
476
+ // Every concurrent composer must hand out the SAME path, and the file's
477
+ // persisted stamp must be the deterministic identity stamp — never a
478
+ // wall-clock mtime from a metadata window.
479
+ const concurrent = await Promise.all([
480
+ presets.standingKeyFor(),
481
+ presets.standingKeyFor(),
482
+ presets.standingKeyFor(),
483
+ presets.standingKeyFor(),
484
+ presets.standingKeyFor(),
485
+ presets.standingKeyFor(),
486
+ ])
487
+ expect(new Set(concurrent.map(key => JSON.stringify(key)))).toHaveLength(1)
488
+ const files = await overlayFiles(rootPath)
489
+ expect(files).toHaveLength(1)
490
+ const details = await stat(files[0]!.path)
491
+ const now = Date.now()
492
+ expect(Math.abs(details.mtimeMs - now)).toBeGreaterThan(60 * 60 * 1000)
493
+ // The persisted whole-second bucket matches the identity-derived stamp's
494
+ // bucket regardless of filesystem mtime granularity, and the persisted
495
+ // sub-second component is the identity-derived one (or its zero-truncated
496
+ // form on a coarse filesystem).
497
+ const rendered = files[0]!.rendered
498
+ const identity = rendered.length > 0
499
+ ? /standard-([0-9a-f]+)\.agent\.cordis\.yml$/u.exec(files[0]!.path)?.[1]
500
+ : undefined
501
+ expect(identity).toBeDefined()
502
+ const persistedStamp = await platformPersistedMs(standingStampMs(identity as string))
503
+ expect(Math.floor(details.mtimeMs / 1000))
504
+ .toBe(Math.floor(persistedStamp / 1000))
505
+ const observedSubSecond = details.mtimeMs % 1000
506
+ const expectedSubSecond = standingStampMs(identity as string) % 1000
507
+ expect(observedSubSecond === 0 || Math.abs(observedSubSecond - expectedSubSecond) < 1).toBe(true)
508
+
509
+ await bundle.dispose()
510
+ })
511
+
512
+ it('switches the standing generation for an equal-length threshold change', async () => {
513
+ await assertStandingSwitch(async () => {
514
+ const namespace = nsBrand('context-compression')
515
+ await ctx!.settings.update(namespace, { autoCompact: { thresholdPercent: 70 } })
516
+ return async () => ctx!.settings.update(namespace, { autoCompact: { thresholdPercent: 80 } })
517
+ })
518
+ })
519
+
520
+ it('switches the standing generation for an equal-length source change at a fixed threshold', async () => {
521
+ await assertStandingSwitch(async () => {
522
+ const namespace = nsBrand('context-compression')
523
+ await ctx!.settings.update(namespace, { autoCompact: { thresholdPercent: 80 } })
524
+ return async () => {
525
+ await rewriteSourceMarker('marker-bbbbbbbbbb.mjs')
526
+ }
527
+ })
528
+ })
529
+
530
+ it('switches the standing generation for an equal-length module identity change', async () => {
531
+ const rootPath = await presetsRoot()
532
+ sourceRoot = rootPath
533
+ ctx = new Context()
534
+ ctx.baseUrl = `${pathToFileURL(rootPath).href}/`
535
+ await ctx.plugin(Loader).await()
536
+ ctx.loader.builtins.include = Include
537
+ ctx.loader.builtins.group = Group
538
+ await ctx.plugin(LlmRuntime).await()
539
+ await ctx.plugin(SessionStore).await()
540
+ await ctx.plugin(SystemPrompt).await()
541
+ await ctx.plugin(ToolRuntime).await()
542
+ await ctx.plugin(AgentRegistry).await()
543
+ await ctx.plugin(AgentLoop).await()
544
+ await ctx.plugin(CommandRuntime).await()
545
+ await ctx.plugin(SessionProjectionRegistry).await()
546
+ await ctx.plugin(TokenMeter).await()
547
+ await ctx.plugin(MemorySettings).await()
548
+ await ctx.plugin({ apply }).await()
549
+ await ctx.plugin(AgentPresets, {
550
+ default: 'standard',
551
+ roots: [{ path: rootPath, trust: 'system' }],
552
+ includeShippedRoot: false,
553
+ includeUserRoot: false,
554
+ }).await()
555
+ const namespace = nsBrand('context-compression')
556
+ await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 80 } })
557
+
558
+ const presets = ctx.agentPresets as unknown as OverlayableAgentPresets
559
+ // Two module sets whose entry paths differ in content but not length.
560
+ const moduleA = await sameLengthModule('module-aaaaaaaaaa')
561
+ const moduleB = await sameLengthModule('module-bbbbbbbbbb')
562
+ const paths = (m: string) => ({
563
+ compactionBasic: m,
564
+ commandCompact: m,
565
+ toolResultPruner: m,
566
+ })
567
+ let installation = decorateAgentPresets(presets, {
568
+ modules: paths(moduleA),
569
+ excludedPresetIds: ['minimal'],
570
+ autoCompactThresholdPercent: () => 80,
571
+ })
572
+ const first = await presets.standingKeyFor()
573
+ const firstFiles = await overlayFiles(rootPath)
574
+ expect(firstFiles).toHaveLength(1)
575
+ const firstPath = firstFiles[0]!.path
576
+ const firstStamp = (await stat(firstPath)).mtimeMs
577
+ expect(firstFiles[0]!.rendered).toContain(moduleA)
578
+
579
+ // Disposing the old decoration also removes its generated store, so the
580
+ // swap is proven by the new composition's path, content, and stamp.
581
+ await installation.dispose()
582
+ installation = decorateAgentPresets(presets, {
583
+ modules: paths(moduleB),
584
+ excludedPresetIds: ['minimal'],
585
+ autoCompactThresholdPercent: () => 80,
586
+ })
587
+ const second = await presets.standingKeyFor()
588
+ const secondFiles = await overlayFiles(rootPath)
589
+ expect(secondFiles).toHaveLength(1)
590
+ expect(second).not.toBe(first)
591
+ expect(secondFiles[0]!.path).not.toBe(firstPath)
592
+ expect(secondFiles[0]!.rendered).toContain(moduleB)
593
+ expect((await stat(secondFiles[0]!.path)).mtimeMs).not.toBe(firstStamp)
594
+ await installation.dispose()
595
+ })
596
+
597
+ it('keeps one generation under concurrent and repeated composition of the same identity', async () => {
598
+ const rootPath = await presetsRoot()
599
+ ctx = new Context()
600
+ ctx.baseUrl = `${pathToFileURL(rootPath).href}/`
601
+ await ctx.plugin(Loader).await()
602
+ ctx.loader.builtins.include = Include
603
+ ctx.loader.builtins.group = Group
604
+ await ctx.plugin(LlmRuntime).await()
605
+ await ctx.plugin(SessionStore).await()
606
+ await ctx.plugin(SystemPrompt).await()
607
+ await ctx.plugin(ToolRuntime).await()
608
+ await ctx.plugin(AgentRegistry).await()
609
+ await ctx.plugin(AgentLoop).await()
610
+ await ctx.plugin(CommandRuntime).await()
611
+ await ctx.plugin(SessionProjectionRegistry).await()
612
+ await ctx.plugin(TokenMeter).await()
613
+ await ctx.plugin(MemorySettings).await()
614
+ await ctx.plugin({ apply }).await()
615
+ await ctx.plugin(AgentPresets, {
616
+ default: 'standard',
617
+ roots: [{ path: rootPath, trust: 'system' }],
618
+ includeShippedRoot: false,
619
+ includeUserRoot: false,
620
+ }).await()
621
+ const namespace = nsBrand('context-compression')
622
+ await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 73 } })
623
+ const bundle = ctx.plugin({ apply: (child) => {
624
+ apply(child, { presetOverlay: true })
625
+ } })
626
+ await bundle.await()
627
+
628
+ const presets = ctx.agentPresets as unknown as OverlayableAgentPresets
629
+ const concurrent = await Promise.all([
630
+ presets.standingKeyFor(),
631
+ presets.standingKeyFor(),
632
+ presets.standingKeyFor(),
633
+ ])
634
+ expect(new Set(concurrent.map(key => JSON.stringify(key)))).toHaveLength(1)
635
+ const files = await overlayFiles(rootPath)
636
+ expect(files).toHaveLength(1)
637
+ const stampFirst = (await stat(files[0]!.path)).mtimeMs
638
+ const repeated = await presets.standingKeyFor()
639
+ expect(JSON.stringify(repeated)).toBe(JSON.stringify(concurrent[0]))
640
+ expect(await overlayFiles(rootPath)).toHaveLength(1)
641
+ expect((await stat(files[0]!.path)).mtimeMs).toBe(stampFirst)
642
+ })
643
+
644
+ it('switches the standing generation for an equal-length threshold change (legacy body)', async () => {
645
+ const rootPath = await presetsRoot()
646
+ ctx = new Context()
647
+ ctx.baseUrl = `${pathToFileURL(rootPath).href}/`
648
+ await ctx.plugin(Loader).await()
649
+ ctx.loader.builtins.include = Include
650
+ ctx.loader.builtins.group = Group
651
+ await ctx.plugin(LlmRuntime).await()
652
+ await ctx.plugin(SessionStore).await()
653
+ await ctx.plugin(SystemPrompt).await()
654
+ await ctx.plugin(ToolRuntime).await()
655
+ await ctx.plugin(AgentRegistry).await()
656
+ await ctx.plugin(AgentLoop).await()
657
+ await ctx.plugin(CommandRuntime).await()
658
+ await ctx.plugin(SessionProjectionRegistry).await()
659
+ await ctx.plugin(TokenMeter).await()
660
+ await ctx.plugin(MemorySettings).await()
661
+ await ctx.plugin({ apply }).await()
662
+ await ctx.plugin(AgentPresets, {
663
+ default: 'standard',
664
+ roots: [{ path: rootPath, trust: 'system' }],
665
+ includeShippedRoot: false,
666
+ includeUserRoot: false,
667
+ }).await()
668
+ const namespace = nsBrand('context-compression')
669
+ await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 70 } })
670
+ const bundle = ctx.plugin({ apply: (child) => {
671
+ apply(child, { presetOverlay: true })
672
+ } })
673
+ await bundle.await()
674
+
675
+ const presets = ctx.agentPresets as unknown as OverlayableAgentPresets
676
+ const first = await presets.standingKeyFor()
677
+ const firstFiles = await overlayFiles(rootPath)
678
+ expect(firstFiles).toHaveLength(1)
679
+ expect(firstFiles[0]?.rendered).toContain('thresholdRatio: 0.7')
680
+ expect(firstFiles[0]?.rendered).toContain('autoCompactThresholdPercent: 70')
681
+
682
+ // Equal-length change: identical rendered sizes, and without the
683
+ // deterministic threshold mtime a same-millisecond switch could have
684
+ // reused the superseded generation.
685
+ await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 80 } })
686
+ const second = await presets.standingKeyFor()
687
+ const secondFiles = await overlayFiles(rootPath)
688
+ expect(secondFiles).toHaveLength(2)
689
+ expect(secondFiles.some(file => file.rendered.includes('thresholdRatio: 0.8')
690
+ && file.rendered.includes('autoCompactThresholdPercent: 80'))).toBe(true)
691
+ expect(second).not.toBe(first)
692
+ const stamps = await Promise.all(secondFiles.map(async file => (await stat(file.path)).mtimeMs))
693
+ expect(new Set(stamps).size).toBe(2)
694
+
695
+ await bundle.dispose()
696
+ })
697
+ })