@unerr-ai/unerr 0.1.6 → 0.1.7

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 (218) hide show
  1. package/README.md +70 -194
  2. package/dist/cli.js +39149 -36991
  3. package/package.json +9 -2
  4. package/dist/__tests__/architecture-guard.test.js +0 -122
  5. package/dist/__tests__/arg-validator.test.js +0 -205
  6. package/dist/__tests__/ast-extractor.test.js +0 -203
  7. package/dist/__tests__/auto-bootstrap.test.js +0 -280
  8. package/dist/__tests__/background-indexer.test.js +0 -228
  9. package/dist/__tests__/blast-radius-engine.test.js +0 -200
  10. package/dist/__tests__/bridge-isolation.test.js +0 -37
  11. package/dist/__tests__/budget-enforcer.test.js +0 -53
  12. package/dist/__tests__/cfg-test-detection-perf.test.js +0 -82
  13. package/dist/__tests__/change-narrative.test.js +0 -190
  14. package/dist/__tests__/check-commit.test.js +0 -258
  15. package/dist/__tests__/checksum.test.js +0 -34
  16. package/dist/__tests__/commit-watcher.test.js +0 -154
  17. package/dist/__tests__/community-detection.test.js +0 -179
  18. package/dist/__tests__/community-tools.test.js +0 -299
  19. package/dist/__tests__/components.test.js +0 -449
  20. package/dist/__tests__/compression-log.test.js +0 -174
  21. package/dist/__tests__/compression-quality-monitor.test.js +0 -40
  22. package/dist/__tests__/config-healer.test.js +0 -165
  23. package/dist/__tests__/context-ledger.test.js +0 -58
  24. package/dist/__tests__/convention-detector.test.js +0 -99
  25. package/dist/__tests__/convention-learner.test.js +0 -86
  26. package/dist/__tests__/correction-detector.test.js +0 -330
  27. package/dist/__tests__/daemon-autostart-install.test.js +0 -283
  28. package/dist/__tests__/daemon-bridge.test.js +0 -222
  29. package/dist/__tests__/daemon-dashboard.test.js +0 -202
  30. package/dist/__tests__/daemon-registry.test.js +0 -240
  31. package/dist/__tests__/daemon-supervisor.test.js +0 -318
  32. package/dist/__tests__/daemon-version-check.test.js +0 -275
  33. package/dist/__tests__/decision-point-detector.test.js +0 -98
  34. package/dist/__tests__/deep-link.test.js +0 -143
  35. package/dist/__tests__/disallowed-tools.test.js +0 -115
  36. package/dist/__tests__/drift-tracker.test.js +0 -582
  37. package/dist/__tests__/durability-scorer.test.js +0 -152
  38. package/dist/__tests__/efficiency-tracker.test.js +0 -65
  39. package/dist/__tests__/enrich.test.js +0 -144
  40. package/dist/__tests__/entity-rewind.test.js +0 -248
  41. package/dist/__tests__/ephemeral.test.js +0 -111
  42. package/dist/__tests__/exploration-cost.test.js +0 -93
  43. package/dist/__tests__/fact-generator.test.js +0 -197
  44. package/dist/__tests__/file-l0-graph.test.js +0 -244
  45. package/dist/__tests__/file-logger.test.js +0 -82
  46. package/dist/__tests__/file-outline.test.js +0 -141
  47. package/dist/__tests__/file-read-protocol.test.js +0 -188
  48. package/dist/__tests__/format-encoder.test.js +0 -233
  49. package/dist/__tests__/git-attribution.test.js +0 -259
  50. package/dist/__tests__/graph-temporal-joiner.test.js +0 -219
  51. package/dist/__tests__/health-grade-enhanced.test.js +0 -138
  52. package/dist/__tests__/health-map-data.test.js +0 -173
  53. package/dist/__tests__/helpers/mcp-harness.js +0 -45
  54. package/dist/__tests__/helpers/mcp-harness.test.js +0 -68
  55. package/dist/__tests__/hook-dedup.test.js +0 -112
  56. package/dist/__tests__/hook-runner.test.js +0 -253
  57. package/dist/__tests__/indexer-cfg.test.js +0 -185
  58. package/dist/__tests__/indexer-cross-file.test.js +0 -172
  59. package/dist/__tests__/indexer-extraction.test.js +0 -245
  60. package/dist/__tests__/indexer-incremental.test.js +0 -232
  61. package/dist/__tests__/indexer-language-expansion.test.js +0 -165
  62. package/dist/__tests__/init-push.test.js +0 -131
  63. package/dist/__tests__/instruction-writer.test.js +0 -179
  64. package/dist/__tests__/intelligence-integration.test.js +0 -217
  65. package/dist/__tests__/intent-correlator.test.js +0 -175
  66. package/dist/__tests__/intent-detector.test.js +0 -235
  67. package/dist/__tests__/intent-encoder.test.js +0 -167
  68. package/dist/__tests__/java-build-tool-detection.test.js +0 -174
  69. package/dist/__tests__/layer3-sprint-q.test.js +0 -160
  70. package/dist/__tests__/layer3-sprint-r.test.js +0 -91
  71. package/dist/__tests__/layer3-sprint-s.test.js +0 -183
  72. package/dist/__tests__/layer3-sprint-t.test.js +0 -201
  73. package/dist/__tests__/layer3-sprint-u.test.js +0 -174
  74. package/dist/__tests__/layer4-sprint-ba2.test.js +0 -354
  75. package/dist/__tests__/layer4-sprint-ba4.test.js +0 -84
  76. package/dist/__tests__/layer4-sprint-vs.test.js +0 -105
  77. package/dist/__tests__/ledger-chains.test.js +0 -162
  78. package/dist/__tests__/lifecycle-machine.test.js +0 -226
  79. package/dist/__tests__/local-chat-provider.test.js +0 -170
  80. package/dist/__tests__/local-convention-detector.test.js +0 -308
  81. package/dist/__tests__/local-embeddings.test.js +0 -422
  82. package/dist/__tests__/local-graph.test.js +0 -540
  83. package/dist/__tests__/local-indexer.test.js +0 -228
  84. package/dist/__tests__/local-intelligence-l3.test.js +0 -332
  85. package/dist/__tests__/local-llm.test.js +0 -253
  86. package/dist/__tests__/local-mode-offline.test.js +0 -187
  87. package/dist/__tests__/local-mode-stats.test.js +0 -273
  88. package/dist/__tests__/local-mode-tui.test.js +0 -343
  89. package/dist/__tests__/local-parse.test.js +0 -199
  90. package/dist/__tests__/log-tailer.test.js +0 -208
  91. package/dist/__tests__/loop-breaker.test.js +0 -276
  92. package/dist/__tests__/loop-miner.test.js +0 -226
  93. package/dist/__tests__/mcp-config.test.js +0 -126
  94. package/dist/__tests__/mcp-content-json.test.js +0 -10
  95. package/dist/__tests__/mcp-envelope.test.js +0 -124
  96. package/dist/__tests__/metrics-store.test.js +0 -223
  97. package/dist/__tests__/native-watcher.test.js +0 -191
  98. package/dist/__tests__/navigation-hooks-agent-aware.test.js +0 -145
  99. package/dist/__tests__/negative-knowledge.test.js +0 -116
  100. package/dist/__tests__/network-boundary.test.js +0 -190
  101. package/dist/__tests__/network-firewall.test.js +0 -112
  102. package/dist/__tests__/nudge-invariants.test.js +0 -160
  103. package/dist/__tests__/nudge-v2.test.js +0 -225
  104. package/dist/__tests__/offline-rewind.test.js +0 -251
  105. package/dist/__tests__/open-threads.test.js +0 -89
  106. package/dist/__tests__/output-compressor.test.js +0 -93
  107. package/dist/__tests__/pending-violations.test.js +0 -112
  108. package/dist/__tests__/persistence-effectiveness.test.js +0 -143
  109. package/dist/__tests__/provider-factory.test.js +0 -42
  110. package/dist/__tests__/providers.test.js +0 -24
  111. package/dist/__tests__/proxy.test.js +0 -314
  112. package/dist/__tests__/query-router.test.js +0 -1018
  113. package/dist/__tests__/reasoning-quality-route.test.js +0 -138
  114. package/dist/__tests__/redactor.test.js +0 -120
  115. package/dist/__tests__/resource-monitor.test.js +0 -57
  116. package/dist/__tests__/response-envelope.test.js +0 -100
  117. package/dist/__tests__/risk-classifier.test.js +0 -101
  118. package/dist/__tests__/risk-signal-scope.test.js +0 -75
  119. package/dist/__tests__/rule-evaluator.test.js +0 -280
  120. package/dist/__tests__/scip-decoder.test.js +0 -49
  121. package/dist/__tests__/scip-downloader.test.js +0 -201
  122. package/dist/__tests__/scip-merger.test.js +0 -103
  123. package/dist/__tests__/search-index.test.js +0 -422
  124. package/dist/__tests__/semantic-enrichment.test.js +0 -360
  125. package/dist/__tests__/session-brief-builder.test.js +0 -187
  126. package/dist/__tests__/session-context.test.js +0 -221
  127. package/dist/__tests__/session-continuity.test.js +0 -144
  128. package/dist/__tests__/session-dedup.test.js +0 -74
  129. package/dist/__tests__/session-event-wiring.test.js +0 -206
  130. package/dist/__tests__/session-events.test.js +0 -149
  131. package/dist/__tests__/session-legend.test.js +0 -20
  132. package/dist/__tests__/session-persistence.test.js +0 -131
  133. package/dist/__tests__/session-resume-block.test.js +0 -107
  134. package/dist/__tests__/session-resume.test.js +0 -97
  135. package/dist/__tests__/session-summary-writer.test.js +0 -134
  136. package/dist/__tests__/shadow-ledger.test.js +0 -203
  137. package/dist/__tests__/shell-classifier.test.js +0 -151
  138. package/dist/__tests__/shell-compression-floor.test.js +0 -189
  139. package/dist/__tests__/shell-compression-v2.test.js +0 -339
  140. package/dist/__tests__/shell-compressor.test.js +0 -35
  141. package/dist/__tests__/shell-hooks.test.js +0 -128
  142. package/dist/__tests__/shell-strategies.test.js +0 -644
  143. package/dist/__tests__/shell-tee.test.js +0 -133
  144. package/dist/__tests__/signal-dedup.test.js +0 -158
  145. package/dist/__tests__/signal-reinforcer.test.js +0 -77
  146. package/dist/__tests__/signal-scorer.test.js +0 -251
  147. package/dist/__tests__/signal-show-store.test.js +0 -108
  148. package/dist/__tests__/smart-truncate.test.js +0 -215
  149. package/dist/__tests__/snapshot-v2.test.js +0 -113
  150. package/dist/__tests__/sprint-l1-local-mode.test.js +0 -130
  151. package/dist/__tests__/sprint-l10-boot.test.js +0 -220
  152. package/dist/__tests__/sprint-l9-offline-commands.test.js +0 -189
  153. package/dist/__tests__/sprint-q-persistent-context.test.js +0 -198
  154. package/dist/__tests__/sprint-s1-wiring.test.js +0 -215
  155. package/dist/__tests__/sprint-s2-wiring.test.js +0 -256
  156. package/dist/__tests__/sprint-s3-wiring.test.js +0 -195
  157. package/dist/__tests__/sprint-s4-wiring.test.js +0 -213
  158. package/dist/__tests__/sprint-s6-hooks.test.js +0 -222
  159. package/dist/__tests__/sprint-s7-persistent.test.js +0 -263
  160. package/dist/__tests__/sprint-s8-value.test.js +0 -167
  161. package/dist/__tests__/sprint-s9-behavioral.test.js +0 -179
  162. package/dist/__tests__/sprint3-intelligence.test.js +0 -297
  163. package/dist/__tests__/sprint5-mcp-server.test.js +0 -136
  164. package/dist/__tests__/startup-display.test.js +0 -302
  165. package/dist/__tests__/startup-log-file.test.js +0 -97
  166. package/dist/__tests__/stash-manager.test.js +0 -229
  167. package/dist/__tests__/state-detector.test.js +0 -92
  168. package/dist/__tests__/status-dashboard.test.js +0 -142
  169. package/dist/__tests__/temporal-facts.test.js +0 -292
  170. package/dist/__tests__/temporal-routes.test.js +0 -142
  171. package/dist/__tests__/test-detector.test.js +0 -174
  172. package/dist/__tests__/theme.test.js +0 -72
  173. package/dist/__tests__/timeline-agents.test.js +0 -122
  174. package/dist/__tests__/timeline-bootstrap.test.js +0 -176
  175. package/dist/__tests__/timeline-filters.test.js +0 -193
  176. package/dist/__tests__/timeline-markers.test.js +0 -151
  177. package/dist/__tests__/timeline-routes.test.js +0 -156
  178. package/dist/__tests__/timeline-store.test.js +0 -171
  179. package/dist/__tests__/token-counter.test.js +0 -86
  180. package/dist/__tests__/token-estimator.test.js +0 -96
  181. package/dist/__tests__/token-flow-api.test.js +0 -239
  182. package/dist/__tests__/token-flow-instrumentation.test.js +0 -437
  183. package/dist/__tests__/token-flow-persistence.test.js +0 -356
  184. package/dist/__tests__/token-flow-routes.test.js +0 -199
  185. package/dist/__tests__/token-flow.test.js +0 -695
  186. package/dist/__tests__/tool-clusters.test.js +0 -177
  187. package/dist/__tests__/transport-mux.test.js +0 -283
  188. package/dist/__tests__/turn-segmenter.test.js +0 -166
  189. package/dist/__tests__/uninstall.test.js +0 -141
  190. package/dist/__tests__/warm-start-policy.test.js +0 -271
  191. package/dist/__tests__/wire-cap-nudge.test.js +0 -77
  192. package/dist/__tests__/worker-pool.test.js +0 -101
  193. package/dist/ui/assets/index-7gl3mIuY.css +0 -1
  194. package/dist/ui/assets/index-CX4FCWGT.js +0 -10
  195. package/dist/ui/assets/rolldown-runtime-S-ySWqyJ.js +0 -1
  196. package/dist/ui/assets/vis-network-NIJHUFI3.js +0 -908
  197. package/dist/ui/fonts/jetbrains-mono-latin-400-normal.woff +0 -0
  198. package/dist/ui/icon-wordmark.png +0 -0
  199. package/dist/ui/icon-wordmark.svg +0 -30
  200. package/dist/ui/icon.png +0 -0
  201. package/dist/ui/icon.svg +0 -25
  202. package/dist/ui/index.html +0 -15
  203. package/dist/ui/prototype-sandbox/index.html +0 -257
  204. package/dist/ui/screenshots/activity.png +0 -0
  205. package/dist/ui/screenshots/code-base-intelligence.png +0 -0
  206. package/dist/ui/screenshots/dashboard.png +0 -0
  207. package/dist/ui/screenshots/project-memory.png +0 -0
  208. package/dist/ui/screenshots/reasoning-quality.png +0 -0
  209. package/dist/ui/screenshots/reasoning-session.png +0 -0
  210. package/dist/ui/screenshots/token-session.png +0 -0
  211. package/dist/ui/screenshots/token-trace-main.png +0 -0
  212. package/dist/ui/screenshots/token-turn.png +0 -0
  213. package/dist/ui/unerr-wordmark.png +0 -0
  214. package/dist/ui/unerr-wordmark.svg +0 -9
  215. package/dist/ui/unerr.png +0 -0
  216. package/dist/ui/unerr.svg +0 -25
  217. package/dist/ui/web-app-manifest-192x192.png +0 -0
  218. package/dist/ui/web-app-manifest-512x512.png +0 -0
