dsh-context-compression-improved 0.11.1 → 0.11.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (311) hide show
  1. package/README.md +15 -110
  2. package/README.zh.md +14 -104
  3. package/THIRD_PARTY_NOTICES.md +25 -7
  4. package/{packages/selector/dsh.plugin.json → dsh.plugin.json} +1 -1
  5. package/{packages/selector/lib → lib}/client.js +27 -10
  6. package/{packages/selector/lib → lib}/index.js +101 -0
  7. package/package.json +125 -112
  8. package/screenshots.json +3 -6
  9. package/.agents/plans/improve/checklist.md +0 -32
  10. package/.agents/plans/improve/findings.md +0 -102
  11. package/.agents/plans/improve/spec.md +0 -53
  12. package/.agents/plans/improve/tasks.md +0 -70
  13. package/.gitattributes +0 -2
  14. package/.githooks/pre-push +0 -37
  15. package/.github/workflows/ci.yml +0 -47
  16. package/CHANGELOG.de.md +0 -580
  17. package/CHANGELOG.es.md +0 -588
  18. package/CHANGELOG.fr.md +0 -576
  19. package/CHANGELOG.it.md +0 -577
  20. package/CHANGELOG.ja.md +0 -261
  21. package/CHANGELOG.ko.md +0 -254
  22. package/CHANGELOG.md +0 -557
  23. package/CHANGELOG.ru.md +0 -554
  24. package/CHANGELOG.zh.md +0 -247
  25. package/CONTRIBUTING.md +0 -22
  26. package/README.de.md +0 -96
  27. package/README.es.md +0 -96
  28. package/README.fr.md +0 -96
  29. package/README.it.md +0 -96
  30. package/README.ja.md +0 -102
  31. package/README.ko.md +0 -102
  32. package/README.ru.md +0 -96
  33. package/SECURITY.md +0 -18
  34. package/assets/board.png +0 -0
  35. package/assets/context.png +0 -0
  36. package/assets/dshfind-card.svg +0 -33
  37. package/docs/assets/context-compression-selector-profiles.jpg +0 -0
  38. package/docs/assets/context-compression-selector-settings.png +0 -0
  39. package/docs/compat-0.1.5-report.md +0 -77
  40. package/docs/installation.de.md +0 -104
  41. package/docs/installation.es.md +0 -104
  42. package/docs/installation.fr.md +0 -104
  43. package/docs/installation.it.md +0 -104
  44. package/docs/installation.ja.md +0 -78
  45. package/docs/installation.ko.md +0 -78
  46. package/docs/installation.md +0 -103
  47. package/docs/installation.ru.md +0 -104
  48. package/docs/installation.zh.md +0 -100
  49. package/docs/repair-log.md +0 -657
  50. package/docs/shallow-teaching-preset-template.md +0 -46
  51. package/eslint.config.js +0 -30
  52. package/packages/selector/LICENSE +0 -21
  53. package/packages/selector/README.md +0 -26
  54. package/packages/selector/README.zh.md +0 -24
  55. package/packages/selector/THIRD_PARTY_NOTICES.md +0 -32
  56. package/packages/selector/docs/history-tool-call-working-set-spec.md +0 -112
  57. package/packages/selector/docs/native-tool-result-selector-spec.md +0 -34
  58. package/packages/selector/docs/subagent-cache-reuse-spec.md +0 -46
  59. package/packages/selector/lib/style.css +0 -350
  60. package/packages/selector/package.json +0 -178
  61. package/packages/selector/screenshots.json +0 -3
  62. package/packages/selector/src/client/CompressionProfileControls.tsx +0 -352
  63. package/packages/selector/src/client/CompressionProfileSelector.module.css +0 -199
  64. package/packages/selector/src/client/CompressionProfileSelector.tsx +0 -89
  65. package/packages/selector/src/client/CustomPolicyEditor.tsx +0 -216
  66. package/packages/selector/src/client/EstimatorControls.tsx +0 -277
  67. package/packages/selector/src/client/bridge-scope.ts +0 -125
  68. package/packages/selector/src/client/decode.ts +0 -68
  69. package/packages/selector/src/client/fab-pos.ts +0 -71
  70. package/packages/selector/src/client/index.ts +0 -438
  71. package/packages/selector/src/client/locales/de.ts +0 -167
  72. package/packages/selector/src/client/locales/es.ts +0 -167
  73. package/packages/selector/src/client/locales/fr.ts +0 -167
  74. package/packages/selector/src/client/locales/it.ts +0 -167
  75. package/packages/selector/src/client/locales/ja.ts +0 -167
  76. package/packages/selector/src/client/locales/ko.ts +0 -167
  77. package/packages/selector/src/client/locales/ru.ts +0 -167
  78. package/packages/selector/src/client/locales.ts +0 -334
  79. package/packages/selector/src/client/monitor-fab.ts +0 -445
  80. package/packages/selector/src/client/preset-options.ts +0 -88
  81. package/packages/selector/src/client/savings-card.tsx +0 -269
  82. package/packages/selector/src/client/scope-face.ts +0 -24
  83. package/packages/selector/src/client/settings-section.tsx +0 -156
  84. package/packages/selector/src/compat/host-generation.ts +0 -96
  85. package/packages/selector/src/compat/llm-messages.ts +0 -50
  86. package/packages/selector/src/compat/settings-lease.ts +0 -108
  87. package/packages/selector/src/compat/tool-result.ts +0 -91
  88. package/packages/selector/src/css-modules.d.ts +0 -6
  89. package/packages/selector/src/deepseek-v4-tokenizer.ts +0 -205
  90. package/packages/selector/src/estimator-catalog.ts +0 -104
  91. package/packages/selector/src/index.ts +0 -890
  92. package/packages/selector/src/invariant.ts +0 -113
  93. package/packages/selector/src/preset-overlay.ts +0 -749
  94. package/packages/selector/src/profiles.ts +0 -554
  95. package/packages/selector/src/pruner/content.ts +0 -199
  96. package/packages/selector/src/pruner/session.ts +0 -97
  97. package/packages/selector/src/pruner/state.ts +0 -61
  98. package/packages/selector/src/pruner/tuning.ts +0 -23
  99. package/packages/selector/src/pruner/types.ts +0 -78
  100. package/packages/selector/src/pruner.ts +0 -3222
  101. package/packages/selector/src/runtime/adaptive-cost.ts +0 -205
  102. package/packages/selector/src/runtime/audit.ts +0 -321
  103. package/packages/selector/src/runtime/config.ts +0 -887
  104. package/packages/selector/src/runtime/custom-policy.ts +0 -300
  105. package/packages/selector/src/runtime/deepseek-official-pricing.ts +0 -298
  106. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +0 -254
  107. package/packages/selector/src/runtime/display-prefs.ts +0 -98
  108. package/packages/selector/src/runtime/fold-router.ts +0 -143
  109. package/packages/selector/src/runtime/measurement.ts +0 -444
  110. package/packages/selector/src/runtime/monitor.ts +0 -341
  111. package/packages/selector/src/runtime/panel-command.ts +0 -213
  112. package/packages/selector/src/runtime/reducers.ts +0 -1755
  113. package/packages/selector/src/runtime/retrieve.ts +0 -505
  114. package/packages/selector/src/runtime/savings-integral.ts +0 -117
  115. package/packages/selector/src/runtime/savings-projection.ts +0 -229
  116. package/packages/selector/src/runtime/savings-verify.ts +0 -446
  117. package/packages/selector/src/runtime/savings.ts +0 -526
  118. package/packages/selector/src/runtime/sediment-card.ts +0 -126
  119. package/packages/selector/src/runtime/sediment-clock.ts +0 -87
  120. package/packages/selector/src/runtime/sediment-guard.ts +0 -136
  121. package/packages/selector/src/runtime/sediment-publish.ts +0 -144
  122. package/packages/selector/src/runtime/sediment-span.ts +0 -170
  123. package/packages/selector/src/runtime/sediment.ts +0 -209
  124. package/packages/selector/src/runtime/session-events.ts +0 -30
  125. package/packages/selector/src/runtime/session-file-decode.ts +0 -523
  126. package/packages/selector/src/runtime/shallow-tools.ts +0 -342
  127. package/packages/selector/src/runtime/stats-backfill.ts +0 -541
  128. package/packages/selector/src/runtime/stats-db.ts +0 -492
  129. package/packages/selector/src/runtime/stats-schema.ts +0 -123
  130. package/packages/selector/src/runtime/stats-sync.ts +0 -307
  131. package/packages/selector/src/runtime/summary-command.ts +0 -127
  132. package/packages/selector/src/runtime/tail-trim.ts +0 -177
  133. package/packages/selector/src/runtime/token-count.ts +0 -72
  134. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +0 -233
  135. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +0 -204
  136. package/packages/selector/src/runtime/tokenpilot/advisor.ts +0 -419
  137. package/packages/selector/src/runtime/tokenpilot/benefit.ts +0 -200
  138. package/packages/selector/src/runtime/tokenpilot/dedup.ts +0 -82
  139. package/packages/selector/src/runtime/tokenpilot/estimator.ts +0 -151
  140. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +0 -53
  141. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +0 -65
  142. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +0 -125
  143. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +0 -37
  144. package/packages/selector/src/runtime/tokenpilot/locator.ts +0 -129
  145. package/packages/selector/src/runtime/tokenpilot/read-state.ts +0 -98
  146. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +0 -303
  147. package/packages/selector/src/runtime/tool-names.ts +0 -42
  148. package/packages/selector/src/runtime/toolclass.ts +0 -103
  149. package/packages/selector/src/runtime/triage/masks.ts +0 -128
  150. package/packages/selector/src/runtime/triage/shallow.ts +0 -132
  151. package/packages/selector/src/runtime/triage/signals.ts +0 -167
  152. package/packages/selector/src/runtime/triage/types.ts +0 -125
  153. package/packages/selector/src/runtime/types.ts +0 -396
  154. package/packages/selector/src/runtime/value.ts +0 -48
  155. package/packages/selector/src/settings-bridge.ts +0 -175
  156. package/packages/selector/tests/advisor-report.host.spec.ts +0 -223
  157. package/packages/selector/tests/auto-compact.client.spec.tsx +0 -214
  158. package/packages/selector/tests/built/client-artifact.spec.ts +0 -56
  159. package/packages/selector/tests/cache-prefix-audit.spec.ts +0 -123
  160. package/packages/selector/tests/code-skeleton.client.spec.ts +0 -98
  161. package/packages/selector/tests/compat/compat-narrow-waist.spec.ts +0 -150
  162. package/packages/selector/tests/custom-contract.client.spec.ts +0 -226
  163. package/packages/selector/tests/estimator-catalog.spec.ts +0 -70
  164. package/packages/selector/tests/estimator-channel.client.spec.tsx +0 -253
  165. package/packages/selector/tests/estimator-route-registration.host.spec.ts +0 -202
  166. package/packages/selector/tests/fab-pos.client.spec.ts +0 -47
  167. package/packages/selector/tests/fixtures/sediment-pool/52adc205-cloud-5.orig.txt +0 -231
  168. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-25.orig.txt +0 -236
  169. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-38.orig.txt +0 -220
  170. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-42.orig.txt +0 -140
  171. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-53.orig.txt +0 -117
  172. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-local-10.orig.txt +0 -67
  173. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-45.orig.txt +0 -119
  174. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-49.orig.txt +0 -119
  175. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-63.orig.txt +0 -131
  176. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-75.orig.txt +0 -196
  177. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-76.orig.txt +0 -71
  178. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-85.orig.txt +0 -126
  179. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-86.orig.txt +0 -86
  180. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-87.orig.txt +0 -50
  181. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-96.orig.txt +0 -102
  182. package/packages/selector/tests/helpers/legacy-namespace.ts +0 -35
  183. package/packages/selector/tests/helpers/legacy-settings/index.ts +0 -15
  184. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +0 -41
  185. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +0 -647
  186. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +0 -78
  187. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +0 -234
  188. package/packages/selector/tests/host-preset-overlay.host.spec.ts +0 -204
  189. package/packages/selector/tests/monitor-fab.client.spec.ts +0 -240
  190. package/packages/selector/tests/preset-options-write.client.spec.ts +0 -192
  191. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +0 -200
  192. package/packages/selector/tests/preset-overlay.host.spec.ts +0 -246
  193. package/packages/selector/tests/profiles.client.spec.tsx +0 -436
  194. package/packages/selector/tests/ptc-custom-write.client.spec.ts +0 -86
  195. package/packages/selector/tests/public/package-contract.client.spec.ts +0 -89
  196. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +0 -167
  197. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +0 -230
  198. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +0 -272
  199. package/packages/selector/tests/runtime/advisor.spec.ts +0 -226
  200. package/packages/selector/tests/runtime/audit.spec.ts +0 -275
  201. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +0 -523
  202. package/packages/selector/tests/runtime/char-basis.spec.ts +0 -30
  203. package/packages/selector/tests/runtime/code-skeleton.spec.ts +0 -152
  204. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +0 -186
  205. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +0 -122
  206. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +0 -122
  207. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +0 -96
  208. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +0 -273
  209. package/packages/selector/tests/runtime/fixtures/session-v4-dump.jsonl +0 -46
  210. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +0 -106
  211. package/packages/selector/tests/runtime/fixtures/vision-golden.json +0 -459
  212. package/packages/selector/tests/runtime/fold-router.spec.ts +0 -140
  213. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +0 -74
  214. package/packages/selector/tests/runtime/fresh-gate.spec.ts +0 -43
  215. package/packages/selector/tests/runtime/html-reducer.spec.ts +0 -212
  216. package/packages/selector/tests/runtime/intent-gate.spec.ts +0 -62
  217. package/packages/selector/tests/runtime/intent-summary.spec.ts +0 -156
  218. package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +0 -79
  219. package/packages/selector/tests/runtime/line-mapping.spec.ts +0 -153
  220. package/packages/selector/tests/runtime/monitor.spec.ts +0 -354
  221. package/packages/selector/tests/runtime/panel-command.spec.ts +0 -101
  222. package/packages/selector/tests/runtime/prose-reducers.spec.ts +0 -133
  223. package/packages/selector/tests/runtime/ptc-profile.spec.ts +0 -133
  224. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +0 -2795
  225. package/packages/selector/tests/runtime/read-input-cap.spec.ts +0 -33
  226. package/packages/selector/tests/runtime/savings-accounting.spec.ts +0 -291
  227. package/packages/selector/tests/runtime/savings-integral.spec.ts +0 -169
  228. package/packages/selector/tests/runtime/savings-projection.spec.ts +0 -89
  229. package/packages/selector/tests/runtime/savings-verify.spec.ts +0 -226
  230. package/packages/selector/tests/runtime/savings.spec.ts +0 -139
  231. package/packages/selector/tests/runtime/search-reducer.spec.ts +0 -110
  232. package/packages/selector/tests/runtime/sediment-card.spec.ts +0 -111
  233. package/packages/selector/tests/runtime/sediment-config.spec.ts +0 -56
  234. package/packages/selector/tests/runtime/sediment-guard.spec.ts +0 -71
  235. package/packages/selector/tests/runtime/sediment-masks.spec.ts +0 -95
  236. package/packages/selector/tests/runtime/sediment-orchestrator.spec.ts +0 -166
  237. package/packages/selector/tests/runtime/sediment-pool-share.spec.ts +0 -65
  238. package/packages/selector/tests/runtime/sediment-publish.spec.ts +0 -142
  239. package/packages/selector/tests/runtime/sediment-real-shapes.spec.ts +0 -158
  240. package/packages/selector/tests/runtime/sediment-settings.spec.ts +0 -73
  241. package/packages/selector/tests/runtime/sediment-signals.spec.ts +0 -124
  242. package/packages/selector/tests/runtime/sediment-span.spec.ts +0 -92
  243. package/packages/selector/tests/runtime/session-events.spec.ts +0 -27
  244. package/packages/selector/tests/runtime/session-file-decode.spec.ts +0 -281
  245. package/packages/selector/tests/runtime/settings-unwrap.spec.ts +0 -58
  246. package/packages/selector/tests/runtime/shallow-primitives.spec.ts +0 -135
  247. package/packages/selector/tests/runtime/sidechannel.spec.ts +0 -241
  248. package/packages/selector/tests/runtime/stats-backfill-scheduler.spec.ts +0 -167
  249. package/packages/selector/tests/runtime/stats-backfill.spec.ts +0 -350
  250. package/packages/selector/tests/runtime/stats-db.spec.ts +0 -361
  251. package/packages/selector/tests/runtime/stats-privacy.spec.ts +0 -55
  252. package/packages/selector/tests/runtime/stats-sync.spec.ts +0 -278
  253. package/packages/selector/tests/runtime/summary-command.spec.ts +0 -154
  254. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +0 -159
  255. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +0 -53
  256. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +0 -217
  257. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +0 -52
  258. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +0 -79
  259. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +0 -76
  260. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +0 -121
  261. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +0 -82
  262. package/packages/selector/tests/runtime/toolclass.spec.ts +0 -156
  263. package/packages/selector/tests/runtime/value.spec.ts +0 -23
  264. package/packages/selector/tests/savings-sessions.client.spec.tsx +0 -140
  265. package/packages/selector/tests/settings-seat.client.spec.ts +0 -215
  266. package/packages/selector/tests/standing-generation.host.spec.ts +0 -724
  267. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +0 -269
  268. package/packages/selector/tests/support/cache-prefix-audit.ts +0 -105
  269. package/packages/selector/tests/support/mock-adapter.ts +0 -37
  270. package/packages/selector/tests/support/ui-primitives.tsx +0 -34
  271. package/packages/selector/tsconfig.json +0 -11
  272. package/packages/selector/tsdown.client.config.ts +0 -102
  273. package/packages/selector/tsdown.config.ts +0 -20
  274. package/pnpm-workspace.yaml +0 -76
  275. package/scripts/capture-profile-baseline.mjs +0 -42
  276. package/scripts/cell-browser-e2e.mjs +0 -354
  277. package/scripts/generate-tokenizer-fixtures.py +0 -81
  278. package/scripts/generate-vision-fixtures.py +0 -208
  279. package/scripts/hosts.d.mts +0 -3
  280. package/scripts/hosts.mjs +0 -81
  281. package/scripts/packed-components-smoke.mjs +0 -763
  282. package/scripts/packed-install-e2e.mjs +0 -1346
  283. package/scripts/sediment-latency-report.mjs +0 -63
  284. package/scripts/sync-hosts.mjs +0 -174
  285. package/scripts/toolclass-corpus-replay.mjs +0 -281
  286. package/scripts/verify-release.mjs +0 -343
  287. package/tests/TEST_INVENTORY.md +0 -41
  288. package/tsconfig.base.json +0 -18
  289. package/tsconfig.json +0 -7
  290. package/tsconfig.tests.json +0 -15
  291. package/vitest.built.config.ts +0 -9
  292. package/vitest.config.ts +0 -54
  293. /package/{packages/selector/assets → assets}/deepseek-v4/LICENSE.DeepSeek-V4-Pro.txt +0 -0
  294. /package/{packages/selector/assets → assets}/deepseek-v4/manifest.json +0 -0
  295. /package/{packages/selector/assets → assets}/deepseek-v4/tokenizer.json +0 -0
  296. /package/{packages/selector/assets → assets}/deepseek-v4/tokenizer_config.json +0 -0
  297. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/LICENSE.DeepSeek-V4-Flash-Vision-Exp.txt +0 -0
  298. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/manifest.json +0 -0
  299. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/tokenizer.json +0 -0
  300. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/tokenizer_config.json +0 -0
  301. /package/{packages/selector/cordis.patch.yml → cordis.patch.yml} +0 -0
  302. /package/{packages/selector/lib → lib}/client.d.ts +0 -0
  303. /package/{packages/selector/lib → lib}/index.d.ts +0 -0
  304. /package/{packages/selector/lib → lib}/invariant.d.ts +0 -0
  305. /package/{packages/selector/lib → lib}/invariant.js +0 -0
  306. /package/{packages/selector/lib → lib}/profiles.d.ts +0 -0
  307. /package/{packages/selector/lib → lib}/pruner.d.ts +0 -0
  308. /package/{packages/selector/lib → lib}/pruner.js +0 -0
  309. /package/{packages/selector/lib → lib}/savings-integral.js +0 -0
  310. /package/{packages/selector/lib → lib}/tail-trim.js +0 -0
  311. /package/{packages/selector/lib → lib}/tool-result.js +0 -0
