dsh-context-compression-improved 0.9.9-beta.0 → 0.9.9

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