@@ -1,86 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { createTokenCounter } from "../proxy/token-counter.js";
3
- describe("createTokenCounter", () => {
4
- it("accumulates tokens saved", () => {
5
- const counter = createTokenCounter({ emitEveryN: 100 });
6
- counter.record(500, 1000);
7
- counter.record(300, 800);
8
- expect(counter.getTotalSaved()).toBe(800);
9
- expect(counter.getTotalProcessed()).toBe(1800);
10
- expect(counter.getCallCount()).toBe(2);
11
- });
12
- it("emits to sink every N calls", () => {
13
- const messages = [];
14
- const counter = createTokenCounter({
15
- emitEveryN: 3,
16
- sink: (msg) => messages.push(msg),
17
- });
18
- counter.record(100, 200);
19
- counter.record(100, 200);
20
- expect(messages).toHaveLength(0);
21
- counter.record(100, 200);
22
- expect(messages).toHaveLength(1);
23
- expect(messages[0]).toContain("tokens saved");
24
- expect(messages[0]).toContain("efficiency");
25
- });
26
- it("formats large token counts with K/M suffixes", () => {
27
- const messages = [];
28
- const counter = createTokenCounter({
29
- emitEveryN: 1,
30
- sink: (msg) => messages.push(msg),
31
- });
32
- counter.record(23_400, 50_000);
33
- expect(messages[0]).toContain("23.4K");
34
- });
35
- it("calculates efficiency correctly", () => {
36
- const counter = createTokenCounter({ emitEveryN: 100 });
37
- counter.record(500, 1000);
38
- expect(counter.getEfficiency()).toBe(50);
39
- });
40
- it("handles zero processed tokens", () => {
41
- const counter = createTokenCounter({ emitEveryN: 100 });
42
- expect(counter.getEfficiency()).toBe(0);
43
- });
44
- it("emits at exactly the Nth call", () => {
45
- const messages = [];
46
- const counter = createTokenCounter({
47
- emitEveryN: 10,
48
- sink: (msg) => messages.push(msg),
49
- });
50
- for (let i = 0; i < 9; i++) {
51
- counter.record(10, 100);
52
- }
53
- expect(messages).toHaveLength(0);
54
- counter.record(10, 100);
55
- expect(messages).toHaveLength(1);
56
- });
57
- it("emits again at 2N calls", () => {
58
- const messages = [];
59
- const counter = createTokenCounter({
60
- emitEveryN: 5,
61
- sink: (msg) => messages.push(msg),
62
- });
63
- for (let i = 0; i < 10; i++) {
64
- counter.record(10, 100);
65
- }
66
- expect(messages).toHaveLength(2);
67
- });
68
- it("reset clears all state", () => {
69
- const counter = createTokenCounter({ emitEveryN: 100 });
70
- counter.record(500, 1000);
71
- counter.reset();
72
- expect(counter.getTotalSaved()).toBe(0);
73
- expect(counter.getTotalProcessed()).toBe(0);
74
- expect(counter.getCallCount()).toBe(0);
75
- });
76
- it("defaults to emitEveryN=10", () => {
77
- const messages = [];
78
- const counter = createTokenCounter({
79
- sink: (msg) => messages.push(msg),
80
- });
81
- for (let i = 0; i < 10; i++) {
82
- counter.record(10, 100);
83
- }
84
- expect(messages).toHaveLength(1);
85
- });
86
- });
@@ -1,96 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { estimateCost, estimateSavings, estimateTokenCount, estimateTokens, getModelCostRate, } from "../intelligence/token-estimator.js";
3
- describe("estimateTokenCount", () => {
4
- it("returns 0 for empty string", () => {
5
- expect(estimateTokenCount("")).toBe(0);
6
- });
7
- it("estimates English prose at ~chars/4", () => {
8
- const text = "The quick brown fox jumps over the lazy dog. This is a sample of English prose that should be tokenized at approximately four characters per token.";
9
- const tokens = estimateTokenCount(text);
10
- const expectedApprox = Math.ceil(text.length / 4);
11
- expect(tokens).toBeGreaterThan(expectedApprox * 0.7);
12
- expect(tokens).toBeLessThan(expectedApprox * 1.4);
13
- });
14
- it("estimates code at ~chars/3.5", () => {
15
- const code = `export function processOrder(orderId: string): Promise<OrderResult> {
16
- const order = await db.findOrder(orderId);
17
- if (!order) throw new Error("Order not found");
18
- const items = await db.getOrderItems(orderId);
19
- return { order, items, total: items.reduce((s, i) => s + i.price, 0) };
20
- }`;
21
- const tokens = estimateTokenCount(code);
22
- expect(tokens).toBeGreaterThan(code.length / 5);
23
- expect(tokens).toBeLessThan(code.length / 2);
24
- });
25
- it("estimates JSON at ~chars/3", () => {
26
- const json = JSON.stringify({
27
- name: "test-project",
28
- version: "1.0.0",
29
- dependencies: { react: "^19.0.0", typescript: "^5.0.0" },
30
- scripts: { build: "tsc", test: "vitest run" },
31
- });
32
- const tokens = estimateTokenCount(json);
33
- const expectedApprox = Math.ceil(json.length / 3);
34
- expect(tokens).toBeGreaterThan(expectedApprox * 0.6);
35
- expect(tokens).toBeLessThan(expectedApprox * 1.5);
36
- });
37
- it("handles whitespace-heavy input", () => {
38
- const text = "hello\n\n\n \n\n world \n\n\n";
39
- const tokens = estimateTokenCount(text);
40
- expect(tokens).toBeGreaterThan(0);
41
- expect(tokens).toBeLessThan(text.length);
42
- });
43
- it("estimates are consistent across multiple calls", () => {
44
- const text = "function hello() { return 42; }";
45
- const t1 = estimateTokenCount(text);
46
- const t2 = estimateTokenCount(text);
47
- expect(t1).toBe(t2);
48
- });
49
- });
50
- describe("estimateTokens", () => {
51
- it("handles null/undefined", () => {
52
- expect(estimateTokens(null)).toBe(0);
53
- expect(estimateTokens(undefined)).toBe(0);
54
- });
55
- it("handles objects by serializing", () => {
56
- const obj = { key: "value" };
57
- const tokens = estimateTokens(obj);
58
- expect(tokens).toBeGreaterThan(0);
59
- });
60
- });
61
- describe("estimateCost", () => {
62
- it("calculates cost for Claude Sonnet", () => {
63
- const cost = estimateCost("claude-sonnet-4-20250514", 1_000_000, 500_000);
64
- expect(cost).toBe(3 + 7.5);
65
- });
66
- it("uses default rates for unknown models", () => {
67
- const cost = estimateCost("unknown-model", 1_000_000, 1_000_000);
68
- expect(cost).toBe(3 + 15);
69
- });
70
- it("returns 0 for Ollama", () => {
71
- const cost = estimateCost("ollama", 1_000_000, 1_000_000);
72
- expect(cost).toBe(0);
73
- });
74
- });
75
- describe("estimateSavings", () => {
76
- it("calculates dollar savings from token reduction", () => {
77
- const savings = estimateSavings("claude-sonnet-4-20250514", 10000, 3000);
78
- expect(savings).toBeGreaterThan(0);
79
- });
80
- it("returns 0 when no savings", () => {
81
- const savings = estimateSavings("claude-sonnet-4-20250514", 1000, 1000);
82
- expect(savings).toBe(0);
83
- });
84
- });
85
- describe("getModelCostRate", () => {
86
- it("returns known model rates", () => {
87
- const rate = getModelCostRate("gpt-4o");
88
- expect(rate.inputPerMillion).toBe(2.5);
89
- expect(rate.outputPerMillion).toBe(10);
90
- });
91
- it("returns default rates for unknown models", () => {
92
- const rate = getModelCostRate("imaginary-model");
93
- expect(rate.inputPerMillion).toBe(3);
94
- expect(rate.outputPerMillion).toBe(15);
95
- });
96
- });
@@ -1,239 +0,0 @@
1
- import { mkdirSync, rmSync } from "node:fs";
2
- import os from "node:os";
3
- import { join } from "node:path";
4
- import { Hono } from "hono";
5
- import { afterEach, beforeEach, describe, expect, it } from "vitest";
6
- import { createTokenFlowRoutes } from "../server/routes/token-flow.js";
7
- import { appendSessionHistory } from "../tracking/session-history.js";
8
- import { TokenFlowWriter } from "../tracking/token-flow.js";
9
- describe("token-flow-api", () => {
10
- let tmpDir;
11
- let unerrDir;
12
- let writer;
13
- let app;
14
- beforeEach(() => {
15
- tmpDir = join(os.tmpdir(), `unerr-tfa-test-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`);
16
- unerrDir = join(tmpDir, ".unerr");
17
- mkdirSync(unerrDir, { recursive: true });
18
- writer = new TokenFlowWriter(unerrDir, "api-test-session");
19
- const routes = createTokenFlowRoutes({
20
- unerrDir,
21
- getTokenFlowWriter: () => writer,
22
- });
23
- app = new Hono();
24
- app.route("/api/token-flow", routes);
25
- });
26
- afterEach(() => {
27
- rmSync(tmpDir, { recursive: true, force: true });
28
- });
29
- // ── /api/token-flow/session ───────────────────────────────────────
30
- describe("GET /api/token-flow/session", () => {
31
- it("returns null data when no events recorded", async () => {
32
- const emptyWriter = new TokenFlowWriter(unerrDir, "empty-session");
33
- const routes = createTokenFlowRoutes({
34
- unerrDir,
35
- getTokenFlowWriter: () => emptyWriter,
36
- });
37
- const testApp = new Hono();
38
- testApp.route("/api/token-flow", routes);
39
- const res = await testApp.request("/api/token-flow/session");
40
- const body = await res.json();
41
- expect(res.status).toBe(200);
42
- expect(body.data.total_tokens_saved).toBe(0);
43
- });
44
- it("returns session summary with mechanism breakdown", async () => {
45
- writer.record({
46
- session_id: "api-test-session",
47
- turn: 1,
48
- mechanism: "graph_query",
49
- tool: "get_callers",
50
- tokens_without: 5000,
51
- tokens_with: 1800,
52
- tokens_saved: 3200,
53
- });
54
- writer.record({
55
- session_id: "api-test-session",
56
- turn: 2,
57
- mechanism: "shell_compression",
58
- tool: null,
59
- tokens_without: 2000,
60
- tokens_with: 800,
61
- tokens_saved: 1200,
62
- });
63
- const res = await app.request("/api/token-flow/session");
64
- const body = await res.json();
65
- expect(res.status).toBe(200);
66
- expect(body.data.total_tokens_saved).toBe(4400);
67
- expect(body.data.efficiency_pct).toBeGreaterThan(0);
68
- expect(body.data.by_mechanism.graph_query).toBeDefined();
69
- expect(body.data.by_mechanism.graph_query.tokens_saved).toBe(3200);
70
- expect(body.data.event_count).toBe(2);
71
- expect(body._meta.latency_ms).toBeDefined();
72
- });
73
- it("includes top_turns sorted by savings", async () => {
74
- writer.record({
75
- session_id: "api-test-session",
76
- turn: 1,
77
- mechanism: "graph_query",
78
- tool: "search_code",
79
- tokens_without: 1000,
80
- tokens_with: 800,
81
- tokens_saved: 200,
82
- });
83
- writer.record({
84
- session_id: "api-test-session",
85
- turn: 2,
86
- mechanism: "graph_query",
87
- tool: "get_callers",
88
- tokens_without: 5000,
89
- tokens_with: 1000,
90
- tokens_saved: 4000,
91
- });
92
- const res = await app.request("/api/token-flow/session");
93
- const body = await res.json();
94
- expect(body.data.top_turns[0].turn).toBe(2);
95
- expect(body.data.top_turns[0].tokens_saved).toBe(4000);
96
- });
97
- });
98
- // ── /api/token-flow/history ───────────────────────────────────────
99
- describe("GET /api/token-flow/history", () => {
100
- it("returns empty array when no history", async () => {
101
- const res = await app.request("/api/token-flow/history");
102
- const body = await res.json();
103
- expect(res.status).toBe(200);
104
- expect(body.data).toEqual([]);
105
- });
106
- it("returns sessions with tokenFlowSummary", async () => {
107
- appendSessionHistory(unerrDir, {
108
- sessionId: "hist-1",
109
- startedAt: "2026-01-01T00:00:00Z",
110
- endedAt: "2026-01-01T00:10:00Z",
111
- durationMs: 600_000,
112
- toolCalls: 10,
113
- tokensSaved: 5000,
114
- tokensProcessed: 15000,
115
- efficiency: 33,
116
- dollarsSaved: 0.15,
117
- modelId: "unknown",
118
- entityCount: 0,
119
- tokenFlowSummary: {
120
- by_mechanism: { graph_query: { tokens_saved: 4000, event_count: 5 } },
121
- top_mechanism: "graph_query",
122
- efficiency_pct: 33,
123
- total_tokens_saved: 5000,
124
- total_tokens_delivered: 10000,
125
- },
126
- });
127
- const res = await app.request("/api/token-flow/history");
128
- const body = await res.json();
129
- expect(body.data).toHaveLength(1);
130
- expect(body.data[0].token_flow.top_mechanism).toBe("graph_query");
131
- expect(body.data[0].tokens_saved).toBe(5000);
132
- });
133
- it("respects limit parameter", async () => {
134
- for (let i = 0; i < 5; i++) {
135
- appendSessionHistory(unerrDir, {
136
- sessionId: `hist-${i}`,
137
- startedAt: new Date(Date.now() - i * 60_000).toISOString(),
138
- endedAt: new Date().toISOString(),
139
- durationMs: 60_000,
140
- toolCalls: 5,
141
- tokensSaved: 1000,
142
- tokensProcessed: 3000,
143
- efficiency: 33,
144
- dollarsSaved: 0,
145
- modelId: "unknown",
146
- entityCount: 0,
147
- tokenFlowSummary: {
148
- by_mechanism: {
149
- graph_query: { tokens_saved: 1000, event_count: 3 },
150
- },
151
- top_mechanism: "graph_query",
152
- efficiency_pct: 33,
153
- total_tokens_saved: 1000,
154
- total_tokens_delivered: 2000,
155
- },
156
- });
157
- }
158
- const res = await app.request("/api/token-flow/history?limit=3");
159
- const body = await res.json();
160
- expect(body.data).toHaveLength(3);
161
- });
162
- });
163
- // ── /api/token-flow/events ────────────────────────────────────────
164
- describe("GET /api/token-flow/events", () => {
165
- it("returns all session events", async () => {
166
- writer.record({
167
- session_id: "api-test-session",
168
- turn: 1,
169
- mechanism: "graph_query",
170
- tool: "t",
171
- tokens_without: 100,
172
- tokens_with: 50,
173
- tokens_saved: 50,
174
- });
175
- writer.record({
176
- session_id: "api-test-session",
177
- turn: 2,
178
- mechanism: "graph_query",
179
- tool: "t",
180
- tokens_without: 200,
181
- tokens_with: 100,
182
- tokens_saved: 100,
183
- });
184
- const res = await app.request("/api/token-flow/events");
185
- const body = await res.json();
186
- expect(body.data).toHaveLength(2);
187
- expect(body.total).toBe(2);
188
- });
189
- it("filters by turn number", async () => {
190
- writer.record({
191
- session_id: "api-test-session",
192
- turn: 1,
193
- mechanism: "graph_query",
194
- tool: "a",
195
- tokens_without: 100,
196
- tokens_with: 50,
197
- tokens_saved: 50,
198
- });
199
- writer.record({
200
- session_id: "api-test-session",
201
- turn: 2,
202
- mechanism: "graph_query",
203
- tool: "b",
204
- tokens_without: 200,
205
- tokens_with: 100,
206
- tokens_saved: 100,
207
- });
208
- writer.record({
209
- session_id: "api-test-session",
210
- turn: 2,
211
- mechanism: "format_encoding",
212
- tool: "b",
213
- tokens_without: 100,
214
- tokens_with: 80,
215
- tokens_saved: 20,
216
- });
217
- const res = await app.request("/api/token-flow/events?turn=2");
218
- const body = await res.json();
219
- expect(body.data).toHaveLength(2);
220
- expect(body.data.every((e) => e.turn === 2)).toBe(true);
221
- });
222
- });
223
- // ── Response structure validation ─────────────────────────────────
224
- describe("response structure", () => {
225
- it("all endpoints include _meta.latency_ms", async () => {
226
- const endpoints = [
227
- "/api/token-flow/session",
228
- "/api/token-flow/history",
229
- "/api/token-flow/events",
230
- ];
231
- for (const ep of endpoints) {
232
- const res = await app.request(ep);
233
- const body = await res.json();
234
- expect(body._meta?.latency_ms).toBeDefined();
235
- expect(typeof body._meta.latency_ms).toBe("number");
236
- }
237
- });
238
- });
239
- });