dsh-context-compression-improved 0.10.1 → 0.10.2

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