dsh-context-compression-improved 0.12.0 → 0.13.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 (330) hide show
  1. package/.agents/plans/improve/checklist.md +32 -0
  2. package/.agents/plans/improve/findings.md +102 -0
  3. package/.agents/plans/improve/spec.md +53 -0
  4. package/.agents/plans/improve/tasks.md +70 -0
  5. package/.gitattributes +2 -0
  6. package/.githooks/pre-push +37 -0
  7. package/.github/workflows/ci.yml +47 -0
  8. package/CHANGELOG.de.md +580 -0
  9. package/CHANGELOG.es.md +588 -0
  10. package/CHANGELOG.fr.md +576 -0
  11. package/CHANGELOG.it.md +577 -0
  12. package/CHANGELOG.ja.md +261 -0
  13. package/CHANGELOG.ko.md +254 -0
  14. package/CHANGELOG.md +582 -0
  15. package/CHANGELOG.pt.md +167 -0
  16. package/CHANGELOG.ru.md +554 -0
  17. package/CHANGELOG.zh.md +247 -0
  18. package/CONTRIBUTING.md +22 -0
  19. package/README.de.md +96 -0
  20. package/README.es.md +96 -0
  21. package/README.fr.md +96 -0
  22. package/README.it.md +96 -0
  23. package/README.ja.md +102 -0
  24. package/README.ko.md +102 -0
  25. package/README.md +128 -22
  26. package/README.pt.md +96 -0
  27. package/README.ru.md +96 -0
  28. package/README.zh.md +114 -24
  29. package/SECURITY.md +18 -0
  30. package/THIRD_PARTY_NOTICES.md +7 -25
  31. package/assets/board.png +0 -0
  32. package/assets/context.png +0 -0
  33. package/assets/dshfind-card.svg +33 -0
  34. package/docs/assets/context-compression-selector-profiles.jpg +0 -0
  35. package/docs/assets/context-compression-selector-settings.png +0 -0
  36. package/docs/compat-0.1.5-report.md +77 -0
  37. package/docs/installation.de.md +104 -0
  38. package/docs/installation.es.md +104 -0
  39. package/docs/installation.fr.md +104 -0
  40. package/docs/installation.it.md +104 -0
  41. package/docs/installation.ja.md +78 -0
  42. package/docs/installation.ko.md +78 -0
  43. package/docs/installation.md +103 -0
  44. package/docs/installation.ru.md +104 -0
  45. package/docs/installation.zh.md +100 -0
  46. package/docs/repair-log.md +657 -0
  47. package/docs/shallow-teaching-preset-template.md +46 -0
  48. package/eslint.config.js +30 -0
  49. package/package.json +112 -127
  50. package/packages/selector/LICENSE +21 -0
  51. package/packages/selector/README.md +26 -0
  52. package/packages/selector/README.zh.md +24 -0
  53. package/packages/selector/THIRD_PARTY_NOTICES.md +32 -0
  54. package/packages/selector/docs/history-tool-call-working-set-spec.md +112 -0
  55. package/packages/selector/docs/native-tool-result-selector-spec.md +34 -0
  56. package/packages/selector/docs/subagent-cache-reuse-spec.md +46 -0
  57. package/{dsh.plugin.json → packages/selector/dsh.plugin.json} +1 -1
  58. package/{lib → packages/selector/lib}/client.js +18 -10
  59. package/packages/selector/lib/style.css +350 -0
  60. package/packages/selector/package.json +180 -0
  61. package/packages/selector/screenshots.json +3 -0
  62. package/packages/selector/src/client/CompressionProfileControls.tsx +352 -0
  63. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -0
  64. package/packages/selector/src/client/CompressionProfileSelector.tsx +89 -0
  65. package/packages/selector/src/client/CustomPolicyEditor.tsx +216 -0
  66. package/packages/selector/src/client/EstimatorControls.tsx +277 -0
  67. package/packages/selector/src/client/bridge-scope.ts +125 -0
  68. package/packages/selector/src/client/decode.ts +68 -0
  69. package/packages/selector/src/client/fab-pos.ts +71 -0
  70. package/packages/selector/src/client/guide-steps.ts +50 -0
  71. package/packages/selector/src/client/guide.tsx +368 -0
  72. package/packages/selector/src/client/index.ts +456 -0
  73. package/packages/selector/src/client/locales/de.ts +167 -0
  74. package/packages/selector/src/client/locales/es.ts +167 -0
  75. package/packages/selector/src/client/locales/fr.ts +167 -0
  76. package/packages/selector/src/client/locales/it.ts +167 -0
  77. package/packages/selector/src/client/locales/ja.ts +167 -0
  78. package/packages/selector/src/client/locales/ko.ts +167 -0
  79. package/packages/selector/src/client/locales/pt.ts +167 -0
  80. package/packages/selector/src/client/locales/ru.ts +167 -0
  81. package/packages/selector/src/client/locales.ts +334 -0
  82. package/packages/selector/src/client/monitor-fab.ts +445 -0
  83. package/packages/selector/src/client/preset-options.ts +88 -0
  84. package/packages/selector/src/client/savings-card.tsx +269 -0
  85. package/packages/selector/src/client/scope-face.ts +24 -0
  86. package/packages/selector/src/client/settings-section.tsx +171 -0
  87. package/packages/selector/src/compat/host-generation.ts +96 -0
  88. package/packages/selector/src/compat/llm-messages.ts +50 -0
  89. package/packages/selector/src/compat/settings-lease.ts +108 -0
  90. package/packages/selector/src/compat/tool-result.ts +91 -0
  91. package/packages/selector/src/css-modules.d.ts +6 -0
  92. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -0
  93. package/packages/selector/src/estimator-catalog.ts +104 -0
  94. package/packages/selector/src/index.ts +909 -0
  95. package/packages/selector/src/invariant.ts +113 -0
  96. package/packages/selector/src/preset-overlay.ts +749 -0
  97. package/packages/selector/src/profiles.ts +554 -0
  98. package/packages/selector/src/pruner/content.ts +199 -0
  99. package/packages/selector/src/pruner/session.ts +97 -0
  100. package/packages/selector/src/pruner/state.ts +61 -0
  101. package/packages/selector/src/pruner/tuning.ts +23 -0
  102. package/packages/selector/src/pruner/types.ts +78 -0
  103. package/packages/selector/src/pruner.ts +3222 -0
  104. package/packages/selector/src/runtime/adaptive-cost.ts +205 -0
  105. package/packages/selector/src/runtime/audit.ts +321 -0
  106. package/packages/selector/src/runtime/config.ts +887 -0
  107. package/packages/selector/src/runtime/custom-policy.ts +300 -0
  108. package/packages/selector/src/runtime/deepseek-official-pricing.ts +298 -0
  109. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +254 -0
  110. package/packages/selector/src/runtime/display-prefs.ts +98 -0
  111. package/packages/selector/src/runtime/fold-router.ts +143 -0
  112. package/packages/selector/src/runtime/measurement.ts +444 -0
  113. package/packages/selector/src/runtime/monitor.ts +341 -0
  114. package/packages/selector/src/runtime/panel-command.ts +213 -0
  115. package/packages/selector/src/runtime/reducers.ts +1755 -0
  116. package/packages/selector/src/runtime/retrieve.ts +505 -0
  117. package/packages/selector/src/runtime/savings-integral.ts +117 -0
  118. package/packages/selector/src/runtime/savings-projection.ts +229 -0
  119. package/packages/selector/src/runtime/savings-verify.ts +446 -0
  120. package/packages/selector/src/runtime/savings.ts +526 -0
  121. package/packages/selector/src/runtime/sediment-card.ts +126 -0
  122. package/packages/selector/src/runtime/sediment-clock.ts +87 -0
  123. package/packages/selector/src/runtime/sediment-guard.ts +136 -0
  124. package/packages/selector/src/runtime/sediment-publish.ts +144 -0
  125. package/packages/selector/src/runtime/sediment-span.ts +170 -0
  126. package/packages/selector/src/runtime/sediment.ts +209 -0
  127. package/packages/selector/src/runtime/session-events.ts +30 -0
  128. package/packages/selector/src/runtime/session-file-decode.ts +523 -0
  129. package/packages/selector/src/runtime/shallow-tools.ts +342 -0
  130. package/packages/selector/src/runtime/stats-backfill.ts +541 -0
  131. package/packages/selector/src/runtime/stats-db.ts +492 -0
  132. package/packages/selector/src/runtime/stats-schema.ts +123 -0
  133. package/packages/selector/src/runtime/stats-sync.ts +307 -0
  134. package/packages/selector/src/runtime/summary-command.ts +127 -0
  135. package/packages/selector/src/runtime/tail-trim.ts +177 -0
  136. package/packages/selector/src/runtime/token-count.ts +72 -0
  137. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -0
  138. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -0
  139. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -0
  140. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -0
  141. package/packages/selector/src/runtime/tokenpilot/dedup.ts +82 -0
  142. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -0
  143. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  144. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  145. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  146. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  147. package/packages/selector/src/runtime/tokenpilot/locator.ts +129 -0
  148. package/packages/selector/src/runtime/tokenpilot/read-state.ts +98 -0
  149. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -0
  150. package/packages/selector/src/runtime/tool-names.ts +42 -0
  151. package/packages/selector/src/runtime/toolclass.ts +103 -0
  152. package/packages/selector/src/runtime/triage/masks.ts +128 -0
  153. package/packages/selector/src/runtime/triage/shallow.ts +132 -0
  154. package/packages/selector/src/runtime/triage/signals.ts +167 -0
  155. package/packages/selector/src/runtime/triage/types.ts +125 -0
  156. package/packages/selector/src/runtime/types.ts +396 -0
  157. package/packages/selector/src/runtime/value.ts +48 -0
  158. package/packages/selector/src/settings-bridge.ts +175 -0
  159. package/packages/selector/src/tui-command.ts +99 -0
  160. package/packages/selector/tests/advisor-report.host.spec.ts +223 -0
  161. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -0
  162. package/packages/selector/tests/built/client-artifact.spec.ts +56 -0
  163. package/packages/selector/tests/cache-prefix-audit.spec.ts +123 -0
  164. package/packages/selector/tests/code-skeleton.client.spec.ts +98 -0
  165. package/packages/selector/tests/compat/compat-narrow-waist.spec.ts +150 -0
  166. package/packages/selector/tests/custom-contract.client.spec.ts +226 -0
  167. package/packages/selector/tests/estimator-catalog.spec.ts +70 -0
  168. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -0
  169. package/packages/selector/tests/estimator-route-registration.host.spec.ts +202 -0
  170. package/packages/selector/tests/fab-pos.client.spec.ts +47 -0
  171. package/packages/selector/tests/fixtures/sediment-pool/52adc205-cloud-5.orig.txt +231 -0
  172. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-25.orig.txt +236 -0
  173. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-38.orig.txt +220 -0
  174. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-42.orig.txt +140 -0
  175. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-53.orig.txt +117 -0
  176. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-local-10.orig.txt +67 -0
  177. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-45.orig.txt +119 -0
  178. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-49.orig.txt +119 -0
  179. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-63.orig.txt +131 -0
  180. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-75.orig.txt +196 -0
  181. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-76.orig.txt +71 -0
  182. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-85.orig.txt +126 -0
  183. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-86.orig.txt +86 -0
  184. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-87.orig.txt +50 -0
  185. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-96.orig.txt +102 -0
  186. package/packages/selector/tests/helpers/legacy-namespace.ts +35 -0
  187. package/packages/selector/tests/helpers/legacy-settings/index.ts +15 -0
  188. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +41 -0
  189. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +647 -0
  190. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +78 -0
  191. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +234 -0
  192. package/packages/selector/tests/host-preset-overlay.host.spec.ts +204 -0
  193. package/packages/selector/tests/monitor-fab.client.spec.ts +240 -0
  194. package/packages/selector/tests/preset-options-write.client.spec.ts +192 -0
  195. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +200 -0
  196. package/packages/selector/tests/preset-overlay.host.spec.ts +246 -0
  197. package/packages/selector/tests/profiles.client.spec.tsx +436 -0
  198. package/packages/selector/tests/ptc-custom-write.client.spec.ts +86 -0
  199. package/packages/selector/tests/public/package-contract.client.spec.ts +91 -0
  200. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +167 -0
  201. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +230 -0
  202. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -0
  203. package/packages/selector/tests/runtime/advisor.spec.ts +226 -0
  204. package/packages/selector/tests/runtime/audit.spec.ts +275 -0
  205. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -0
  206. package/packages/selector/tests/runtime/behavior-lock-profiles.spec.ts +128 -0
  207. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -0
  208. package/packages/selector/tests/runtime/code-skeleton.spec.ts +152 -0
  209. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +186 -0
  210. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -0
  211. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +122 -0
  212. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -0
  213. package/packages/selector/tests/runtime/fallback-diversity.spec.ts +75 -0
  214. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +273 -0
  215. package/packages/selector/tests/runtime/fixtures/session-v4-dump.jsonl +46 -0
  216. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +106 -0
  217. package/packages/selector/tests/runtime/fixtures/vision-golden.json +459 -0
  218. package/packages/selector/tests/runtime/fold-router.spec.ts +140 -0
  219. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -0
  220. package/packages/selector/tests/runtime/fresh-gate.spec.ts +43 -0
  221. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -0
  222. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  223. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  224. package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +79 -0
  225. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -0
  226. package/packages/selector/tests/runtime/monitor.spec.ts +354 -0
  227. package/packages/selector/tests/runtime/panel-command.spec.ts +101 -0
  228. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -0
  229. package/packages/selector/tests/runtime/ptc-profile.spec.ts +133 -0
  230. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2795 -0
  231. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -0
  232. package/packages/selector/tests/runtime/savings-accounting.spec.ts +291 -0
  233. package/packages/selector/tests/runtime/savings-integral.spec.ts +169 -0
  234. package/packages/selector/tests/runtime/savings-projection.spec.ts +89 -0
  235. package/packages/selector/tests/runtime/savings-verify.spec.ts +226 -0
  236. package/packages/selector/tests/runtime/savings.spec.ts +139 -0
  237. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -0
  238. package/packages/selector/tests/runtime/sediment-card.spec.ts +111 -0
  239. package/packages/selector/tests/runtime/sediment-config.spec.ts +56 -0
  240. package/packages/selector/tests/runtime/sediment-guard.spec.ts +71 -0
  241. package/packages/selector/tests/runtime/sediment-masks.spec.ts +95 -0
  242. package/packages/selector/tests/runtime/sediment-orchestrator.spec.ts +166 -0
  243. package/packages/selector/tests/runtime/sediment-pool-share.spec.ts +65 -0
  244. package/packages/selector/tests/runtime/sediment-publish.spec.ts +142 -0
  245. package/packages/selector/tests/runtime/sediment-real-shapes.spec.ts +158 -0
  246. package/packages/selector/tests/runtime/sediment-settings.spec.ts +73 -0
  247. package/packages/selector/tests/runtime/sediment-signals.spec.ts +124 -0
  248. package/packages/selector/tests/runtime/sediment-span.spec.ts +92 -0
  249. package/packages/selector/tests/runtime/session-events.spec.ts +27 -0
  250. package/packages/selector/tests/runtime/session-file-decode.spec.ts +281 -0
  251. package/packages/selector/tests/runtime/settings-unwrap.spec.ts +58 -0
  252. package/packages/selector/tests/runtime/shallow-primitives.spec.ts +135 -0
  253. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -0
  254. package/packages/selector/tests/runtime/source-kind-audit.spec.ts +79 -0
  255. package/packages/selector/tests/runtime/stats-backfill-scheduler.spec.ts +167 -0
  256. package/packages/selector/tests/runtime/stats-backfill.spec.ts +350 -0
  257. package/packages/selector/tests/runtime/stats-db.spec.ts +361 -0
  258. package/packages/selector/tests/runtime/stats-privacy.spec.ts +55 -0
  259. package/packages/selector/tests/runtime/stats-sync.spec.ts +278 -0
  260. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  261. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -0
  262. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +53 -0
  263. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -0
  264. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +52 -0
  265. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -0
  266. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +76 -0
  267. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +121 -0
  268. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +82 -0
  269. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -0
  270. package/packages/selector/tests/runtime/value.spec.ts +23 -0
  271. package/packages/selector/tests/savings-sessions.client.spec.tsx +140 -0
  272. package/packages/selector/tests/settings-seat.client.spec.ts +215 -0
  273. package/packages/selector/tests/standing-generation.host.spec.ts +729 -0
  274. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +269 -0
  275. package/packages/selector/tests/support/cache-prefix-audit.ts +105 -0
  276. package/packages/selector/tests/support/mock-adapter.ts +37 -0
  277. package/packages/selector/tests/support/ui-primitives.tsx +34 -0
  278. package/packages/selector/tsconfig.json +11 -0
  279. package/packages/selector/tsdown.client.config.ts +102 -0
  280. package/packages/selector/tsdown.config.ts +20 -0
  281. package/pnpm-workspace.yaml +76 -0
  282. package/screenshots.json +6 -3
  283. package/scripts/capture-profile-baseline.mjs +42 -0
  284. package/scripts/cell-browser-e2e.mjs +354 -0
  285. package/scripts/generate-tokenizer-fixtures.py +81 -0
  286. package/scripts/generate-vision-fixtures.py +208 -0
  287. package/scripts/hosts.d.mts +3 -0
  288. package/scripts/hosts.mjs +81 -0
  289. package/scripts/packed-components-smoke.mjs +763 -0
  290. package/scripts/packed-install-e2e.mjs +1346 -0
  291. package/scripts/sediment-latency-report.mjs +63 -0
  292. package/scripts/sync-hosts.mjs +176 -0
  293. package/scripts/toolclass-corpus-replay.mjs +281 -0
  294. package/scripts/verify-release.mjs +342 -0
  295. package/tests/TEST_INVENTORY.md +41 -0
  296. package/tsconfig.base.json +18 -0
  297. package/tsconfig.json +7 -0
  298. package/tsconfig.tests.json +15 -0
  299. package/vitest.built.config.ts +9 -0
  300. package/vitest.config.ts +54 -0
  301. /package/{assets → packages/selector/assets}/deepseek-v4/LICENSE.DeepSeek-V4-Pro.txt +0 -0
  302. /package/{assets → packages/selector/assets}/deepseek-v4/manifest.json +0 -0
  303. /package/{assets → packages/selector/assets}/deepseek-v4/tokenizer.json +0 -0
  304. /package/{assets → packages/selector/assets}/deepseek-v4/tokenizer_config.json +0 -0
  305. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/LICENSE.DeepSeek-V4-Flash-Vision-Exp.txt +0 -0
  306. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/manifest.json +0 -0
  307. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/tokenizer.json +0 -0
  308. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/tokenizer_config.json +0 -0
  309. /package/{cordis.patch.yml → packages/selector/cordis.patch.yml} +0 -0
  310. /package/{lib → packages/selector/lib}/client.d.ts +0 -0
  311. /package/{lib → packages/selector/lib}/index.d.ts +0 -0
  312. /package/{lib → packages/selector/lib}/index.js +0 -0
  313. /package/{lib → packages/selector/lib}/invariant.d.ts +0 -0
  314. /package/{lib → packages/selector/lib}/invariant.js +0 -0
  315. /package/{lib → packages/selector/lib}/profiles.d.ts +0 -0
  316. /package/{lib → packages/selector/lib}/pruner.d.ts +0 -0
  317. /package/{lib → packages/selector/lib}/pruner.js +0 -0
  318. /package/{lib → packages/selector/lib}/savings-integral.js +0 -0
  319. /package/{lib → packages/selector/lib}/tail-trim.js +0 -0
  320. /package/{lib → packages/selector/lib}/tool-result.js +0 -0
  321. /package/{locale → packages/selector/locale}/de.json +0 -0
  322. /package/{locale → packages/selector/locale}/en.json +0 -0
  323. /package/{locale → packages/selector/locale}/es.json +0 -0
  324. /package/{locale → packages/selector/locale}/fr.json +0 -0
  325. /package/{locale → packages/selector/locale}/it.json +0 -0
  326. /package/{locale → packages/selector/locale}/ja.json +0 -0
  327. /package/{locale → packages/selector/locale}/ko.json +0 -0
  328. /package/{locale → packages/selector/locale}/pt.json +0 -0
  329. /package/{locale → packages/selector/locale}/ru.json +0 -0
  330. /package/{locale → packages/selector/locale}/zh.json +0 -0
