dsh-context-compression-improved 0.10.2 → 0.10.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (264) 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 +549 -0
  15. package/CHANGELOG.ru.md +554 -0
  16. package/CHANGELOG.zh.md +238 -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 +116 -129
  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/{dsh.plugin.json → packages/selector/dsh.plugin.json} +2 -2
  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/fab-pos.ts +71 -0
  65. package/packages/selector/src/client/index.ts +424 -0
  66. package/packages/selector/src/client/locales/de.ts +158 -0
  67. package/packages/selector/src/client/locales/es.ts +158 -0
  68. package/packages/selector/src/client/locales/fr.ts +158 -0
  69. package/packages/selector/src/client/locales/it.ts +158 -0
  70. package/packages/selector/src/client/locales/ja.ts +158 -0
  71. package/packages/selector/src/client/locales/ko.ts +158 -0
  72. package/packages/selector/src/client/locales/ru.ts +158 -0
  73. package/packages/selector/src/client/locales.ts +316 -0
  74. package/packages/selector/src/client/monitor-fab.ts +431 -0
  75. package/packages/selector/src/client/preset-options.ts +88 -0
  76. package/packages/selector/src/client/savings-card.tsx +269 -0
  77. package/packages/selector/src/client/scope-face.ts +24 -0
  78. package/packages/selector/src/client/settings-section.tsx +140 -0
  79. package/packages/selector/src/compat/host-generation.ts +96 -0
  80. package/packages/selector/src/compat/llm-messages.ts +50 -0
  81. package/packages/selector/src/compat/settings-lease.ts +108 -0
  82. package/packages/selector/src/compat/tool-result.ts +91 -0
  83. package/packages/selector/src/css-modules.d.ts +6 -0
  84. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -0
  85. package/packages/selector/src/estimator-catalog.ts +104 -0
  86. package/packages/selector/src/index.ts +890 -0
  87. package/packages/selector/src/invariant.ts +113 -0
  88. package/packages/selector/src/preset-overlay.ts +749 -0
  89. package/packages/selector/src/profiles.ts +431 -0
  90. package/packages/selector/src/pruner/content.ts +198 -0
  91. package/packages/selector/src/pruner/session.ts +97 -0
  92. package/packages/selector/src/pruner/state.ts +61 -0
  93. package/packages/selector/src/pruner/tuning.ts +23 -0
  94. package/packages/selector/src/pruner/types.ts +78 -0
  95. package/packages/selector/src/pruner.ts +2914 -0
  96. package/packages/selector/src/runtime/adaptive-cost.ts +205 -0
  97. package/packages/selector/src/runtime/audit.ts +320 -0
  98. package/packages/selector/src/runtime/config.ts +756 -0
  99. package/packages/selector/src/runtime/custom-policy.ts +278 -0
  100. package/packages/selector/src/runtime/deepseek-official-pricing.ts +298 -0
  101. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +254 -0
  102. package/packages/selector/src/runtime/display-prefs.ts +98 -0
  103. package/packages/selector/src/runtime/measurement.ts +444 -0
  104. package/packages/selector/src/runtime/monitor.ts +310 -0
  105. package/packages/selector/src/runtime/panel-command.ts +213 -0
  106. package/packages/selector/src/runtime/reducers.ts +1754 -0
  107. package/packages/selector/src/runtime/retrieve.ts +503 -0
  108. package/packages/selector/src/runtime/savings-integral.ts +117 -0
  109. package/packages/selector/src/runtime/savings-projection.ts +229 -0
  110. package/packages/selector/src/runtime/savings-verify.ts +446 -0
  111. package/packages/selector/src/runtime/savings.ts +526 -0
  112. package/packages/selector/src/runtime/session-events.ts +30 -0
  113. package/packages/selector/src/runtime/session-file-decode.ts +523 -0
  114. package/packages/selector/src/runtime/stats-backfill.ts +541 -0
  115. package/packages/selector/src/runtime/stats-db.ts +492 -0
  116. package/packages/selector/src/runtime/stats-schema.ts +123 -0
  117. package/packages/selector/src/runtime/stats-sync.ts +307 -0
  118. package/packages/selector/src/runtime/summary-command.ts +127 -0
  119. package/packages/selector/src/runtime/tail-trim.ts +176 -0
  120. package/packages/selector/src/runtime/token-count.ts +72 -0
  121. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -0
  122. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -0
  123. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -0
  124. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -0
  125. package/packages/selector/src/runtime/tokenpilot/dedup.ts +81 -0
  126. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -0
  127. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  128. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  129. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  130. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  131. package/packages/selector/src/runtime/tokenpilot/locator.ts +128 -0
  132. package/packages/selector/src/runtime/tokenpilot/read-state.ts +98 -0
  133. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -0
  134. package/packages/selector/src/runtime/toolclass.ts +103 -0
  135. package/packages/selector/src/runtime/types.ts +365 -0
  136. package/packages/selector/src/runtime/value.ts +48 -0
  137. package/packages/selector/src/settings-bridge.ts +175 -0
  138. package/packages/selector/tests/advisor-report.host.spec.ts +223 -0
  139. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -0
  140. package/packages/selector/tests/built/client-artifact.spec.ts +56 -0
  141. package/packages/selector/tests/cache-prefix-audit.spec.ts +123 -0
  142. package/packages/selector/tests/code-skeleton.client.spec.ts +98 -0
  143. package/packages/selector/tests/compat/compat-narrow-waist.spec.ts +150 -0
  144. package/packages/selector/tests/custom-contract.client.spec.ts +226 -0
  145. package/packages/selector/tests/estimator-catalog.spec.ts +70 -0
  146. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -0
  147. package/packages/selector/tests/estimator-route-registration.host.spec.ts +202 -0
  148. package/packages/selector/tests/fab-pos.client.spec.ts +47 -0
  149. package/packages/selector/tests/helpers/legacy-namespace.ts +35 -0
  150. package/packages/selector/tests/helpers/legacy-settings/index.ts +15 -0
  151. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +41 -0
  152. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +647 -0
  153. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +78 -0
  154. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +234 -0
  155. package/packages/selector/tests/host-preset-overlay.host.spec.ts +204 -0
  156. package/packages/selector/tests/monitor-fab.client.spec.ts +240 -0
  157. package/packages/selector/tests/preset-options-write.client.spec.ts +192 -0
  158. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +200 -0
  159. package/packages/selector/tests/preset-overlay.host.spec.ts +246 -0
  160. package/packages/selector/tests/profiles.client.spec.tsx +436 -0
  161. package/packages/selector/tests/public/package-contract.client.spec.ts +86 -0
  162. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +167 -0
  163. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +230 -0
  164. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -0
  165. package/packages/selector/tests/runtime/advisor.spec.ts +226 -0
  166. package/packages/selector/tests/runtime/audit.spec.ts +275 -0
  167. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -0
  168. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -0
  169. package/packages/selector/tests/runtime/code-skeleton.spec.ts +152 -0
  170. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +186 -0
  171. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -0
  172. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +122 -0
  173. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -0
  174. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +273 -0
  175. package/packages/selector/tests/runtime/fixtures/session-v4-dump.jsonl +46 -0
  176. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +106 -0
  177. package/packages/selector/tests/runtime/fixtures/vision-golden.json +459 -0
  178. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -0
  179. package/packages/selector/tests/runtime/fresh-gate.spec.ts +43 -0
  180. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -0
  181. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  182. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  183. package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +79 -0
  184. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -0
  185. package/packages/selector/tests/runtime/monitor.spec.ts +354 -0
  186. package/packages/selector/tests/runtime/panel-command.spec.ts +101 -0
  187. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -0
  188. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2781 -0
  189. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -0
  190. package/packages/selector/tests/runtime/savings-accounting.spec.ts +291 -0
  191. package/packages/selector/tests/runtime/savings-integral.spec.ts +169 -0
  192. package/packages/selector/tests/runtime/savings-projection.spec.ts +89 -0
  193. package/packages/selector/tests/runtime/savings-verify.spec.ts +226 -0
  194. package/packages/selector/tests/runtime/savings.spec.ts +139 -0
  195. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -0
  196. package/packages/selector/tests/runtime/session-events.spec.ts +27 -0
  197. package/packages/selector/tests/runtime/session-file-decode.spec.ts +281 -0
  198. package/packages/selector/tests/runtime/settings-unwrap.spec.ts +58 -0
  199. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -0
  200. package/packages/selector/tests/runtime/stats-backfill-scheduler.spec.ts +167 -0
  201. package/packages/selector/tests/runtime/stats-backfill.spec.ts +348 -0
  202. package/packages/selector/tests/runtime/stats-db.spec.ts +361 -0
  203. package/packages/selector/tests/runtime/stats-privacy.spec.ts +55 -0
  204. package/packages/selector/tests/runtime/stats-sync.spec.ts +278 -0
  205. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  206. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -0
  207. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +53 -0
  208. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -0
  209. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +52 -0
  210. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -0
  211. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +76 -0
  212. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +119 -0
  213. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +82 -0
  214. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -0
  215. package/packages/selector/tests/runtime/value.spec.ts +23 -0
  216. package/packages/selector/tests/savings-sessions.client.spec.tsx +140 -0
  217. package/packages/selector/tests/settings-seat.client.spec.ts +215 -0
  218. package/packages/selector/tests/standing-generation.host.spec.ts +724 -0
  219. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +269 -0
  220. package/packages/selector/tests/support/cache-prefix-audit.ts +105 -0
  221. package/packages/selector/tests/support/mock-adapter.ts +37 -0
  222. package/packages/selector/tests/support/ui-primitives.tsx +34 -0
  223. package/packages/selector/tsconfig.json +11 -0
  224. package/packages/selector/tsdown.client.config.ts +102 -0
  225. package/packages/selector/tsdown.config.ts +20 -0
  226. package/pnpm-workspace.yaml +76 -0
  227. package/screenshots.json +6 -3
  228. package/scripts/capture-profile-baseline.mjs +42 -0
  229. package/scripts/cell-browser-e2e.mjs +354 -0
  230. package/scripts/generate-tokenizer-fixtures.py +81 -0
  231. package/scripts/generate-vision-fixtures.py +208 -0
  232. package/scripts/hosts.mjs +78 -0
  233. package/scripts/packed-components-smoke.mjs +763 -0
  234. package/scripts/packed-install-e2e.mjs +1346 -0
  235. package/scripts/sync-hosts.mjs +174 -0
  236. package/scripts/toolclass-corpus-replay.mjs +281 -0
  237. package/scripts/verify-release.mjs +338 -0
  238. package/tests/TEST_INVENTORY.md +41 -0
  239. package/tsconfig.base.json +18 -0
  240. package/tsconfig.json +7 -0
  241. package/tsconfig.tests.json +15 -0
  242. package/vitest.built.config.ts +9 -0
  243. package/vitest.config.ts +54 -0
  244. /package/{assets → packages/selector/assets}/deepseek-v4/LICENSE.DeepSeek-V4-Pro.txt +0 -0
  245. /package/{assets → packages/selector/assets}/deepseek-v4/manifest.json +0 -0
  246. /package/{assets → packages/selector/assets}/deepseek-v4/tokenizer.json +0 -0
  247. /package/{assets → packages/selector/assets}/deepseek-v4/tokenizer_config.json +0 -0
  248. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/LICENSE.DeepSeek-V4-Flash-Vision-Exp.txt +0 -0
  249. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/manifest.json +0 -0
  250. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/tokenizer.json +0 -0
  251. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/tokenizer_config.json +0 -0
  252. /package/{cordis.patch.yml → packages/selector/cordis.patch.yml} +0 -0
  253. /package/{lib → packages/selector/lib}/client.d.ts +0 -0
  254. /package/{lib → packages/selector/lib}/client.js +0 -0
  255. /package/{lib → packages/selector/lib}/index.d.ts +0 -0
  256. /package/{lib → packages/selector/lib}/index.js +0 -0
  257. /package/{lib → packages/selector/lib}/invariant.d.ts +0 -0
  258. /package/{lib → packages/selector/lib}/invariant.js +0 -0
  259. /package/{lib → packages/selector/lib}/profiles.d.ts +0 -0
  260. /package/{lib → packages/selector/lib}/pruner.d.ts +0 -0
  261. /package/{lib → packages/selector/lib}/pruner.js +0 -0
  262. /package/{lib → packages/selector/lib}/savings-integral.js +0 -0
  263. /package/{lib → packages/selector/lib}/tail-trim.js +0 -0
  264. /package/{lib → packages/selector/lib}/tool-result.js +0 -0
