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,419 +0,0 @@
1
- /**
2
- * Advisory relevance advisor: LLM relevance statistics and suggestions bound
3
- * to the session todolist.
4
- *
5
- * The advisor is NOT a reviewer or gate. Every output — tail-task summaries,
6
- * per-candidate relevance scores, the prefix-decay figure, recertification
7
- * marks — is observational: it must never suppress, delay, or rewrite any
8
- * reduction that would land, and nothing here is consulted by any decision
9
- * path this round. Failures are fail-open; every call is fire-and-forget from
10
- * the turn-stopping boundary.
11
- *
12
- * Task semantics come from the most recent `todo/write` session event
13
- * (defensively parsed — the payload carries no public type), falling back to
14
- * recent user/message text when no todolist exists.
15
- */
16
- import type { SessionEvent } from '@deepseek-ai/dsh-session'
17
- import { charsForTokens, codePointLength } from '../config.ts'
18
- import type { CompressionProfile } from '../types.ts'
19
- import type { AdvisorOutcomeAuditRecord } from '../audit.ts'
20
- import {
21
- getAdvisorState,
22
- invalidateOnTaskChange,
23
- recordRecertified,
24
- recordScore,
25
- type AdvisorState,
26
- } from './advisor-state.ts'
27
- import type { SideChannel } from './sidechannel.ts'
28
- import {
29
- buildAdvisorScoringSystemPrompt,
30
- buildAdvisorScoringUserPrompt,
31
- buildAdvisorSummarySystemPrompt,
32
- buildAdvisorSummaryUserPrompt,
33
- parseAdvisorScores,
34
- parseAdvisorSummary,
35
- } from './advisor-prompt.ts'
36
-
37
- /** Character cap for the recent-text fallback and the tail-text summary input. */
38
- export const TAIL_TEXT_CHAR_BUDGET = 4_000
39
- /** Score the advisor assigns to candidates it has no answer for. */
40
- const NEUTRAL_RELEVANCE = 0.5
41
-
42
- /** Task semantics harvested from the session log, bound to the todolist. */
43
- export interface TaskSemantics {
44
- /** `todos`: structured todo/write payload; `raw-todo`: degraded JSON string; `messages`: recent user text. */
45
- readonly source: 'todos' | 'raw-todo' | 'messages'
46
- /** Stable version token of the task semantics (scores/summaries invalidate on change). */
47
- readonly todoVersion: string
48
- /** Human-readable task description fed to the summary and scoring prompts. */
49
- readonly taskText: string
50
- }
51
-
52
- /** Minimal candidate face the advisor needs; satisfied by SnapshotCandidate. */
53
- export interface AdvisorCandidate {
54
- readonly seq: number
55
- readonly characterPressure: number
56
- /** Short content sample for the scoring prompt (tool-call name + text head). */
57
- readonly preview: string
58
- }
59
-
60
- /** One scoring-pass candidate with its local keyword-overlap prescreen rank. */
61
- interface ScoredCandidateView extends AdvisorCandidate {
62
- readonly overlap: number
63
- }
64
-
65
- /** Deterministic djb2-derived hex digest for task-semantics versioning. */
66
- function versionDigest(text: string): string {
67
- let hash = 5381
68
- for (let index = 0; index < text.length; index += 1) {
69
- hash = ((hash * 33) ^ text.charCodeAt(index)) >>> 0
70
- }
71
- return hash.toString(16).padStart(8, '0')
72
- }
73
-
74
- /** Truncate on the character basis (Unicode code points), never UTF-16 units. */
75
- function truncateChars(text: string, budget: number): string {
76
- if (codePointLength(text) <= budget) return text
77
- return Array.from(text).slice(0, budget).join('')
78
- }
79
-
80
- /** Character cap of one candidate preview line offered to the scoring prompt. */
81
- const PREVIEW_CHAR_BUDGET = 200
82
-
83
- /**
84
- * One candidate face for the scoring prompt: tool-call name plus the head of
85
- * the result text. Pure and shape-defensive.
86
- */
87
- export function advisorCandidatePreview(callName: string, blocks: unknown): string {
88
- const text = textBlocks(blocks)
89
- return truncateChars(`${callName} ${text}`.trim(), PREVIEW_CHAR_BUDGET)
90
- }
91
-
92
- /**
93
- * Collect the recent assistant narration tail (bounded, oldest-first join) as
94
- * summary-prompt context. Pure.
95
- */
96
- export function collectTailText(events: readonly SessionEvent[], budget: number = TAIL_TEXT_CHAR_BUDGET): string {
97
- const parts: string[] = []
98
- let size = 0
99
- for (let index = events.length - 1; index >= 0; index -= 1) {
100
- const event = events[index]
101
- if (event?.type !== 'assistant/message') continue
102
- const text = textBlocks(event.data).trim()
103
- if (text.length === 0) continue
104
- parts.unshift(text)
105
- size += codePointLength(text)
106
- if (size >= budget) break
107
- }
108
- return truncateChars(parts.join('\n'), budget)
109
- }
110
-
111
- function textBlocks(data: unknown): string {
112
- const content = (data as { content?: { type?: unknown, text?: unknown }[] } | undefined)?.content
113
- if (!Array.isArray(content)) return ''
114
- const parts: string[] = []
115
- for (const block of content) {
116
- if (block?.type === 'text' && typeof block.text === 'string') parts.push(block.text)
117
- }
118
- return parts.join('\n')
119
- }
120
-
121
- /** Structured probe of one `todo/write` payload: the list of task strings, or undefined. */
122
- function extractTodoItems(data: unknown): string[] | undefined {
123
- const todos = (data as { todos?: unknown } | undefined)?.todos
124
- const list = Array.isArray(todos) ? todos : Array.isArray(data) ? data : undefined
125
- if (list === undefined || list.length === 0) return undefined
126
- const items: string[] = []
127
- for (const entry of list) {
128
- if (typeof entry === 'string') {
129
- if (entry.trim().length > 0) items.push(entry.trim())
130
- continue
131
- }
132
- if (entry !== null && typeof entry === 'object') {
133
- const record = entry as Record<string, unknown>
134
- const text = [record.content, record.text, record.title, record.name]
135
- .find(candidate => typeof candidate === 'string' && candidate.trim().length > 0)
136
- if (typeof text === 'string') {
137
- items.push(text.trim())
138
- continue
139
- }
140
- // Structured shape the advisor does not recognize: keep the item visible
141
- // as its raw JSON so the LLM still sees the todolist instead of nothing.
142
- items.push(JSON.stringify(record))
143
- }
144
- }
145
- return items.length > 0 ? items : undefined
146
- }
147
-
148
- /**
149
- * Harvest task semantics for the summary/scoring prompts: the most recent
150
- * `todo/write` event (structured probe first, then the raw JSON string),
151
- * falling back to recent user/message text. Pure — log in, semantics out.
152
- */
153
- export function collectTaskSemantics(events: readonly SessionEvent[]): TaskSemantics | undefined {
154
- for (let index = events.length - 1; index >= 0; index -= 1) {
155
- const event = events[index]
156
- // `todo/write` is plugin-merged into the runtime event vocabulary but not
157
- // the static SessionEventMap union, so the probe compares widened types.
158
- if (event === undefined || (event.type as string) !== 'todo/write') continue
159
- const data: unknown = (event as { data?: unknown }).data
160
- const items = extractTodoItems(data)
161
- if (items !== undefined) {
162
- const taskText = truncateChars(items.join('\n'), TAIL_TEXT_CHAR_BUDGET)
163
- return { source: 'todos', todoVersion: versionDigest(taskText), taskText }
164
- }
165
- const raw = truncateChars(JSON.stringify(event.data) ?? '', TAIL_TEXT_CHAR_BUDGET)
166
- if (raw.length > 2) {
167
- return { source: 'raw-todo', todoVersion: versionDigest(raw), taskText: raw }
168
- }
169
- }
170
- // No usable todolist: fall back to the most recent user/message text.
171
- for (let index = events.length - 1; index >= 0; index -= 1) {
172
- const event = events[index]
173
- if (event?.type !== 'user/message') continue
174
- const text = truncateChars(textBlocks(event.data).trim(), TAIL_TEXT_CHAR_BUDGET)
175
- if (text.length === 0) continue
176
- return { source: 'messages', todoVersion: versionDigest(text), taskText: text }
177
- }
178
- return undefined
179
- }
180
-
181
- /**
182
- * Prefix-decay figure: 1 minus the character-pressure-weighted mean relevance
183
- * of the prefix candidates. Unscored candidates count as neutral 0.5. Pure,
184
- * deterministic, no LLM and no I/O.
185
- */
186
- export function prefixDecay(
187
- candidates: readonly { readonly seq: number, readonly characterPressure: number }[],
188
- scores: ReadonlyMap<number, { readonly score: number }>,
189
- ): { readonly decay: number, readonly weightedChars: number } {
190
- let totalWeight = 0
191
- let weightedRelevance = 0
192
- for (const candidate of candidates) {
193
- const weight = candidate.characterPressure > 0 ? candidate.characterPressure : 0
194
- if (weight === 0) continue
195
- totalWeight += weight
196
- weightedRelevance += weight * (scores.get(candidate.seq)?.score ?? NEUTRAL_RELEVANCE)
197
- }
198
- if (totalWeight === 0) return { decay: 0, weightedChars: 0 }
199
- return {
200
- decay: 1 - weightedRelevance / totalWeight,
201
- weightedChars: totalWeight,
202
- }
203
- }
204
-
205
- /** Lowercase word tokens used by the local keyword-overlap prescreen. */
206
- function keywordsOf(text: string): Set<string> {
207
- const matches = text.toLowerCase().match(/[\p{L}\p{N}_-]{3,}/gu) ?? []
208
- return new Set(matches)
209
- }
210
-
211
- function overlapCount(left: ReadonlySet<string>, right: ReadonlySet<string>): number {
212
- let count = 0
213
- for (const token of right) {
214
- if (left.has(token)) count += 1
215
- }
216
- return count
217
- }
218
-
219
- /**
220
- * Incremental scoring selection: candidates newer than the watermark whose
221
- * character pressure reaches the token-named floor, ranked by local keyword
222
- * overlap with the task semantics and cut at the sample limit. When the task
223
- * semantics changed, the watermark is ignored so every eligible candidate can
224
- * rescore. Pure.
225
- */
226
- export function selectScoringCandidates(
227
- candidates: readonly AdvisorCandidate[],
228
- state: Pick<AdvisorState, 'watermarkSeq'>,
229
- input: {
230
- readonly taskKeywords: ReadonlySet<string>
231
- readonly minChars: number
232
- readonly sampleLimit: number
233
- readonly taskChanged: boolean
234
- },
235
- ): AdvisorCandidate[] {
236
- const eligible: ScoredCandidateView[] = []
237
- for (const candidate of candidates) {
238
- if (!input.taskChanged && candidate.seq <= state.watermarkSeq) continue
239
- if (candidate.characterPressure < input.minChars) continue
240
- eligible.push({
241
- ...candidate,
242
- overlap: overlapCount(input.taskKeywords, keywordsOf(candidate.preview)),
243
- })
244
- }
245
- eligible.sort((left, right) => right.overlap - left.overlap || right.characterPressure - left.characterPressure)
246
- return eligible.slice(0, input.sampleLimit).map(({ overlap: _overlap, ...candidate }) => candidate)
247
- }
248
-
249
- /** Advisor inputs the pruner owns; the advisor never reaches into pruner state. */
250
- export interface AdvisorPassInput {
251
- readonly profile: CompressionProfile
252
- readonly sessionId: string
253
- readonly turn: number
254
- readonly candidates: readonly AdvisorCandidate[]
255
- readonly task: TaskSemantics | undefined
256
- readonly advisor: {
257
- readonly refreshTurns: number
258
- readonly scoreThreshold: number
259
- readonly sampleLimit: number
260
- readonly minTokens: number
261
- }
262
- /** Tail assistant text offered to the summary prompt (already char-bounded). */
263
- readonly tailText: string
264
- readonly signal: AbortSignal
265
- }
266
-
267
- /** One ask-shaped LLM channel; satisfied by SideChannel.ask. */
268
- export type AdvisorChannel = Pick<SideChannel, 'ask' | 'identity'>
269
-
270
- export interface AdvisorPassOutcome {
271
- readonly decay: number
272
- readonly weightedChars: number
273
- readonly sampled: number
274
- }
275
-
276
- function advisorAudit(
277
- input: AdvisorPassInput,
278
- phase: AdvisorOutcomeAuditRecord['phase'],
279
- fields: Partial<AdvisorOutcomeAuditRecord> & { ok: boolean, latencyMs: number },
280
- ): AdvisorOutcomeAuditRecord {
281
- return {
282
- schemaVersion: 1,
283
- kind: 'advisor-outcome',
284
- sessionId: input.sessionId,
285
- phase,
286
- turnIndex: input.turn,
287
- ...fields,
288
- }
289
- }
290
-
291
- /**
292
- * One full advisor pass: summary refresh (todo change or every refreshTurns),
293
- * incremental batch scoring with recertification marks, then the decay
294
- * figure. State is written only on success; any failure leaves state
295
- * untouched, emits ok:false audits with reason codes, and never throws.
296
- */
297
- export async function runAdvisorPass(
298
- state: AdvisorState,
299
- channel: AdvisorChannel,
300
- emit: (record: AdvisorOutcomeAuditRecord) => void,
301
- input: AdvisorPassInput,
302
- ): Promise<AdvisorPassOutcome | undefined> {
303
- if (input.task === undefined) return undefined
304
- const taskChanged = invalidateOnTaskChange(state, input.task.todoVersion)
305
- const turn = input.turn
306
- const needSummary = state.summary === undefined || turn - state.lastSummaryTurn >= input.advisor.refreshTurns
307
-
308
- // 1. Tail-task summary: bound to the todolist, refreshed on change or interval.
309
- if (needSummary) {
310
- const summaryStarted = Date.now()
311
- const summaryText = await channel.ask({
312
- system: buildAdvisorSummarySystemPrompt(),
313
- user: buildAdvisorSummaryUserPrompt(input.task.taskText, input.tailText),
314
- signal: input.signal,
315
- })
316
- const summaryLatencyMs = Date.now() - summaryStarted
317
- const summary = input.signal.aborted ? undefined : parseAdvisorSummary(summaryText)
318
- if (summary === undefined) {
319
- emit(advisorAudit(input, 'summary', {
320
- ok: false,
321
- latencyMs: summaryLatencyMs,
322
- ...(input.signal.aborted
323
- ? { reason: 'aborted' }
324
- : summaryText === undefined ? { reason: 'channel-empty' } : { reason: 'parse-failed' }),
325
- }))
326
- return undefined
327
- }
328
- state.summary = { ...summary, todoVersion: input.task.todoVersion, turn }
329
- state.lastSummaryTurn = turn
330
- emit(advisorAudit(input, 'summary', { ok: true, latencyMs: summaryLatencyMs }))
331
- }
332
-
333
- const summary = state.summary
334
- if (summary === undefined) return undefined
335
-
336
- // 2. Incremental batch scoring: prescreened candidates, one LLM call.
337
- const sampled = selectScoringCandidates(input.candidates, state, {
338
- taskKeywords: keywordsOf(`${input.task.taskText}\n${summary.keywords.join(' ')}`),
339
- minChars: charsForTokens(input.advisor.minTokens),
340
- sampleLimit: input.advisor.sampleLimit,
341
- taskChanged,
342
- })
343
- let scored = 0
344
- let highestScored = 0
345
- if (sampled.length > 0) {
346
- const scoringStarted = Date.now()
347
- const scoresText = await channel.ask({
348
- system: buildAdvisorScoringSystemPrompt(),
349
- user: buildAdvisorScoringUserPrompt(input.task.taskText, summary.activeSubtasks, sampled),
350
- signal: input.signal,
351
- })
352
- const scoringLatencyMs = Date.now() - scoringStarted
353
- const scores = input.signal.aborted ? undefined : parseAdvisorScores(scoresText, new Set(sampled.map(item => item.seq)))
354
- if (scores === undefined || scores.size === 0) {
355
- emit(advisorAudit(input, 'scoring', {
356
- ok: false,
357
- sampledCount: sampled.length,
358
- latencyMs: scoringLatencyMs,
359
- ...(input.signal.aborted
360
- ? { reason: 'aborted' }
361
- : scoresText === undefined ? { reason: 'channel-empty' } : { reason: 'parse-failed' }),
362
- }))
363
- return undefined
364
- }
365
- for (const candidate of sampled) {
366
- const answer = scores.get(candidate.seq)
367
- if (answer === undefined) continue
368
- recordScore(state, candidate.seq, { score: answer.score, turn })
369
- scored += 1
370
- if (candidate.seq > highestScored) highestScored = candidate.seq
371
- // R5: low-relevance segments are LLM-recertified as suggestions only —
372
- // nothing consumes the marks this round, and the caller is expected to
373
- // have filtered protected candidates out of `candidates`.
374
- if (answer.score < input.advisor.scoreThreshold) recordRecertified(state, candidate.seq, turn)
375
- }
376
- emit(advisorAudit(input, 'scoring', { ok: true, sampledCount: sampled.length, latencyMs: scoringLatencyMs }))
377
- // The watermark only moves past candidates that actually received a
378
- // score: rows the channel dropped stay eligible so a later pass can
379
- // rescore them instead of silently losing them behind the cut.
380
- if (highestScored > state.watermarkSeq) state.watermarkSeq = highestScored
381
- }
382
-
383
- // 3. Decay figure over the whole prefix: local, always emitted on a pass
384
- // that got this far (even with zero samples this round). Stored on the
385
- // state so the report route serves the exact same figure (J3).
386
- const decay = prefixDecay(input.candidates, state.scores)
387
- state.lastDecay = { decay: decay.decay, weightedChars: decay.weightedChars, turn }
388
- emit(advisorAudit(input, 'decay', {
389
- ok: true,
390
- sampledCount: scored,
391
- decay: decay.decay,
392
- weightedChars: decay.weightedChars,
393
- latencyMs: 0,
394
- }))
395
- return { decay: decay.decay, weightedChars: decay.weightedChars, sampled: sampled.length }
396
- }
397
-
398
- /**
399
- * Convenience entry used by the pruner: fetch-or-create the session state and
400
- * run one pass against it.
401
- */
402
- export async function runSessionAdvisorPass(
403
- session: Parameters<typeof getAdvisorState>[0],
404
- channel: AdvisorChannel,
405
- emit: (record: AdvisorOutcomeAuditRecord) => void,
406
- input: Omit<AdvisorPassInput, 'sessionId'> & { readonly sessionId?: string },
407
- ): Promise<AdvisorPassOutcome | undefined> {
408
- const state = getAdvisorState(session)
409
- if (state.inFlight) return undefined
410
- state.inFlight = true
411
- try {
412
- return await runAdvisorPass(state, channel, emit, {
413
- ...input,
414
- sessionId: input.sessionId ?? String(session.id),
415
- })
416
- } finally {
417
- state.inFlight = false
418
- }
419
- }
@@ -1,200 +0,0 @@
1
- /**
2
- * TokenPilot-inspired benefit model — **advisory only**.
3
- *
4
- * This module prices one pass's planned replacements as ONE merged mutation and
5
- * labels the batch with the band the model would have chosen. The label is
6
- * ADVICE: nothing here suppresses, delays, or rewrites a reduction. The former
7
- * human-gated review pipeline consumed these bands to withhold the batch from
8
- * landing; that gate was retired because a reduction must never block automatic
9
- * processing. The bands now feed the `reduction-advice` audit and the advisor
10
- * report, and every planned replacement that the rule engine produced lands.
11
- *
12
- * Cache accounting (TokenPilot paper): one merged mutation pays a one-time tail
13
- * KV-cache refill penalty of `(1−α)·tailTokens`, and every later turn recovers
14
- * the reclaimed tokens at the cache-hit discount `α`:
15
- *
16
- * ```
17
- * R = Σ(tokensBefore − tokensAfter) // net reclaimed tokens
18
- * paybackTurns = (1−α)·tailTokens / (α·R) // one-time refill / per-turn saving
19
- * expectedSaving = α·R·max(0, Ŝ − paybackTurns) // Ŝ = estimated remaining turns
20
- * ```
21
- *
22
- * The refill penalty only models mutations of already-cached context. A
23
- * fresh-stage batch (shaped before its first request) is exempt via
24
- * `refillPenaltyExempt`: payback is 0 and every reclaimed token saves from
25
- * the very first turn. Without that exemption every realistic fresh batch
26
- * prices into the `not-worth-it` band, which makes the advice useless exactly
27
- * where it is most often consulted.
28
- *
29
- * `expectedSaving` is only produced when Ŝ is known (the estimator answered
30
- * with `expectedRemainingTurns`); it is never fabricated from a guess.
31
- *
32
- * Pure functions only: the classifier needs no I/O, no session state, and no
33
- * host services, so every label is unit-testable and audit-replayable.
34
- */
35
-
36
- /** The minimal per-candidate face the benefit model consumes. */
37
- export interface BenefitCandidate {
38
- readonly sourceSeq: number
39
- readonly tokensBefore: number
40
- readonly tokensAfter: number
41
- }
42
-
43
- export interface BenefitInput {
44
- /** Cache-hit discount rate α ∈ (0,1); validated upstream by config parsing. */
45
- readonly alpha: number
46
- /** Token mass of the protected tail that must be refilled after a mutation. */
47
- readonly tailTokens: number
48
- /** Estimated remaining turns Ŝ; `undefined` keeps expectedSaving out of the result. */
49
- readonly remainingTurns?: number | undefined
50
- /** True for fresh-stage batches: their content was never served, so it is
51
- * not in the KV cache and shaping it causes no cache break — no refill
52
- * penalty applies and the whole discounted recovery is pure gain. */
53
- readonly refillPenaltyExempt?: boolean | undefined
54
- }
55
-
56
- export interface BenefitEstimate {
57
- /** Net reclaimed tokens across the batch; may be ≤ 0 when a batch is not worth it. */
58
- readonly recoveredTokens: number
59
- /** The one-time cache-refill penalty the merged mutation pays: (1−α)·tailTokens. */
60
- readonly penaltyTokens: number
61
- /** Turns of discounted recovery needed to recoup the penalty; `undefined` when α·R ≤ 0. */
62
- readonly paybackTurns?: number
63
- /** Discounted net benefit over the remaining session; omitted when Ŝ is unknown. */
64
- readonly expectedSaving?: number
65
- }
66
-
67
- /**
68
- * The band one priced batch falls into. Advisory vocabulary only — every band
69
- * lands; the label says what the model thought of the landing, not whether it
70
- * was allowed to happen.
71
- */
72
- export type AdviceBand =
73
- /** Payback ≤ 1 turn, or ≤ a quarter of the estimated remaining turns. */
74
- | 'profitable'
75
- /** At least one candidate reaches the high-impact threshold: the batch is
76
- * large enough that a human would want to know it moved. */
77
- | 'high-impact'
78
- /** Ŝ known and payback ∈ (1, 3]: it does pay back, but slowly. */
79
- | 'slow-payback'
80
- /** α·R ≤ 0: the accounting has no discounted recovery to argue from. */
81
- | 'unpriceable'
82
- /** Ŝ known and payback > 3 turns: the model would not have spent the cache break. */
83
- | 'not-worth-it'
84
-
85
- export interface AdviceInput {
86
- /** Cache-hit discount rate α ∈ (0,1); validated upstream by config parsing. */
87
- readonly alpha: number
88
- /** Token mass of the protected tail that must be refilled after a mutation. */
89
- readonly tailTokens: number
90
- /** Candidates at or above this token impact are labelled `high-impact`. */
91
- readonly highImpactTokens: number
92
- /** Estimated remaining turns Ŝ; `undefined` closes the slow-payback band. */
93
- readonly remainingTurns?: number | undefined
94
- /** Landing stage of the batch: `'fresh'` batches are priced without the
95
- * tail-refill penalty (first-exposure shaping causes no cache break);
96
- * `'history'` batches — already-served content — pay it in full. */
97
- readonly stage?: 'fresh' | 'history' | undefined
98
- }
99
-
100
- export interface AdviceResult {
101
- readonly band: AdviceBand
102
- /** The full benefit estimate the band was derived from. */
103
- readonly benefit: BenefitEstimate
104
- /** Number of candidates that carried a positive recovery and were priced. */
105
- readonly priced: number
106
- /** Largest single-candidate token mass in the batch (the high-impact evidence). */
107
- readonly maxTokensBefore: number
108
- }
109
-
110
- /**
111
- * Shipped defaults of the advisory model. They are constants rather than
112
- * settings keys because the machine no longer acts on them: after the review
113
- * gate was retired these numbers only shape a label, so exposing them as
114
- * tunable configuration would advertise a control that changes no behavior.
115
- */
116
- export const DEFAULT_ADVICE_ALPHA = 0.1
117
- export const DEFAULT_ADVICE_HIGH_IMPACT_TOKENS = 4_000
118
-
119
- /**
120
- * Aggregate the batch-level benefit of a set of reduction candidates.
121
- *
122
- * Individual candidates whose replacement would grow the context contribute
123
- * zero recovery (they never make a batch look better than dropping them).
124
- */
125
- export function computeBenefit(candidates: readonly BenefitCandidate[], input: BenefitInput): BenefitEstimate {
126
- const { alpha, tailTokens, remainingTurns } = input
127
- let recoveredTokens = 0
128
- for (const candidate of candidates) {
129
- recoveredTokens += Math.max(0, candidate.tokensBefore - candidate.tokensAfter)
130
- }
131
- const penaltyTokens = input.refillPenaltyExempt === true ? 0 : (1 - alpha) * tailTokens
132
- const perTurnSaving = alpha * recoveredTokens
133
- if (perTurnSaving <= 0) {
134
- return remainingTurns === undefined
135
- ? { recoveredTokens, penaltyTokens }
136
- : { recoveredTokens, penaltyTokens, expectedSaving: -penaltyTokens }
137
- }
138
- const paybackTurns = penaltyTokens / perTurnSaving
139
- if (remainingTurns === undefined) {
140
- return { recoveredTokens, penaltyTokens, paybackTurns }
141
- }
142
- return {
143
- recoveredTokens,
144
- penaltyTokens,
145
- paybackTurns,
146
- expectedSaving: perTurnSaving * Math.max(0, remainingTurns - paybackTurns),
147
- }
148
- }
149
-
150
- /**
151
- * Label one batch of planned replacements.
152
- *
153
- * Pipeline: zero/negative-recovery candidates are priced out first (they never
154
- * make a batch look better), the surviving batch is priced once through
155
- * `computeBenefit`, and the band is a batch decision — the refill penalty is a
156
- * property of the landing event, not of any single candidate, so pricing per
157
- * candidate would overstate payback N-fold.
158
- *
159
- * Band precedence (identical thresholds to the retired triage model):
160
- * - α too small to price a payback → `unpriceable`;
161
- * - any candidate at `highImpactTokens` → `high-impact`;
162
- * - `paybackTurns ≤ 1`, or Ŝ known and `paybackTurns ≤ 0.25·Ŝ` → `profitable`;
163
- * - Ŝ known and `paybackTurns ∈ (1, 3]` → `slow-payback`;
164
- * - everything else → `not-worth-it`.
165
- *
166
- * @param candidates - planned replacements of one pass, in any order.
167
- * @param input - pricing inputs and the stage of the batch.
168
- * @returns the advice, or `undefined` when nothing carried a positive recovery.
169
- */
170
- export function adviseCandidates(
171
- candidates: readonly BenefitCandidate[],
172
- input: AdviceInput,
173
- ): AdviceResult | undefined {
174
- const usable: BenefitCandidate[] = []
175
- for (const candidate of candidates) {
176
- if (Math.max(0, candidate.tokensBefore - candidate.tokensAfter) <= 0) continue
177
- usable.push(candidate)
178
- }
179
- if (usable.length === 0) return undefined
180
-
181
- const benefit = computeBenefit(usable, {
182
- alpha: input.alpha,
183
- tailTokens: input.tailTokens,
184
- ...input.remainingTurns !== undefined ? { remainingTurns: input.remainingTurns } : {},
185
- refillPenaltyExempt: input.stage === 'fresh',
186
- })
187
- const payback = benefit.paybackTurns
188
- const maxTokensBefore = usable.reduce((max, candidate) => Math.max(max, candidate.tokensBefore), 0)
189
- const band: AdviceBand = payback === undefined
190
- ? 'unpriceable'
191
- : maxTokensBefore >= input.highImpactTokens
192
- ? 'high-impact'
193
- : payback <= 1
194
- || (input.remainingTurns !== undefined && payback <= 0.25 * input.remainingTurns)
195
- ? 'profitable'
196
- : input.remainingTurns !== undefined && payback <= 3
197
- ? 'slow-payback'
198
- : 'not-worth-it'
199
- return { band, benefit, priced: usable.length, maxTokensBefore }
200
- }