@@ -0,0 +1,729 @@
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
+ // 本组每个用例都要真起一整套宿主插件栈(Loader/LlmRuntime/SessionStore/SystemPrompt/
289
+ // ToolRuntime/AgentRegistry/AgentLoop/CommandRuntime/SessionProjectionRegistry/TokenMeter/
290
+ // AgentPresets)。单跑约 1.0s,但全量 900 用例满载时会胀到 5.4s+,直接撞默认 5s 超时
291
+ // (满载复现:`Test timed out in 5000ms`,同文件其余重用例已胀到 2.9s)。
292
+ // 预算给到 30s:不改变断言语义,只把“慢”和“错”分开。
293
+ describe('real AgentPresets standing generations with the overlay threshold', { timeout: 30_000 }, () => {
294
+ it('separates colliding equal-size generations on a whole-second metadata surface before publish', async () => {
295
+ const rootPath = await presetsRoot()
296
+ sourceRoot = rootPath
297
+ const sourcePath = join(rootPath, 'standard', 'agent.cordis.yml')
298
+ const marker = join(rootPath, 'marker-aaaaaaaaaa.mjs')
299
+ const modules = resolveCompressionModulePaths()
300
+ const collision = coarseCollisionFixture(marker, modules)
301
+ expect(collision.first).toHaveLength(collision.second.length)
302
+ expect(collision.firstIdentity.slice(0, 8)).toBe(collision.secondIdentity.slice(0, 8))
303
+ await writeFile(sourcePath, collision.first)
304
+
305
+ ctx = new Context()
306
+ ctx.baseUrl = `${pathToFileURL(rootPath).href}/`
307
+ await ctx.plugin(Loader).await()
308
+ ctx.loader.builtins.include = Include
309
+ ctx.loader.builtins.group = Group
310
+ await ctx.plugin(LlmRuntime).await()
311
+ await ctx.plugin(SessionStore).await()
312
+ await ctx.plugin(SystemPrompt).await()
313
+ await ctx.plugin(ToolRuntime).await()
314
+ await ctx.plugin(AgentRegistry).await()
315
+ await ctx.plugin(AgentLoop).await()
316
+ await ctx.plugin(CommandRuntime).await()
317
+ await ctx.plugin(SessionProjectionRegistry).await()
318
+ await ctx.plugin(TokenMeter).await()
319
+ await ctx.plugin(AgentPresets, {
320
+ default: 'standard',
321
+ roots: [{ path: rootPath, trust: 'system' }],
322
+ includeShippedRoot: false,
323
+ includeUserRoot: false,
324
+ }).await()
325
+
326
+ const coarseMetadataIo: PresetOverlayMetadataIo = {
327
+ async setTimes(path, stamp) {
328
+ const wholeSecond = new Date(Math.floor(stamp.getTime() / 1000) * 1000)
329
+ await utimes(path, wholeSecond, wholeSecond)
330
+ },
331
+ async read(path) {
332
+ const observed = await stat(path)
333
+ return { mtimeMs: observed.mtimeMs, size: observed.size }
334
+ },
335
+ }
336
+ const presets = ctx.agentPresets as unknown as OverlayableAgentPresets
337
+ const installation = decorateAgentPresets(presets, {
338
+ modules,
339
+ autoCompactThresholdPercent: () => 80,
340
+ metadataIo: coarseMetadataIo,
341
+ })
342
+
343
+ const firstKey = await presets.standingKeyFor()
344
+ await writeFile(sourcePath, collision.second)
345
+ const changedSourceStamp = new Date(Date.now() + 2_000)
346
+ await utimes(sourcePath, changedSourceStamp, changedSourceStamp)
347
+ const secondKey = await presets.standingKeyFor()
348
+ // Scope keys are structurally `{ agentPreset: id }`; a new object identity
349
+ // proves real AgentPresets observed a different composition stamp and
350
+ // created a new standing generation.
351
+ expect(secondKey).not.toBe(firstKey)
352
+
353
+ const files = await overlayFiles(rootPath)
354
+ expect(files).toHaveLength(2)
355
+ const byIdentity = new Map(files.map(file => [
356
+ /standard-([0-9a-f]+)\.agent\.cordis\.yml$/u.exec(file.path)?.[1],
357
+ file.path,
358
+ ]))
359
+ const firstFile = byIdentity.get(collision.firstIdentity)
360
+ const secondFile = byIdentity.get(collision.secondIdentity)
361
+ expect(firstFile).toBeDefined()
362
+ expect(secondFile).toBeDefined()
363
+ const firstStat = await stat(firstFile as string)
364
+ const secondStat = await stat(secondFile as string)
365
+ expect(firstStat.size).toBe(secondStat.size)
366
+ expect(firstStat.mtimeMs % 1000).toBe(0)
367
+ expect(secondStat.mtimeMs % 1000).toBe(0)
368
+ // The coarse metadata surface floors both stamps to a whole second, and the
369
+ // platform may additionally wrap the seconds field (platformPersistedMs),
370
+ // so require exactly what the filesystem stores for those identity stamps.
371
+ const firstStamp = await platformPersistedMs(
372
+ Math.floor(standingStampMsAtWindow(collision.firstIdentity, 0) / 1000) * 1000,
373
+ )
374
+ const secondStamp = await platformPersistedMs(
375
+ Math.floor(standingStampMsAtWindow(collision.secondIdentity, 1) / 1000) * 1000,
376
+ )
377
+ expect(Math.floor(firstStat.mtimeMs / 1000)).toBe(Math.floor(firstStamp / 1000))
378
+ expect(Math.floor(secondStat.mtimeMs / 1000)).toBe(Math.floor(secondStamp / 1000))
379
+
380
+ await installation.dispose()
381
+ })
382
+
383
+ it('publishes distinct second buckets for equal-length colliding sources on the real filesystem', async () => {
384
+ const rootPath = await presetsRoot()
385
+ sourceRoot = rootPath
386
+ ctx = new Context()
387
+ ctx.baseUrl = `${pathToFileURL(rootPath).href}/`
388
+ await ctx.plugin(Loader).await()
389
+ ctx.loader.builtins.include = Include
390
+ ctx.loader.builtins.group = Group
391
+ await ctx.plugin(LlmRuntime).await()
392
+ await ctx.plugin(SessionStore).await()
393
+ await ctx.plugin(SystemPrompt).await()
394
+ await ctx.plugin(ToolRuntime).await()
395
+ await ctx.plugin(AgentRegistry).await()
396
+ await ctx.plugin(AgentLoop).await()
397
+ await ctx.plugin(CommandRuntime).await()
398
+ await ctx.plugin(SessionProjectionRegistry).await()
399
+ await ctx.plugin(TokenMeter).await()
400
+ await ctx.plugin(MemorySettings).await()
401
+ await ctx.plugin(LegacyNamespaceRegistrar).await()
402
+ await ctx.plugin({ apply }).await()
403
+ await ctx.plugin(AgentPresets, {
404
+ default: 'standard',
405
+ roots: [{ path: rootPath, trust: 'system' }],
406
+ includeShippedRoot: false,
407
+ includeUserRoot: false,
408
+ }).await()
409
+ const namespace = nsBrand('context-compression')
410
+ await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 80 } })
411
+ const bundle = ctx.plugin({ apply: (child) => {
412
+ apply(child, { presetOverlay: true })
413
+ } })
414
+ await bundle.await()
415
+
416
+ const presets = ctx.agentPresets as unknown as OverlayableAgentPresets
417
+ await presets.standingKeyFor()
418
+ // Two equal-length sources (55 bytes each, matching the collision
419
+ // fixture's shape): distinct identities whose stamps must never collapse
420
+ // onto the same whole second even if the filesystem truncates mtimes.
421
+ await rewriteSourceMarker('marker-00000aa9.mjs')
422
+ await presets.standingKeyFor()
423
+ await rewriteSourceMarker('marker-00000wil.mjs')
424
+ const third = await presets.standingKeyFor()
425
+ expect(third).toBeDefined()
426
+
427
+ const files = await overlayFiles(rootPath)
428
+ expect(files.length).toBeGreaterThanOrEqual(3)
429
+ const buckets = await Promise.all(files.map(async file => Math.floor((await stat(file.path)).mtimeMs / 1000)))
430
+ expect(new Set(buckets).size).toBe(buckets.length)
431
+ // No staging leftovers survive a publish. A spec file running in parallel
432
+ // disposes its own store while this scan runs, so a vanished directory means
433
+ // "no leftovers to find" rather than a failure (mirrors overlayFiles).
434
+ // No staging leftovers survive a publish. Scan only this test's own store,
435
+ // identified by its latest source marker: a concurrently running spec's
436
+ // store may legitimately hold .tmp staging while this scan runs, and a
437
+ // vanished directory means "no leftovers to find" (mirrors overlayFiles).
438
+ const storeDirs = await Promise.all(
439
+ (await readdir(tmpdir(), { withFileTypes: true }))
440
+ .filter(entry => entry.isDirectory() && entry.name.startsWith('dsh-context-compression-presets-'))
441
+ .map(async entry => {
442
+ const directory = join(tmpdir(), entry.name)
443
+ try {
444
+ return { directory, entries: await readdir(directory) }
445
+ } catch {
446
+ return { directory: '', entries: [] as string[] }
447
+ }
448
+ }),
449
+ )
450
+ const ownStores: string[] = []
451
+ await Promise.all(storeDirs.map(async ({ directory, entries }) => {
452
+ if (directory === '') return
453
+ for (const name of entries) {
454
+ if (!name.startsWith('standard-') || !name.endsWith('.agent.cordis.yml')) continue
455
+ try {
456
+ const rendered = await readFile(join(directory, name), 'utf8')
457
+ if (rendered.includes('marker-00000wil.mjs')) {
458
+ ownStores.push(directory)
459
+ return
460
+ }
461
+ } catch { /* a concurrent spec disposed its store mid-scan */ }
462
+ }
463
+ }))
464
+ const leftovers = (await Promise.all(ownStores.map(directory => readdir(directory))))
465
+ .flat()
466
+ .filter(name => name.endsWith('.tmp'))
467
+ expect(leftovers).toEqual([])
468
+
469
+ await bundle.dispose()
470
+ })
471
+
472
+ it('keeps one fully-identical generation under concurrent composition of the same identity', async () => {
473
+ const rootPath = await presetsRoot()
474
+ ctx = new Context()
475
+ ctx.baseUrl = `${pathToFileURL(rootPath).href}/`
476
+ await ctx.plugin(Loader).await()
477
+ ctx.loader.builtins.include = Include
478
+ ctx.loader.builtins.group = Group
479
+ await ctx.plugin(LlmRuntime).await()
480
+ await ctx.plugin(SessionStore).await()
481
+ await ctx.plugin(SystemPrompt).await()
482
+ await ctx.plugin(ToolRuntime).await()
483
+ await ctx.plugin(AgentRegistry).await()
484
+ await ctx.plugin(AgentLoop).await()
485
+ await ctx.plugin(CommandRuntime).await()
486
+ await ctx.plugin(SessionProjectionRegistry).await()
487
+ await ctx.plugin(TokenMeter).await()
488
+ await ctx.plugin(MemorySettings).await()
489
+ await ctx.plugin(LegacyNamespaceRegistrar).await()
490
+ await ctx.plugin({ apply }).await()
491
+ await ctx.plugin(AgentPresets, {
492
+ default: 'standard',
493
+ roots: [{ path: rootPath, trust: 'system' }],
494
+ includeShippedRoot: false,
495
+ includeUserRoot: false,
496
+ }).await()
497
+ const namespace = nsBrand('context-compression')
498
+ await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 73 } })
499
+ const bundle = ctx.plugin({ apply: (child) => {
500
+ apply(child, { presetOverlay: true })
501
+ } })
502
+ await bundle.await()
503
+
504
+ const presets = ctx.agentPresets as unknown as OverlayableAgentPresets
505
+ // Every concurrent composer must hand out the SAME path, and the file's
506
+ // persisted stamp must be the deterministic identity stamp — never a
507
+ // wall-clock mtime from a metadata window.
508
+ const concurrent = await Promise.all([
509
+ presets.standingKeyFor(),
510
+ presets.standingKeyFor(),
511
+ presets.standingKeyFor(),
512
+ presets.standingKeyFor(),
513
+ presets.standingKeyFor(),
514
+ presets.standingKeyFor(),
515
+ ])
516
+ expect(new Set(concurrent.map(key => JSON.stringify(key)))).toHaveLength(1)
517
+ const files = await overlayFiles(rootPath)
518
+ expect(files).toHaveLength(1)
519
+ const details = await stat(files[0]!.path)
520
+ const now = Date.now()
521
+ expect(Math.abs(details.mtimeMs - now)).toBeGreaterThan(60 * 60 * 1000)
522
+ // The persisted whole-second bucket matches the identity-derived stamp's
523
+ // bucket regardless of filesystem mtime granularity, and the persisted
524
+ // sub-second component is the identity-derived one (or its zero-truncated
525
+ // form on a coarse filesystem).
526
+ const rendered = files[0]!.rendered
527
+ const identity = rendered.length > 0
528
+ ? /standard-([0-9a-f]+)\.agent\.cordis\.yml$/u.exec(files[0]!.path)?.[1]
529
+ : undefined
530
+ expect(identity).toBeDefined()
531
+ const persistedStamp = await platformPersistedMs(standingStampMs(identity as string))
532
+ expect(Math.floor(details.mtimeMs / 1000))
533
+ .toBe(Math.floor(persistedStamp / 1000))
534
+ const observedSubSecond = details.mtimeMs % 1000
535
+ const expectedSubSecond = standingStampMs(identity as string) % 1000
536
+ expect(observedSubSecond === 0 || Math.abs(observedSubSecond - expectedSubSecond) < 1).toBe(true)
537
+
538
+ await bundle.dispose()
539
+ })
540
+
541
+ it('switches the standing generation for an equal-length threshold change', async () => {
542
+ await assertStandingSwitch(async () => {
543
+ const namespace = nsBrand('context-compression')
544
+ await ctx!.settings.update(namespace, { autoCompact: { thresholdPercent: 70 } })
545
+ return async () => ctx!.settings.update(namespace, { autoCompact: { thresholdPercent: 80 } })
546
+ })
547
+ })
548
+
549
+ it('switches the standing generation for an equal-length source change at a fixed threshold', async () => {
550
+ await assertStandingSwitch(async () => {
551
+ const namespace = nsBrand('context-compression')
552
+ await ctx!.settings.update(namespace, { autoCompact: { thresholdPercent: 80 } })
553
+ return async () => {
554
+ await rewriteSourceMarker('marker-bbbbbbbbbb.mjs')
555
+ }
556
+ })
557
+ })
558
+
559
+ it('switches the standing generation for an equal-length module identity change', async () => {
560
+ const rootPath = await presetsRoot()
561
+ sourceRoot = rootPath
562
+ ctx = new Context()
563
+ ctx.baseUrl = `${pathToFileURL(rootPath).href}/`
564
+ await ctx.plugin(Loader).await()
565
+ ctx.loader.builtins.include = Include
566
+ ctx.loader.builtins.group = Group
567
+ await ctx.plugin(LlmRuntime).await()
568
+ await ctx.plugin(SessionStore).await()
569
+ await ctx.plugin(SystemPrompt).await()
570
+ await ctx.plugin(ToolRuntime).await()
571
+ await ctx.plugin(AgentRegistry).await()
572
+ await ctx.plugin(AgentLoop).await()
573
+ await ctx.plugin(CommandRuntime).await()
574
+ await ctx.plugin(SessionProjectionRegistry).await()
575
+ await ctx.plugin(TokenMeter).await()
576
+ await ctx.plugin(MemorySettings).await()
577
+ await ctx.plugin(LegacyNamespaceRegistrar).await()
578
+ await ctx.plugin({ apply }).await()
579
+ await ctx.plugin(AgentPresets, {
580
+ default: 'standard',
581
+ roots: [{ path: rootPath, trust: 'system' }],
582
+ includeShippedRoot: false,
583
+ includeUserRoot: false,
584
+ }).await()
585
+ const namespace = nsBrand('context-compression')
586
+ await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 80 } })
587
+
588
+ const presets = ctx.agentPresets as unknown as OverlayableAgentPresets
589
+ // Two module sets whose entry paths differ in content but not length.
590
+ const moduleA = await sameLengthModule('module-aaaaaaaaaa')
591
+ const moduleB = await sameLengthModule('module-bbbbbbbbbb')
592
+ const paths = (m: string) => ({
593
+ compactionBasic: m,
594
+ commandCompact: m,
595
+ toolResultPruner: m,
596
+ })
597
+ let installation = decorateAgentPresets(presets, {
598
+ modules: paths(moduleA),
599
+ excludedPresetIds: ['minimal'],
600
+ autoCompactThresholdPercent: () => 80,
601
+ })
602
+ const first = await presets.standingKeyFor()
603
+ const firstFiles = await overlayFiles(rootPath)
604
+ expect(firstFiles).toHaveLength(1)
605
+ const firstPath = firstFiles[0]!.path
606
+ const firstStamp = (await stat(firstPath)).mtimeMs
607
+ expect(firstFiles[0]!.rendered).toContain(moduleA)
608
+
609
+ // Disposing the old decoration also removes its generated store, so the
610
+ // swap is proven by the new composition's path, content, and stamp.
611
+ await installation.dispose()
612
+ installation = decorateAgentPresets(presets, {
613
+ modules: paths(moduleB),
614
+ excludedPresetIds: ['minimal'],
615
+ autoCompactThresholdPercent: () => 80,
616
+ })
617
+ const second = await presets.standingKeyFor()
618
+ const secondFiles = await overlayFiles(rootPath)
619
+ expect(secondFiles).toHaveLength(1)
620
+ expect(second).not.toBe(first)
621
+ expect(secondFiles[0]!.path).not.toBe(firstPath)
622
+ expect(secondFiles[0]!.rendered).toContain(moduleB)
623
+ expect((await stat(secondFiles[0]!.path)).mtimeMs).not.toBe(firstStamp)
624
+ await installation.dispose()
625
+ })
626
+
627
+ it('keeps one generation under concurrent and repeated composition of the same identity', async () => {
628
+ const rootPath = await presetsRoot()
629
+ ctx = new Context()
630
+ ctx.baseUrl = `${pathToFileURL(rootPath).href}/`
631
+ await ctx.plugin(Loader).await()
632
+ ctx.loader.builtins.include = Include
633
+ ctx.loader.builtins.group = Group
634
+ await ctx.plugin(LlmRuntime).await()
635
+ await ctx.plugin(SessionStore).await()
636
+ await ctx.plugin(SystemPrompt).await()
637
+ await ctx.plugin(ToolRuntime).await()
638
+ await ctx.plugin(AgentRegistry).await()
639
+ await ctx.plugin(AgentLoop).await()
640
+ await ctx.plugin(CommandRuntime).await()
641
+ await ctx.plugin(SessionProjectionRegistry).await()
642
+ await ctx.plugin(TokenMeter).await()
643
+ await ctx.plugin(MemorySettings).await()
644
+ await ctx.plugin(LegacyNamespaceRegistrar).await()
645
+ await ctx.plugin({ apply }).await()
646
+ await ctx.plugin(AgentPresets, {
647
+ default: 'standard',
648
+ roots: [{ path: rootPath, trust: 'system' }],
649
+ includeShippedRoot: false,
650
+ includeUserRoot: false,
651
+ }).await()
652
+ const namespace = nsBrand('context-compression')
653
+ await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 73 } })
654
+ const bundle = ctx.plugin({ apply: (child) => {
655
+ apply(child, { presetOverlay: true })
656
+ } })
657
+ await bundle.await()
658
+
659
+ const presets = ctx.agentPresets as unknown as OverlayableAgentPresets
660
+ const concurrent = await Promise.all([
661
+ presets.standingKeyFor(),
662
+ presets.standingKeyFor(),
663
+ presets.standingKeyFor(),
664
+ ])
665
+ expect(new Set(concurrent.map(key => JSON.stringify(key)))).toHaveLength(1)
666
+ const files = await overlayFiles(rootPath)
667
+ expect(files).toHaveLength(1)
668
+ const stampFirst = (await stat(files[0]!.path)).mtimeMs
669
+ const repeated = await presets.standingKeyFor()
670
+ expect(JSON.stringify(repeated)).toBe(JSON.stringify(concurrent[0]))
671
+ expect(await overlayFiles(rootPath)).toHaveLength(1)
672
+ expect((await stat(files[0]!.path)).mtimeMs).toBe(stampFirst)
673
+ })
674
+
675
+ it('switches the standing generation for an equal-length threshold change (legacy body)', async () => {
676
+ const rootPath = await presetsRoot()
677
+ ctx = new Context()
678
+ ctx.baseUrl = `${pathToFileURL(rootPath).href}/`
679
+ await ctx.plugin(Loader).await()
680
+ ctx.loader.builtins.include = Include
681
+ ctx.loader.builtins.group = Group
682
+ await ctx.plugin(LlmRuntime).await()
683
+ await ctx.plugin(SessionStore).await()
684
+ await ctx.plugin(SystemPrompt).await()
685
+ await ctx.plugin(ToolRuntime).await()
686
+ await ctx.plugin(AgentRegistry).await()
687
+ await ctx.plugin(AgentLoop).await()
688
+ await ctx.plugin(CommandRuntime).await()
689
+ await ctx.plugin(SessionProjectionRegistry).await()
690
+ await ctx.plugin(TokenMeter).await()
691
+ await ctx.plugin(MemorySettings).await()
692
+ await ctx.plugin(LegacyNamespaceRegistrar).await()
693
+ await ctx.plugin({ apply }).await()
694
+ await ctx.plugin(AgentPresets, {
695
+ default: 'standard',
696
+ roots: [{ path: rootPath, trust: 'system' }],
697
+ includeShippedRoot: false,
698
+ includeUserRoot: false,
699
+ }).await()
700
+ const namespace = nsBrand('context-compression')
701
+ await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 70 } })
702
+ const bundle = ctx.plugin({ apply: (child) => {
703
+ apply(child, { presetOverlay: true })
704
+ } })
705
+ await bundle.await()
706
+
707
+ const presets = ctx.agentPresets as unknown as OverlayableAgentPresets
708
+ const first = await presets.standingKeyFor()
709
+ const firstFiles = await overlayFiles(rootPath)
710
+ expect(firstFiles).toHaveLength(1)
711
+ expect(firstFiles[0]?.rendered).toContain('thresholdRatio: 0.7')
712
+ expect(firstFiles[0]?.rendered).toContain('autoCompactThresholdPercent: 70')
713
+
714
+ // Equal-length change: identical rendered sizes, and without the
715
+ // deterministic threshold mtime a same-millisecond switch could have
716
+ // reused the superseded generation.
717
+ await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 80 } })
718
+ const second = await presets.standingKeyFor()
719
+ const secondFiles = await overlayFiles(rootPath)
720
+ expect(secondFiles).toHaveLength(2)
721
+ expect(secondFiles.some(file => file.rendered.includes('thresholdRatio: 0.8')
722
+ && file.rendered.includes('autoCompactThresholdPercent: 80'))).toBe(true)
723
+ expect(second).not.toBe(first)
724
+ const stamps = await Promise.all(secondFiles.map(async file => (await stat(file.path)).mtimeMs))
725
+ expect(new Set(stamps).size).toBe(2)
726
+
727
+ await bundle.dispose()
728
+ })
729
+ })