@unerr-ai/unerr 0.2.1 → 0.2.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.
- package/README.md +6 -0
- package/dist/cli.js +37236 -35793
- package/package.json +1 -1
- package/dist/behaviors/agent-llm-bridge.js +0 -166
- package/dist/behaviors/architecture-guard.js +0 -256
- package/dist/behaviors/auto-doc.js +0 -247
- package/dist/behaviors/cascade-guard.js +0 -289
- package/dist/behaviors/change-narrative.js +0 -270
- package/dist/behaviors/convention-drift.js +0 -290
- package/dist/behaviors/framework.js +0 -235
- package/dist/behaviors/guard-formatter.js +0 -44
- package/dist/behaviors/incomplete-work.js +0 -270
- package/dist/behaviors/loop-breaker.js +0 -300
- package/dist/behaviors/session-continuity.js +0 -208
- package/dist/commands/branches.js +0 -97
- package/dist/commands/check-commit.js +0 -225
- package/dist/commands/compress-output.js +0 -64
- package/dist/commands/config-verify.js +0 -243
- package/dist/commands/daemon.js +0 -905
- package/dist/commands/dashboard.js +0 -52
- package/dist/commands/debug.js +0 -200
- package/dist/commands/enrich.js +0 -184
- package/dist/commands/exec.js +0 -233
- package/dist/commands/gain.js +0 -156
- package/dist/commands/hook.js +0 -88
- package/dist/commands/index.js +0 -88
- package/dist/commands/init.js +0 -74
- package/dist/commands/install.js +0 -505
- package/dist/commands/learn.js +0 -116
- package/dist/commands/manifest.js +0 -193
- package/dist/commands/rewind.js +0 -103
- package/dist/commands/serve.js +0 -19
- package/dist/commands/setup-wizard.js +0 -414
- package/dist/commands/skills.js +0 -64
- package/dist/commands/stats.js +0 -20
- package/dist/commands/status.js +0 -654
- package/dist/commands/timeline.js +0 -139
- package/dist/commands/uninstall.js +0 -230
- package/dist/components/App.js +0 -109
- package/dist/components/Banner.js +0 -12
- package/dist/components/ConfirmPrompt.js +0 -25
- package/dist/components/DriftSummary.js +0 -23
- package/dist/components/GradeBadge.js +0 -15
- package/dist/components/HealthCard.js +0 -18
- package/dist/components/InkSpinner.js +0 -22
- package/dist/components/InputBox.js +0 -17
- package/dist/components/KeyValue.js +0 -13
- package/dist/components/MessageList.js +0 -14
- package/dist/components/ProgressBar.js +0 -26
- package/dist/components/Section.js +0 -16
- package/dist/components/SessionSummaryCard.js +0 -73
- package/dist/components/StartupDisplay.js +0 -24
- package/dist/components/StatusDashboard.js +0 -57
- package/dist/components/StatusLine.js +0 -8
- package/dist/components/StepLine.js +0 -22
- package/dist/components/Theme.js +0 -20
- package/dist/components/ToolProgress.js +0 -8
- package/dist/components/ViolationList.js +0 -21
- package/dist/components/render.js +0 -13
- package/dist/config/agent-registry.js +0 -237
- package/dist/config/claude-settings-hooks.js +0 -304
- package/dist/config/hook-installer.js +0 -65
- package/dist/config/instruction-writer.js +0 -388
- package/dist/config/mcp-config-writer.js +0 -266
- package/dist/config/settings.js +0 -174
- package/dist/config/tool-detector.js +0 -42
- package/dist/config/value-surfacing.js +0 -119
- package/dist/core/context-assembly.js +0 -108
- package/dist/core/conversation.js +0 -33
- package/dist/core/local-chat-provider.js +0 -475
- package/dist/core/provider-factory.js +0 -55
- package/dist/core/providers.js +0 -90
- package/dist/core/query-engine.js +0 -174
- package/dist/daemon/api.js +0 -312
- package/dist/daemon/autostart.js +0 -119
- package/dist/daemon/bootstrap.js +0 -39
- package/dist/daemon/client.js +0 -164
- package/dist/daemon/detect-ci.js +0 -81
- package/dist/daemon/platform-linux.js +0 -146
- package/dist/daemon/platform-macos.js +0 -134
- package/dist/daemon/platform-windows.js +0 -116
- package/dist/daemon/process-manager.js +0 -299
- package/dist/daemon/protocol.js +0 -23
- package/dist/daemon/registry.js +0 -270
- package/dist/daemon/settings-schema.js +0 -72
- package/dist/daemon/system-health.js +0 -134
- package/dist/daemon/version-checker.js +0 -262
- package/dist/daemon/warm-start.js +0 -223
- package/dist/entrypoints/cli.js +0 -1043
- package/dist/entrypoints/daemon.js +0 -380
- package/dist/entrypoints/repl.js +0 -147
- package/dist/hooks/adapters/claude-code.js +0 -90
- package/dist/hooks/adapters/cline.js +0 -100
- package/dist/hooks/adapters/cursor.js +0 -98
- package/dist/hooks/hook-dedup.js +0 -79
- package/dist/hooks/hook-runner.js +0 -113
- package/dist/hooks/navigation-hooks.js +0 -175
- package/dist/hooks/prompt-hooks.js +0 -63
- package/dist/hooks/shell-hooks.js +0 -47
- package/dist/ignore.js +0 -111
- package/dist/intelligence/approach-suggester.js +0 -61
- package/dist/intelligence/ast-extractor.js +0 -2615
- package/dist/intelligence/ast-worker.js +0 -34
- package/dist/intelligence/background-indexer.js +0 -121
- package/dist/intelligence/blast-radius.js +0 -200
- package/dist/intelligence/community-detection.js +0 -691
- package/dist/intelligence/community-detector.js +0 -184
- package/dist/intelligence/computation-scheduler.js +0 -75
- package/dist/intelligence/confidence-propagation.js +0 -47
- package/dist/intelligence/convention-detector.js +0 -242
- package/dist/intelligence/convention-learner.js +0 -205
- package/dist/intelligence/convention-matcher.js +0 -205
- package/dist/intelligence/cozo-schema.js +0 -376
- package/dist/intelligence/decision-point-detector.js +0 -90
- package/dist/intelligence/deep-dive-tools.js +0 -586
- package/dist/intelligence/durability-scorer.js +0 -84
- package/dist/intelligence/exploration-cost.js +0 -204
- package/dist/intelligence/exploration-pattern-tracker.js +0 -61
- package/dist/intelligence/fact-generator.js +0 -322
- package/dist/intelligence/facts-schema.js +0 -90
- package/dist/intelligence/file-intelligence.js +0 -59
- package/dist/intelligence/graph-holder.js +0 -220
- package/dist/intelligence/graph-temporal-joiner.js +0 -238
- package/dist/intelligence/health-grade.js +0 -423
- package/dist/intelligence/health-grader.js +0 -200
- package/dist/intelligence/health-map-data.js +0 -259
- package/dist/intelligence/import-symbols.js +0 -136
- package/dist/intelligence/incremental-indexer.js +0 -658
- package/dist/intelligence/indexer/centrality.js +0 -62
- package/dist/intelligence/indexer/cfg-context.js +0 -95
- package/dist/intelligence/indexer/confidence.js +0 -34
- package/dist/intelligence/indexer/cross-file-resolver.js +0 -104
- package/dist/intelligence/indexer/edge-repair.js +0 -89
- package/dist/intelligence/indexer/entity-key.js +0 -17
- package/dist/intelligence/indexer/export-map.js +0 -132
- package/dist/intelligence/indexer/git-cochange.js +0 -128
- package/dist/intelligence/indexer/graph-patch.js +0 -147
- package/dist/intelligence/indexer/incremental.js +0 -78
- package/dist/intelligence/indexer/ingest.js +0 -160
- package/dist/intelligence/indexer/language-detect.js +0 -226
- package/dist/intelligence/indexer/metadata.js +0 -63
- package/dist/intelligence/indexer/mutation-tracker.js +0 -79
- package/dist/intelligence/indexer/orchestrator.js +0 -155
- package/dist/intelligence/indexer/plugin-interface.js +0 -31
- package/dist/intelligence/indexer/plugins/csharp.js +0 -440
- package/dist/intelligence/indexer/plugins/go.js +0 -335
- package/dist/intelligence/indexer/plugins/java.js +0 -370
- package/dist/intelligence/indexer/plugins/python.js +0 -358
- package/dist/intelligence/indexer/plugins/regex-fallback.js +0 -82
- package/dist/intelligence/indexer/plugins/ruby.js +0 -290
- package/dist/intelligence/indexer/plugins/rust.js +0 -484
- package/dist/intelligence/indexer/plugins/tier2-generic.js +0 -310
- package/dist/intelligence/indexer/plugins/typescript.js +0 -456
- package/dist/intelligence/indexer/resource-monitor.js +0 -93
- package/dist/intelligence/indexer/scip/decoder.js +0 -253
- package/dist/intelligence/indexer/scip/detector.js +0 -232
- package/dist/intelligence/indexer/scip/downloader.js +0 -427
- package/dist/intelligence/indexer/scip/fallback.js +0 -34
- package/dist/intelligence/indexer/scip/merger.js +0 -109
- package/dist/intelligence/indexer/scip/orchestrator.js +0 -433
- package/dist/intelligence/indexer/scip/runner.js +0 -98
- package/dist/intelligence/indexer/snapshot.js +0 -66
- package/dist/intelligence/indexer/test-detector.js +0 -196
- package/dist/intelligence/indexer/watch-integration.js +0 -61
- package/dist/intelligence/indexer/worker.js +0 -85
- package/dist/intelligence/local-convention-detector.js +0 -437
- package/dist/intelligence/local-embeddings.js +0 -190
- package/dist/intelligence/local-graph.js +0 -1946
- package/dist/intelligence/local-indexer.js +0 -1575
- package/dist/intelligence/local-llm.js +0 -163
- package/dist/intelligence/local-rule-generator.js +0 -154
- package/dist/intelligence/local-snapshot.js +0 -213
- package/dist/intelligence/negative-knowledge.js +0 -103
- package/dist/intelligence/persistent-db.js +0 -85
- package/dist/intelligence/query-router.js +0 -2556
- package/dist/intelligence/risk-classifier.js +0 -116
- package/dist/intelligence/rule-evaluator.js +0 -380
- package/dist/intelligence/rule-generator.js +0 -49
- package/dist/intelligence/search-index.js +0 -173
- package/dist/intelligence/semantic/docstring-extractor.js +0 -67
- package/dist/intelligence/semantic/embedding-store.js +0 -52
- package/dist/intelligence/semantic/enrichment-orchestrator.js +0 -48
- package/dist/intelligence/semantic/git-message-miner.js +0 -114
- package/dist/intelligence/semantic/identifier-tokenizer.js +0 -51
- package/dist/intelligence/semantic/node2vec-embeddings.js +0 -71
- package/dist/intelligence/semantic/node2vec-walks.js +0 -103
- package/dist/intelligence/semantic/path-domain-inference.js +0 -112
- package/dist/intelligence/semantic/similarity-engine.js +0 -60
- package/dist/intelligence/semantic/tfidf-vectors.js +0 -88
- package/dist/intelligence/session-brief-builder.js +0 -159
- package/dist/intelligence/session-context.js +0 -221
- package/dist/intelligence/session-health-monitor.js +0 -211
- package/dist/intelligence/session-narrative.js +0 -197
- package/dist/intelligence/session-pattern-analyzer.js +0 -218
- package/dist/intelligence/signal-scorer.js +0 -390
- package/dist/intelligence/signal-show-store.js +0 -182
- package/dist/intelligence/smart-truncate.js +0 -158
- package/dist/intelligence/subgraph-cache.js +0 -88
- package/dist/intelligence/temporal-facts.js +0 -494
- package/dist/intelligence/token-estimator.js +0 -100
- package/dist/intelligence/tool-injector.js +0 -87
- package/dist/intelligence/tree-sitter-loader.js +0 -71
- package/dist/intelligence/worker-pool.js +0 -116
- package/dist/proxy/arg-validator.js +0 -79
- package/dist/proxy/auto-bootstrap.js +0 -167
- package/dist/proxy/bridge.js +0 -147
- package/dist/proxy/budget-enforcer.js +0 -70
- package/dist/proxy/compression-quality-monitor.js +0 -160
- package/dist/proxy/compression-stats.js +0 -51
- package/dist/proxy/context-rot-detector.js +0 -137
- package/dist/proxy/drift-detector.js +0 -139
- package/dist/proxy/efficiency-tracker.js +0 -79
- package/dist/proxy/fact-ranking.js +0 -154
- package/dist/proxy/format-encoder.js +0 -266
- package/dist/proxy/http-transport.js +0 -90
- package/dist/proxy/lifecycle-actor.js +0 -55
- package/dist/proxy/lifecycle-machine.js +0 -187
- package/dist/proxy/log-tailer.js +0 -265
- package/dist/proxy/model-pricing.js +0 -98
- package/dist/proxy/network-firewall.js +0 -141
- package/dist/proxy/nudge-state.js +0 -93
- package/dist/proxy/output-compressor.js +0 -185
- package/dist/proxy/pid-lock.js +0 -291
- package/dist/proxy/proxy-context.js +0 -11
- package/dist/proxy/proxy.js +0 -2633
- package/dist/proxy/response-enrichment.js +0 -32
- package/dist/proxy/response-envelope.js +0 -313
- package/dist/proxy/session-dedup.js +0 -82
- package/dist/proxy/session-legend.js +0 -30
- package/dist/proxy/session-persistence.js +0 -210
- package/dist/proxy/session-resume.js +0 -94
- package/dist/proxy/session-stats.js +0 -513
- package/dist/proxy/shell-classifier.js +0 -1346
- package/dist/proxy/shell-compression-log.js +0 -93
- package/dist/proxy/shell-compressor.js +0 -390
- package/dist/proxy/shell-graph-boost.js +0 -202
- package/dist/proxy/shell-monitor-map.js +0 -18
- package/dist/proxy/shell-stats.js +0 -54
- package/dist/proxy/shell-strategies/cloud.js +0 -215
- package/dist/proxy/shell-strategies/diff.js +0 -159
- package/dist/proxy/shell-strategies/error-diagnostic.js +0 -796
- package/dist/proxy/shell-strategies/filter-dsl.js +0 -358
- package/dist/proxy/shell-strategies/git-status.js +0 -177
- package/dist/proxy/shell-strategies/key-value.js +0 -193
- package/dist/proxy/shell-strategies/log-text.js +0 -154
- package/dist/proxy/shell-strategies/omni.js +0 -188
- package/dist/proxy/shell-strategies/progress.js +0 -55
- package/dist/proxy/shell-strategies/redact.js +0 -76
- package/dist/proxy/shell-strategies/structured.js +0 -241
- package/dist/proxy/shell-strategies/tabular.js +0 -243
- package/dist/proxy/shell-strategies/test-results-types.js +0 -13
- package/dist/proxy/shell-strategies/test-results.js +0 -784
- package/dist/proxy/shell-strategies/tree-paths.js +0 -144
- package/dist/proxy/shell-strategies/yaml.js +0 -182
- package/dist/proxy/shell-tee.js +0 -111
- package/dist/proxy/signal-dedup.js +0 -171
- package/dist/proxy/startup-renderer.js +0 -158
- package/dist/proxy/task-token-display.js +0 -38
- package/dist/proxy/token-counter.js +0 -61
- package/dist/proxy/tool-clusters.js +0 -273
- package/dist/proxy/tool-definitions.js +0 -525
- package/dist/proxy/transport-mux.js +0 -229
- package/dist/proxy/wire-cap.js +0 -268
- package/dist/rules/developer.mozilla.org.json +0 -9
- package/dist/rules/github.com.json +0 -21
- package/dist/schemas/api/skills.js +0 -19
- package/dist/schemas/common/errors.js +0 -7
- package/dist/schemas/common/headers.js +0 -5
- package/dist/schemas/entities/edge.js +0 -25
- package/dist/schemas/entities/entity.js +0 -22
- package/dist/schemas/entities/rule.js +0 -18
- package/dist/schemas/index.js +0 -14
- package/dist/server/event-bus.js +0 -59
- package/dist/server/http.js +0 -156
- package/dist/server/middleware.js +0 -70
- package/dist/server/routes/drift.js +0 -97
- package/dist/server/routes/intelligence.js +0 -1217
- package/dist/server/routes/reasoning-quality.js +0 -444
- package/dist/server/routes/session.js +0 -86
- package/dist/server/routes/stream.js +0 -120
- package/dist/server/routes/system.js +0 -73
- package/dist/server/routes/temporal.js +0 -170
- package/dist/server/routes/timeline.js +0 -232
- package/dist/server/routes/token-flow.js +0 -403
- package/dist/skills/effectiveness-tracker.js +0 -93
- package/dist/skills/local-pack.js +0 -380
- package/dist/skills/resolver.js +0 -495
- package/dist/state-detector.js +0 -83
- package/dist/timeline/intent-detector.js +0 -263
- package/dist/timeline/loop-miner.js +0 -140
- package/dist/timeline/open-threads.js +0 -49
- package/dist/timeline/signal-reinforcer.js +0 -62
- package/dist/timeline/timeline-bootstrap.js +0 -151
- package/dist/timeline/timeline-store.js +0 -618
- package/dist/tools/coding/bash.js +0 -49
- package/dist/tools/coding/file-edit.js +0 -72
- package/dist/tools/coding/file-outline.js +0 -227
- package/dist/tools/coding/file-read-protocol.js +0 -425
- package/dist/tools/coding/file-read.js +0 -35
- package/dist/tools/coding/file-write.js +0 -43
- package/dist/tools/coding/glob-tool.js +0 -109
- package/dist/tools/coding/grep.js +0 -162
- package/dist/tools/coding/index.js +0 -27
- package/dist/tools/intelligence/index.js +0 -269
- package/dist/tools/intelligence/record-fact.js +0 -48
- package/dist/tools/intelligence/timeline-markers.js +0 -130
- package/dist/tools/registry.js +0 -47
- package/dist/tools/types.js +0 -8
- package/dist/tracking/auto-snapshot-triggers.js +0 -246
- package/dist/tracking/branch-context.js +0 -115
- package/dist/tracking/branch-snapshot.js +0 -217
- package/dist/tracking/causal-bridge.js +0 -317
- package/dist/tracking/circuit-breaker.js +0 -147
- package/dist/tracking/commit-watcher.js +0 -114
- package/dist/tracking/context-ledger.js +0 -119
- package/dist/tracking/correction-detector.js +0 -324
- package/dist/tracking/drift-tracker.js +0 -874
- package/dist/tracking/durability-tracker.js +0 -94
- package/dist/tracking/entity-rewind.js +0 -200
- package/dist/tracking/file-hash-state.js +0 -114
- package/dist/tracking/git-attribution.js +0 -132
- package/dist/tracking/git-trailers.js +0 -171
- package/dist/tracking/intelligence-counter.js +0 -46
- package/dist/tracking/intent-correlator.js +0 -202
- package/dist/tracking/intent-encoder.js +0 -52
- package/dist/tracking/intent-token-tracker.js +0 -159
- package/dist/tracking/ledger-archiver.js +0 -94
- package/dist/tracking/ledger-chains.js +0 -245
- package/dist/tracking/metrics-store.js +0 -361
- package/dist/tracking/native-watcher.js +0 -131
- package/dist/tracking/offline-rewind.js +0 -295
- package/dist/tracking/pending-violations.js +0 -74
- package/dist/tracking/persistence-effectiveness.js +0 -167
- package/dist/tracking/prompt-durability.js +0 -202
- package/dist/tracking/quality-signals.js +0 -213
- package/dist/tracking/redactor.js +0 -73
- package/dist/tracking/rewind-engine.js +0 -161
- package/dist/tracking/session-history.js +0 -128
- package/dist/tracking/session-receipt.js +0 -88
- package/dist/tracking/session-summary-writer.js +0 -157
- package/dist/tracking/shadow-ledger.js +0 -321
- package/dist/tracking/stash-manager.js +0 -258
- package/dist/tracking/timeline-fork.js +0 -213
- package/dist/tracking/timeline.js +0 -69
- package/dist/tracking/token-flow.js +0 -276
- package/dist/tracking/turn-segmenter.js +0 -122
- package/dist/tracking/weekly-accumulator.js +0 -179
- package/dist/tracking/working-snapshots.js +0 -188
- package/dist/tracking/workspace-manifest.js +0 -176
- package/dist/transport/http.js +0 -102
- package/dist/utils/counterfactual.js +0 -65
- package/dist/utils/deep-link.js +0 -34
- package/dist/utils/detect.js +0 -193
- package/dist/utils/exec.js +0 -73
- package/dist/utils/file-logger.js +0 -87
- package/dist/utils/format-error.js +0 -29
- package/dist/utils/git.js +0 -181
- package/dist/utils/log.js +0 -57
- package/dist/utils/logger.js +0 -35
- package/dist/utils/mcp-content-json.js +0 -8
- package/dist/utils/session-logger.js +0 -154
- package/dist/utils/startup-log.js +0 -512
- package/dist/utils/ui.js +0 -56
|
@@ -1,276 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Token Flow — unified observability + attribution for token savings.
|
|
3
|
-
*
|
|
4
|
-
* Layer 10: Every token that flows through unerr gets attributed to the mechanism
|
|
5
|
-
* that handled it, aggregated across hierarchical scopes (operation → turn →
|
|
6
|
-
* session → lifetime), and persisted to `.unerr/metrics.db` (token_flow_events
|
|
7
|
-
* table).
|
|
8
|
-
*
|
|
9
|
-
* This replaces the fragmented tracking across EfficiencyTracker, ExplorationCost,
|
|
10
|
-
* IntentTokenTracker, SessionStats, CompressionLog, and WeeklyAccumulator with a
|
|
11
|
-
* single event-sourced model.
|
|
12
|
-
*
|
|
13
|
-
* Performance contract:
|
|
14
|
-
* - Token estimation: <0.01ms (delegated to token-estimator.ts)
|
|
15
|
-
* - SQLite insert: <0.05ms (better-sqlite3, prepared statement, WAL)
|
|
16
|
-
* - Total hot-path overhead: <0.2ms per tool call
|
|
17
|
-
*/
|
|
18
|
-
import { openMetricsStore } from "./metrics-store.js";
|
|
19
|
-
// ── Writer ──────────────────────────────────────────────────────────
|
|
20
|
-
/** RC-5: Maximum in-memory session events before eviction. */
|
|
21
|
-
const MAX_SESSION_EVENTS = 5000;
|
|
22
|
-
function rowToEvent(r) {
|
|
23
|
-
let detail;
|
|
24
|
-
if (r.detail) {
|
|
25
|
-
try {
|
|
26
|
-
detail = JSON.parse(r.detail);
|
|
27
|
-
}
|
|
28
|
-
catch {
|
|
29
|
-
// corrupt payload — return the row without detail rather than throwing
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
return {
|
|
33
|
-
id: r.id,
|
|
34
|
-
ts: r.ts_iso,
|
|
35
|
-
session_id: r.session_id,
|
|
36
|
-
pid: r.pid,
|
|
37
|
-
turn: r.turn,
|
|
38
|
-
mechanism: r.mechanism,
|
|
39
|
-
tool: r.tool ?? null,
|
|
40
|
-
tokens_without: r.tokens_without,
|
|
41
|
-
tokens_with: r.tokens_with,
|
|
42
|
-
tokens_saved: r.tokens_saved,
|
|
43
|
-
detail,
|
|
44
|
-
};
|
|
45
|
-
}
|
|
46
|
-
export class TokenFlowWriter {
|
|
47
|
-
sessionId;
|
|
48
|
-
unerrDir;
|
|
49
|
-
/** In-memory buffer of this process's events for fast aggregation + SSE relay. */
|
|
50
|
-
sessionEvents = [];
|
|
51
|
-
constructor(unerrDir, sessionId) {
|
|
52
|
-
this.sessionId = sessionId;
|
|
53
|
-
this.unerrDir = unerrDir;
|
|
54
|
-
// Eager-open the store so first record() doesn't pay the bootstrap cost.
|
|
55
|
-
openMetricsStore(unerrDir);
|
|
56
|
-
}
|
|
57
|
-
/**
|
|
58
|
-
* Record a token flow event. Synchronous, <0.1ms.
|
|
59
|
-
* Inserts into `.unerr/metrics.db` (token_flow_events) and keeps an
|
|
60
|
-
* in-memory copy for session aggregation + SSE relay.
|
|
61
|
-
*/
|
|
62
|
-
record(input) {
|
|
63
|
-
const now = new Date();
|
|
64
|
-
const tsIso = now.toISOString();
|
|
65
|
-
let rowId = 0;
|
|
66
|
-
try {
|
|
67
|
-
rowId = openMetricsStore(this.unerrDir).insertTokenFlow({
|
|
68
|
-
ts: now.getTime(),
|
|
69
|
-
ts_iso: tsIso,
|
|
70
|
-
session_id: input.session_id,
|
|
71
|
-
pid: process.pid,
|
|
72
|
-
turn: input.turn,
|
|
73
|
-
mechanism: input.mechanism,
|
|
74
|
-
tool: input.tool,
|
|
75
|
-
tokens_without: input.tokens_without,
|
|
76
|
-
tokens_with: input.tokens_with,
|
|
77
|
-
tokens_saved: input.tokens_saved,
|
|
78
|
-
detail: input.detail ? JSON.stringify(input.detail) : null,
|
|
79
|
-
});
|
|
80
|
-
}
|
|
81
|
-
catch {
|
|
82
|
-
/* best effort — never block the hot path */
|
|
83
|
-
}
|
|
84
|
-
const event = {
|
|
85
|
-
id: rowId,
|
|
86
|
-
ts: tsIso,
|
|
87
|
-
pid: process.pid,
|
|
88
|
-
...input,
|
|
89
|
-
};
|
|
90
|
-
this.sessionEvents.push(event);
|
|
91
|
-
// RC-5: Evict oldest events if buffer exceeds limit
|
|
92
|
-
if (this.sessionEvents.length > MAX_SESSION_EVENTS) {
|
|
93
|
-
this.sessionEvents = this.sessionEvents.slice(-Math.floor(MAX_SESSION_EVENTS * 0.75));
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
/** Get all events this process has recorded for the current session. */
|
|
97
|
-
getSessionEvents() {
|
|
98
|
-
return this.sessionEvents;
|
|
99
|
-
}
|
|
100
|
-
/** Running total of tokens saved this session (in-memory, O(1) amortized). */
|
|
101
|
-
getSessionTokensSaved() {
|
|
102
|
-
let total = 0;
|
|
103
|
-
for (const e of this.sessionEvents)
|
|
104
|
-
total += e.tokens_saved;
|
|
105
|
-
return total;
|
|
106
|
-
}
|
|
107
|
-
/** Running session efficiency percentage. */
|
|
108
|
-
getSessionEfficiency() {
|
|
109
|
-
let totalWithout = 0;
|
|
110
|
-
let totalSaved = 0;
|
|
111
|
-
for (const e of this.sessionEvents) {
|
|
112
|
-
totalWithout += e.tokens_without;
|
|
113
|
-
totalSaved += e.tokens_saved;
|
|
114
|
-
}
|
|
115
|
-
if (totalWithout === 0)
|
|
116
|
-
return 0;
|
|
117
|
-
return Math.round((totalSaved / totalWithout) * 100);
|
|
118
|
-
}
|
|
119
|
-
/**
|
|
120
|
-
* Ingest an event produced by another process (relayed via the log-tailer's
|
|
121
|
-
* SQLite poll). Pushes to in-memory buffer for SSE streaming; does NOT
|
|
122
|
-
* re-insert into the DB (the originating process already did).
|
|
123
|
-
*/
|
|
124
|
-
ingestExternal(event) {
|
|
125
|
-
if (event.pid === process.pid)
|
|
126
|
-
return;
|
|
127
|
-
this.sessionEvents.push(event);
|
|
128
|
-
if (this.sessionEvents.length > MAX_SESSION_EVENTS) {
|
|
129
|
-
this.sessionEvents = this.sessionEvents.slice(-Math.floor(MAX_SESSION_EVENTS * 0.75));
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
/**
|
|
134
|
-
* Read token flow events from the SQLite store with optional filtering.
|
|
135
|
-
* Used for CLI status, dashboard, and session summaries.
|
|
136
|
-
* Performance: <1ms for 1000 events (indexed lookup + row mapping).
|
|
137
|
-
*/
|
|
138
|
-
export function readTokenFlowEvents(unerrDir, filter) {
|
|
139
|
-
let rows;
|
|
140
|
-
try {
|
|
141
|
-
const store = openMetricsStore(unerrDir);
|
|
142
|
-
rows = filter?.session_id
|
|
143
|
-
? store.tokenFlowBySession(filter.session_id)
|
|
144
|
-
: store.allTokenFlow();
|
|
145
|
-
}
|
|
146
|
-
catch {
|
|
147
|
-
return [];
|
|
148
|
-
}
|
|
149
|
-
const events = [];
|
|
150
|
-
for (const r of rows) {
|
|
151
|
-
if (filter?.mechanism && r.mechanism !== filter.mechanism)
|
|
152
|
-
continue;
|
|
153
|
-
if (filter?.from_ts && r.ts_iso < filter.from_ts)
|
|
154
|
-
continue;
|
|
155
|
-
if (filter?.to_ts && r.ts_iso > filter.to_ts)
|
|
156
|
-
continue;
|
|
157
|
-
events.push(rowToEvent(r));
|
|
158
|
-
}
|
|
159
|
-
return events;
|
|
160
|
-
}
|
|
161
|
-
// ── Aggregation ─────────────────────────────────────────────────────
|
|
162
|
-
/**
|
|
163
|
-
* Aggregate events into a session-level summary.
|
|
164
|
-
* Computed on-read from the event stream (event sourcing principle).
|
|
165
|
-
*/
|
|
166
|
-
export function aggregateSession(events, sessionId) {
|
|
167
|
-
const sessionEvents = events.filter((e) => e.session_id === sessionId);
|
|
168
|
-
const mechanismMap = new Map();
|
|
169
|
-
const turnMap = new Map();
|
|
170
|
-
let totalWithout = 0;
|
|
171
|
-
let totalWith = 0;
|
|
172
|
-
let totalSaved = 0;
|
|
173
|
-
const turnNumbers = new Set();
|
|
174
|
-
for (const e of sessionEvents) {
|
|
175
|
-
totalWithout += e.tokens_without;
|
|
176
|
-
totalWith += e.tokens_with;
|
|
177
|
-
totalSaved += e.tokens_saved;
|
|
178
|
-
turnNumbers.add(e.turn);
|
|
179
|
-
// Per-mechanism accumulation
|
|
180
|
-
const mech = mechanismMap.get(e.mechanism) ?? {
|
|
181
|
-
saved: 0,
|
|
182
|
-
delivered: 0,
|
|
183
|
-
count: 0,
|
|
184
|
-
};
|
|
185
|
-
mech.saved += e.tokens_saved;
|
|
186
|
-
mech.delivered += e.tokens_with;
|
|
187
|
-
mech.count++;
|
|
188
|
-
mechanismMap.set(e.mechanism, mech);
|
|
189
|
-
// Per-turn accumulation
|
|
190
|
-
const turn = turnMap.get(e.turn) ?? {
|
|
191
|
-
tool: e.tool ?? "unknown",
|
|
192
|
-
tokens_without: 0,
|
|
193
|
-
tokens_delivered: 0,
|
|
194
|
-
tokens_saved: 0,
|
|
195
|
-
mechanisms: new Map(),
|
|
196
|
-
};
|
|
197
|
-
turn.tokens_without += e.tokens_without;
|
|
198
|
-
turn.tokens_delivered += e.tokens_with;
|
|
199
|
-
turn.tokens_saved += e.tokens_saved;
|
|
200
|
-
turn.mechanisms.set(e.mechanism, (turn.mechanisms.get(e.mechanism) ?? 0) + e.tokens_saved);
|
|
201
|
-
if (e.tool)
|
|
202
|
-
turn.tool = e.tool;
|
|
203
|
-
turnMap.set(e.turn, turn);
|
|
204
|
-
}
|
|
205
|
-
// Build mechanism summary with percentage of total
|
|
206
|
-
const byMechanism = {};
|
|
207
|
-
for (const [mechanism, data] of mechanismMap) {
|
|
208
|
-
byMechanism[mechanism] = {
|
|
209
|
-
tokens_saved: data.saved,
|
|
210
|
-
tokens_delivered: data.delivered,
|
|
211
|
-
event_count: data.count,
|
|
212
|
-
pct_of_total: totalSaved > 0 ? Math.round((data.saved / totalSaved) * 1000) / 10 : 0,
|
|
213
|
-
};
|
|
214
|
-
}
|
|
215
|
-
// Build top turns sorted by tokens_saved descending, take top 5
|
|
216
|
-
const topTurns = [...turnMap.entries()]
|
|
217
|
-
.map(([turn, data]) => {
|
|
218
|
-
let primaryMechanism = "unknown";
|
|
219
|
-
let maxSaved = 0;
|
|
220
|
-
for (const [mech, saved] of data.mechanisms) {
|
|
221
|
-
if (saved > maxSaved) {
|
|
222
|
-
maxSaved = saved;
|
|
223
|
-
primaryMechanism = mech;
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
return {
|
|
227
|
-
turn,
|
|
228
|
-
tool: data.tool,
|
|
229
|
-
tokens_without: data.tokens_without,
|
|
230
|
-
tokens_delivered: data.tokens_delivered,
|
|
231
|
-
tokens_saved: data.tokens_saved,
|
|
232
|
-
primary_mechanism: primaryMechanism,
|
|
233
|
-
};
|
|
234
|
-
})
|
|
235
|
-
.sort((a, b) => b.tokens_saved - a.tokens_saved)
|
|
236
|
-
.slice(0, 5);
|
|
237
|
-
return {
|
|
238
|
-
session_id: sessionId,
|
|
239
|
-
total_turns: turnNumbers.size,
|
|
240
|
-
total_tokens_without: totalWithout,
|
|
241
|
-
total_tokens_with: totalWith,
|
|
242
|
-
total_tokens_saved: totalSaved,
|
|
243
|
-
efficiency_pct: totalWithout > 0 ? Math.round((totalSaved / totalWithout) * 100) : 0,
|
|
244
|
-
by_mechanism: byMechanism,
|
|
245
|
-
top_turns: topTurns,
|
|
246
|
-
};
|
|
247
|
-
}
|
|
248
|
-
/**
|
|
249
|
-
* Aggregate events by mechanism across all sessions (for cross-session trends).
|
|
250
|
-
*/
|
|
251
|
-
export function aggregateByMechanism(events) {
|
|
252
|
-
let totalSaved = 0;
|
|
253
|
-
const mechanismMap = new Map();
|
|
254
|
-
for (const e of events) {
|
|
255
|
-
totalSaved += e.tokens_saved;
|
|
256
|
-
const mech = mechanismMap.get(e.mechanism) ?? {
|
|
257
|
-
saved: 0,
|
|
258
|
-
delivered: 0,
|
|
259
|
-
count: 0,
|
|
260
|
-
};
|
|
261
|
-
mech.saved += e.tokens_saved;
|
|
262
|
-
mech.delivered += e.tokens_with;
|
|
263
|
-
mech.count++;
|
|
264
|
-
mechanismMap.set(e.mechanism, mech);
|
|
265
|
-
}
|
|
266
|
-
const result = {};
|
|
267
|
-
for (const [mechanism, data] of mechanismMap) {
|
|
268
|
-
result[mechanism] = {
|
|
269
|
-
tokens_saved: data.saved,
|
|
270
|
-
tokens_delivered: data.delivered,
|
|
271
|
-
event_count: data.count,
|
|
272
|
-
pct_of_total: totalSaved > 0 ? Math.round((data.saved / totalSaved) * 1000) / 10 : 0,
|
|
273
|
-
};
|
|
274
|
-
}
|
|
275
|
-
return result;
|
|
276
|
-
}
|
|
@@ -1,122 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Turn Segmenter — assigns ledger entries to logical "turns" (one user→agent
|
|
3
|
-
* round-trip). Embedded inside ShadowLedger.record(); does not write or read
|
|
4
|
-
* files. Pure in-memory state, isolated per session.
|
|
5
|
-
*
|
|
6
|
-
* Boundary detection (in priority order):
|
|
7
|
-
* 1. `closeTurn(sessionId)` — called by Stop hooks (Claude Code) or session
|
|
8
|
-
* shutdown. Anchors an exact boundary. Next observed entry opens a new
|
|
9
|
-
* turn with confidence "first_call".
|
|
10
|
-
* 2. Idle gap > IDLE_GAP_MS between consecutive entries on the same session
|
|
11
|
-
* closes the previous turn and opens a new one with confidence "idle_gap".
|
|
12
|
-
* 3. The very first entry on a session opens turn 1 with confidence
|
|
13
|
-
* "first_call".
|
|
14
|
-
*
|
|
15
|
-
* Subscribers get notified on every turn close via onTurnClose(listener).
|
|
16
|
-
* The timeline subsystem uses this to upsert turn rollups into timeline.db
|
|
17
|
-
* — but the segmenter itself has no dependency on that subsystem and is safe
|
|
18
|
-
* to use standalone (e.g., in tests, or when UNERR_TIMELINE_V2=0).
|
|
19
|
-
*/
|
|
20
|
-
import { randomBytes } from "node:crypto";
|
|
21
|
-
const DEFAULT_IDLE_GAP_MS = 20_000;
|
|
22
|
-
export class TurnSegmenter {
|
|
23
|
-
state = new Map();
|
|
24
|
-
listeners = [];
|
|
25
|
-
idleGapMs;
|
|
26
|
-
constructor(options = {}) {
|
|
27
|
-
this.idleGapMs = options.idleGapMs ?? DEFAULT_IDLE_GAP_MS;
|
|
28
|
-
}
|
|
29
|
-
/**
|
|
30
|
-
* Subscribe to turn-close events. Returns an unsubscribe function.
|
|
31
|
-
*/
|
|
32
|
-
onTurnClose(listener) {
|
|
33
|
-
this.listeners.push(listener);
|
|
34
|
-
return () => {
|
|
35
|
-
const idx = this.listeners.indexOf(listener);
|
|
36
|
-
if (idx >= 0)
|
|
37
|
-
this.listeners.splice(idx, 1);
|
|
38
|
-
};
|
|
39
|
-
}
|
|
40
|
-
/**
|
|
41
|
-
* Observe an entry and stamp it with turn_id + turn_confidence in place.
|
|
42
|
-
* May emit a close event for the previous turn if an idle gap is detected.
|
|
43
|
-
*/
|
|
44
|
-
observe(entry) {
|
|
45
|
-
const ts = Date.parse(entry.ts);
|
|
46
|
-
const s = this.state.get(entry.session_id) ?? this.initState();
|
|
47
|
-
if (s.currentTurnId === null) {
|
|
48
|
-
// Opening a new turn — openedBy is whatever the prior closeTurn or
|
|
49
|
-
// initState set ("first_call" for the very first or after stop_hook).
|
|
50
|
-
s.currentTurnId = generateTurnId();
|
|
51
|
-
}
|
|
52
|
-
else if (Number.isFinite(ts) &&
|
|
53
|
-
ts - s.lastEntryTs > this.idleGapMs &&
|
|
54
|
-
s.lastEntryTs > 0) {
|
|
55
|
-
this.emitClose({
|
|
56
|
-
turn_id: s.currentTurnId,
|
|
57
|
-
session_id: entry.session_id,
|
|
58
|
-
closed_at: s.lastEntryTs,
|
|
59
|
-
reason: "idle_gap",
|
|
60
|
-
});
|
|
61
|
-
s.currentTurnId = generateTurnId();
|
|
62
|
-
s.openedBy = "idle_gap";
|
|
63
|
-
}
|
|
64
|
-
entry.turn_id = s.currentTurnId;
|
|
65
|
-
entry.turn_confidence = s.openedBy;
|
|
66
|
-
if (Number.isFinite(ts))
|
|
67
|
-
s.lastEntryTs = ts;
|
|
68
|
-
this.state.set(entry.session_id, s);
|
|
69
|
-
}
|
|
70
|
-
/**
|
|
71
|
-
* Anchor an exact turn boundary. The next observed entry will open a new
|
|
72
|
-
* turn with confidence "first_call" (the boundary is known precisely).
|
|
73
|
-
* Idempotent — calling with no active turn is a no-op.
|
|
74
|
-
*/
|
|
75
|
-
closeTurn(sessionId, reason = "stop_hook") {
|
|
76
|
-
const s = this.state.get(sessionId);
|
|
77
|
-
if (!s || s.currentTurnId === null)
|
|
78
|
-
return;
|
|
79
|
-
this.emitClose({
|
|
80
|
-
turn_id: s.currentTurnId,
|
|
81
|
-
session_id: sessionId,
|
|
82
|
-
closed_at: s.lastEntryTs,
|
|
83
|
-
reason,
|
|
84
|
-
});
|
|
85
|
-
s.currentTurnId = null;
|
|
86
|
-
s.openedBy = "first_call";
|
|
87
|
-
this.state.set(sessionId, s);
|
|
88
|
-
}
|
|
89
|
-
/**
|
|
90
|
-
* Inspect the current turn id for a session. Returns null if no turn is open.
|
|
91
|
-
* Intended for diagnostics / tests.
|
|
92
|
-
*/
|
|
93
|
-
getCurrentTurnId(sessionId) {
|
|
94
|
-
return this.state.get(sessionId)?.currentTurnId ?? null;
|
|
95
|
-
}
|
|
96
|
-
/**
|
|
97
|
-
* Drop all state. For tests and clean shutdown.
|
|
98
|
-
*/
|
|
99
|
-
reset() {
|
|
100
|
-
this.state.clear();
|
|
101
|
-
}
|
|
102
|
-
initState() {
|
|
103
|
-
return {
|
|
104
|
-
currentTurnId: null,
|
|
105
|
-
lastEntryTs: 0,
|
|
106
|
-
openedBy: "first_call",
|
|
107
|
-
};
|
|
108
|
-
}
|
|
109
|
-
emitClose(event) {
|
|
110
|
-
for (const l of this.listeners) {
|
|
111
|
-
try {
|
|
112
|
-
l(event);
|
|
113
|
-
}
|
|
114
|
-
catch (err) {
|
|
115
|
-
process.stderr.write(`[unerr:turn-segmenter] WARN: listener error: ${err instanceof Error ? err.message : String(err)}\n`);
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
function generateTurnId() {
|
|
121
|
-
return randomBytes(6).toString("hex");
|
|
122
|
-
}
|
|
@@ -1,179 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Weekly Summary Accumulator — unified cross-session stats persistence.
|
|
3
|
-
*
|
|
4
|
-
* S8.4: Persists session metrics to ~/.unerr/stats.json.
|
|
5
|
-
* Replaces the separate cumulative-stats.json and cumulative-local-stats.json.
|
|
6
|
-
*
|
|
7
|
-
* Features:
|
|
8
|
-
* - Weekly auto-reset (Monday boundary)
|
|
9
|
-
* - All-time counters that persist across resets
|
|
10
|
-
* - Feeds into `unerr stats` command and session guard
|
|
11
|
-
*/
|
|
12
|
-
function getWeekStart() {
|
|
13
|
-
const now = new Date();
|
|
14
|
-
const day = now.getDay();
|
|
15
|
-
const diff = now.getDate() - day + (day === 0 ? -6 : 1);
|
|
16
|
-
const monday = new Date(now);
|
|
17
|
-
monday.setDate(diff);
|
|
18
|
-
return monday.toISOString().slice(0, 10);
|
|
19
|
-
}
|
|
20
|
-
function getStatsPath() {
|
|
21
|
-
const home = process.env.HOME ?? process.env.USERPROFILE ?? process.cwd();
|
|
22
|
-
return `${home}/.unerr/stats.json`;
|
|
23
|
-
}
|
|
24
|
-
function createEmptyWeekly(weekStart) {
|
|
25
|
-
return {
|
|
26
|
-
weekStart,
|
|
27
|
-
sessions: 0,
|
|
28
|
-
tokensSaved: 0,
|
|
29
|
-
dollarsSaved: 0,
|
|
30
|
-
toolCalls: 0,
|
|
31
|
-
violationsCaught: 0,
|
|
32
|
-
chokepointWarnings: 0,
|
|
33
|
-
correctionsApplied: 0,
|
|
34
|
-
blastRadiusComputed: 0,
|
|
35
|
-
avgEfficiency: 0,
|
|
36
|
-
avgLatencyP50: 0,
|
|
37
|
-
};
|
|
38
|
-
}
|
|
39
|
-
function createEmptyAllTime() {
|
|
40
|
-
return {
|
|
41
|
-
firstSessionDate: new Date().toISOString(),
|
|
42
|
-
totalSessions: 0,
|
|
43
|
-
totalTokensSaved: 0,
|
|
44
|
-
totalDollarsSaved: 0,
|
|
45
|
-
totalViolationsCaught: 0,
|
|
46
|
-
};
|
|
47
|
-
}
|
|
48
|
-
export function loadStats() {
|
|
49
|
-
const currentWeek = getWeekStart();
|
|
50
|
-
try {
|
|
51
|
-
const { readFileSync } = require("node:fs");
|
|
52
|
-
const raw = JSON.parse(readFileSync(getStatsPath(), "utf-8"));
|
|
53
|
-
if (raw.version !== 1) {
|
|
54
|
-
return {
|
|
55
|
-
version: 1,
|
|
56
|
-
weekly: createEmptyWeekly(currentWeek),
|
|
57
|
-
allTime: createEmptyAllTime(),
|
|
58
|
-
lastUpdated: new Date().toISOString(),
|
|
59
|
-
};
|
|
60
|
-
}
|
|
61
|
-
// Reset weekly if new week, preserve all-time
|
|
62
|
-
if (raw.weekly.weekStart !== currentWeek) {
|
|
63
|
-
raw.weekly = createEmptyWeekly(currentWeek);
|
|
64
|
-
}
|
|
65
|
-
return raw;
|
|
66
|
-
}
|
|
67
|
-
catch {
|
|
68
|
-
return {
|
|
69
|
-
version: 1,
|
|
70
|
-
weekly: createEmptyWeekly(currentWeek),
|
|
71
|
-
allTime: createEmptyAllTime(),
|
|
72
|
-
lastUpdated: new Date().toISOString(),
|
|
73
|
-
};
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
/**
|
|
77
|
-
* Accumulate a session's metrics into the unified stats file.
|
|
78
|
-
* Returns the updated stats for display.
|
|
79
|
-
*/
|
|
80
|
-
export function accumulateSession(input) {
|
|
81
|
-
const stats = loadStats();
|
|
82
|
-
// Weekly
|
|
83
|
-
stats.weekly.sessions += 1;
|
|
84
|
-
stats.weekly.tokensSaved += input.tokensSaved;
|
|
85
|
-
stats.weekly.dollarsSaved += input.dollarsSaved;
|
|
86
|
-
stats.weekly.toolCalls += input.toolCalls;
|
|
87
|
-
stats.weekly.violationsCaught += input.violationsCaught;
|
|
88
|
-
stats.weekly.chokepointWarnings += input.chokepointWarnings;
|
|
89
|
-
stats.weekly.correctionsApplied += input.correctionsApplied;
|
|
90
|
-
stats.weekly.blastRadiusComputed += input.blastRadiusComputed;
|
|
91
|
-
// Rolling average for efficiency and latency
|
|
92
|
-
const n = stats.weekly.sessions;
|
|
93
|
-
stats.weekly.avgEfficiency =
|
|
94
|
-
stats.weekly.avgEfficiency * ((n - 1) / n) + input.efficiency * (1 / n);
|
|
95
|
-
stats.weekly.avgLatencyP50 =
|
|
96
|
-
stats.weekly.avgLatencyP50 * ((n - 1) / n) + input.latencyP50 * (1 / n);
|
|
97
|
-
// Layer 10: Accumulate per-mechanism token savings
|
|
98
|
-
if (input.tokensByMechanism) {
|
|
99
|
-
if (!stats.weekly.tokensByMechanism)
|
|
100
|
-
stats.weekly.tokensByMechanism = {};
|
|
101
|
-
for (const [mech, saved] of Object.entries(input.tokensByMechanism)) {
|
|
102
|
-
stats.weekly.tokensByMechanism[mech] =
|
|
103
|
-
(stats.weekly.tokensByMechanism[mech] ?? 0) + saved;
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
// All-time
|
|
107
|
-
stats.allTime.totalSessions += 1;
|
|
108
|
-
stats.allTime.totalTokensSaved += input.tokensSaved;
|
|
109
|
-
stats.allTime.totalDollarsSaved += input.dollarsSaved;
|
|
110
|
-
stats.allTime.totalViolationsCaught += input.violationsCaught;
|
|
111
|
-
stats.lastUpdated = new Date().toISOString();
|
|
112
|
-
persistStats(stats);
|
|
113
|
-
return stats;
|
|
114
|
-
}
|
|
115
|
-
function persistStats(stats) {
|
|
116
|
-
try {
|
|
117
|
-
const fs = require("node:fs");
|
|
118
|
-
const path = require("node:path");
|
|
119
|
-
const filePath = getStatsPath();
|
|
120
|
-
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
121
|
-
fs.writeFileSync(filePath, JSON.stringify(stats, null, 2));
|
|
122
|
-
}
|
|
123
|
-
catch {
|
|
124
|
-
// Non-critical — don't break session shutdown
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
/**
|
|
128
|
-
* Format stats for the `unerr stats` command output.
|
|
129
|
-
*/
|
|
130
|
-
export function formatStatsReport(stats) {
|
|
131
|
-
const w = stats.weekly;
|
|
132
|
-
const a = stats.allTime;
|
|
133
|
-
const lines = [
|
|
134
|
-
"",
|
|
135
|
-
"── unerr stats ────────────────────────────────",
|
|
136
|
-
"",
|
|
137
|
-
" This week:",
|
|
138
|
-
` Sessions: ${w.sessions}`,
|
|
139
|
-
` Tool calls: ${w.toolCalls}`,
|
|
140
|
-
` Tokens saved: ~${formatTokenCount(w.tokensSaved)}`,
|
|
141
|
-
` Dollar savings: $${w.dollarsSaved.toFixed(2)}`,
|
|
142
|
-
` Efficiency: ${Math.round(w.avgEfficiency)}%`,
|
|
143
|
-
` Violations: ${w.violationsCaught} caught`,
|
|
144
|
-
];
|
|
145
|
-
if (w.blastRadiusComputed > 0) {
|
|
146
|
-
lines.push(` Blast radius: ${w.blastRadiusComputed} computations`);
|
|
147
|
-
}
|
|
148
|
-
// Layer 10: Mechanism breakdown
|
|
149
|
-
if (w.tokensByMechanism && Object.keys(w.tokensByMechanism).length > 0) {
|
|
150
|
-
lines.push("");
|
|
151
|
-
lines.push(" By mechanism:");
|
|
152
|
-
const sorted = Object.entries(w.tokensByMechanism).sort(([, a], [, b]) => b - a);
|
|
153
|
-
const totalMech = sorted.reduce((s, [, v]) => s + v, 0);
|
|
154
|
-
for (const [mech, saved] of sorted) {
|
|
155
|
-
const pct = totalMech > 0 ? Math.round((saved / totalMech) * 100) : 0;
|
|
156
|
-
const barLen = Math.max(1, Math.round(pct / 5));
|
|
157
|
-
const bar = "█".repeat(barLen) + "░".repeat(20 - barLen);
|
|
158
|
-
lines.push(` ${mech.padEnd(22)} ${formatTokenCount(saved).padStart(6)} ${String(pct).padStart(3)}% ${bar}`);
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
lines.push("");
|
|
162
|
-
lines.push(" All time:");
|
|
163
|
-
lines.push(` Sessions: ${a.totalSessions}`);
|
|
164
|
-
lines.push(` Tokens saved: ~${formatTokenCount(a.totalTokensSaved)}`);
|
|
165
|
-
lines.push(` Dollar savings: $${a.totalDollarsSaved.toFixed(2)}`);
|
|
166
|
-
lines.push(` Violations: ${a.totalViolationsCaught} caught`);
|
|
167
|
-
lines.push(` Since: ${a.firstSessionDate.slice(0, 10)}`);
|
|
168
|
-
lines.push("");
|
|
169
|
-
lines.push("───────────────────────────────────────────────");
|
|
170
|
-
lines.push("");
|
|
171
|
-
return lines.join("\n");
|
|
172
|
-
}
|
|
173
|
-
function formatTokenCount(n) {
|
|
174
|
-
if (n >= 1_000_000)
|
|
175
|
-
return `${(n / 1_000_000).toFixed(1)}M`;
|
|
176
|
-
if (n >= 1_000)
|
|
177
|
-
return `${(n / 1_000).toFixed(1)}K`;
|
|
178
|
-
return String(n);
|
|
179
|
-
}
|