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,361 @@
1
+ /**
2
+ * 持久层主干(T1–T5)单测:开关纪律 / schema 幂等 / claims 落库与聚合 /
3
+ * BC #2671 两断言 / 双连接写 / 生命周期与可见降级。
4
+ *
5
+ * 全部用临时目录注入路径,绝不触碰真实 `~/.dsh`。
6
+ */
7
+ import { mkdtempSync, rmSync } from 'node:fs'
8
+ import { homedir, tmpdir } from 'node:os'
9
+ import { join } from 'node:path'
10
+ import { DatabaseSync } from 'node:sqlite'
11
+ import { afterEach, describe, expect, it, vi } from 'vitest'
12
+ import {
13
+ StatsStore,
14
+ closeStatsStore,
15
+ getStatsStore,
16
+ openStatsDatabase,
17
+ statsPersistenceState,
18
+ } from '../../src/runtime/stats-db.ts'
19
+ import {
20
+ CCI_STATS_APPLICATION_ID,
21
+ OFFICIAL_SESSION_QUERY_APPLICATION_ID,
22
+ STATS_SCHEMA_VERSION,
23
+ resolveStatsDbPath,
24
+ } from '../../src/runtime/stats-schema.ts'
25
+
26
+ const dirs: string[] = []
27
+
28
+ /** 每个用例一个独立临时目录,收尾删干净。 */
29
+ function tempDir(name: string): string {
30
+ const dir = mkdtempSync(join(tmpdir(), `cci-stats-${name}-`))
31
+ dirs.push(dir)
32
+ return dir
33
+ }
34
+
35
+ const tempDbPath = (name: string): string => join(tempDir(name), 'stats.sqlite')
36
+
37
+ async function openStore(path: string): Promise<StatsStore> {
38
+ const opened = await openStatsDatabase(path)
39
+ if (opened === null) throw new Error('no sqlite driver in this environment')
40
+ return new StatsStore(opened.db, opened.driver)
41
+ }
42
+
43
+ function pragma(db: DatabaseSync, sql: string): Record<string, unknown> {
44
+ return db.prepare(sql).get() as Record<string, unknown>
45
+ }
46
+
47
+ function countRows(path: string, table: string): number {
48
+ const db = new DatabaseSync(path)
49
+ try {
50
+ return Number((db.prepare(`SELECT COUNT(*) AS c FROM ${table}`).get() as { c: number | bigint }).c)
51
+ } finally {
52
+ db.close()
53
+ }
54
+ }
55
+
56
+ afterEach(() => {
57
+ closeStatsStore()
58
+ vi.restoreAllMocks()
59
+ while (dirs.length > 0) {
60
+ const dir = dirs.pop()!
61
+ try { rmSync(dir, { recursive: true, force: true }) } catch { /* Windows 句柄释放滞后时尽力而为 */ }
62
+ }
63
+ })
64
+
65
+ describe('stats-db 开关纪律(T1:打开/拒他人库/版本不符重建)', () => {
66
+ it('空库打开:建表齐三张 + pragma 到位 + application_id/user_version 盖章', async () => {
67
+ const opened = await openStatsDatabase(tempDbPath('open'))
68
+ expect(opened).not.toBeNull()
69
+ const { db, driver } = opened!
70
+ expect(['better-sqlite3', 'node:sqlite']).toContain(driver)
71
+ try {
72
+ expect(Number(pragma(db, 'PRAGMA application_id').application_id)).toBe(CCI_STATS_APPLICATION_ID)
73
+ expect(Number(pragma(db, 'PRAGMA user_version').user_version)).toBe(STATS_SCHEMA_VERSION)
74
+ expect(Number(pragma(db, 'PRAGMA busy_timeout').timeout)).toBe(5000)
75
+ expect(String(pragma(db, 'PRAGMA journal_mode').journal_mode).toLowerCase()).toBe('wal')
76
+ const tables = db.prepare(
77
+ `SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name`,
78
+ ).all() as { name: string }[]
79
+ expect(tables.map(row => row.name)).toEqual(['claims', 'meta', 'sessions'])
80
+ } finally {
81
+ db.close()
82
+ }
83
+ })
84
+
85
+ it('拒开他人库:官方派生库与任意第三方 application_id 都抛错', async () => {
86
+ // 官方 session-query 派生库(0x44534851)
87
+ const officialPath = tempDbPath('foreign-official')
88
+ const rawOfficial = new DatabaseSync(officialPath)
89
+ rawOfficial.exec(`CREATE TABLE IF NOT EXISTS sentinel (x INTEGER)`)
90
+ rawOfficial.exec(`PRAGMA application_id = ${OFFICIAL_SESSION_QUERY_APPLICATION_ID}`)
91
+ rawOfficial.close()
92
+ await expect(openStatsDatabase(officialPath)).rejects.toThrow(/refusing to open/)
93
+
94
+ // 不认识的第三方库
95
+ const otherPath = tempDbPath('foreign-other')
96
+ const rawOther = new DatabaseSync(otherPath)
97
+ rawOther.exec(`CREATE TABLE IF NOT EXISTS sentinel (x INTEGER)`)
98
+ rawOther.exec(`PRAGMA application_id = ${0x0DEADBEE}`)
99
+ rawOther.close()
100
+ await expect(openStatsDatabase(otherPath)).rejects.toThrow(/another application/)
101
+ })
102
+
103
+ it('版本不符 drop 重建:user_version 被篡成高值后重开 = 空表 + 版本复位', async () => {
104
+ const path = tempDbPath('rebuild')
105
+ const first = await openStore(path)
106
+ first.recordClaims('s1', [{ seq: 3, kind: 'saving', component: 'fresh', basis: 'exact-tokenizer', tokens: 42, at: 1 }])
107
+ first.close()
108
+
109
+ // 外部篡改 user_version(模拟不兼容代际)
110
+ const raw = new DatabaseSync(path)
111
+ raw.exec(`PRAGMA user_version = ${STATS_SCHEMA_VERSION + 99}`)
112
+ raw.close()
113
+
114
+ const reopened = await openStatsDatabase(path)
115
+ expect(reopened).not.toBeNull()
116
+ const { db } = reopened!
117
+ try {
118
+ expect(Number(pragma(db, 'PRAGMA user_version').user_version)).toBe(STATS_SCHEMA_VERSION)
119
+ expect(Number(pragma(db, 'PRAGMA application_id').application_id)).toBe(CCI_STATS_APPLICATION_ID)
120
+ expect(countRows(path, 'claims')).toBe(0)
121
+ } finally {
122
+ db.close()
123
+ }
124
+ })
125
+
126
+ it('二次打开幂等:数据原样保留,建表语句空转不报错', async () => {
127
+ const path = tempDbPath('idempotent-open')
128
+ const first = await openStore(path)
129
+ expect(first.recordClaims('s1', [{ seq: 1, kind: 'usage', component: 'input', basis: '', tokens: 10, at: 1 }])).toBe(1)
130
+ first.close()
131
+ const second = await openStore(path) // ensureSchema 空转不抛
132
+ expect(countRows(path, 'claims')).toBe(1)
133
+ second.close()
134
+ })
135
+ })
136
+
137
+ describe('resolveStatsDbPath(T2 路径解析优先级)', () => {
138
+ const expected = (home: string) => join(home, 'storages', 'dsh-context-compression', 'stats.sqlite')
139
+
140
+ it('dbPath 显式覆盖最高优先;空白串按未设置', () => {
141
+ expect(resolveStatsDbPath({ dbPath: 'X:/custom/stats.sqlite', dshHome: 'X:/home' })).toBe('X:/custom/stats.sqlite')
142
+ expect(resolveStatsDbPath({ dbPath: ' ', dshHome: 'X:/home' })).toBe(expected('X:/home'))
143
+ })
144
+
145
+ it('dshHome > $DSH_HOME > homedir/.dsh;空 env 按未设置(镜像宿主 resolveDshHome 语义)', () => {
146
+ expect(resolveStatsDbPath({ dshHome: 'X:/explicit', env: { DSH_HOME: 'X:/env' } })).toBe(expected('X:/explicit'))
147
+ expect(resolveStatsDbPath({ env: { DSH_HOME: 'X:/env' } })).toBe(expected('X:/env'))
148
+ // 空白 env 按未设置 → 兜底 homedir/.dsh(宿主 resolveDshHome 同语义)
149
+ expect(resolveStatsDbPath({ env: { DSH_HOME: ' ' } })).toBe(join(homedir(), '.dsh', 'storages', 'dsh-context-compression', 'stats.sqlite'))
150
+ expect(resolveStatsDbPath({ env: {} })).toBe(join(homedir(), '.dsh', 'storages', 'dsh-context-compression', 'stats.sqlite'))
151
+ })
152
+ })
153
+
154
+ describe('recordClaims 与聚合(T3 + BC #2671 两断言 + 写后读回对账)', () => {
155
+ it('幂等重放零新增:同一批行二次落库 added=0 且总行数不变', async () => {
156
+ const path = tempDbPath('replay')
157
+ const store = await openStore(path)
158
+ const rows = [
159
+ { seq: 5, kind: 'saving' as const, component: 'fresh', basis: 'exact-tokenizer', tokens: 900, at: 10 },
160
+ { seq: 5, kind: 'offset' as const, component: 'retrieve', basis: 'characters', tokens: 200, at: 11 },
161
+ { seq: 6, kind: 'usage' as const, component: 'input', basis: '', tokens: 1234, at: 12 },
162
+ ]
163
+ expect(store.recordClaims('s1', rows)).toBe(3)
164
+ expect(store.recordClaims('s1', rows)).toBe(0)
165
+ expect(countRows(path, 'claims')).toBe(3)
166
+ store.close()
167
+ })
168
+
169
+ it('跨会话不覆盖(BC #2671-2):同 (seq,kind,component,basis) 两会话各自完整', async () => {
170
+ const store = await openStore(tempDbPath('cross-session'))
171
+ store.recordClaims('s1', [{ seq: 7, kind: 'saving', component: 'fresh', basis: 'exact-tokenizer', tokens: 100, at: 1 }])
172
+ store.recordClaims('s2', [{ seq: 7, kind: 'saving', component: 'fresh', basis: 'exact-tokenizer', tokens: 250, at: 2 }])
173
+ const per = store.perSessionAggregates()
174
+ expect(per).toHaveLength(2)
175
+ expect(per.find(row => row.sessionId === 's1')?.gross.exact).toBe(100)
176
+ expect(per.find(row => row.sessionId === 's2')?.gross.exact).toBe(250)
177
+ // 净额精确降序
178
+ expect(per[0]?.sessionId).toBe('s2')
179
+ store.close()
180
+ })
181
+
182
+ it('latestActiveSessionId:claims.at 最大者为最近压缩会话(空库 undefined)', async () => {
183
+ const store = await openStore(tempDbPath('latest-active'))
184
+ expect(store.latestActiveSessionId()).toBeUndefined()
185
+ store.recordClaims('s-old', [{ seq: 1, kind: 'saving', component: 'fresh', basis: 'characters', tokens: 10, at: 100 }])
186
+ store.recordClaims('s-new', [{ seq: 1, kind: 'usage', component: 'input', basis: '', tokens: 20, at: 200 }])
187
+ expect(store.latestActiveSessionId()).toBe('s-new')
188
+ store.close()
189
+ })
190
+ it('sessionComponents:按路径×口径聚合 saving,可聚焦单会话,不含 usage/offset', async () => {
191
+ const store = await openStore(tempDbPath('components'))
192
+ store.recordClaims('s1', [
193
+ { seq: 1, kind: 'saving', component: 'fresh', basis: 'exact-tokenizer', tokens: 900, at: 1 },
194
+ { seq: 2, kind: 'saving', component: 'fresh', basis: 'exact-tokenizer', tokens: 100, at: 2 },
195
+ { seq: 3, kind: 'saving', component: 'history', basis: 'characters', tokens: 400, at: 3 },
196
+ { seq: 4, kind: 'offset', component: 'retrieve', basis: 'characters', tokens: 150, at: 4 },
197
+ { seq: 5, kind: 'usage', component: 'input', basis: '', tokens: 5000, at: 5 },
198
+ ])
199
+ store.recordClaims('s2', [{ seq: 1, kind: 'saving', component: 'tail-trim', basis: 'characters', tokens: 77, at: 6 }])
200
+ expect(store.sessionComponents('s1')).toEqual([
201
+ { component: 'fresh', basis: 'exact-tokenizer', tokens: 1000, events: 2 },
202
+ { component: 'history', basis: 'characters', tokens: 400, events: 1 },
203
+ ])
204
+ // 无 sessionId = 全库组成,按 tokens 降序
205
+ const all = store.sessionComponents()
206
+ expect(all[0]).toEqual({ component: 'fresh', basis: 'exact-tokenizer', tokens: 1000, events: 2 })
207
+ expect(all).toHaveLength(3)
208
+ store.close()
209
+ })
210
+
211
+ it('绝对 seq 写后读回对账(BC #2671-1):perSession/total 与逐条目手算一致', async () => {
212
+ const store = await openStore(tempDbPath('reconcile'))
213
+ store.recordClaims('s1', [
214
+ { seq: 3, kind: 'saving', component: 'fresh', basis: 'exact-tokenizer', tokens: 1000, at: 1 },
215
+ { seq: 9, kind: 'saving', component: 'history', basis: 'characters', tokens: 400, at: 2 },
216
+ { seq: 12, kind: 'offset', component: 'retrieve', basis: 'characters', tokens: 150, at: 3 },
217
+ ])
218
+ store.recordClaims('s2', [
219
+ { seq: 4, kind: 'saving', component: 'tail-trim', basis: 'exact-tokenizer', tokens: 700, at: 4 },
220
+ { seq: 8, kind: 'offset', component: 'full-read', basis: 'exact-tokenizer', tokens: 300, at: 5 },
221
+ ])
222
+ const per = store.perSessionAggregates()
223
+ const s1 = per.find(row => row.sessionId === 's1')!
224
+ const s2 = per.find(row => row.sessionId === 's2')!
225
+ expect(s1.gross).toEqual({ exact: 1000, estimated: 400 })
226
+ expect(s1.offsets).toEqual({ exact: 0, estimated: 150 })
227
+ expect(s1.net).toEqual({ exact: 1000, estimated: 250 })
228
+ expect(s2.net).toEqual({ exact: 400, estimated: 0 })
229
+ expect(store.total()).toEqual({
230
+ gross: { exact: 1700, estimated: 400 },
231
+ offsets: { exact: 300, estimated: 150 },
232
+ net: { exact: 1400, estimated: 250 },
233
+ })
234
+ store.close()
235
+ })
236
+
237
+ it('sumSamples:边界采样按组件累计、calls=distinct 边界数;重放零增量', async () => {
238
+ const store = await openStore(tempDbPath('samples'))
239
+ const sampleRows = (seq: number, netExact: number, netEstimated: number, cached: number, uncached: number) => ([
240
+ { seq, kind: 'sample' as const, component: 'netExact', basis: '', tokens: netExact, at: seq * 10 },
241
+ { seq, kind: 'sample' as const, component: 'netEstimated', basis: '', tokens: netEstimated, at: seq * 10 },
242
+ { seq, kind: 'sample' as const, component: 'cachedInput', basis: '', tokens: cached, at: seq * 10 },
243
+ { seq, kind: 'sample' as const, component: 'uncachedInput', basis: '', tokens: uncached, at: seq * 10 },
244
+ ])
245
+ const batch = [...sampleRows(10, 100, 50, 900, 100), ...sampleRows(11, 80, 40, 950, 50)]
246
+ expect(store.recordClaims('s1', batch)).toBe(8)
247
+ expect(store.recordClaims('s1', batch)).toBe(0)
248
+ expect(store.sumSamples('s1')).toEqual({ netExact: 180, netEstimated: 90, cachedInput: 1850, uncachedInput: 150, calls: 2 })
249
+ // 别的会话没有采样
250
+ expect(store.sumSamples('s2').calls).toBe(0)
251
+ store.close()
252
+ })
253
+
254
+ it('水位单调不减 + source 一旦 live 不被 backfill 降级', async () => {
255
+ const path = tempDbPath('watermark')
256
+ const store = await openStore(path)
257
+ expect(store.getSessionWatermark('unknown')).toBe(0)
258
+ store.setSessionWatermark('s1', 7, { project: 'p', source: 'live' })
259
+ expect(store.getSessionWatermark('s1')).toBe(7)
260
+ store.setSessionWatermark('s1', 3, { source: 'backfill' })
261
+ expect(store.getSessionWatermark('s1')).toBe(7)
262
+ store.setSessionWatermark('s1', 9, { source: 'backfill' })
263
+ expect(store.getSessionWatermark('s1')).toBe(9)
264
+ const db = new DatabaseSync(path)
265
+ try {
266
+ const row = db.prepare(`SELECT project, source FROM sessions WHERE session_id = 's1'`).get() as { project: string; source: string }
267
+ expect(row).toEqual({ project: 'p', source: 'live' })
268
+ } finally {
269
+ db.close()
270
+ }
271
+ store.close()
272
+ })
273
+
274
+ it('拒收坏行:未知 kind / 非有限数抛错;关闭后调用即抛', async () => {
275
+ const store = await openStore(tempDbPath('bad-rows'))
276
+ expect(() => store.recordClaims('s1', [{ seq: 1, kind: 'wat' as never, component: 'x', basis: '', tokens: 1, at: 1 }])).toThrow(/unsupported claim kind/)
277
+ expect(() => store.recordClaims('s1', [{ seq: Number.NaN, kind: 'usage', component: 'x', basis: '', tokens: 1, at: 1 }])).toThrow(/non-finite/)
278
+ expect(() => store.setSessionWatermark('s1', -2)).toThrow(/non-negative/)
279
+ store.close()
280
+ expect(store.isOpen).toBe(false)
281
+ expect(() => store.recordClaims('s1', [{ seq: 1, kind: 'usage', component: 'x', basis: '', tokens: 1, at: 1 }])).toThrow(/closed/)
282
+ })
283
+ })
284
+
285
+ describe('双连接并发写(busy_timeout/多实例拓扑)', () => {
286
+ it('同一文件两个句柄交替写小事务互不失败,合并对账一致', async () => {
287
+ const path = tempDbPath('two-conns')
288
+ const a = await openStore(path)
289
+ const b = await openStore(path)
290
+ try {
291
+ a.recordClaims('s1', [{ seq: 1, kind: 'saving', component: 'fresh', basis: 'exact-tokenizer', tokens: 10, at: 1 }])
292
+ b.recordClaims('s2', [{ seq: 1, kind: 'saving', component: 'fresh', basis: 'exact-tokenizer', tokens: 20, at: 2 }])
293
+ a.recordClaims('s1', [{ seq: 2, kind: 'offset', component: 'retrieve', basis: 'characters', tokens: 4, at: 3 }])
294
+ b.recordClaims('s2', [{ seq: 2, kind: 'offset', component: 'retrieve', basis: 'characters', tokens: 8, at: 4 }])
295
+ expect(b.total().net).toEqual({ exact: 30, estimated: -12 })
296
+ expect(a.perSessionAggregates()).toHaveLength(2)
297
+ // 另一连接写过的行重放:幂等零新增(跨连接的主键去重)
298
+ expect(b.recordClaims('s1', [{ seq: 1, kind: 'saving', component: 'fresh', basis: 'exact-tokenizer', tokens: 10, at: 1 }])).toBe(0)
299
+ expect(countRows(path, 'claims')).toBe(4)
300
+ } finally {
301
+ a.close()
302
+ b.close()
303
+ }
304
+ })
305
+ })
306
+
307
+ describe('生命周期与可见降级(T5:warn 恰一次 + persisted 状态导出)', () => {
308
+ /** resetModules 拿全新模块实例,单例与 warn 门闩互不串扰。 */
309
+ async function freshStatsDbModule() {
310
+ vi.resetModules()
311
+ return await import('../../src/runtime/stats-db.ts')
312
+ }
313
+
314
+ it('ensureStatsStore 幂等打开;closeStatsStore 后状态回落 not-opened', async () => {
315
+ const mod = await freshStatsDbModule()
316
+ const path = tempDbPath('lifecycle')
317
+ const store = await mod.ensureStatsStore(path)
318
+ expect(store).not.toBeNull()
319
+ expect(mod.getStatsStore()).toBe(store)
320
+ expect(mod.statsPersistenceState()).toMatchObject({ persisted: true })
321
+ const again = await mod.ensureStatsStore(path)
322
+ expect(again).toBe(store)
323
+ mod.closeStatsStore()
324
+ expect(mod.getStatsStore()).toBeNull()
325
+ expect(mod.statsPersistenceState()).toMatchObject({ persisted: false, reason: 'not-opened', driver: null })
326
+ expect(store?.isOpen).toBe(false)
327
+ })
328
+
329
+ it('open 失败(他人库)→ 不抛、persisted:false reason=open-failed、warn 恰一次', async () => {
330
+ const mod = await freshStatsDbModule()
331
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
332
+ const path = join(tempDir('foreign-lc'), 'stats.sqlite')
333
+ const raw = new DatabaseSync(path)
334
+ raw.exec(`CREATE TABLE IF NOT EXISTS sentinel (x INTEGER)`)
335
+ raw.exec(`PRAGMA application_id = ${OFFICIAL_SESSION_QUERY_APPLICATION_ID}`)
336
+ raw.close()
337
+
338
+ const first = await mod.ensureStatsStore(path)
339
+ const second = await mod.ensureStatsStore(path)
340
+ expect(first).toBeNull()
341
+ expect(second).toBeNull()
342
+ expect(mod.statsPersistenceState()).toMatchObject({ persisted: false, reason: 'open-failed', driver: null })
343
+ expect(warn).toHaveBeenCalledTimes(1)
344
+ })
345
+
346
+ it('ctx.effect 卸载缝:close 后句柄不泄漏(isOpen=false + 目录可整体删除)', async () => {
347
+ const mod = await freshStatsDbModule()
348
+ const dir = tempDir('effect-close')
349
+ const path = join(dir, 'stats.sqlite')
350
+ const store = await mod.ensureStatsStore(path)
351
+ expect(store?.isOpen).toBe(true)
352
+ // 模拟 ctx.effect 清理器:再次卸载幂等,不抛
353
+ mod.closeStatsStore()
354
+ mod.closeStatsStore()
355
+ expect(store?.isOpen).toBe(false)
356
+ // 句柄已释放:WAL 残留文件不阻碍整目录删除
357
+ rmSync(dir, { recursive: true, force: true })
358
+ expect(getStatsStore()).toBeNull()
359
+ expect(statsPersistenceState()).toMatchObject({ persisted: false, reason: 'not-opened' })
360
+ })
361
+ })
@@ -0,0 +1,55 @@
1
+ /**
2
+ * T33:审计消息净化 + 统计库隐私守卫——errorMessage 首行/截断/控制字符折叠,
3
+ * 以及 claims 表字段封闭性(component/kind 全部白名单枚举,自由文本无处落表)。
4
+ */
5
+ import { mkdtempSync, rmSync } from 'node:fs'
6
+ import { tmpdir } from 'node:os'
7
+ import { join } from 'node:path'
8
+ import { DatabaseSync } from 'node:sqlite'
9
+ import { afterEach, describe, expect, it } from 'vitest'
10
+ import { AUDIT_MESSAGE_MAX_CHARS, sanitizeAuditMessage } from '../../src/runtime/audit.ts'
11
+ import { STATS_CLAIM_KINDS } from '../../src/runtime/stats-schema.ts'
12
+ import { closeStatsStore, ensureStatsStore, getStatsStore } from '../../src/runtime/stats-db.ts'
13
+ import { claimFromLand } from '../../src/runtime/stats-sync.ts'
14
+
15
+ const dirs: string[] = []
16
+
17
+ afterEach(() => {
18
+ closeStatsStore()
19
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
20
+ })
21
+
22
+ describe('sanitizeAuditMessage(T33)', () => {
23
+ it('多行取首行、控制字符折叠、超长截断', () => {
24
+ expect(sanitizeAuditMessage(new Error('boom at line1\n at stack (file.ts:1)\n at deeper'))).toBe('boom at line1')
25
+ expect(sanitizeAuditMessage('a\tb\u0000c')).toBe('a b c')
26
+ const long = 'x'.repeat(500)
27
+ expect(sanitizeAuditMessage(long)).toHaveLength(AUDIT_MESSAGE_MAX_CHARS)
28
+ expect(sanitizeAuditMessage(new Error('普通长度消息'))).toBe('普通长度消息')
29
+ expect(sanitizeAuditMessage(42)).toBe('42')
30
+ })
31
+ })
32
+
33
+ describe('统计库隐私守卫(自由文本无处落表)', () => {
34
+ it('claims 表的 kind/component 恒为封闭枚举;无自由文本列', async () => {
35
+ const dir = mkdtempSync(join(tmpdir(), 'cci-privacy-'))
36
+ dirs.push(dir)
37
+ const store = await ensureStatsStore(join(dir, 'stats.sqlite'))
38
+ if (store === null || getStatsStore() === null) throw new Error('no sqlite driver')
39
+ claimFromLand({ sessionId: 'sess-privacy', component: 'fresh', tokensBefore: 500, tokensAfter: 100, basis: 'exact-tokenizer', replacementSeq: 7 })
40
+ const db = new DatabaseSync(join(dir, 'stats.sqlite'))
41
+ try {
42
+ const kinds = (db.prepare(`SELECT DISTINCT kind FROM claims`).all() as { kind: string }[]).map(row => row.kind)
43
+ expect(kinds.every(kind => (STATS_CLAIM_KINDS as readonly string[]).includes(kind))).toBe(true)
44
+ const components = (db.prepare(`SELECT DISTINCT component FROM claims`).all() as { component: string }[]).map(row => row.component)
45
+ // component 全部是白名单枚举值(保存组件/科目/sample 字段名),绝非任意文本
46
+ const COMPONENT_WHITELIST = new Set(['fresh', 'aggregate', 'history', 'tail-trim', 'dedupe', 'native', 'projection', 'retrieve', 'tailtrim-retrieve', 'full-read', 'input', 'output', 'cacheRead', 'cacheWrite', 'netExact', 'netEstimated', 'cachedInput', 'uncachedInput'])
47
+ expect(components.every(component => COMPONENT_WHITELIST.has(component))).toBe(true)
48
+ // claims 表无 message/text/note 类列——自由文本没有落表位置
49
+ const columns = (db.prepare(`PRAGMA table_info(claims)`).all() as { name: string }[]).map(row => row.name)
50
+ expect(columns).toEqual(['session_id', 'seq', 'kind', 'component', 'basis', 'tokens', 'at'])
51
+ } finally {
52
+ db.close()
53
+ }
54
+ })
55
+ })