@@ -0,0 +1,1754 @@
1
+ /** Deterministic, evidence-backed reducers for fresh tool results. */
2
+
3
+ import { codePointLength } from './config.ts'
4
+ import { classifyToolSource } from './toolclass.ts'
5
+
6
+ /** Input shared by every fresh-result reducer. */
7
+ export interface ReducerInput {
8
+ readonly toolName: string
9
+ readonly argumentsText: string
10
+ readonly text: string
11
+ readonly budgetChars: number
12
+ readonly sourceRef: string
13
+ readonly isError: boolean
14
+ /**
15
+ * Orthogonal user gate for the `hypa-code-skeleton` candidate. Absent or
16
+ * false keeps source-code content on its existing head/tail reducers.
17
+ */
18
+ readonly codeSkeleton?: boolean
19
+ }
20
+
21
+ /** One verified reducer candidate. */
22
+ export interface ReducerOutput {
23
+ readonly text: string
24
+ readonly reducer: string
25
+ readonly lossy: boolean
26
+ /**
27
+ * Structured telemetry (task_4c/G7): how many ORIGINAL-event lines the
28
+ * reducer elided, when the reducer knows it. Never printed into `text` —
29
+ * host-side logging is what turns this into the compress→retrieve M/N ratio.
30
+ */
31
+ readonly elidedLines?: number
32
+ }
33
+
34
+ /** Internal face every reducer sees: the normalized text plus its line mapping. */
35
+ type PreparedInput = ReducerInput & {
36
+ readonly lines: readonly NormalizedLine[]
37
+ /** Gutter-stripped view of `text`; form detection reads this, never `text`. */
38
+ readonly contentText: string
39
+ }
40
+
41
+ /**
42
+ * Optional side-channel ranking (S1a/S1b) handed to the form-dispatched
43
+ * reducers. Selection and order ONLY — the mechanical fold stays the sole
44
+ * content authority, and `undefined` reproduces the mechanical output
45
+ * byte-for-byte. The ranking itself always comes from outside the reducers:
46
+ * the mechanical layer never calls a model.
47
+ */
48
+ export interface ReductionRanking {
49
+ /** Search file paths, most relevant first (S1a). Unknown paths are ignored. */
50
+ readonly files?: readonly string[]
51
+ /** Document section heading texts, most relevant first (S1b). */
52
+ readonly sections?: readonly string[]
53
+ }
54
+
55
+ /**
56
+ * Per-file search node summaries for the S1a rank prompt (SC8: the judgment
57
+ * input must carry a content sample, not just the identifier). Derived from
58
+ * the raw event text.
59
+ */
60
+ export function searchNodeSummaries(text: string): readonly { readonly id: string, readonly count: number, readonly sample: string }[] {
61
+ const groups = new Map<string, { count: number, sample: string }>()
62
+ for (const line of splitLines(text)) {
63
+ const match = PATH_LINE_PATTERN.exec(line)
64
+ if (match === null) continue
65
+ const path = match[1] ?? '<unknown>'
66
+ const bucket = groups.get(path) ?? { count: 0, sample: Array.from(line.trim()).slice(0, 160).join('') }
67
+ bucket.count += 1
68
+ groups.set(path, bucket)
69
+ }
70
+ return [...groups.entries()].map(([id, bucket]) => ({ id, count: bucket.count, sample: bucket.sample }))
71
+ }
72
+
73
+ /**
74
+ * Per-section document node summaries for the S1b rank prompt: heading text,
75
+ * level, section character mass, and the section's first content line (AD9:
76
+ * headings are the author's structure, not the relevance structure).
77
+ */
78
+ export function documentSectionSummaries(text: string): readonly { readonly id: string, readonly level: number, readonly chars: number, readonly sample: string }[] {
79
+ const lines = splitLines(text)
80
+ const headings: { id: string, level: number, line: number }[] = []
81
+ for (let index = 0; index < lines.length; index++) {
82
+ const match = /^#{1,6}\s+(.*)$/.exec(lines[index] ?? '')
83
+ if (match !== null) headings.push({ id: match[1]!.trim(), level: (lines[index]!.match(/^#+/) ?? ['#'])[0]!.length, line: index })
84
+ }
85
+ return headings.map((heading, position) => {
86
+ const from = heading.line + 1
87
+ const to = position + 1 < headings.length ? headings[position + 1]!.line : lines.length
88
+ let chars = 0
89
+ let sample = ''
90
+ for (let index = from; index < to; index++) {
91
+ const line = lines[index] ?? ''
92
+ if (line.trim() === '') continue
93
+ chars += line.length + 1
94
+ if (sample === '') sample = Array.from(line.trim()).slice(0, 160).join('')
95
+ }
96
+ return { id: heading.id, level: heading.level, chars, sample }
97
+ })
98
+ }
99
+
100
+ /** Ranked-first ordering: ranked ids keep their rank, the rest append in order. */
101
+ function rankedFirst<T extends { readonly id: string }>(items: readonly T[], ranking: readonly string[] | undefined): readonly T[] {
102
+ if (ranking === undefined || ranking.length === 0) return items
103
+ const ranked = new Map<string, T>()
104
+ for (const id of ranking) {
105
+ const found = items.find(item => item.id === id)
106
+ if (found !== undefined && !ranked.has(id)) ranked.set(id, found)
107
+ }
108
+ return [...ranked.values(), ...items.filter(item => !ranked.has(item.id))]
109
+ }
110
+
111
+ const ANSI_PATTERN = /\u001B(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007]*(?:\u0007|\u001B\\))/gu
112
+ const IMPORTANT_PATTERN = new RegExp([
113
+ String.raw`\b(?:error|failed|failure|fatal|panic|exception|warning|warn|conflict|denied|forbidden|`,
114
+ String.raw`timeout|timed out|not found|cannot|unable|invalid|exit(?:ed)?\s+(?:code|status)|traceback|`,
115
+ String.raw`assert(?:ion)?|segmentation fault|oom|out of memory)\b`,
116
+ ].join(''), 'i')
117
+ const STATUS_PATTERN = new RegExp([
118
+ String.raw`\b(?:success|succeeded|passed|installed|added|removed|updated|built|compiled|`,
119
+ String.raw`tests?\s+(?:passed|failed)|exit(?:ed)?\s+(?:code|status))\b`,
120
+ ].join(''), 'i')
121
+ const PATH_LINE_PATTERN = /^(.*?):(\d+)(?::\d+)?(?::|\s+-\s+)(.*)$/
122
+ const GIT_STATUS_PATTERN = new RegExp([
123
+ String.raw`^(?:On branch|Your branch|HEAD detached|Changes |Untracked |Unmerged |\s*(?:modified|deleted|`,
124
+ String.raw`new file|renamed|both modified):)`,
125
+ ].join(''), 'i')
126
+ const CODE_IMPORT_PATTERN = new RegExp([
127
+ String.raw`^\s*(?:import\b|from\s+[\w.]+\s+import\b|use\s+\w|package\s+|#include\b|`,
128
+ String.raw`using\s+[\w.]+;|require\s*\(|extern\s+crate\b)`,
129
+ ].join(''))
130
+ const CODE_STRUCTURE_PATTERN = new RegExp([
131
+ String.raw`^\s*(?:@[\w.]+|export\s+|default\s+|declare\s+|abstract\s+|public\s+|private\s+|protected\s+|`,
132
+ String.raw`internal\s+|static\s+|final\s+|sealed\s+|override\s+|pub(?:\([^)]*\))?\s+|async\s+|unsafe\s+)*`,
133
+ String.raw`(?:function\b|class\b|interface\b|enum\b|struct\b|impl\b|trait\b|type\s+\w|fn\s|func\b|`,
134
+ String.raw`def\s|module\b|namespace\b|sub\s)`,
135
+ ].join(''))
136
+ const PYTHON_STRUCTURE_PATTERN = /^\s*(?:async\s+)?def\s|^\s*class\s/
137
+ const CODE_DECORATOR_PATTERN = /^\s*@[\w.]+/
138
+ const CODE_COMMENT_PATTERN = /^\s*(?:\/\/|#|\/\*|\*)/
139
+ const MARKDOWN_HEADING_PATTERN = /^#{1,6}\s+\S/
140
+ const LIST_ITEM_PATTERN = /^\s*(?:[-*+]|\d+[.)])\s+\S/
141
+ const TABLE_ROW_PATTERN = /^\s*\|/
142
+ const FENCE_PATTERN = /^\s*(?:```|~~~)/
143
+ const UUID_PATTERN = /\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/g
144
+ const LONG_HEX_PATTERN = /\b[0-9a-fA-F]{64,}\b/g
145
+ const LONG_BASE64_PATTERN = /[A-Za-z0-9+/]{200,}={0,2}/g
146
+ const HTML_TAG_PATTERN = /<!DOCTYPE html|<html\b|<head\b|<div\b|<span\b|<script\b|<style\b|<body\b|<p>|<table\b|<a\s/i
147
+ const HTML_COMMENT_PATTERN = /<!--[\s\S]*?-->/g
148
+ const HTML_DROPPED_ELEMENTS = /<(script|style|noscript|svg|head)\b[^>]*>[\s\S]*?<\/\1\s*>/gi
149
+ const HTML_DATA_URI_PATTERN = /\s(?:src|href)="data:[^"]*"/gi
150
+ const HTML_TAG_PATTERN_FULL = /<([a-z][a-z0-9]*)((?:\s[^<>]*?)?)\/?>/gi
151
+ const HTML_INLINE_TAG_PATTERN = /<\/?(?:em|strong|b|i|u|s|code|small|sub|sup|span|br)\b[^<>]*>/gi
152
+ const HTML_WHITELISTED_ATTRIBUTES = /\s(?:href|src|alt|title|id)="[^"]*"/gi
153
+ const ADJACENT_REPEAT_MARKER = '[previous line repeated'
154
+ /** Non-adjacent folding only pays off once a line recurs enough to beat the marker cost. */
155
+ const NON_ADJACENT_FOLD_THRESHOLD = 3
156
+ /** Read-output line-number gutter added unconditionally by the host's `formatReadOutput`. */
157
+ const READ_GUTTER_PATTERN = /^(\d+): ?/
158
+ /** JSONL/NDJSON preview: records kept from the head and tail of the stream. */
159
+ const JSONL_HEAD_RECORDS = 3
160
+ const JSONL_TAIL_RECORDS = 2
161
+ /** JSONL detection validates a bounded prefix so a multi-MB stream stays cheap. */
162
+ const JSONL_DETECT_SCAN = 512
163
+
164
+ /**
165
+ * Block-level read-gutter detection (GF-1). The host prefixes read output with
166
+ * `N: ` line numbers unconditionally and cannot be configured off. The gutter
167
+ * is only recognized when the block as a whole reads like a numbered listing —
168
+ * enough non-empty lines, a large majority guttered, and the numbers strictly
169
+ * increasing — so prose like `12:30 pm` (one stray gutter-looking line) is
170
+ * never stripped. The stripping happens on the CONTENT view only; the output
171
+ * view keeps the gutter because it is the model's only inline locator into the
172
+ * original file (and its measured cost, 9.16% of read bodies, never gets
173
+ * retrieved anyway).
174
+ */
175
+ function hasReadGutter(lines: readonly string[]): boolean {
176
+ let nonEmpty = 0
177
+ let guttered = 0
178
+ let previousNumber = 0
179
+ for (const line of lines) {
180
+ if (line.trim() === '') continue
181
+ nonEmpty += 1
182
+ const match = READ_GUTTER_PATTERN.exec(line)
183
+ if (match === null) continue
184
+ const number = Number(match[1])
185
+ if (number <= previousNumber) return false
186
+ previousNumber = number
187
+ guttered += 1
188
+ }
189
+ return nonEmpty >= 4 && guttered / nonEmpty >= 0.75
190
+ }
191
+
192
+ /**
193
+ * Replace long opaque literals with length summaries (R12). Data URIs, base64
194
+ * blobs, and long hex dumps are pure noise in a compressed view; the prefix is
195
+ * kept so the model can still recognize the value. Short strings are never
196
+ * touched, and replacements never span lines, so the line mapping survives.
197
+ */
198
+ function placeholderizeLongStrings(line: string): string {
199
+ if (!/[0-9a-zA-Z+/]{32}/.test(line) && !/\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-/.test(line)) return line
200
+ let result = line.replace(UUID_PATTERN, '[uuid]')
201
+ result = result.replace(LONG_HEX_PATTERN, (match) => `[hex ${String(match.length)} chars: ${match.slice(0, 16)}…]`)
202
+ result = result.replace(LONG_BASE64_PATTERN, (match) => `[base64 ${String(match.length)} chars: ${match.slice(0, 16)}…]`)
203
+ return result
204
+ }
205
+
206
+ /**
207
+ * Select a reducer from verified tool, command, and content evidence.
208
+ * @param input - original result text, recovery source, and output budget.
209
+ * @returns a verified candidate, or `null` when every reducer fails open.
210
+ */
211
+ export function reduceFreshToolResult(input: ReducerInput, ranking?: ReductionRanking): ReducerOutput | null {
212
+ const normalized = normalizeTerminalLines(input.text)
213
+ const prepared: PreparedInput = {
214
+ ...input,
215
+ text: normalized.text,
216
+ lines: normalized.folded,
217
+ contentText: normalized.contentText,
218
+ }
219
+ const command = extractCommand(input.argumentsText)
220
+ const name = input.toolName.toLowerCase()
221
+ const toolClass = classifyToolSource(input.toolName, command, normalized.contentText)
222
+ // TOC-first (G6): for a large read-class result the structure lines ARE the
223
+ // table of contents. The code skeleton gets a vote before head/tail
224
+ // truncation, without waiting for the orthogonal `codeSkeleton` user gate.
225
+ const readTocFirst = toolClass === 'read' && codePointLength(normalized.contentText) >= READ_TOC_MIN_CHARS
226
+ const candidates: Array<() => ReducerOutput | null> = []
227
+
228
+ // JSONL first: a line-delimited stream also passes `looksLikeJson` (its first
229
+ // and last chars are braces) yet `JSON.parse` of the whole blob fails, so the
230
+ // single-value branch would bail and silently drop it to head/tail. Detect the
231
+ // line form explicitly and give it a record-sampling preview.
232
+ if (looksLikeJsonl(normalized.contentText)) candidates.push(() => reduceJsonl(prepared))
233
+ else if (looksLikeJson(normalized.contentText)) candidates.push(() => reduceJson(prepared))
234
+ // R10-B (bundled/minified JS): must sit before every line-anchored candidate
235
+ // — a bundle's statement structure lives INSIDE lines, not at line starts.
236
+ if (looksLikeMinified(normalized.contentText)) candidates.push(() => reduceBundledJs(prepared))
237
+ if (toolClass === 'search') candidates.push(() => reduceSearch(prepared, ranking?.files))
238
+ if (isGitCommand(name, command)) candidates.push(() => reduceGit(prepared, command))
239
+ if (isPackageCommand(command)) candidates.push(() => reducePatternLog(prepared, 'hypa-package', packagePattern()))
240
+ if (isBuildOrTestCommand(command)) candidates.push(() => reducePatternLog(prepared, 'hypa-build-test', buildPattern()))
241
+ if (looksLikeSourceCode(normalized.contentText)) {
242
+ if (input.codeSkeleton === true) candidates.push(() => reduceCodeSkeleton(prepared))
243
+ else if (readTocFirst) candidates.push(() => tocGuardedCodeSkeleton(prepared))
244
+ }
245
+ // Form-dispatched prose candidates (R8/R8b): classification reads content
246
+ // shape only — never the tool name, the path extension, or the command.
247
+ if (looksLikeHtml(normalized.contentText)) candidates.push(() => reduceHtml(prepared))
248
+ if (looksLikeDocument(normalized.contentText)) candidates.push(() => reduceDocSkeleton(prepared, ranking?.sections))
249
+ if (toolClass === 'shell' || command !== '') candidates.push(() => reduceShell(prepared))
250
+ candidates.push(() => reduceProseKeep(prepared))
251
+ if (toolClass === 'read') candidates.push(() => reduceHead(prepared, 'pi-head'))
252
+ candidates.push(() => reduceSalient(prepared, 'generic-salience'))
253
+
254
+ for (const make of candidates) {
255
+ const candidate = make()
256
+ if (candidate !== null && verifyReduction(input, candidate)) return candidate
257
+ }
258
+ return null
259
+ }
260
+
261
+ /**
262
+ * Build a recoverable placeholder for an old tool result.
263
+ * @param input - tool identity, source reference, size, status, and retained evidence.
264
+ * @returns a lossy placeholder that cites the immutable source event.
265
+ */
266
+ export function historicalPlaceholder(input: {
267
+ readonly toolName: string
268
+ readonly sourceRef: string
269
+ readonly charsBefore: number
270
+ readonly isError: boolean
271
+ readonly text: string
272
+ readonly compact?: boolean
273
+ }): ReducerOutput {
274
+ const anchor = input.compact ? '' : importantAnchor(input.text, 360)
275
+ const normalized = normalizeTerminalLines(input.text)
276
+ // The placeholder replaces the ENTIRE result, so the elided span is the
277
+ // whole original event (task_4c/G7 telemetry; audit record only).
278
+ const lastFolded = normalized.folded.at(-1)
279
+ const elidedLines = lastFolded === undefined
280
+ ? undefined
281
+ : (lastFolded.originalLineEnd ?? lastFolded.originalLine)
282
+ // The retrieve hint starts at the anchor's ORIGINAL line: that is the one
283
+ // row of context worth re-reading first (R9b site).
284
+ const anchorLine = input.compact
285
+ ? undefined
286
+ : (normalized.folded
287
+ .find(line => IMPORTANT_PATTERN.test(line.text))
288
+ ?? undefined)?.originalLine
289
+ const retrieveHint = anchorLine === undefined
290
+ ? `retrieve: context_compression_retrieve({"ref":"${input.sourceRef}"})`
291
+ : `retrieve: context_compression_retrieve({"ref":"${input.sourceRef}","start_line":${String(anchorLine)},"max_lines":${String(RETRIEVE_HINT_MAX_LINES)}})`
292
+ const lines = [
293
+ '[Old tool result content cleared from active context]',
294
+ `tool: ${input.toolName || 'unknown'}`,
295
+ `status: ${input.isError ? 'error' : 'completed'}`,
296
+ `original_chars: ${String(input.charsBefore)}`,
297
+ `source: ${input.sourceRef}`,
298
+ retrieveHint,
299
+ ]
300
+ if (anchor !== '') lines.push(`retained_anchor: ${anchor}`)
301
+ return {
302
+ text: lines.join('\n'),
303
+ reducer: input.compact ? 'pair-preserving-tail-aging' : 'historical-tool-result-aging',
304
+ lossy: true,
305
+ ...(elidedLines === undefined ? {} : { elidedLines }),
306
+ }
307
+ }
308
+
309
+ /**
310
+ * Validate shrinkage, budget, recovery, and error retention.
311
+ * @param input - original reducer input and its safety requirements.
312
+ * @param output - candidate reduced text and reducer metadata.
313
+ * @returns whether the candidate is safe to land.
314
+ */
315
+ export function verifyReduction(input: ReducerInput, output: ReducerOutput): boolean {
316
+ const before = codePointLength(input.text)
317
+ const after = codePointLength(output.text)
318
+ if (after <= 0 || after >= before || after > input.budgetChars) return false
319
+ if (output.lossy && !output.text.includes(input.sourceRef)) return false
320
+ if ((input.isError || IMPORTANT_PATTERN.test(input.text))
321
+ && !IMPORTANT_PATTERN.test(output.text) && !output.text.includes('status: error')) return false
322
+ return true
323
+ }
324
+
325
+ /**
326
+ * Strip ANSI, collapse carriage-return progress redraws, and fold exact repeats.
327
+ * @param text - raw terminal output.
328
+ * @returns normalized terminal text.
329
+ */
330
+ export function normalizeTerminalText(text: string): string {
331
+ return normalizeTerminalLines(text).text
332
+ }
333
+
334
+ /** One folded output line that remembers its place in the original event. */
335
+ export interface NormalizedLine {
336
+ /** Output view: byte-identical with the original event line (gutter kept). */
337
+ readonly text: string
338
+ /**
339
+ * Content view: the same line with a block-detected read gutter (`N: `)
340
+ * stripped. Form detection, skeleton retention, and repeat keys read this;
341
+ * the printed output never does (GF-1 dual view).
342
+ */
343
+ readonly content: string
344
+ /** 1-based line number in the ORIGINAL event text (before normalization). */
345
+ readonly originalLine: number
346
+ /**
347
+ * Last original line this entry covers. Only the synthetic repeat marker
348
+ * spans more than one original line (the occurrences it replaces).
349
+ */
350
+ readonly originalLineEnd?: number
351
+ }
352
+
353
+ export interface NormalizedTerminal {
354
+ /** Adjacent-duplicate-folded lines; `folded.map(l => l.text).join('\n')` is `text`. */
355
+ readonly folded: readonly NormalizedLine[]
356
+ /** The folded text, byte-identical with `normalizeTerminalText`. */
357
+ readonly text: string
358
+ /** The folded text with the read gutter stripped (detection view). */
359
+ readonly contentText: string
360
+ }
361
+
362
+ /**
363
+ * Structured normalization (R9a): `retrieve` reads the original event, so any
364
+ * line number a reducer prints must resolve against the ORIGINAL text, not the
365
+ * normalized surface. ANSI stripping and `\r` redraw collapse never change the
366
+ * line count (logical lines are 1:1 with original lines); only the adjacent
367
+ * duplicate fold drops lines, so every folded entry carries the original line
368
+ * (range) it was kept from.
369
+ */
370
+ export function normalizeTerminalLines(text: string): NormalizedTerminal {
371
+ const withoutAnsi = text.replace(ANSI_PATTERN, '')
372
+ const logical = withoutAnsi.split('\n').map((line) => {
373
+ const redraws = line.split('\r').filter(part => part !== '')
374
+ return placeholderizeLongStrings(redraws.at(-1) ?? '')
375
+ })
376
+ const stripGutter = hasReadGutter(logical)
377
+ const folded: NormalizedLine[] = []
378
+ let previous: string | undefined
379
+ let firstText = ''
380
+ let count = 0
381
+ let firstOriginal = 0
382
+ const flush = (nextOriginal: number): void => {
383
+ if (previous === undefined) return
384
+ folded.push({ text: firstText, content: previous, originalLine: firstOriginal })
385
+ if (count > 1) {
386
+ const marker = `[previous line repeated ${String(count - 1)} more times]`
387
+ folded.push({
388
+ text: marker,
389
+ content: marker,
390
+ originalLine: firstOriginal + 1,
391
+ originalLineEnd: nextOriginal - 1,
392
+ })
393
+ }
394
+ }
395
+ logical.forEach((line, index) => {
396
+ const originalLine = index + 1
397
+ const content = stripGutter ? line.replace(READ_GUTTER_PATTERN, '') : line
398
+ if (content === previous) {
399
+ count++
400
+ return
401
+ }
402
+ flush(originalLine)
403
+ previous = content
404
+ firstText = line
405
+ count = 1
406
+ firstOriginal = originalLine
407
+ })
408
+ flush(logical.length + 1)
409
+ const result = foldNonAdjacentRepeats(folded)
410
+ return {
411
+ folded: result,
412
+ text: result.map(line => line.text).join('\n'),
413
+ contentText: result.map(line => line.content).join('\n'),
414
+ }
415
+ }
416
+
417
+ /**
418
+ * Fold non-adjacent exact repeats (R11). Adjacent folding runs FIRST and only
419
+ * handles consecutive runs (0.03–0.32% of real duplicate content); separated
420
+ * repeats reached 8.37% in large results. Each surviving occurrence — a kept
421
+ * line plus its optional adjacent-repeat marker — is one unit; once a text
422
+ * recurs ≥ threshold times, the first unit is kept and every later unit is
423
+ * replaced by ONE counted marker citing the original-event span it covers.
424
+ * A pure consecutive run forms a single unit, so this pass is a no-op on it
425
+ * and can never double-fold the adjacent marker.
426
+ */
427
+ function foldNonAdjacentRepeats(folded: readonly NormalizedLine[]): NormalizedLine[] {
428
+ interface Unit { readonly lead: NormalizedLine, repeat?: NormalizedLine }
429
+ const units: Unit[] = []
430
+ for (const entry of folded) {
431
+ if (entry.text.startsWith(ADJACENT_REPEAT_MARKER) && units.length > 0) {
432
+ units[units.length - 1]!.repeat = entry
433
+ } else {
434
+ units.push({ lead: entry })
435
+ }
436
+ }
437
+ const totals = new Map<string, number>()
438
+ for (const unit of units) totals.set(unit.lead.content, (totals.get(unit.lead.content) ?? 0) + 1)
439
+ if (totals.size === units.length) return [...folded]
440
+ // Precompute, per repeated text, where the first kept occurrence and the
441
+ // last folded occurrence sit in the ORIGINAL event. Keys are the CONTENT
442
+ // view: guttered read output numbers every line, so `900: )` and `950: )`
443
+ // are different strings in the output view but the same content.
444
+ const firstOriginal = new Map<string, number>()
445
+ const lastOriginalEnd = new Map<string, number>()
446
+ for (const unit of units) {
447
+ const content = unit.lead.content
448
+ if (totals.get(content)! < NON_ADJACENT_FOLD_THRESHOLD) continue
449
+ if (!firstOriginal.has(content)) firstOriginal.set(content, unit.lead.originalLine)
450
+ const end = unit.repeat?.originalLineEnd ?? unit.lead.originalLineEnd ?? unit.lead.originalLine
451
+ lastOriginalEnd.set(content, end)
452
+ }
453
+ const seen = new Map<string, number>()
454
+ const result: NormalizedLine[] = []
455
+ for (const unit of units) {
456
+ const content = unit.lead.content
457
+ const total = totals.get(content)!
458
+ if (total < NON_ADJACENT_FOLD_THRESHOLD) {
459
+ result.push(unit.lead)
460
+ if (unit.repeat !== undefined) result.push(unit.repeat)
461
+ continue
462
+ }
463
+ if (!seen.has(content)) {
464
+ seen.set(content, 1)
465
+ result.push(unit.lead)
466
+ if (unit.repeat !== undefined) result.push(unit.repeat)
467
+ continue
468
+ }
469
+ const ordinal = (seen.get(content) ?? 1) + 1
470
+ seen.set(content, ordinal)
471
+ if (ordinal > 2) continue
472
+ const end = lastOriginalEnd.get(content)!
473
+ const marker = `[× ${String(total)} total: same as line ${String(firstOriginal.get(content)!)}; original lines ${String(unit.lead.originalLine)}-${String(end)}]`
474
+ result.push({
475
+ text: marker,
476
+ content: marker,
477
+ originalLine: unit.lead.originalLine,
478
+ originalLineEnd: end,
479
+ })
480
+ }
481
+ return result
482
+ }
483
+
484
+ /** Default line window a retrieve hint suggests the model paste. */
485
+ const RETRIEVE_HINT_MAX_LINES = 80
486
+
487
+ /**
488
+ * TOC-first (G6): read-class results at or above this size let the code
489
+ * skeleton compete before head/tail truncation. The 14,000-char boundary is
490
+ * the studied real-read cohort (findings §7), well above p90 of actual reads
491
+ * so ordinary results keep their existing dispatch.
492
+ */
493
+ const READ_TOC_MIN_CHARS = 14_000
494
+ /**
495
+ * A skeleton whose output is dominated by elision markers is worse than
496
+ * head/tail for the model (task_4b risk: structure-poor files degenerate into
497
+ * "almost all markers") — above this marker-char share the TOC candidate fails
498
+ * open to the prose reducers.
499
+ */
500
+ const TOC_MARKER_RATIO_LIMIT = 0.5
501
+
502
+ /**
503
+ * Fail-open wrapper for the TOC-first code-skeleton candidate: a skeleton that
504
+ * degenerates into mostly-elision markers (minified bundles, generated files)
505
+ * returns null so the prose head/tail pair takes over.
506
+ */
507
+ function tocGuardedCodeSkeleton(input: PreparedInput): ReducerOutput | null {
508
+ const output = reduceCodeSkeleton(input)
509
+ if (output === null) return null
510
+ const total = codePointLength(output.text)
511
+ const markerChars = output.text.split('\n')
512
+ .filter(line => line.startsWith('[...'))
513
+ .reduce((sum, line) => sum + codePointLength(line) + 1, 0)
514
+ return markerChars / total > TOC_MARKER_RATIO_LIMIT ? null : output
515
+ }
516
+
517
+ /** R10a thresholds: one giant line, uniformly fat lines, or very few fat lines. */
518
+ const MINIFIED_MAX_LINE_CHARS = 2_000
519
+ const MINIFIED_AVG_LINE_CHARS = 300
520
+ const MINIFIED_FEW_LINES = 40
521
+ const MINIFIED_FEW_LINES_TOTAL_CHARS = 20_000
522
+
523
+ /**
524
+ * Require form evidence of a bundled/minified module (R10a): line-anchored
525
+ * reducers cannot see inside a 135k-character line, and R9 line ranges on a
526
+ * 53-line bundle cannot address anything smaller than the whole file.
527
+ * @param text - normalized result text.
528
+ * @returns whether the text reads as a bundled/minified module.
529
+ */
530
+ export function looksLikeMinified(text: string): boolean {
531
+ const lines = splitLines(text)
532
+ if (lines.length === 0) return false
533
+ let total = 0
534
+ let max = 0
535
+ for (const line of lines) {
536
+ const length = line.length
537
+ total += length
538
+ if (length > max) max = length
539
+ }
540
+ if (max > MINIFIED_MAX_LINE_CHARS) return true
541
+ if (total / lines.length > MINIFIED_AVG_LINE_CHARS) return true
542
+ return lines.length < MINIFIED_FEW_LINES && total > MINIFIED_FEW_LINES_TOTAL_CHARS
543
+ }
544
+
545
+ /**
546
+ * Statement-level declaration patterns scanned GLOBALLY per line: a bundle's
547
+ * statements are separated by `;` / `},{` / `);` inside one physical line, so
548
+ * line-anchored matching is useless here. Reserved-name traces (`exports.*`,
549
+ * `module.exports`) are extracted first and called out in the header because
550
+ * minifiers rename local symbols.
551
+ */
552
+ const BUNDLED_DECLARATION_PATTERNS: readonly RegExp[] = [
553
+ /\bexports\.([A-Za-z_$][\w$]*)\s*=/g,
554
+ /\bmodule\.exports\s*=\s*([A-Za-z_$][\w$]*)/g,
555
+ /\b(?:function|class)\s+([A-Za-z_$][\w$]*)/g,
556
+ /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=/g,
557
+ /\b([A-Za-z_$][\w$]*)\s*:\s*function\b/g,
558
+ ]
559
+ const SOURCEMAP_DIRECTIVE = '//# sourceMappingURL='
560
+
561
+ /**
562
+ * Bundled/minified JS directory (R10-B). The useful first answer is the
563
+ * declaration/export directory — WHAT the bundle exposes — plus one honest
564
+ * whole-span marker: the host's continuation is line-addressed, so a
565
+ * line-range retrieve on a 53-line bundle hands back the whole file (R10d:
566
+ * character-range retrieval is a separate, undecided extension).
567
+ */
568
+ function reduceBundledJs(input: PreparedInput): ReducerOutput | null {
569
+ const declarations = new Map<string, number>()
570
+ for (const line of input.lines) {
571
+ for (const pattern of BUNDLED_DECLARATION_PATTERNS) {
572
+ pattern.lastIndex = 0
573
+ let match = pattern.exec(line.content)
574
+ while (match !== null) {
575
+ const symbol = match[1]
576
+ if (symbol !== undefined && !declarations.has(symbol)) declarations.set(symbol, line.originalLine)
577
+ match = pattern.exec(line.content)
578
+ }
579
+ }
580
+ }
581
+ if (declarations.size === 0) return null
582
+ const hasSourceMap = input.contentText.includes(SOURCEMAP_DIRECTIVE)
583
+ const entries = [...declarations.entries()].sort((a, b) => a[1] - b[1])
584
+ const header = `[bundled/minified JS detected; ${String(entries.length)} declarations; minified symbols may be renamed — exports.*/module.exports traces are the reliable ones;${hasSourceMap ? ' source map present, prefer reading the original source;' : ''} source: ${input.sourceRef}; retrieve with context_compression_retrieve({"ref":"${input.sourceRef}"}) (line-addressed: single-line bundles come back whole)]`
585
+ const kept = [header, ...entries.slice(0, 400).map(([symbol, line]) => `${symbol} (line ${String(line)})`)]
586
+ const start = input.lines[0]?.originalLine ?? 1
587
+ const end = originalEnd(input.lines, input.lines.length - 1)
588
+ if (end > start) kept.push(elidedRangeMarker(start, end))
589
+ const text = fitLines(kept, input.budgetChars, input.sourceRef)
590
+ return text === null ? null : { text, reducer: 'bundled-js-directory', lossy: true }
591
+ }
592
+
593
+ /**
594
+ * Continuous-mask marker (R9b): cites the ORIGINAL-event line range it elides
595
+ * and carries a pasteable retrieve hint starting at the first elided line.
596
+ * Falls back to the compact plain marker when the hint would not fit.
597
+ */
598
+ function reduceHead(input: PreparedInput, reducer: string): ReducerOutput | null {
599
+ const marker = omissionMarker(input, reducer)
600
+ const available = input.budgetChars - codePointLength(marker) - 1
601
+ if (available <= 0) return null
602
+ const head = takeWholeLinesFromHead(input.text, available)
603
+ if (head === input.text || head === '') return null
604
+ const keptCount = head.split('\n').length
605
+ const firstElided = input.lines[keptCount]
606
+ if (firstElided !== undefined) {
607
+ const elidedEnd = originalEnd(input.lines, input.lines.length - 1)
608
+ const ranged = rangeOmissionMarker(input, reducer, firstElided.originalLine, elidedEnd)
609
+ if (codePointLength(head) + codePointLength(ranged) + 1 <= input.budgetChars) {
610
+ return { text: `${head}\n${ranged}`, reducer, lossy: true }
611
+ }
612
+ }
613
+ return { text: `${head}\n${marker}`, reducer, lossy: true }
614
+ }
615
+
616
+ function reduceTail(input: PreparedInput, reducer: string): ReducerOutput | null {
617
+ const marker = omissionMarker(input, reducer)
618
+ const available = input.budgetChars - codePointLength(marker) - 1
619
+ if (available <= 0) return null
620
+ const tail = takeWholeLinesFromTail(input.text, available)
621
+ if (tail === input.text || tail === '') return null
622
+ const firstKept = input.lines.length - tail.split('\n').length
623
+ if (firstKept > 0) {
624
+ const elidedEnd = originalEnd(input.lines, firstKept - 1)
625
+ const ranged = rangeOmissionMarker(input, reducer, input.lines[0]!.originalLine, elidedEnd)
626
+ if (codePointLength(ranged) + codePointLength(tail) + 1 <= input.budgetChars) {
627
+ return { text: `${ranged}\n${tail}`, reducer, lossy: true }
628
+ }
629
+ }
630
+ return { text: `${marker}\n${tail}`, reducer, lossy: true }
631
+ }
632
+
633
+ function reduceJson(input: PreparedInput): ReducerOutput | null {
634
+ let value: unknown
635
+ try {
636
+ value = JSON.parse(input.text)
637
+ } catch {
638
+ return null
639
+ }
640
+ const minified = JSON.stringify(value)
641
+ if (codePointLength(minified) < codePointLength(input.text)
642
+ && codePointLength(minified) <= input.budgetChars) {
643
+ return { text: minified, reducer: 'json-minify', lossy: false }
644
+ }
645
+ const envelope = {
646
+ $dsh_compression: {
647
+ kind: 'json-preview',
648
+ source: input.sourceRef,
649
+ original_chars: codePointLength(input.text),
650
+ },
651
+ value: shrinkJson(value, 0),
652
+ }
653
+ const text = JSON.stringify(envelope, null, 2)
654
+ if (codePointLength(text) <= input.budgetChars) {
655
+ return { text, reducer: 'json-structure-preview', lossy: true }
656
+ }
657
+ return null
658
+ }
659
+
660
+ /**
661
+ * Reduce line-delimited JSON (JSONL/NDJSON): keep a head and tail sample of
662
+ * records — each run through the same `shrinkJson` as the single-value branch —
663
+ * and collapse the middle into an omitted-record count. Reads the gutter-
664
+ * stripped content view so a host read listing (`N: ` prefix) still resolves.
665
+ * Returns null when the sampled envelope cannot fit the budget (or when there
666
+ * are too few records to omit anything), letting head/tail take over.
667
+ */
668
+ function reduceJsonl(input: PreparedInput): ReducerOutput | null {
669
+ const recordLines: string[] = []
670
+ for (const line of input.contentText.split('\n')) {
671
+ const trimmed = line.trim()
672
+ if (trimmed !== '' && (trimmed.startsWith('{') || trimmed.startsWith('['))) recordLines.push(trimmed)
673
+ }
674
+ const total = recordLines.length
675
+ if (total < 2) return null
676
+ const parseRecord = (text: string): unknown => {
677
+ try {
678
+ return JSON.parse(text) as unknown
679
+ } catch {
680
+ return text
681
+ }
682
+ }
683
+ const headCount = Math.min(JSONL_HEAD_RECORDS, total)
684
+ const tailCount = total > headCount ? Math.min(JSONL_TAIL_RECORDS, total - headCount) : 0
685
+ const head = recordLines.slice(0, headCount).map(entry => shrinkJson(parseRecord(entry), 0))
686
+ const tail = tailCount > 0
687
+ ? recordLines.slice(total - tailCount).map(entry => shrinkJson(parseRecord(entry), 0))
688
+ : []
689
+ const omitted = total - headCount - tailCount
690
+ const envelope: Record<string, unknown> = {
691
+ $dsh_compression: {
692
+ kind: 'jsonl-preview',
693
+ source: input.sourceRef,
694
+ original_chars: codePointLength(input.text),
695
+ records: total,
696
+ },
697
+ head,
698
+ }
699
+ if (omitted > 0) envelope.$dsh_omitted_records = omitted
700
+ if (tail.length > 0) envelope.tail = tail
701
+ const text = JSON.stringify(envelope, null, 2)
702
+ if (codePointLength(text) >= codePointLength(input.text) || codePointLength(text) > input.budgetChars) return null
703
+ return { text, reducer: 'jsonl-structure-preview', lossy: true }
704
+ }
705
+
706
+ /**
707
+ * Detect JSONL/NDJSON: at least two non-empty lines, each of which parses on
708
+ * its own as a JSON object or array. A pretty-printed single JSON fails this
709
+ * (its interior lines are not standalone values), so the two forms never
710
+ * collide. Only a bounded prefix is validated to keep multi-MB streams cheap.
711
+ */
712
+ function looksLikeJsonl(text: string): boolean {
713
+ let records = 0
714
+ for (const line of text.split('\n')) {
715
+ const trimmed = line.trim()
716
+ if (trimmed === '') continue
717
+ if (!(trimmed.startsWith('{') || trimmed.startsWith('['))) return false
718
+ try {
719
+ const parsed = JSON.parse(trimmed) as unknown
720
+ if (typeof parsed !== 'object' || parsed === null) return false
721
+ records += 1
722
+ } catch {
723
+ return false
724
+ }
725
+ if (records >= JSONL_DETECT_SCAN) break
726
+ }
727
+ return records >= 2
728
+ }
729
+
730
+ function shrinkJson(value: unknown, depth: number): unknown {
731
+ if (depth >= 5) {
732
+ if (Array.isArray(value)) return `[array length=${String(value.length)} omitted]`
733
+ if (typeof value === 'object' && value !== null) return '[object omitted]'
734
+ return value
735
+ }
736
+ if (Array.isArray(value)) {
737
+ if (value.length <= 8) return value.map(entry => shrinkJson(entry, depth + 1))
738
+ return [
739
+ ...value.slice(0, 3).map(entry => shrinkJson(entry, depth + 1)),
740
+ { $dsh_omitted_items: value.length - 5 },
741
+ ...value.slice(-2).map(entry => shrinkJson(entry, depth + 1)),
742
+ ]
743
+ }
744
+ if (typeof value !== 'object' || value === null) {
745
+ if (typeof value === 'string' && codePointLength(value) > 800) {
746
+ return `${Array.from(value).slice(0, 500).join('')}…[${String(codePointLength(value) - 700)} chars omitted]…${Array.from(value).slice(-200).join('')}`
747
+ }
748
+ return value
749
+ }
750
+ const entries = Object.entries(value)
751
+ const important = entries.filter(([key]) => /error|warn|status|code|message|path|file|line|summary/i.test(key))
752
+ const selected = entries.length <= 18
753
+ ? entries
754
+ : [...entries.slice(0, 10), ...important.filter(entry => !entries.slice(0, 10).includes(entry)).slice(0, 6), ...entries.slice(-2)]
755
+ const result: Record<string, unknown> = {}
756
+ for (const [key, entry] of selected) result[key] = shrinkJson(entry, depth + 1)
757
+ if (selected.length < entries.length) result.$dsh_omitted_keys = entries.length - selected.length
758
+ return result
759
+ }
760
+
761
+ /**
762
+ * Two-tier search folding (R10). L1 is a LOSSLESS per-file locator —
763
+ * `## <path> (<N> matches) L12,L15,…` — one line number per hit, taken from
764
+ * the hit's own `path:line` prefix (falling back to the original-event line).
765
+ * L2 is the content quota, water-filled round-robin so no file vanishes and
766
+ * no file runs more than one row ahead of another; the budget is reserved for
767
+ * L1 first. When L1 itself cannot fit, the shortfall is ANNOUNCED
768
+ * (withheld file/match counts) — never silently truncated. Outputs without
769
+ * any `path:line` form fail open to salience.
770
+ */
771
+ function reduceSearch(input: PreparedInput, fileRanking?: readonly string[]): ReducerOutput | null {
772
+ interface Row { readonly text: string, readonly fileLine: number, readonly important: boolean }
773
+ const groups = new Map<string, Row[]>()
774
+ const ungrouped: Row[] = []
775
+ input.lines.forEach((line) => {
776
+ const match = PATH_LINE_PATTERN.exec(line.text)
777
+ const row: Row = {
778
+ text: line.text,
779
+ fileLine: match !== null ? Number(match[2]) : line.originalLine,
780
+ important: IMPORTANT_PATTERN.test(line.text),
781
+ }
782
+ if (match === null) {
783
+ ungrouped.push(row)
784
+ return
785
+ }
786
+ const path = match[1] ?? '<unknown>'
787
+ const bucket = groups.get(path) ?? []
788
+ bucket.push(row)
789
+ groups.set(path, bucket)
790
+ })
791
+ if (groups.size === 0) return reduceSalient(input, 'search-salience')
792
+
793
+ const totalMatches = [...groups.values()].reduce((sum, rows) => sum + rows.length, 0)
794
+ const locatorFor = (path: string, rows: readonly Row[]): string =>
795
+ `## ${path} (${String(rows.length)} matches) ${rows.map(row => `L${String(row.fileLine)}`).join(',')}`
796
+ // Rows within a file are offered to the quota important-first, then by
797
+ // line. Files are visited in side-channel rank order when one was supplied
798
+ // (ranked files first, the rest in original order) — the water-filling
799
+ // round order is the only thing ranking changes.
800
+ const perFile = new Map<string, Row[]>()
801
+ for (const entry of rankedFirst([...groups.entries()].map(([id, rows]) => ({ id, rows })), fileRanking)) {
802
+ perFile.set(entry.id, [...entry.rows].sort((a, b) => a.important === b.important
803
+ ? a.fileLine - b.fileLine
804
+ : a.important ? -1 : 1))
805
+ }
806
+ const allLocators = [...perFile.keys()].map(path => locatorFor(path, groups.get(path)!))
807
+
808
+ const headerFor = (l2Rows: number, omitted: number): string =>
809
+ `[search results compressed; ${String(groups.size)} files, ${String(totalMatches)} matches; ${String(l2Rows)} content rows shown, ${String(omitted)} matches omitted; source: ${input.sourceRef}; retrieve with context_compression_retrieve({"ref":"${input.sourceRef}"})]`
810
+
811
+ // L2 water-filling: one unchosen row per file per round, so no file
812
+ // disappears and no file outpaces another by more than one round. Important
813
+ // rows are offered first within each file.
814
+ const fillL2 = (output: string[], quotaChars: number): { shown: number, omitted: number } => {
815
+ let used = 0
816
+ let shown = 0
817
+ let round = 0
818
+ let progress = true
819
+ while (progress && round < 512) {
820
+ progress = false
821
+ for (const rows of perFile.values()) {
822
+ if (round >= rows.length) continue
823
+ const row = rows[round]!
824
+ const cost = codePointLength(row.text) + 1
825
+ if (used + cost > quotaChars) continue
826
+ output.push(row.text)
827
+ used += cost
828
+ shown += 1
829
+ progress = true
830
+ }
831
+ round += 1
832
+ }
833
+ // Locator-less important rows keep their bounded salience slot.
834
+ for (const row of ungrouped.filter(entry => entry.important).slice(0, 12)) {
835
+ const cost = codePointLength(row.text) + 1
836
+ if (used + cost > quotaChars) break
837
+ output.push(row.text)
838
+ used += cost
839
+ shown += 1
840
+ }
841
+ return { shown, omitted: totalMatches - shown }
842
+ }
843
+
844
+ const finish = (output: readonly string[]): ReducerOutput | null => {
845
+ const text = output.join('\n')
846
+ return text.includes(input.sourceRef) ? { text, reducer: 'search-by-file', lossy: true } : null
847
+ }
848
+
849
+ const headerProbe = headerFor(0, 0)
850
+ const budget = input.budgetChars - codePointLength(headerProbe) - 2
851
+ if (budget <= 0) return null
852
+ const locatorCost = allLocators.reduce((sum, line) => sum + codePointLength(line) + 1, 0)
853
+ if (locatorCost > budget) {
854
+ // Visible degradation: include locators while they fit, ANNOUNCE the rest.
855
+ // The announcement line's own cost is reserved up front so the final text
856
+ // stays inside the budget and survives verifyReduction.
857
+ const announcementReserve = 160
858
+ const output: string[] = []
859
+ let used = 0
860
+ let withheldFiles = 0
861
+ let withheldMatches = 0
862
+ for (let index = 0; index < allLocators.length; index++) {
863
+ const cost = codePointLength(allLocators[index]!) + 1 + announcementReserve
864
+ if (used + cost > budget) {
865
+ withheldFiles = allLocators.length - index
866
+ withheldMatches = totalMatches
867
+ - [...groups.values()].slice(0, index).reduce((sum, rows) => sum + rows.length, 0)
868
+ break
869
+ }
870
+ output.push(allLocators[index]!)
871
+ used += cost - announcementReserve
872
+ }
873
+ if (withheldFiles > 0) {
874
+ output.push(`[L1 locator partially withheld: ${String(withheldFiles)} file(s) / ${String(withheldMatches)} matches' line lists did not fit the budget; retrieve for the full hit list]`)
875
+ }
876
+ const { shown, omitted } = fillL2(output, Math.max(0, budget - used - (withheldFiles > 0 ? announcementReserve : 0)))
877
+ output.unshift(headerFor(shown, omitted + withheldMatches))
878
+ return finish(output)
879
+ }
880
+ const output: string[] = [...allLocators]
881
+ const { shown, omitted } = fillL2(output, budget - locatorCost)
882
+ output.unshift(headerFor(shown, omitted))
883
+ return finish(output)
884
+ }
885
+
886
+ function reduceGit(input: PreparedInput, command: string): ReducerOutput | null {
887
+ const lines = input.lines
888
+ const lower = command.toLowerCase()
889
+ let keep: string[]
890
+ let reducer: string
891
+ if (/\bgit\s+(?:diff|show)\b/.test(lower)) {
892
+ reducer = 'hypa-git-diff'
893
+ keep = lines.map(line => line.text).filter(line => /^(?:diff --git|index |--- |\+\+\+ |@@ |[+-](?![+-]))/.test(line)
894
+ || IMPORTANT_PATTERN.test(line))
895
+ } else if (/\bgit\s+(?:status|switch|checkout|merge|rebase|cherry-pick)\b/.test(lower)) {
896
+ reducer = 'hypa-git-status'
897
+ keep = lines.map(line => line.text).filter(line => GIT_STATUS_PATTERN.test(line)
898
+ || IMPORTANT_PATTERN.test(line))
899
+ } else {
900
+ reducer = 'hypa-git-log'
901
+ keep = lines.map(line => line.text).filter(line => /^(?:commit\s+[0-9a-f]+|Author:|Date:|[0-9a-f]{7,}\s)/i.test(line)
902
+ || IMPORTANT_PATTERN.test(line))
903
+ }
904
+ if (keep.length === 0) return reduceSalient(input, reducer)
905
+ const header = `[git output compressed; ${scannedTotals(input, keep.length)}; source: ${input.sourceRef}; scatter-masked: retrieve with context_compression_retrieve({"ref":"${input.sourceRef}","query":"<keyword>"}) for missed rows]`
906
+ const text = fitLines([header, ...keep, ...lines.slice(-8).map(line => line.text)], input.budgetChars, input.sourceRef)
907
+ return text === null ? null : { text, reducer, lossy: true }
908
+ }
909
+
910
+ function reducePatternLog(input: PreparedInput, reducer: string, pattern: RegExp): ReducerOutput | null {
911
+ const lines = input.lines
912
+ const kept = lines.filter(line => pattern.test(line.text) || IMPORTANT_PATTERN.test(line.text) || STATUS_PATTERN.test(line.text))
913
+ const header = `[command output compressed by ${reducer}; ${scannedTotals(input, kept.length)}; source: ${input.sourceRef}; scatter-masked: retrieve with context_compression_retrieve({"ref":"${input.sourceRef}","query":"<keyword>"}) for missed rows]`
914
+ const text = fitLines([header, ...kept.map(line => line.text), ...lines.slice(-20).map(line => line.text)], input.budgetChars, input.sourceRef)
915
+ return text === null ? null : { text, reducer, lossy: true }
916
+ }
917
+
918
+ function reduceShell(input: PreparedInput): ReducerOutput | null {
919
+ const lines = input.lines
920
+ const important = lines.filter(line => IMPORTANT_PATTERN.test(line.text))
921
+ if (important.length === 0) return reduceTail(input, 'pi-tail')
922
+ const header = `[shell/log output compressed; ${scannedTotals(input, important.length)}; source: ${input.sourceRef}; scatter-masked: retrieve with context_compression_retrieve({"ref":"${input.sourceRef}","query":"<keyword>"}) for missed rows]`
923
+ const text = fitLines([header, ...important.map(line => line.text), '--- final output ---', ...lines.slice(-40).map(line => line.text)], input.budgetChars, input.sourceRef)
924
+ return text === null ? null : { text, reducer: 'shell-salience-tail', lossy: true }
925
+ }
926
+
927
+ function reduceSalient(input: PreparedInput, reducer: string): ReducerOutput | null {
928
+ const lines = input.lines
929
+ if (lines.length < 3) return reduceHead(input, reducer)
930
+ const marker = omissionMarker(input, reducer)
931
+ const headBudget = Math.max(1, Math.floor((input.budgetChars - codePointLength(marker)) * 0.34))
932
+ const tailBudget = headBudget
933
+ const head = takeWholeLinesFromHead(input.text, headBudget)
934
+ const tail = takeWholeLinesFromTail(input.text, tailBudget)
935
+ const salient = lines.filter(line => IMPORTANT_PATTERN.test(line.text) || STATUS_PATTERN.test(line.text)).slice(0, 24)
936
+ const keptCount = head.split('\n').length + salient.length + tail.split('\n').length
937
+ const text = fitLines([head, ...salient.map(line => line.text), `${marker} [${scannedTotals(input, keptCount)}]`, tail], input.budgetChars, input.sourceRef)
938
+ return text === null ? null : { text, reducer, lossy: true }
939
+ }
940
+
941
+ /**
942
+ * Require content evidence of a structured document: enough Markdown heading
943
+ * lines among a bounded prefix. Pure form evidence — tool names, path
944
+ * extensions, and commands are never read (MCP output has no predictable
945
+ * identity). Real logs and build output carry no `#`-heading lines, which is
946
+ * the misjudgment guard.
947
+ * @param text - normalized result text.
948
+ * @returns whether the text qualifies as a structured document.
949
+ */
950
+ export function looksLikeDocument(text: string): boolean {
951
+ const lines = splitLines(text)
952
+ let headings = 0
953
+ // C26 (AD5): the window covers 600 lines so a document whose headings only
954
+ // start past line 400 still reaches doc-skeleton; the `^#{1,6}\s+\S` anchor
955
+ // itself is unchanged (RK-4 — pure logs carry no heading lines).
956
+ for (const line of lines.slice(0, 600)) {
957
+ if (MARKDOWN_HEADING_PATTERN.test(line)) {
958
+ headings += 1
959
+ if (headings >= 3) return true
960
+ }
961
+ }
962
+ return false
963
+ }
964
+
965
+ /** One R9-spec elision marker: an original-event line range plus its count. */
966
+ function elidedRangeMarker(start: number, end: number): string {
967
+ return `[... lines ${String(start)}-${String(end)} elided (${String(end - start + 1)} lines) ...]`
968
+ }
969
+
970
+ /**
971
+ * Require content evidence of HTML: enough lines carrying real markup tags
972
+ * among a bounded prefix. Angle-bracket prose (TS generics, comparisons) does
973
+ * not match the tag list, which is the misjudgment guard.
974
+ */
975
+ function looksLikeHtml(text: string): boolean {
976
+ const lines = splitLines(text)
977
+ let tags = 0
978
+ for (const line of lines.slice(0, 400)) {
979
+ if (HTML_TAG_PATTERN.test(line)) {
980
+ tags += 1
981
+ if (tags >= 3) return true
982
+ }
983
+ }
984
+ return false
985
+ }
986
+
987
+ const HTML_DROPPED_OPEN = /<(script|style|noscript|svg|head)\b[^>]*>/i
988
+
989
+ /** One stage-1 survivor; `marker` entries are synthetic repeated-block folds. */
990
+ interface HtmlSlimEntry { readonly text: string, readonly index: number, readonly marker?: boolean }
991
+
992
+ const HTML_BLOCK_MIN_LINES = 2
993
+ const HTML_BLOCK_MAX_LINES = 8
994
+ const HTML_BLOCK_MIN_OCCURRENCES = 3
995
+ const HTML_TABLE_TAG_PATTERN = /<table\b|<tr\b|<th\b|<\/tr\b|<\/table\b/i
996
+
997
+ /**
998
+ * Deterministic repeated-block folding for slimmed HTML (R4/RK-3): contiguous
999
+ * runs of 2–8 non-table lines whose digit-normalized signature recurs ≥3 times
1000
+ * keep their first occurrence; every later occurrence becomes ONE counted
1001
+ * marker. Tables never fold, and different copy never shares a signature —
1002
+ * only counter/number drift does.
1003
+ */
1004
+ export function foldRepeatedHtmlBlocks(
1005
+ slim: readonly { readonly text: string, readonly index: number }[],
1006
+ originalLineFor: (index: number) => number,
1007
+ ): readonly HtmlSlimEntry[] {
1008
+ const signatureOf = (from: number, length: number): string | null => {
1009
+ let signature = `${String(length)}|`
1010
+ for (let position = from; position < from + length; position++) {
1011
+ const text = slim[position]!.text
1012
+ if (HTML_TABLE_TAG_PATTERN.test(text)) return null
1013
+ signature += `${text.replace(/\d+/g, '#').replace(/\s+/g, ' ').trim()}\n`
1014
+ }
1015
+ return signature
1016
+ }
1017
+ const counts = new Map<string, { count: number, first: number }>()
1018
+ for (let length = HTML_BLOCK_MIN_LINES; length <= HTML_BLOCK_MAX_LINES; length++) {
1019
+ for (let start = 0; start + length <= slim.length; start++) {
1020
+ const signature = signatureOf(start, length)
1021
+ if (signature === null) continue
1022
+ const bucket = counts.get(signature)
1023
+ if (bucket === undefined) counts.set(signature, { count: 1, first: start })
1024
+ else bucket.count += 1
1025
+ }
1026
+ }
1027
+ const result: HtmlSlimEntry[] = []
1028
+ let position = 0
1029
+ while (position < slim.length) {
1030
+ let foldedLength = 0
1031
+ let matched: { count: number, first: number } | undefined
1032
+ for (let length = HTML_BLOCK_MAX_LINES; length >= HTML_BLOCK_MIN_LINES; length--) {
1033
+ if (position + length > slim.length) continue
1034
+ const signature = signatureOf(position, length)
1035
+ const bucket = signature === null ? undefined : counts.get(signature)
1036
+ if (bucket !== undefined && bucket.count >= HTML_BLOCK_MIN_OCCURRENCES) {
1037
+ foldedLength = length
1038
+ matched = bucket
1039
+ break
1040
+ }
1041
+ }
1042
+ if (matched === undefined) {
1043
+ result.push({ text: slim[position]!.text, index: slim[position]!.index })
1044
+ position += 1
1045
+ continue
1046
+ }
1047
+ if (matched.first === position) {
1048
+ for (let offset = 0; offset < foldedLength; offset++) {
1049
+ result.push({ text: slim[position + offset]!.text, index: slim[position + offset]!.index })
1050
+ }
1051
+ } else {
1052
+ const firstLine = originalLineFor(slim[matched.first]!.index)
1053
+ result.push({
1054
+ text: `[×${String(matched.count)} repeated block, first at line ${String(firstLine)}]`,
1055
+ index: slim[position]!.index,
1056
+ marker: true,
1057
+ })
1058
+ }
1059
+ position += foldedLength
1060
+ }
1061
+ return result
1062
+ }
1063
+
1064
+ /**
1065
+ * Two-stage HTML reduction (R13). HTML previously fell into `pi-head`, which
1066
+ * keeps exactly the useless `<head>` metadata and drops the body.
1067
+ *
1068
+ * Stage 1 (`html-slim`) is a deterministic, line-aligned slimming pass:
1069
+ * comments, script/style/noscript/svg/head elements (single- or multi-line),
1070
+ * data URIs, non-whitelisted attributes, and inline-tag markup disappear;
1071
+ * every surviving line keeps its original-event position for the R9 ranges.
1072
+ * Stage 2 (`html-skeleton`) runs only when the slim output still exceeds the
1073
+ * budget: heading hierarchy, each section's first line, and table header rows
1074
+ * survive; the rest is elided with original-event line ranges.
1075
+ */
1076
+ function reduceHtml(input: PreparedInput): ReducerOutput | null {
1077
+ interface SlimLine { readonly text: string, readonly index: number }
1078
+ const slim: SlimLine[] = []
1079
+ let dropping: string | null = null
1080
+ input.lines.forEach((line, index) => {
1081
+ let text = line.content
1082
+ if (dropping !== null) {
1083
+ const close = new RegExp(`</${dropping}\\s*>`, 'i').exec(text)
1084
+ if (close === null) return
1085
+ text = text.slice(close.index + close[0].length)
1086
+ dropping = null
1087
+ }
1088
+ text = text.replace(HTML_COMMENT_PATTERN, '')
1089
+ text = text.replace(HTML_DROPPED_ELEMENTS, '')
1090
+ const open = HTML_DROPPED_OPEN.exec(text)
1091
+ if (open !== null) {
1092
+ const close = new RegExp(`</${open[1] ?? ''}\\s*>`, 'i').exec(text.slice(open.index))
1093
+ if (close !== null) {
1094
+ const end = open.index + open[0].length + close.index + close[0].length
1095
+ text = text.slice(0, open.index) + text.slice(end)
1096
+ } else {
1097
+ dropping = open[1] ?? null
1098
+ text = text.slice(0, open.index)
1099
+ }
1100
+ }
1101
+ text = text.replace(HTML_DATA_URI_PATTERN, '')
1102
+ text = text.replace(HTML_TAG_PATTERN_FULL, (match: string, name: string, attrs: string) =>
1103
+ `<${name}${attrs.match(HTML_WHITELISTED_ATTRIBUTES)?.join('') ?? ''}>`)
1104
+ text = text.replace(HTML_INLINE_TAG_PATTERN, '')
1105
+ text = text.trim()
1106
+ if (text !== '') slim.push({ text, index })
1107
+ })
1108
+ if (slim.length === 0) return null
1109
+
1110
+ const buildHeader = (reducer: string, firstElided?: { readonly start: number }): string => {
1111
+ const startLine = firstElided === undefined ? '' : `,"start_line":${String(firstElided.start)},"max_lines":${String(RETRIEVE_HINT_MAX_LINES)}`
1112
+ return `[html compressed by ${reducer}; source: ${input.sourceRef}; retrieve with context_compression_retrieve({"ref":"${input.sourceRef}"${startLine}})]`
1113
+ }
1114
+
1115
+ // Third level (R4): deterministic repeated-block folding. Nav/footer/
1116
+ // boilerplate runs of ≥2 slimmed lines that recur ≥3 times collapse to a
1117
+ // counted marker citing the first occurrence's original line. Table blocks
1118
+ // never fold (their rows are the payload), and the signature normalizes
1119
+ // digits so counter-only variants still match while different copy does not.
1120
+ const foldedSlim = foldRepeatedHtmlBlocks(slim, index =>
1121
+ input.lines[index]?.originalLine ?? 1)
1122
+
1123
+ const slimChars = foldedSlim.reduce((sum, line) => sum + codePointLength(line.text) + 1, 0)
1124
+ if (slimChars + 160 <= input.budgetChars) {
1125
+ const text = fitLines([buildHeader('html-slim'), ...foldedSlim.map(line => line.text)], input.budgetChars, input.sourceRef)
1126
+ if (text !== null) return { text, reducer: 'html-slim', lossy: true }
1127
+ }
1128
+
1129
+ // Stage 2: tag-aware skeleton over the slimmed lines.
1130
+ const keep = new Array<boolean>(foldedSlim.length).fill(false)
1131
+ let tableRows = 0
1132
+ let lastHeading = -2
1133
+ for (let position = 0; position < foldedSlim.length; position++) {
1134
+ const text = foldedSlim[position]!.text
1135
+ if (foldedSlim[position]!.marker === true) {
1136
+ keep[position] = true
1137
+ continue
1138
+ }
1139
+ if (/<h[1-6]\b/i.test(text)) {
1140
+ keep[position] = true
1141
+ lastHeading = position
1142
+ continue
1143
+ }
1144
+ if (lastHeading === position - 1) {
1145
+ // First content line of the section keeps one sentence of context.
1146
+ keep[position] = true
1147
+ continue
1148
+ }
1149
+ if (/<table\b|<tr\b|<th\b/i.test(text)) {
1150
+ // Header + separator rows survive, matching the reduceDocSkeleton
1151
+ // `< 2` convention — one lone row is not table structure (R4).
1152
+ if (tableRows < 2) keep[position] = true
1153
+ tableRows += 1
1154
+ continue
1155
+ }
1156
+ if (!/<\/(tr|table)\b/i.test(text)) tableRows = 0
1157
+ if (IMPORTANT_PATTERN.test(text)) keep[position] = true
1158
+ }
1159
+ const kept: string[] = []
1160
+ let position = 0
1161
+ let firstElided: number | undefined
1162
+ let elidedLines = 0
1163
+ while (position < foldedSlim.length) {
1164
+ if (keep[position]) {
1165
+ kept.push(foldedSlim[position]!.text)
1166
+ position += 1
1167
+ continue
1168
+ }
1169
+ const runStart = position
1170
+ while (position < foldedSlim.length && !keep[position]) position += 1
1171
+ const start = input.lines[foldedSlim[runStart]!.index]!.originalLine
1172
+ const end = originalEnd(input.lines, foldedSlim[position - 1]!.index)
1173
+ if (firstElided === undefined) firstElided = start
1174
+ elidedLines += end - start + 1
1175
+ kept.push(elidedRangeMarker(start, end))
1176
+ }
1177
+ const text = fitLines([buildHeader('html-skeleton', firstElided === undefined ? undefined : { start: firstElided }), ...kept], input.budgetChars, input.sourceRef)
1178
+ return text === null ? null : { text, reducer: 'html-skeleton', lossy: true, elidedLines }
1179
+ }
1180
+
1181
+ /** Original-event end line of folded entry `lines[index]`. */
1182
+ function originalEnd(lines: readonly NormalizedLine[], index: number): number {
1183
+ const line = lines[index]
1184
+ return line?.originalLineEnd ?? line?.originalLine ?? 0
1185
+ }
1186
+
1187
+ /**
1188
+ * Keep a document skeleton: the heading hierarchy, each section's first and
1189
+ * last content line, list-item starts, table headers, and fence markers,
1190
+ * eliding the remaining bodies with R9 line-range markers. Fails open (null)
1191
+ * when nothing is elidable or the budget cannot be met, so the next candidate
1192
+ * takes over.
1193
+ */
1194
+ function reduceDocSkeleton(input: PreparedInput, sectionRanking?: readonly string[]): ReducerOutput | null {
1195
+ const lines = input.lines
1196
+ const keep = new Array<boolean>(lines.length).fill(false)
1197
+ const headingIndex: number[] = []
1198
+ let inFence = false
1199
+ for (let index = 0; index < lines.length; index++) {
1200
+ const line = lines[index]!.content
1201
+ if (FENCE_PATTERN.test(line)) {
1202
+ inFence = !inFence
1203
+ keep[index] = true
1204
+ continue
1205
+ }
1206
+ if (!inFence && MARKDOWN_HEADING_PATTERN.test(line)) {
1207
+ headingIndex.push(index)
1208
+ keep[index] = true
1209
+ continue
1210
+ }
1211
+ if (IMPORTANT_PATTERN.test(line)) keep[index] = true
1212
+ else if (!inFence && LIST_ITEM_PATTERN.test(line)) keep[index] = true
1213
+ }
1214
+ // Table blocks keep their first two rows (header + separator) in every
1215
+ // variant — table structure is part of the skeleton, not section content.
1216
+ let tableRows = 0
1217
+ let fenceOpen = false
1218
+ for (let index = 0; index < lines.length; index++) {
1219
+ const line = lines[index]!.content
1220
+ if (FENCE_PATTERN.test(line)) {
1221
+ fenceOpen = !fenceOpen
1222
+ tableRows = 0
1223
+ continue
1224
+ }
1225
+ if (fenceOpen || line.trim() === '') continue
1226
+ if (TABLE_ROW_PATTERN.test(line)) {
1227
+ if (tableRows < 2) keep[index] = true
1228
+ tableRows += 1
1229
+ continue
1230
+ }
1231
+ tableRows = 0
1232
+ }
1233
+ const sectionStarts = [-1, ...headingIndex]
1234
+ const sectionEnds = [...headingIndex, lines.length]
1235
+ const sections = headingIndex.map((heading, position) => ({
1236
+ id: lines[heading]!.content.replace(/^#+\s*/, '').trim(),
1237
+ heading,
1238
+ from: heading + 1,
1239
+ to: position + 1 < headingIndex.length ? headingIndex[position + 1]! : lines.length,
1240
+ }))
1241
+ // Mechanical floor: every section keeps its first and last content line.
1242
+ const floorKeep = new Array<boolean>(lines.length).fill(false)
1243
+ for (let section = 0; section < sectionStarts.length; section++) {
1244
+ const from = sectionStarts[section]! + 1
1245
+ const to = sectionEnds[section]!
1246
+ let first = -1
1247
+ let last = -1
1248
+ for (let index = from; index < to; index++) {
1249
+ if (lines[index]!.content.trim() === '') continue
1250
+ if (first === -1) first = index
1251
+ last = index
1252
+ }
1253
+ if (first !== -1) floorKeep[first] = true
1254
+ if (last !== -1) floorKeep[last] = true
1255
+ }
1256
+
1257
+ /** Emit the skeleton for one keep-set: header, kept lines, R9 range markers. */
1258
+ const assemble = (flags: readonly boolean[], budget: number): { text: string | null, firstElided?: number, elidedLines: number } => {
1259
+ const kept: string[] = []
1260
+ let index = 0
1261
+ let firstElided: number | undefined
1262
+ let elidedLines = 0
1263
+ while (index < lines.length) {
1264
+ if (flags[index]) {
1265
+ kept.push(lines[index]!.text)
1266
+ index += 1
1267
+ continue
1268
+ }
1269
+ const runStart = index
1270
+ while (index < lines.length && !flags[index]) index += 1
1271
+ const start = lines[runStart]!.originalLine
1272
+ const end = originalEnd(lines, index - 1)
1273
+ if (firstElided === undefined) firstElided = start
1274
+ elidedLines += end - start + 1
1275
+ kept.push(elidedRangeMarker(start, end))
1276
+ }
1277
+ const hint = firstElided === undefined
1278
+ ? ''
1279
+ : `,"start_line":${String(firstElided)},"max_lines":${String(RETRIEVE_HINT_MAX_LINES)}`
1280
+ kept.unshift(`[document compressed by doc-skeleton; source: ${input.sourceRef}; retrieve with context_compression_retrieve({"ref":"${input.sourceRef}"${hint}})]`)
1281
+ const text = fitLines(kept, budget, input.sourceRef)
1282
+ return { text, ...(firstElided === undefined ? {} : { firstElided }), elidedLines }
1283
+ }
1284
+
1285
+ const combine = (base: readonly boolean[], overlay: readonly boolean[]): boolean[] =>
1286
+ lines.map((_, index) => (base[index] ?? false) || (overlay[index] ?? false))
1287
+
1288
+ // Structural lines (headings/fences/important/list items) are part of every
1289
+ // variant; the mechanical floor rides on top of them.
1290
+ const mechanicalKeep = combine(keep, floorKeep)
1291
+ const mechanical = assemble(mechanicalKeep, input.budgetChars)
1292
+ if (mechanical.text === null) return null
1293
+ if (sectionRanking === undefined || sectionRanking.length === 0) {
1294
+ return { text: mechanical.text, reducer: 'doc-skeleton', lossy: true, elidedLines: mechanical.elidedLines }
1295
+ }
1296
+
1297
+ // Ranked mode (S1b): floors (every heading + each section's first line)
1298
+ // are reserved first; the remaining budget is filled most relevant-first,
1299
+ // line by line, with an EXACT assembly check per line so the final output
1300
+ // never exceeds min(budgetChars, inputChars - 1) — a ranked skeleton must
1301
+ // always shrink the text at least as much as verifyReduction demands.
1302
+ const cap = Math.min(input.budgetChars, codePointLength(input.text) - 1)
1303
+ const rankedFloor = new Array<boolean>(lines.length).fill(false)
1304
+ // First lines only: a ranked unselected section falls back to its first
1305
+ // sentence, so the mechanical last-line floor must NOT ride along.
1306
+ for (const section of sections) {
1307
+ for (let index = section.from; index < section.to; index++) {
1308
+ if (lines[index]!.content.trim() === '') continue
1309
+ rankedFloor[index] = true
1310
+ break
1311
+ }
1312
+ }
1313
+ /** Exact packed-output size of a keep-set: header + kept lines + markers. */
1314
+ const packedSize = (flags: readonly boolean[]): number => {
1315
+ let size = 180 /* header with hint */
1316
+ let index = 0
1317
+ while (index < lines.length) {
1318
+ if (flags[index]) {
1319
+ size += codePointLength(lines[index]!.text) + 1
1320
+ index += 1
1321
+ continue
1322
+ }
1323
+ const runStart = index
1324
+ while (index < lines.length && !flags[index]) index += 1
1325
+ size += codePointLength(elidedRangeMarker(lines[runStart]!.originalLine, originalEnd(lines, index - 1))) + 1
1326
+ }
1327
+ return size
1328
+ }
1329
+ const fill = new Array<boolean>(lines.length).fill(false)
1330
+ for (const section of rankedFirst(sections, sectionRanking)) {
1331
+ for (let index = section.from; index < section.to; index++) {
1332
+ if (rankedFloor[index] || fill[index] || lines[index]!.content.trim() === '') continue
1333
+ fill[index] = true
1334
+ if (packedSize(combine(combine(keep, rankedFloor), fill)) > cap) {
1335
+ fill[index] = false
1336
+ break
1337
+ }
1338
+ }
1339
+ }
1340
+ const ranked = assemble(combine(combine(keep, rankedFloor), fill), cap)
1341
+ return ranked.text === null
1342
+ ? null
1343
+ : { text: ranked.text, reducer: 'doc-skeleton', lossy: true, elidedLines: ranked.elidedLines }
1344
+ }
1345
+
1346
+ /**
1347
+ * Universal prose fallback (R8b, the main force): keep the head AND the tail
1348
+ * of any non-code text and one R9 line-range marker for everything elided in
1349
+ * between. Unstructured prose (85%+ of large results) previously landed on
1350
+ * head-only truncation; a tail keep preserves conclusions and closing state.
1351
+ * Fails open for code-like text and when the budget cannot hold both ends.
1352
+ */
1353
+ function reduceProseKeep(input: PreparedInput): ReducerOutput | null {
1354
+ const lines = input.lines
1355
+ if (lines.length < 8) return null
1356
+ if (looksLikeSourceCode(input.contentText)) return null
1357
+ const first = lines[0]!
1358
+ const last = lines[lines.length - 1]!
1359
+ const tailLine = last.originalLineEnd ?? last.originalLine
1360
+ const markerTemplate = elidedRangeMarker(first.originalLine, tailLine)
1361
+ const sourceNoteTemplate = `; source: ${input.sourceRef}; retrieve with context_compression_retrieve({"ref":"${input.sourceRef}"})`
1362
+ const reserved = codePointLength(markerTemplate) + codePointLength(sourceNoteTemplate) + 2
1363
+ const bodyBudget = input.budgetChars - reserved
1364
+ if (bodyBudget <= 0) return null
1365
+ const headBudget = Math.floor(bodyBudget / 2)
1366
+ const tailBudget = bodyBudget - headBudget
1367
+ let headCount = 0
1368
+ let used = 0
1369
+ while (headCount < lines.length) {
1370
+ const cost = codePointLength(lines[headCount]!.text) + (headCount === 0 ? 0 : 1)
1371
+ if (used + cost > headBudget) break
1372
+ used += cost
1373
+ headCount += 1
1374
+ }
1375
+ let tailCount = 0
1376
+ used = 0
1377
+ while (tailCount < lines.length - headCount) {
1378
+ const index = lines.length - 1 - tailCount
1379
+ const cost = codePointLength(lines[index]!.text) + (tailCount === 0 ? 0 : 1)
1380
+ if (used + cost > tailBudget) break
1381
+ used += cost
1382
+ tailCount += 1
1383
+ }
1384
+ if (headCount === 0 || tailCount === 0 || headCount + tailCount >= lines.length) return null
1385
+ const elidedStart = lines[headCount]!.originalLine
1386
+ const elidedEnd = originalEnd(lines, lines.length - tailCount - 1)
1387
+ if (elidedEnd < elidedStart) return null
1388
+ const sourceNote = `; source: ${input.sourceRef}; retrieve with context_compression_retrieve({"ref":"${input.sourceRef}","start_line":${String(elidedStart)},"max_lines":${String(RETRIEVE_HINT_MAX_LINES)}})`
1389
+ const text = [
1390
+ ...lines.slice(0, headCount).map(line => line.text),
1391
+ elidedRangeMarker(elidedStart, elidedEnd) + sourceNote,
1392
+ ...lines.slice(lines.length - tailCount).map(line => line.text),
1393
+ ].join('\n')
1394
+ return { text, reducer: 'prose-keep', lossy: true, elidedLines: elidedEnd - elidedStart + 1 }
1395
+ }
1396
+
1397
+ /**
1398
+ * Keep a source-file skeleton: imports, decorators, declaration signatures,
1399
+ * comments at brace depth zero, and every error-signalling line, eliding the
1400
+ * remaining bodies with counted markers. Covers brace languages (TS/JS, Rust,
1401
+ * Go, Java, C family) and indent blocks (Python); unknown syntax fails open to
1402
+ * the next candidate. Output is compressed evidence, not required to parse.
1403
+ * @param input - original result text, recovery source, and output budget.
1404
+ * @returns a verified candidate, or `null` when the text is not code-like.
1405
+ */
1406
+ function reduceCodeSkeleton(input: PreparedInput): ReducerOutput | null {
1407
+ // The skeleton logic reads the CONTENT view (gutter-stripped) so structure
1408
+ // lines survive the host's read gutter; markers still cite originalLine.
1409
+ const lines = input.lines.map(line => line.content)
1410
+ const kept: string[] = []
1411
+ let elided = 0
1412
+ let elidedTotal = 0
1413
+ let firstElided: { readonly start: number, readonly end: number } | undefined
1414
+ const flushElided = (): void => {
1415
+ if (elided > 0) {
1416
+ const start = input.lines[index - elided]?.originalLine ?? 0
1417
+ const end = originalEnd(input.lines, index - 1)
1418
+ if (firstElided === undefined) firstElided = { start, end }
1419
+ kept.push(elidedRangeMarker(start, end))
1420
+ elidedTotal += elided
1421
+ }
1422
+ elided = 0
1423
+ }
1424
+ let depth = 0
1425
+ let index = 0
1426
+ const elideBraceBody = (): void => {
1427
+ const startDepth = depth
1428
+ index += 1
1429
+ while (index < lines.length && depth > startDepth) {
1430
+ const body = lines[index]
1431
+ if (body === undefined) break
1432
+ if (IMPORTANT_PATTERN.test(body)) {
1433
+ flushElided()
1434
+ kept.push(body)
1435
+ } else {
1436
+ elided += 1
1437
+ }
1438
+ depth += braceDelta(body)
1439
+ index += 1
1440
+ }
1441
+ flushElided()
1442
+ }
1443
+ const keepPythonSignature = (signatureLine: string): void => {
1444
+ // The signature line is already kept; every path below must advance the
1445
+ // cursor past it so the caller's `continue` cannot revisit the same line.
1446
+ index += 1
1447
+ if (/:\s*$/.test(signatureLine)) {
1448
+ elideIndentedBody(leadingIndent(signatureLine))
1449
+ return
1450
+ }
1451
+ // Multi-line signature: keep continuation lines until the colon, then
1452
+ // elide the indented body at the colon line's indent.
1453
+ for (let guard = 0; guard < 6 && index < lines.length; guard += 1) {
1454
+ const next = lines[index]
1455
+ if (next === undefined) break
1456
+ if (next.trim() !== '' && leadingIndent(next) <= leadingIndent(signatureLine)) break
1457
+ flushElided()
1458
+ kept.push(next)
1459
+ index += 1
1460
+ if (/:\s*$/.test(next)) {
1461
+ elideIndentedBody(leadingIndent(next))
1462
+ return
1463
+ }
1464
+ if (next.trim() !== '' && !/[:,(]\s*$/.test(next)) break
1465
+ }
1466
+ }
1467
+ const elideIndentedBody = (indent: number): void => {
1468
+ while (index < lines.length) {
1469
+ const body = lines[index]
1470
+ if (body === undefined) break
1471
+ if (body.trim() !== '' && leadingIndent(body) <= indent) break
1472
+ if (IMPORTANT_PATTERN.test(body)) {
1473
+ flushElided()
1474
+ kept.push(body)
1475
+ index += 1
1476
+ continue
1477
+ }
1478
+ if (isCodeStructureLine(body) || CODE_DECORATOR_PATTERN.test(body)) {
1479
+ flushElided()
1480
+ kept.push(body)
1481
+ keepPythonSignature(body)
1482
+ continue
1483
+ }
1484
+ elided += 1
1485
+ index += 1
1486
+ }
1487
+ flushElided()
1488
+ }
1489
+ while (index < lines.length) {
1490
+ const line = lines[index]
1491
+ if (line === undefined) break
1492
+ const delta = braceDelta(line)
1493
+ if (IMPORTANT_PATTERN.test(line)) {
1494
+ flushElided()
1495
+ kept.push(line)
1496
+ depth += delta
1497
+ index += 1
1498
+ continue
1499
+ }
1500
+ if (isCodeStructureLine(line) || CODE_IMPORT_PATTERN.test(line) || CODE_DECORATOR_PATTERN.test(line)) {
1501
+ flushElided()
1502
+ kept.push(line)
1503
+ depth += delta
1504
+ if (delta > 0) {
1505
+ elideBraceBody()
1506
+ continue
1507
+ }
1508
+ if (PYTHON_STRUCTURE_PATTERN.test(line)) {
1509
+ keepPythonSignature(line)
1510
+ continue
1511
+ }
1512
+ // Brace-language signature continuation: keep following lines until one
1513
+ // opens a block, then elide that block.
1514
+ let opened = false
1515
+ for (let guard = 0; guard < 6 && index + 1 < lines.length; guard += 1) {
1516
+ const next = lines[index + 1]
1517
+ if (next === undefined) break
1518
+ const nextDelta = braceDelta(next)
1519
+ if (nextDelta === 0 && next.trim() !== '' && !/[:,(]\s*$/.test(next)) break
1520
+ flushElided()
1521
+ kept.push(next)
1522
+ depth += nextDelta
1523
+ index += 1
1524
+ if (nextDelta > 0) {
1525
+ opened = true
1526
+ break
1527
+ }
1528
+ }
1529
+ if (opened) elideBraceBody()
1530
+ else index += 1
1531
+ continue
1532
+ }
1533
+ if (depth === 0 && CODE_COMMENT_PATTERN.test(line)) {
1534
+ flushElided()
1535
+ kept.push(line)
1536
+ } else {
1537
+ elided += 1
1538
+ }
1539
+ depth += delta
1540
+ index += 1
1541
+ }
1542
+ flushElided()
1543
+ return finishSkeleton(kept, lines, input, firstElided, elidedTotal)
1544
+ }
1545
+
1546
+ function finishSkeleton(
1547
+ kept: readonly string[],
1548
+ lines: readonly string[],
1549
+ input: PreparedInput,
1550
+ firstElided: { readonly start: number, readonly end: number } | undefined,
1551
+ elidedLines: number,
1552
+ ): ReducerOutput | null {
1553
+ const hint = firstElided === undefined
1554
+ ? ''
1555
+ : `; retrieve with context_compression_retrieve({"ref":"${input.sourceRef}","start_line":${String(firstElided.start)},"max_lines":${String(RETRIEVE_HINT_MAX_LINES)}})`
1556
+ const header = `[code output compressed by hypa-code-skeleton; source: ${input.sourceRef}${hint}]`
1557
+ const text = fitLines([header, ...kept, ...lines.slice(-4)], input.budgetChars, input.sourceRef)
1558
+ return text === null ? null : { text, reducer: 'hypa-code-skeleton', lossy: true, elidedLines }
1559
+ }
1560
+
1561
+ /** Net brace delta of one line, ignoring braces inside string literals. */
1562
+ function braceDelta(line: string): number {
1563
+ let delta = 0
1564
+ let quote: string | null = null
1565
+ for (let position = 0; position < line.length; position += 1) {
1566
+ const char = line[position]
1567
+ if (quote !== null) {
1568
+ if (char === '\\') position += 1
1569
+ else if (char === quote) quote = null
1570
+ continue
1571
+ }
1572
+ if (char === '"' || char === "'" || char === '`') {
1573
+ quote = char
1574
+ continue
1575
+ }
1576
+ if (char === '{') delta += 1
1577
+ else if (char === '}') delta -= 1
1578
+ }
1579
+ return delta
1580
+ }
1581
+
1582
+ function leadingIndent(line: string): number {
1583
+ return codePointLength(line) - codePointLength(line.trimStart())
1584
+ }
1585
+
1586
+ function isCodeStructureLine(line: string): boolean {
1587
+ return CODE_STRUCTURE_PATTERN.test(line) || PYTHON_STRUCTURE_PATTERN.test(line)
1588
+ }
1589
+
1590
+ /**
1591
+ * Require content evidence of source code: enough declaration, import, or
1592
+ * decorator lines among a bounded prefix. Failing this keeps prose, logs, and
1593
+ * data on their existing reducers.
1594
+ * @param text - normalized result text.
1595
+ * @returns whether the text qualifies as source code.
1596
+ */
1597
+ function looksLikeSourceCode(text: string): boolean {
1598
+ const lines = splitLines(text)
1599
+ if (lines.length < 12) return false
1600
+ let evidence = 0
1601
+ for (const line of lines.slice(0, 400)) {
1602
+ if (isCodeStructureLine(line) || CODE_IMPORT_PATTERN.test(line) || CODE_DECORATOR_PATTERN.test(line)) {
1603
+ evidence += 1
1604
+ if (evidence >= 3) return true
1605
+ }
1606
+ }
1607
+ return false
1608
+ }
1609
+
1610
+ function omissionMarker(input: PreparedInput, reducer: string): string {
1611
+ return `[... ${reducer} omitted content; original_chars=${String(codePointLength(input.text))}; source=${input.sourceRef}; retrieve with context_compression_retrieve ...]`
1612
+ }
1613
+
1614
+ /**
1615
+ * Continuous-mask marker (R9b): an original-event line range plus a pasteable
1616
+ * retrieve hint whose start_line is the first elided line. Line numbers point
1617
+ * at the RAW event because retrieve reads raw events (D8).
1618
+ */
1619
+ function rangeOmissionMarker(
1620
+ input: PreparedInput,
1621
+ reducer: string,
1622
+ elidedStart: number,
1623
+ elidedEnd: number,
1624
+ ): string {
1625
+ return `[... lines ${String(elidedStart)}-${String(elidedEnd)} elided (${String(elidedEnd - elidedStart + 1)} lines); ${reducer}; original_chars=${String(codePointLength(input.text))}; source=${input.sourceRef}; retrieve with context_compression_retrieve({"ref":"${input.sourceRef}","start_line":${String(elidedStart)},"max_lines":${String(RETRIEVE_HINT_MAX_LINES)}}) ...]`
1626
+ }
1627
+
1628
+ /** Scatter-mask note (R9b): totals instead of fragmented per-run ranges. */
1629
+ function scannedTotals(input: PreparedInput, kept: number): string {
1630
+ const last = input.lines[input.lines.length - 1]
1631
+ const lastLine = Math.max(last?.originalLineEnd ?? 0, last?.originalLine ?? 0, input.lines.length)
1632
+ return `lines 1-${String(lastLine)} scanned, ${String(kept)} kept`
1633
+ }
1634
+
1635
+ function importantAnchor(text: string, maxChars: number): string {
1636
+ const lines = splitLines(normalizeTerminalText(text))
1637
+ const chosen = lines.find(line => IMPORTANT_PATTERN.test(line)) ?? lines.at(-1) ?? ''
1638
+ return Array.from(chosen.trim()).slice(0, maxChars).join('')
1639
+ }
1640
+
1641
+ function fitLines(lines: readonly string[], budgetChars: number, requiredRef: string): string | null {
1642
+ const unique: string[] = []
1643
+ const seen = new Set<string>()
1644
+ for (const line of lines) {
1645
+ if (line === '' || seen.has(line)) continue
1646
+ seen.add(line)
1647
+ unique.push(line)
1648
+ }
1649
+ const output: string[] = []
1650
+ let used = 0
1651
+ for (const line of unique) {
1652
+ const cost = codePointLength(line) + (output.length === 0 ? 0 : 1)
1653
+ if (used + cost > budgetChars) continue
1654
+ output.push(line)
1655
+ used += cost
1656
+ }
1657
+ const text = output.join('\n')
1658
+ return text.includes(requiredRef) ? text : null
1659
+ }
1660
+
1661
+ function takeWholeLinesFromHead(text: string, budgetChars: number): string {
1662
+ const output: string[] = []
1663
+ let used = 0
1664
+ for (const line of splitLines(text)) {
1665
+ const cost = codePointLength(line) + (output.length === 0 ? 0 : 1)
1666
+ if (used + cost > budgetChars) break
1667
+ output.push(line)
1668
+ used += cost
1669
+ }
1670
+ if (output.length === 0) return Array.from(text).slice(0, budgetChars).join('')
1671
+ return output.join('\n')
1672
+ }
1673
+
1674
+ function takeWholeLinesFromTail(text: string, budgetChars: number): string {
1675
+ const lines = splitLines(text)
1676
+ const output: string[] = []
1677
+ let used = 0
1678
+ for (let index = lines.length - 1; index >= 0; index--) {
1679
+ const line = lines[index]
1680
+ if (line === undefined) continue
1681
+ const cost = codePointLength(line) + (output.length === 0 ? 0 : 1)
1682
+ if (used + cost > budgetChars) break
1683
+ output.unshift(line)
1684
+ used += cost
1685
+ }
1686
+ if (output.length === 0) return Array.from(text).slice(-budgetChars).join('')
1687
+ return output.join('\n')
1688
+ }
1689
+
1690
+ function splitLines(text: string): string[] {
1691
+ const lines = text.split('\n')
1692
+ if (text.endsWith('\n')) lines.pop()
1693
+ return lines
1694
+ }
1695
+
1696
+ /**
1697
+ * Extract the command argument from a tool call's arguments (task_10/AD2):
1698
+ * ONLY `command` / `cmd` / `script` are command keys. `input` was removed —
1699
+ * any MCP tool with a non-empty `input` string parameter would otherwise be
1700
+ * misrouted into the shell reducer, the single largest misroute source.
1701
+ * @param argumentsText - raw JSON arguments of the tool call.
1702
+ * @returns the command string, or '' when absent.
1703
+ */
1704
+ export function extractCommand(argumentsText: string): string {
1705
+ try {
1706
+ const parsed = JSON.parse(argumentsText) as unknown
1707
+ if (typeof parsed !== 'object' || parsed === null) return ''
1708
+ const record = parsed as Record<string, unknown>
1709
+ for (const key of ['command', 'cmd', 'script']) {
1710
+ const value = record[key]
1711
+ if (typeof value === 'string') return value
1712
+ }
1713
+ } catch {
1714
+ return ''
1715
+ }
1716
+ return ''
1717
+ }
1718
+
1719
+ function looksLikeJson(text: string): boolean {
1720
+ const trimmed = text.trim()
1721
+ return (trimmed.startsWith('{') && trimmed.endsWith('}'))
1722
+ || (trimmed.startsWith('[') && trimmed.endsWith(']'))
1723
+ }
1724
+
1725
+ function isGitCommand(name: string, command: string): boolean {
1726
+ return name.includes('git') || /(?:^|\s)git\s/.test(command)
1727
+ }
1728
+
1729
+ function isPackageCommand(command: string): boolean {
1730
+ return /(?:^|\s)(?:npm|pnpm|yarn|bun|pip|pip3|uv|poetry)\s/.test(command)
1731
+ }
1732
+
1733
+ function isBuildOrTestCommand(command: string): boolean {
1734
+ const pattern = new RegExp([
1735
+ String.raw`(?:^|\s)(?:tsc|dotnet\s+(?:build|test)|pytest|cargo\s+(?:build|test|check)|go\s+test|mvn\s+test|`,
1736
+ String.raw`gradle|npm\s+(?:test|run\s+build)|pnpm\s+(?:test|build|lint)|yarn\s+(?:test|build|lint))\b`,
1737
+ ].join(''))
1738
+ return pattern.test(command)
1739
+ }
1740
+
1741
+ function packagePattern(): RegExp {
1742
+ return new RegExp([
1743
+ String.raw`(?:ERR!|WARN|warning|error|failed|conflict|peer dep|added\s+\d+|removed\s+\d+|installed|success|`,
1744
+ String.raw`up to date|packages?\s+(?:added|removed|changed)|resolution|No matching distribution|Could not find a version)`,
1745
+ ].join(''), 'i')
1746
+ }
1747
+
1748
+ function buildPattern(): RegExp {
1749
+ return new RegExp([
1750
+ String.raw`(?:error\s+TS\d+|warning\s+TS\d+|FAILED|FAIL\b|AssertionError|expected|actual|`,
1751
+ String.raw`tests?\s+(?:run|passed|failed|skipped)|Build\s+(?:succeeded|FAILED)|\d+\s+Error\(s\)|`,
1752
+ String.raw`\d+\s+Warning\(s\)|Finished\s+test|compilation failed)`,
1753
+ ].join(''), 'i')
1754
+ }