dsh-context-compression-improved 0.10.3 → 0.10.4

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 (264) 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} +2 -2
  5. package/{packages/selector/lib → lib}/client.d.ts +4 -0
  6. package/{packages/selector/lib → lib}/client.js +70 -5
  7. package/{packages/selector/lib → lib}/invariant.js +1 -1
  8. package/{packages/selector/lib → lib}/profiles.d.ts +3 -1
  9. package/{packages/selector/lib → lib}/pruner.d.ts +4 -2
  10. package/{packages/selector/lib → lib}/pruner.js +40 -37
  11. package/{packages/selector/lib → lib}/savings-integral.js +83 -24
  12. package/{packages/selector/lib → lib}/tail-trim.js +2 -2
  13. package/{packages/selector/lib → lib}/tool-result.js +22 -1
  14. package/package.json +129 -116
  15. package/screenshots.json +3 -6
  16. package/.agents/plans/improve/checklist.md +0 -32
  17. package/.agents/plans/improve/findings.md +0 -102
  18. package/.agents/plans/improve/spec.md +0 -53
  19. package/.agents/plans/improve/tasks.md +0 -70
  20. package/.gitattributes +0 -2
  21. package/.githooks/pre-push +0 -37
  22. package/.github/workflows/ci.yml +0 -39
  23. package/CHANGELOG.de.md +0 -580
  24. package/CHANGELOG.es.md +0 -588
  25. package/CHANGELOG.fr.md +0 -576
  26. package/CHANGELOG.it.md +0 -577
  27. package/CHANGELOG.ja.md +0 -261
  28. package/CHANGELOG.ko.md +0 -254
  29. package/CHANGELOG.md +0 -549
  30. package/CHANGELOG.ru.md +0 -554
  31. package/CHANGELOG.zh.md +0 -238
  32. package/CONTRIBUTING.md +0 -22
  33. package/README.de.md +0 -96
  34. package/README.es.md +0 -96
  35. package/README.fr.md +0 -96
  36. package/README.it.md +0 -96
  37. package/README.ja.md +0 -102
  38. package/README.ko.md +0 -102
  39. package/README.ru.md +0 -96
  40. package/SECURITY.md +0 -18
  41. package/assets/board.png +0 -0
  42. package/assets/context.png +0 -0
  43. package/docs/assets/context-compression-selector-profiles.jpg +0 -0
  44. package/docs/assets/context-compression-selector-settings.png +0 -0
  45. package/docs/compat-0.1.5-report.md +0 -77
  46. package/docs/installation.de.md +0 -104
  47. package/docs/installation.es.md +0 -104
  48. package/docs/installation.fr.md +0 -104
  49. package/docs/installation.it.md +0 -104
  50. package/docs/installation.ja.md +0 -78
  51. package/docs/installation.ko.md +0 -78
  52. package/docs/installation.md +0 -103
  53. package/docs/installation.ru.md +0 -104
  54. package/docs/installation.zh.md +0 -100
  55. package/docs/repair-log.md +0 -657
  56. package/eslint.config.js +0 -30
  57. package/packages/selector/LICENSE +0 -21
  58. package/packages/selector/README.md +0 -26
  59. package/packages/selector/README.zh.md +0 -24
  60. package/packages/selector/THIRD_PARTY_NOTICES.md +0 -32
  61. package/packages/selector/docs/history-tool-call-working-set-spec.md +0 -112
  62. package/packages/selector/docs/native-tool-result-selector-spec.md +0 -34
  63. package/packages/selector/docs/subagent-cache-reuse-spec.md +0 -46
  64. package/packages/selector/lib/style.css +0 -350
  65. package/packages/selector/package.json +0 -178
  66. package/packages/selector/screenshots.json +0 -3
  67. package/packages/selector/src/client/CompressionProfileControls.tsx +0 -293
  68. package/packages/selector/src/client/CompressionProfileSelector.module.css +0 -199
  69. package/packages/selector/src/client/CompressionProfileSelector.tsx +0 -85
  70. package/packages/selector/src/client/CustomPolicyEditor.tsx +0 -216
  71. package/packages/selector/src/client/EstimatorControls.tsx +0 -277
  72. package/packages/selector/src/client/bridge-scope.ts +0 -125
  73. package/packages/selector/src/client/decode.ts +0 -57
  74. package/packages/selector/src/client/fab-pos.ts +0 -71
  75. package/packages/selector/src/client/index.ts +0 -424
  76. package/packages/selector/src/client/locales/de.ts +0 -158
  77. package/packages/selector/src/client/locales/es.ts +0 -158
  78. package/packages/selector/src/client/locales/fr.ts +0 -158
  79. package/packages/selector/src/client/locales/it.ts +0 -158
  80. package/packages/selector/src/client/locales/ja.ts +0 -158
  81. package/packages/selector/src/client/locales/ko.ts +0 -158
  82. package/packages/selector/src/client/locales/ru.ts +0 -158
  83. package/packages/selector/src/client/locales.ts +0 -316
  84. package/packages/selector/src/client/monitor-fab.ts +0 -431
  85. package/packages/selector/src/client/preset-options.ts +0 -88
  86. package/packages/selector/src/client/savings-card.tsx +0 -269
  87. package/packages/selector/src/client/scope-face.ts +0 -24
  88. package/packages/selector/src/client/settings-section.tsx +0 -140
  89. package/packages/selector/src/compat/host-generation.ts +0 -96
  90. package/packages/selector/src/compat/llm-messages.ts +0 -50
  91. package/packages/selector/src/compat/settings-lease.ts +0 -108
  92. package/packages/selector/src/compat/tool-result.ts +0 -91
  93. package/packages/selector/src/css-modules.d.ts +0 -6
  94. package/packages/selector/src/deepseek-v4-tokenizer.ts +0 -205
  95. package/packages/selector/src/estimator-catalog.ts +0 -104
  96. package/packages/selector/src/index.ts +0 -890
  97. package/packages/selector/src/invariant.ts +0 -113
  98. package/packages/selector/src/preset-overlay.ts +0 -749
  99. package/packages/selector/src/profiles.ts +0 -431
  100. package/packages/selector/src/pruner/content.ts +0 -198
  101. package/packages/selector/src/pruner/session.ts +0 -97
  102. package/packages/selector/src/pruner/state.ts +0 -61
  103. package/packages/selector/src/pruner/tuning.ts +0 -23
  104. package/packages/selector/src/pruner/types.ts +0 -78
  105. package/packages/selector/src/pruner.ts +0 -2914
  106. package/packages/selector/src/runtime/adaptive-cost.ts +0 -205
  107. package/packages/selector/src/runtime/audit.ts +0 -320
  108. package/packages/selector/src/runtime/config.ts +0 -756
  109. package/packages/selector/src/runtime/custom-policy.ts +0 -278
  110. package/packages/selector/src/runtime/deepseek-official-pricing.ts +0 -298
  111. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +0 -254
  112. package/packages/selector/src/runtime/display-prefs.ts +0 -98
  113. package/packages/selector/src/runtime/measurement.ts +0 -444
  114. package/packages/selector/src/runtime/monitor.ts +0 -310
  115. package/packages/selector/src/runtime/panel-command.ts +0 -213
  116. package/packages/selector/src/runtime/reducers.ts +0 -1754
  117. package/packages/selector/src/runtime/retrieve.ts +0 -503
  118. package/packages/selector/src/runtime/savings-integral.ts +0 -117
  119. package/packages/selector/src/runtime/savings-projection.ts +0 -229
  120. package/packages/selector/src/runtime/savings-verify.ts +0 -446
  121. package/packages/selector/src/runtime/savings.ts +0 -526
  122. package/packages/selector/src/runtime/session-events.ts +0 -30
  123. package/packages/selector/src/runtime/session-file-decode.ts +0 -523
  124. package/packages/selector/src/runtime/stats-backfill.ts +0 -541
  125. package/packages/selector/src/runtime/stats-db.ts +0 -492
  126. package/packages/selector/src/runtime/stats-schema.ts +0 -123
  127. package/packages/selector/src/runtime/stats-sync.ts +0 -307
  128. package/packages/selector/src/runtime/summary-command.ts +0 -127
  129. package/packages/selector/src/runtime/tail-trim.ts +0 -176
  130. package/packages/selector/src/runtime/token-count.ts +0 -72
  131. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +0 -233
  132. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +0 -204
  133. package/packages/selector/src/runtime/tokenpilot/advisor.ts +0 -419
  134. package/packages/selector/src/runtime/tokenpilot/benefit.ts +0 -200
  135. package/packages/selector/src/runtime/tokenpilot/dedup.ts +0 -81
  136. package/packages/selector/src/runtime/tokenpilot/estimator.ts +0 -151
  137. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +0 -53
  138. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +0 -65
  139. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +0 -125
  140. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +0 -37
  141. package/packages/selector/src/runtime/tokenpilot/locator.ts +0 -128
  142. package/packages/selector/src/runtime/tokenpilot/read-state.ts +0 -98
  143. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +0 -303
  144. package/packages/selector/src/runtime/toolclass.ts +0 -103
  145. package/packages/selector/src/runtime/types.ts +0 -365
  146. package/packages/selector/src/runtime/value.ts +0 -48
  147. package/packages/selector/src/settings-bridge.ts +0 -175
  148. package/packages/selector/tests/advisor-report.host.spec.ts +0 -223
  149. package/packages/selector/tests/auto-compact.client.spec.tsx +0 -214
  150. package/packages/selector/tests/built/client-artifact.spec.ts +0 -56
  151. package/packages/selector/tests/cache-prefix-audit.spec.ts +0 -123
  152. package/packages/selector/tests/code-skeleton.client.spec.ts +0 -98
  153. package/packages/selector/tests/compat/compat-narrow-waist.spec.ts +0 -150
  154. package/packages/selector/tests/custom-contract.client.spec.ts +0 -226
  155. package/packages/selector/tests/estimator-catalog.spec.ts +0 -70
  156. package/packages/selector/tests/estimator-channel.client.spec.tsx +0 -253
  157. package/packages/selector/tests/estimator-route-registration.host.spec.ts +0 -202
  158. package/packages/selector/tests/fab-pos.client.spec.ts +0 -47
  159. package/packages/selector/tests/helpers/legacy-namespace.ts +0 -35
  160. package/packages/selector/tests/helpers/legacy-settings/index.ts +0 -15
  161. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +0 -41
  162. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +0 -647
  163. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +0 -78
  164. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +0 -234
  165. package/packages/selector/tests/host-preset-overlay.host.spec.ts +0 -204
  166. package/packages/selector/tests/monitor-fab.client.spec.ts +0 -240
  167. package/packages/selector/tests/preset-options-write.client.spec.ts +0 -192
  168. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +0 -200
  169. package/packages/selector/tests/preset-overlay.host.spec.ts +0 -246
  170. package/packages/selector/tests/profiles.client.spec.tsx +0 -436
  171. package/packages/selector/tests/public/package-contract.client.spec.ts +0 -86
  172. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +0 -167
  173. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +0 -230
  174. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +0 -272
  175. package/packages/selector/tests/runtime/advisor.spec.ts +0 -226
  176. package/packages/selector/tests/runtime/audit.spec.ts +0 -275
  177. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +0 -523
  178. package/packages/selector/tests/runtime/char-basis.spec.ts +0 -30
  179. package/packages/selector/tests/runtime/code-skeleton.spec.ts +0 -152
  180. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +0 -186
  181. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +0 -122
  182. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +0 -122
  183. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +0 -96
  184. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +0 -273
  185. package/packages/selector/tests/runtime/fixtures/session-v4-dump.jsonl +0 -46
  186. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +0 -106
  187. package/packages/selector/tests/runtime/fixtures/vision-golden.json +0 -459
  188. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +0 -74
  189. package/packages/selector/tests/runtime/fresh-gate.spec.ts +0 -43
  190. package/packages/selector/tests/runtime/html-reducer.spec.ts +0 -212
  191. package/packages/selector/tests/runtime/intent-gate.spec.ts +0 -62
  192. package/packages/selector/tests/runtime/intent-summary.spec.ts +0 -156
  193. package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +0 -79
  194. package/packages/selector/tests/runtime/line-mapping.spec.ts +0 -153
  195. package/packages/selector/tests/runtime/monitor.spec.ts +0 -354
  196. package/packages/selector/tests/runtime/panel-command.spec.ts +0 -101
  197. package/packages/selector/tests/runtime/prose-reducers.spec.ts +0 -133
  198. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +0 -2781
  199. package/packages/selector/tests/runtime/read-input-cap.spec.ts +0 -33
  200. package/packages/selector/tests/runtime/savings-accounting.spec.ts +0 -291
  201. package/packages/selector/tests/runtime/savings-integral.spec.ts +0 -169
  202. package/packages/selector/tests/runtime/savings-projection.spec.ts +0 -89
  203. package/packages/selector/tests/runtime/savings-verify.spec.ts +0 -226
  204. package/packages/selector/tests/runtime/savings.spec.ts +0 -139
  205. package/packages/selector/tests/runtime/search-reducer.spec.ts +0 -110
  206. package/packages/selector/tests/runtime/session-events.spec.ts +0 -27
  207. package/packages/selector/tests/runtime/session-file-decode.spec.ts +0 -281
  208. package/packages/selector/tests/runtime/settings-unwrap.spec.ts +0 -58
  209. package/packages/selector/tests/runtime/sidechannel.spec.ts +0 -241
  210. package/packages/selector/tests/runtime/stats-backfill-scheduler.spec.ts +0 -167
  211. package/packages/selector/tests/runtime/stats-backfill.spec.ts +0 -348
  212. package/packages/selector/tests/runtime/stats-db.spec.ts +0 -361
  213. package/packages/selector/tests/runtime/stats-privacy.spec.ts +0 -55
  214. package/packages/selector/tests/runtime/stats-sync.spec.ts +0 -278
  215. package/packages/selector/tests/runtime/summary-command.spec.ts +0 -154
  216. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +0 -159
  217. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +0 -53
  218. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +0 -217
  219. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +0 -52
  220. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +0 -79
  221. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +0 -76
  222. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +0 -119
  223. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +0 -82
  224. package/packages/selector/tests/runtime/toolclass.spec.ts +0 -156
  225. package/packages/selector/tests/runtime/value.spec.ts +0 -23
  226. package/packages/selector/tests/savings-sessions.client.spec.tsx +0 -140
  227. package/packages/selector/tests/settings-seat.client.spec.ts +0 -215
  228. package/packages/selector/tests/standing-generation.host.spec.ts +0 -724
  229. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +0 -269
  230. package/packages/selector/tests/support/cache-prefix-audit.ts +0 -105
  231. package/packages/selector/tests/support/mock-adapter.ts +0 -37
  232. package/packages/selector/tests/support/ui-primitives.tsx +0 -34
  233. package/packages/selector/tsconfig.json +0 -11
  234. package/packages/selector/tsdown.client.config.ts +0 -102
  235. package/packages/selector/tsdown.config.ts +0 -20
  236. package/pnpm-workspace.yaml +0 -76
  237. package/scripts/capture-profile-baseline.mjs +0 -42
  238. package/scripts/cell-browser-e2e.mjs +0 -354
  239. package/scripts/generate-tokenizer-fixtures.py +0 -81
  240. package/scripts/generate-vision-fixtures.py +0 -208
  241. package/scripts/hosts.mjs +0 -78
  242. package/scripts/packed-components-smoke.mjs +0 -763
  243. package/scripts/packed-install-e2e.mjs +0 -1346
  244. package/scripts/sync-hosts.mjs +0 -174
  245. package/scripts/toolclass-corpus-replay.mjs +0 -281
  246. package/scripts/verify-release.mjs +0 -338
  247. package/tests/TEST_INVENTORY.md +0 -41
  248. package/tsconfig.base.json +0 -18
  249. package/tsconfig.json +0 -7
  250. package/tsconfig.tests.json +0 -15
  251. package/vitest.built.config.ts +0 -9
  252. package/vitest.config.ts +0 -54
  253. /package/{packages/selector/assets → assets}/deepseek-v4/LICENSE.DeepSeek-V4-Pro.txt +0 -0
  254. /package/{packages/selector/assets → assets}/deepseek-v4/manifest.json +0 -0
  255. /package/{packages/selector/assets → assets}/deepseek-v4/tokenizer.json +0 -0
  256. /package/{packages/selector/assets → assets}/deepseek-v4/tokenizer_config.json +0 -0
  257. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/LICENSE.DeepSeek-V4-Flash-Vision-Exp.txt +0 -0
  258. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/manifest.json +0 -0
  259. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/tokenizer.json +0 -0
  260. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/tokenizer_config.json +0 -0
  261. /package/{packages/selector/cordis.patch.yml → cordis.patch.yml} +0 -0
  262. /package/{packages/selector/lib → lib}/index.d.ts +0 -0
  263. /package/{packages/selector/lib → lib}/index.js +0 -0
  264. /package/{packages/selector/lib → lib}/invariant.d.ts +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
- })