@@ -1,272 +0,0 @@
1
- /**
2
- * Advisor integration and the advisory-only invariant.
3
- *
4
- * The invariant this spec exists to pin (K13): the advisor is statistics and
5
- * suggestions only. Whatever its channel returns — extreme scores, a hostile
6
- * summary, garbage, or nothing at all — `pruneSession` must land exactly the
7
- * same reductions it lands with the advisor off and the state empty.
8
- */
9
- import { describe, expect, it } from 'vitest'
10
- import { Context } from '@deepseek-ai/cordis'
11
- import {
12
- ToolCallId as CallId,
13
- createMessage,
14
- createUserMessage,
15
- createToolResultMessage,
16
- } from '@deepseek-ai/dsh-llm'
17
- import { canonicalHeader, Session, SessionId } from '@deepseek-ai/dsh-session'
18
- import type { SessionEvent } from '@deepseek-ai/dsh-session'
19
- import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
20
- import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
21
- import TokenMeter from '@deepseek-ai/dsh-token-meter'
22
- import ToolRuntime from '@deepseek-ai/dsh-tools'
23
- import SessionStore from '@deepseek-ai/dsh-session'
24
- import ToolResultPruner from '../../src/pruner.ts'
25
- import {
26
- collectTaskSemantics,
27
- runSessionAdvisorPass,
28
- type AdvisorCandidate,
29
- } from '../../src/runtime/tokenpilot/advisor.ts'
30
- import { getAdvisorState, recordScore } from '../../src/runtime/tokenpilot/advisor-state.ts'
31
- import type { AdvisorOutcomeAuditRecord } from '../../src/runtime/audit.ts'
32
- import type { AdvisorChannel } from '../../src/runtime/tokenpilot/advisor.ts'
33
-
34
- // ── Orchestration against a scripted channel ───────────────────────────────
35
-
36
- const CANDIDATES: AdvisorCandidate[] = [
37
- { seq: 3, characterPressure: 4_000, preview: 'auth module login flow' },
38
- { seq: 5, characterPressure: 6_000, preview: 'database migration notes' },
39
- ]
40
-
41
- const TASK = {
42
- source: 'todos' as const,
43
- todoVersion: 'aaaa1111',
44
- taskText: 'migrate the auth module',
45
- }
46
-
47
- function advisorInput(turn: number, signal: AbortSignal): Parameters<typeof runSessionAdvisorPass>[3] {
48
- return {
49
- profile: 'tokenpilot-inspired',
50
- turn,
51
- candidates: CANDIDATES,
52
- task: TASK,
53
- advisor: { refreshTurns: 8, scoreThreshold: 0.35, sampleLimit: 16, minTokens: 250 },
54
- tailText: 'working on the migration',
55
- signal,
56
- }
57
- }
58
-
59
- function scriptedChannel(responses: (string | undefined)[]): { channel: AdvisorChannel, calls: { system: string, user: string }[] } {
60
- const calls: { system: string, user: string }[] = []
61
- return {
62
- calls,
63
- channel: {
64
- identity: () => 'host:mock/model',
65
- ask: async request => {
66
- calls.push({ system: request.system, user: request.user })
67
- return responses.shift()
68
- },
69
- },
70
- }
71
- }
72
-
73
- describe('runSessionAdvisorPass orchestration (K11)', () => {
74
- it('writes summary, scores, recertification marks, and emits three audits on success', async () => {
75
- const session = Session.create(SessionId('advisor-ok'))
76
- const { channel, calls } = scriptedChannel([
77
- '{"overallTask":"migrate the auth module","activeSubtasks":["port login flow"],"keywords":["auth","login"]}',
78
- '{"seq":3,"score":0.95,"reason":"current task"}\n{"seq":5,"score":0.10,"reason":"stale"}',
79
- ])
80
- const audits: AdvisorOutcomeAuditRecord[] = []
81
- const outcome = await runSessionAdvisorPass(session, channel, record => audits.push(record), advisorInput(4, new AbortController().signal))
82
-
83
- expect(calls).toHaveLength(2)
84
- expect(outcome).toBeDefined()
85
- const state = getAdvisorState(session)
86
- expect(state.summary?.overallTask).toBe('migrate the auth module')
87
- expect(state.scores.get(3)?.score).toBe(0.95)
88
- expect(state.scores.get(5)?.score).toBe(0.10)
89
- // Below-threshold segment recertified as a suggestion only.
90
- expect(state.recertified.get(5)).toBe(4)
91
- expect(state.recertified.has(3)).toBe(false)
92
- expect(state.watermarkSeq).toBe(5)
93
- expect(audits.map(record => record.phase)).toEqual(['summary', 'scoring', 'decay'])
94
- expect(audits.every(record => record.ok)).toBe(true)
95
- expect(audits.find(record => record.phase === 'decay')?.decay).toBeDefined()
96
- })
97
-
98
- it('leaves state untouched and audits ok:false when the channel answers nothing', async () => {
99
- const session = Session.create(SessionId('advisor-fail'))
100
- const { channel, calls } = scriptedChannel([undefined, undefined])
101
- const audits: AdvisorOutcomeAuditRecord[] = []
102
- const outcome = await runSessionAdvisorPass(session, channel, record => audits.push(record), advisorInput(2, new AbortController().signal))
103
-
104
- expect(outcome).toBeUndefined()
105
- expect(calls).toHaveLength(1) // summary failed; scoring never ran
106
- const state = getAdvisorState(session)
107
- expect(state.summary).toBeUndefined()
108
- expect(state.scores.size).toBe(0)
109
- expect(audits).toHaveLength(1)
110
- expect(audits[0]?.ok).toBe(false)
111
- expect(audits[0]?.reason).toBe('channel-empty')
112
- expect(state.inFlight).toBe(false)
113
- })
114
-
115
- it('skips entirely while a pass is in flight (re-entry guard)', async () => {
116
- const session = Session.create(SessionId('advisor-reentry'))
117
- const { channel, calls } = scriptedChannel([])
118
- const state = getAdvisorState(session)
119
- state.inFlight = true
120
- const outcome = await runSessionAdvisorPass(session, channel, () => undefined, advisorInput(1, new AbortController().signal))
121
- expect(outcome).toBeUndefined()
122
- expect(calls).toHaveLength(0)
123
- state.inFlight = false
124
- })
125
-
126
- it('does not advance the watermark on failure, so candidates rescore later', async () => {
127
- const session = Session.create(SessionId('advisor-watermark'))
128
- const failing = scriptedChannel([undefined])
129
- await runSessionAdvisorPass(session, failing.channel, () => undefined, advisorInput(1, new AbortController().signal))
130
- expect(getAdvisorState(session).watermarkSeq).toBe(0)
131
-
132
- const succeeding = scriptedChannel([
133
- '{"overallTask":"t","activeSubtasks":[],"keywords":["auth"]}',
134
- '{"seq":3,"score":0.9}',
135
- ])
136
- const audits: AdvisorOutcomeAuditRecord[] = []
137
- const outcome = await runSessionAdvisorPass(session, succeeding.channel, record => audits.push(record), advisorInput(2, new AbortController().signal))
138
- expect(outcome).toBeDefined()
139
- expect(getAdvisorState(session).watermarkSeq).toBe(3)
140
- })
141
-
142
- it('returns undefined without any channel call when the session has no task semantics', async () => {
143
- const session = Session.create(SessionId('advisor-notask'))
144
- const { channel, calls } = scriptedChannel(['{"overallTask":"x","keywords":["k"]}'])
145
- const outcome = await runSessionAdvisorPass(session, channel, () => undefined, {
146
- ...advisorInput(1, new AbortController().signal),
147
- task: undefined,
148
- })
149
- expect(outcome).toBeUndefined()
150
- expect(calls).toHaveLength(0)
151
- })
152
- })
153
-
154
- describe('collectTaskSemantics over real event shapes', () => {
155
- it('reads a todo/write event appended alongside message events', () => {
156
- const events = [
157
- {
158
- type: 'user/message',
159
- seq: 1,
160
- time: 0,
161
- data: { content: [{ type: 'text', text: 'start the migration' }] },
162
- },
163
- {
164
- type: 'todo/write',
165
- seq: 2,
166
- time: 0,
167
- data: { todos: ['migrate the auth module', { content: 'write tests', status: 'pending' }] },
168
- },
169
- ] as unknown as readonly SessionEvent[]
170
- const task = collectTaskSemantics(events)
171
- expect(task?.source).toBe('todos')
172
- expect(task?.taskText).toContain('write tests')
173
- })
174
- })
175
-
176
- // ── K13: the advisory-only invariant, against the real pruner ──────────────
177
-
178
- describe('advisory-only invariant (K13): advisor outputs never change landings', () => {
179
- async function prunedResult(session: Session): Promise<unknown> {
180
- const ctx = new Context()
181
- try {
182
- await ctx.plugin(SessionStore).await()
183
- await ctx.plugin(SystemPrompt).await()
184
- await ctx.plugin(ToolRuntime).await()
185
- await ctx.plugin(SessionProjectionRegistry).await()
186
- await ctx.plugin(TokenMeter).await()
187
- await ctx.plugin(ToolResultPruner, {
188
- profile: 'native',
189
- nativeTriggerTokens: 100,
190
- nativeTargetTokens: 64,
191
- headChars: 8,
192
- tailChars: 8,
193
- }).await()
194
- return ctx.toolResultPruner.pruneSession(session, { stage: 'pressure' })
195
- } finally {
196
- await ctx.fiber.dispose()
197
- }
198
- }
199
-
200
- function buildSession(id: string): Session {
201
- const session = Session.create(SessionId(id))
202
- const callId = CallId('call-1')
203
- session.append('turn/start', { turn: 1 })
204
- session.append('request/header', {
205
- reason: 'initial',
206
- header: canonicalHeader({ config: { provider: 'deepseek', model: 'deepseek-v4-flash' } }),
207
- })
208
- session.append('user/message', createUserMessage({
209
- content: [{ type: 'text', text: 'please inspect the failing module' }],
210
- source: { kind: 'user' },
211
- }), { surfaceOp: 'append' })
212
- session.append('step/start', { turn: 1, step: 1 })
213
- session.append('assistant/message', {
214
- stream: [],
215
- turn: 1,
216
- step: 1,
217
- message: createMessage({
218
- role: 'assistant',
219
- content: [{ type: 'tool-call', id: callId, name: 'bash', arguments: '{}' }],
220
- source: { kind: 'model', provider: 'deepseek', model: 'deepseek-v4-flash' },
221
- }),
222
- }, { surfaceOp: 'append' })
223
- session.append('tool/call', { turn: 1, step: 1, callId, name: 'bash', arguments: '{}' })
224
- session.append('tool/result', {
225
- turn: 1,
226
- step: 1,
227
- message: createToolResultMessage({
228
- callId,
229
- content: [{ type: 'text', text: 'gate evidence '.repeat(800) }],
230
- isError: false,
231
- }),
232
- }, { surfaceOp: 'append' })
233
- session.append('step/end', { turn: 1, step: 1 })
234
- // No turn/end: pruning lands its replacement inside the still-open turn.
235
- return session
236
- }
237
-
238
- it('lands identically with the advisor off, and with extreme scores or a failed pass', async () => {
239
- const scenarios: string[] = ['off', 'extreme-scores', 'failed-pass']
240
- const shapes: unknown[] = []
241
- for (const scenario of scenarios) {
242
- // One shared session id: replacement markers embed it, and the advisor
243
- // state is keyed by Session object identity, so this cannot cross-talk.
244
- const session = buildSession('advisor-invariant')
245
- if (scenario !== 'off') {
246
- const state = getAdvisorState(session)
247
- if (scenario === 'extreme-scores') {
248
- state.summary = {
249
- overallTask: 'ALL MUST BE KEPT',
250
- activeSubtasks: ['keep everything forever'],
251
- keywords: ['evidence'],
252
- todoVersion: 'deadbeef',
253
- turn: 1,
254
- }
255
- // Zero relevance everywhere: the most hostile score a channel could
256
- // return must still not delete, delay, or rewrite anything.
257
- recordScore(state, 2, { score: 0, turn: 1 })
258
- }
259
- if (scenario === 'failed-pass') {
260
- state.failures = { failures: 9, cooldownUntil: Date.now() + 600_000 }
261
- }
262
- }
263
- shapes.push(structuredClone(await prunedResult(session)))
264
- }
265
- for (const shape of shapes.slice(1)) {
266
- expect(shape).toEqual(shapes[0])
267
- }
268
- // And the baseline scenario actually reduced something (the test is real).
269
- const baseline = shapes[0] as { pruned: unknown[] }
270
- expect(baseline.pruned).toHaveLength(1)
271
- })
272
- })
@@ -1,226 +0,0 @@
1
- import { describe, expect, it } from 'vitest'
2
- import type { SessionEvent } from '@deepseek-ai/dsh-session'
3
- import {
4
- collectTaskSemantics,
5
- prefixDecay,
6
- selectScoringCandidates,
7
- type AdvisorCandidate,
8
- } from '../../src/runtime/tokenpilot/advisor.ts'
9
- import {
10
- ADVISOR_RECERTIFIED_LIMIT,
11
- ADVISOR_SCORES_LIMIT,
12
- getAdvisorState,
13
- invalidateOnTaskChange,
14
- recordRecertified,
15
- recordScore,
16
- } from '../../src/runtime/tokenpilot/advisor-state.ts'
17
- import {
18
- buildAdvisorScoringUserPrompt,
19
- parseAdvisorScores,
20
- parseAdvisorSummary,
21
- } from '../../src/runtime/tokenpilot/advisor-prompt.ts'
22
-
23
- function todoWriteEvent(data: unknown): SessionEvent {
24
- return { type: 'todo/write', seq: 1, time: 0, data } as unknown as SessionEvent
25
- }
26
-
27
- function userMessageEvent(text: string): SessionEvent {
28
- return {
29
- type: 'user/message',
30
- seq: 2,
31
- time: 0,
32
- data: { content: [{ type: 'text', text }] },
33
- } as unknown as SessionEvent
34
- }
35
-
36
- describe('collectTaskSemantics (K5)', () => {
37
- it('parses a structured todo/write payload', () => {
38
- const semantics = collectTaskSemantics([
39
- todoWriteEvent({ todos: [{ content: 'migrate gates', status: 'in_progress' }, 'write tests'] }),
40
- ])
41
- expect(semantics).toBeDefined()
42
- expect(semantics?.source).toBe('todos')
43
- expect(semantics?.taskText).toContain('migrate gates')
44
- expect(semantics?.taskText).toContain('write tests')
45
- // Same content ⇒ same version token (deterministic).
46
- const again = collectTaskSemantics([todoWriteEvent({ todos: [{ content: 'migrate gates', status: 'in_progress' }, 'write tests'] })])
47
- expect(again?.todoVersion).toBe(semantics?.todoVersion)
48
- })
49
-
50
- it('degrades a malformed todo payload to its raw JSON string', () => {
51
- const semantics = collectTaskSemantics([todoWriteEvent({ todos: 'not-an-array' })])
52
- expect(semantics).toBeDefined()
53
- expect(semantics?.source).toBe('raw-todo')
54
- expect(semantics?.taskText).toContain('not-an-array')
55
- })
56
-
57
- it('falls back to recent user/message text when no todo/write exists', () => {
58
- const semantics = collectTaskSemantics([
59
- userMessageEvent('earlier request'),
60
- userMessageEvent('please refactor the pruner gates'),
61
- ])
62
- expect(semantics).toBeDefined()
63
- expect(semantics?.source).toBe('messages')
64
- expect(semantics?.taskText).toContain('refactor the pruner gates')
65
- })
66
-
67
- it('picks the most recent todo/write event', () => {
68
- const semantics = collectTaskSemantics([
69
- todoWriteEvent({ todos: ['old task'] }),
70
- userMessageEvent('something else'),
71
- todoWriteEvent({ todos: ['new task'] }),
72
- ])
73
- expect(semantics?.taskText).toBe('new task')
74
- })
75
-
76
- it('returns undefined for an empty log', () => {
77
- expect(collectTaskSemantics([])).toBeUndefined()
78
- })
79
- })
80
-
81
- describe('prefixDecay (K6)', () => {
82
- const candidates: AdvisorCandidate[] = [
83
- { seq: 1, characterPressure: 3_000, preview: 'a' },
84
- { seq: 2, characterPressure: 1_000, preview: 'b' },
85
- ]
86
- // prefixDecay takes the weight face only; previews are scoring-prompt inputs.
87
- const weights = candidates.map(({ seq, characterPressure }) => ({ seq, characterPressure }))
88
-
89
- it('is deterministic and weights by character pressure', () => {
90
- const scores = new Map([[1, { score: 0 }], [2, { score: 1 }]])
91
- const first = prefixDecay(weights, scores)
92
- const second = prefixDecay(weights, scores)
93
- expect(first).toEqual(second)
94
- // weight 3000×0 + 1000×1 over 4000 ⇒ relevance 0.25 ⇒ decay 0.75.
95
- expect(first.decay).toBeCloseTo(0.75, 12)
96
- expect(first.weightedChars).toBe(4_000)
97
- })
98
-
99
- it('counts unscored candidates as neutral 0.5', () => {
100
- const decay = prefixDecay(weights, new Map())
101
- expect(decay.decay).toBeCloseTo(0.5, 12)
102
- })
103
-
104
- it('is 0 with no candidates and ignores zero-pressure candidates', () => {
105
- expect(prefixDecay([], new Map()).decay).toBe(0)
106
- expect(prefixDecay([{ seq: 9, characterPressure: 0 }], new Map()).decay).toBe(0)
107
- })
108
- })
109
-
110
- describe('selectScoringCandidates', () => {
111
- const candidates: AdvisorCandidate[] = [
112
- { seq: 1, characterPressure: 8_000, preview: 'auth module login handling' },
113
- { seq: 2, characterPressure: 2_000, preview: 'tiny fragment' },
114
- { seq: 3, characterPressure: 9_000, preview: 'login auth token refresh' },
115
- { seq: 4, characterPressure: 12_000, preview: 'unrelated weather report' },
116
- ]
117
-
118
- it('applies the watermark, the character floor, and the sample limit', () => {
119
- const state = { watermarkSeq: 1 }
120
- const picked = selectScoringCandidates(candidates, state, {
121
- taskKeywords: new Set(['login', 'auth', 'token']),
122
- minChars: 4_000,
123
- sampleLimit: 1,
124
- taskChanged: false,
125
- })
126
- // seq 2 below floor, seq 1 at/below watermark; overlap ranks seq 3 first.
127
- expect(picked.map(item => item.seq)).toEqual([3])
128
- })
129
-
130
- it('ignores the watermark when the task semantics changed', () => {
131
- const picked = selectScoringCandidates(candidates, { watermarkSeq: 4 }, {
132
- taskKeywords: new Set(['login']),
133
- minChars: 4_000,
134
- sampleLimit: 16,
135
- taskChanged: true,
136
- })
137
- // Overlap ties (seq 1 and 3 both match "login") break by character pressure.
138
- expect(picked.map(item => item.seq)).toEqual([3, 1, 4])
139
- })
140
- })
141
-
142
- describe('advisor-state bounds (K8)', () => {
143
- it('evicts the oldest score beyond the LRU limit', () => {
144
- const session = {} as Parameters<typeof getAdvisorState>[0]
145
- const state = getAdvisorState(session)
146
- for (let seq = 0; seq < ADVISOR_SCORES_LIMIT + 10; seq += 1) {
147
- recordScore(state, seq, { score: 0.5, turn: seq })
148
- }
149
- expect(state.scores.size).toBe(ADVISOR_SCORES_LIMIT)
150
- expect(state.scores.has(0)).toBe(false)
151
- expect(state.scores.has(ADVISOR_SCORES_LIMIT + 9)).toBe(true)
152
- // Re-touching a seq moves it to the newest position.
153
- recordScore(state, 10, { score: 0.9, turn: 999 })
154
- recordScore(state, ADVISOR_SCORES_LIMIT + 10, { score: 0.1, turn: 1_000 })
155
- expect(state.scores.has(10)).toBe(true)
156
- expect(state.scores.size).toBe(ADVISOR_SCORES_LIMIT)
157
- })
158
-
159
- it('bounds recertified marks the same way', () => {
160
- const session = {} as Parameters<typeof getAdvisorState>[0]
161
- const state = getAdvisorState(session)
162
- for (let seq = 0; seq < ADVISOR_RECERTIFIED_LIMIT + 5; seq += 1) {
163
- recordRecertified(state, seq, seq)
164
- }
165
- expect(state.recertified.size).toBe(ADVISOR_RECERTIFIED_LIMIT)
166
- expect(state.recertified.has(0)).toBe(false)
167
- })
168
-
169
- it('invalidates the summary when the task version changes', () => {
170
- const session = {} as Parameters<typeof getAdvisorState>[0]
171
- const state = getAdvisorState(session)
172
- state.summary = { overallTask: 'x', activeSubtasks: [], keywords: [], todoVersion: 'aaa', turn: 1 }
173
- state.lastSummaryTurn = 1
174
- expect(invalidateOnTaskChange(state, 'bbb')).toBe(true)
175
- expect(state.summary).toBeUndefined()
176
- expect(state.lastSummaryTurn).toBe(-1)
177
- expect(invalidateOnTaskChange(state, 'bbb')).toBe(false)
178
- })
179
- })
180
-
181
- describe('advisor prompts (K7)', () => {
182
- it('parses a well-formed summary answer', () => {
183
- const parsed = parseAdvisorSummary(
184
- 'Sure! {"overallTask":"migrate gates","activeSubtasks":["port fresh gate"],"keywords":["gates","pruner"]}',
185
- )
186
- expect(parsed?.overallTask).toBe('migrate gates')
187
- expect(parsed?.keywords).toEqual(['gates', 'pruner'])
188
- })
189
-
190
- it('fails open on a malformed summary answer', () => {
191
- expect(parseAdvisorSummary(undefined)).toBeUndefined()
192
- expect(parseAdvisorSummary('')).toBeUndefined()
193
- expect(parseAdvisorSummary('not json at all')).toBeUndefined()
194
- expect(parseAdvisorSummary('{"overallTask":""}')).toBeUndefined()
195
- expect(parseAdvisorSummary('{"overallTask":"x"}')).toBeUndefined()
196
- })
197
-
198
- it('parses JSON-lines scoring answers and drops invalid rows', () => {
199
- const parsed = parseAdvisorScores(
200
- '{"seq":1,"score":0.9,"reason":"current task"}\n'
201
- + 'noise line {"seq":2,"score":1.5}\n'
202
- + '{"seq":99,"score":0.5}\n'
203
- + '{"seq":3,"score":0.1}\n',
204
- new Set([1, 2, 3]),
205
- )
206
- expect(parsed?.size).toBe(2)
207
- expect(parsed?.get(1)?.score).toBe(0.9)
208
- expect(parsed?.get(3)?.score).toBe(0.1)
209
- expect(parsed?.has(2)).toBe(false)
210
- expect(parsed?.has(99)).toBe(false)
211
- })
212
-
213
- it('fails open on empty or all-garbage scoring answers', () => {
214
- expect(parseAdvisorScores(undefined, new Set([1]))).toBeUndefined()
215
- expect(parseAdvisorScores('', new Set([1]))).toBeUndefined()
216
- expect(parseAdvisorScores('garbage only', new Set([1]))).toBeUndefined()
217
- })
218
-
219
- it('builds a scoring prompt that keeps previews one-per-line', () => {
220
- const prompt = buildAdvisorScoringUserPrompt('task text', ['sub'], [
221
- { seq: 7, preview: 'some\npreview' },
222
- ])
223
- expect(prompt).toContain('task: task text')
224
- expect(prompt).toContain('seq=7 | some preview')
225
- })
226
- })