dsh-context-compression-improved 0.10.4 → 0.11.0

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