dsh-token-usage-ledger 0.0.0-stage → 0.0.36

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 (46) hide show
  1. package/CHANGELOG.md +1067 -0
  2. package/LICENSE +21 -0
  3. package/README.md +237 -2
  4. package/cordis.patch.yml +30 -0
  5. package/lib/client.js +4469 -0
  6. package/lib/host/aggregate.d.ts +132 -0
  7. package/lib/host/aggregate.js +840 -0
  8. package/lib/host/api.d.ts +118 -0
  9. package/lib/host/api.js +346 -0
  10. package/lib/host/backfill.d.ts +54 -0
  11. package/lib/host/backfill.js +265 -0
  12. package/lib/host/collector.d.ts +139 -0
  13. package/lib/host/collector.js +441 -0
  14. package/lib/host/ledger-io.d.ts +125 -0
  15. package/lib/host/ledger-io.js +211 -0
  16. package/lib/host/operation-error.d.ts +22 -0
  17. package/lib/host/operation-error.js +28 -0
  18. package/lib/host/paths.d.ts +35 -0
  19. package/lib/host/paths.js +63 -0
  20. package/lib/host/pricing-module.d.ts +112 -0
  21. package/lib/host/pricing-module.js +63 -0
  22. package/lib/host/pricing-modules/deepseek-2026-09-10.d.ts +31 -0
  23. package/lib/host/pricing-modules/deepseek-2026-09-10.js +67 -0
  24. package/lib/host/pricing-modules/index.d.ts +27 -0
  25. package/lib/host/pricing-modules/index.js +30 -0
  26. package/lib/host/pricing.d.ts +192 -0
  27. package/lib/host/pricing.js +287 -0
  28. package/lib/host/records.d.ts +47 -0
  29. package/lib/host/records.js +116 -0
  30. package/lib/host/runtime-marker.d.ts +67 -0
  31. package/lib/host/runtime-marker.js +71 -0
  32. package/lib/host/schema.d.ts +77 -0
  33. package/lib/host/schema.js +158 -0
  34. package/lib/host/store.d.ts +171 -0
  35. package/lib/host/store.js +337 -0
  36. package/lib/host/workspace-titles.d.ts +38 -0
  37. package/lib/host/workspace-titles.js +136 -0
  38. package/lib/host/zstd.d.ts +41 -0
  39. package/lib/host/zstd.js +134 -0
  40. package/lib/index.d.ts +82 -0
  41. package/lib/index.js +512 -0
  42. package/lib/shared/format.d.ts +415 -0
  43. package/lib/shared/format.js +714 -0
  44. package/lib/shared/protocol.d.ts +646 -0
  45. package/lib/shared/protocol.js +129 -0
  46. package/package.json +85 -4
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Startup marker: which build is RUNNING, written where it can be read.
3
+ *
4
+ * The panel reports the version, but reading it there requires a browser and a
5
+ * session cookie — and the launch token that mints that cookie lives only in the
6
+ * terminal's scrollback. That made the obvious question ("did my restart pick up
7
+ * the new build?") awkward to answer from a script, and copying a URL out of a
8
+ * terminal is exactly the kind of step that ends with Ctrl-C killing the service.
9
+ *
10
+ * So the host half drops a small JSON file in its own data directory when it
11
+ * loads and removes it when it unloads. `scripts/deploy_production.py --check`
12
+ * reads it and compares the version with the freshly built `lib/`, which answers
13
+ * the question with no token, no cookie and no HTTP.
14
+ *
15
+ * Two rules this module exists to enforce:
16
+ *
17
+ * - **Never throw.** It runs during `apply()`, where an exception is a broken
18
+ * plugin row; a marker that cannot be written is a missing convenience, not a
19
+ * failure to record usage.
20
+ * - **The version comes from the artifact.** The caller passes
21
+ * `PLUGIN_VERSION`, the same constant the payload reports, so the marker and
22
+ * the panel can never disagree.
23
+ *
24
+ * @module dsh-token-usage-ledger/host/runtime-marker
25
+ */
26
+ /** Marker file name, inside the plugin's data directory. */
27
+ export declare const RUNTIME_MARKER_FILE = "runtime.json";
28
+ /** Marker schema version, bumped only when the shape changes. */
29
+ export declare const RUNTIME_MARKER_SCHEMA = 1;
30
+ /** What the marker records. */
31
+ export interface RuntimeMarker {
32
+ /** Shape version, so a future reader can tell what it is looking at. */
33
+ schema: number;
34
+ /** Version of the build that is running (same constant the payload reports). */
35
+ pluginVersion: string;
36
+ /** Process id of the harness that loaded it. */
37
+ pid: number;
38
+ /** When this row loaded, ISO 8601 with offset. */
39
+ startedAt: string;
40
+ /** Ledger directory this instance owns. */
41
+ dataDir: string;
42
+ /** Route prefix the summary endpoint is served under. */
43
+ apiPath: string;
44
+ /** Price era id and currency in force. */
45
+ pricing: {
46
+ module: string;
47
+ currency: string;
48
+ };
49
+ }
50
+ /**
51
+ * Write the startup marker, best effort.
52
+ *
53
+ * @param dir - the plugin's data directory (created when missing).
54
+ * @param marker - what to record.
55
+ * @param warn - sink for a failure message.
56
+ * @returns true when the file was written.
57
+ */
58
+ export declare function writeRuntimeMarker(dir: string, marker: Omit<RuntimeMarker, 'schema'>, warn: (message: string) => void): boolean;
59
+ /**
60
+ * Remove the startup marker, best effort.
61
+ *
62
+ * Called from the effect's disposer, so a stopped or disabled row stops claiming
63
+ * to be running: "no marker" is then an honest answer to "is it up?".
64
+ *
65
+ * @param dir - the plugin's data directory.
66
+ */
67
+ export declare function removeRuntimeMarker(dir: string): void;
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Startup marker: which build is RUNNING, written where it can be read.
3
+ *
4
+ * The panel reports the version, but reading it there requires a browser and a
5
+ * session cookie — and the launch token that mints that cookie lives only in the
6
+ * terminal's scrollback. That made the obvious question ("did my restart pick up
7
+ * the new build?") awkward to answer from a script, and copying a URL out of a
8
+ * terminal is exactly the kind of step that ends with Ctrl-C killing the service.
9
+ *
10
+ * So the host half drops a small JSON file in its own data directory when it
11
+ * loads and removes it when it unloads. `scripts/deploy_production.py --check`
12
+ * reads it and compares the version with the freshly built `lib/`, which answers
13
+ * the question with no token, no cookie and no HTTP.
14
+ *
15
+ * Two rules this module exists to enforce:
16
+ *
17
+ * - **Never throw.** It runs during `apply()`, where an exception is a broken
18
+ * plugin row; a marker that cannot be written is a missing convenience, not a
19
+ * failure to record usage.
20
+ * - **The version comes from the artifact.** The caller passes
21
+ * `PLUGIN_VERSION`, the same constant the payload reports, so the marker and
22
+ * the panel can never disagree.
23
+ *
24
+ * @module dsh-token-usage-ledger/host/runtime-marker
25
+ */
26
+ import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
27
+ import { join } from 'node:path';
28
+ /** Marker file name, inside the plugin's data directory. */
29
+ export const RUNTIME_MARKER_FILE = 'runtime.json';
30
+ /** Marker schema version, bumped only when the shape changes. */
31
+ export const RUNTIME_MARKER_SCHEMA = 1;
32
+ /**
33
+ * Write the startup marker, best effort.
34
+ *
35
+ * @param dir - the plugin's data directory (created when missing).
36
+ * @param marker - what to record.
37
+ * @param warn - sink for a failure message.
38
+ * @returns true when the file was written.
39
+ */
40
+ export function writeRuntimeMarker(dir, marker, warn) {
41
+ try {
42
+ mkdirSync(dir, { recursive: true });
43
+ writeFileSync(join(dir, RUNTIME_MARKER_FILE), `${JSON.stringify({ schema: RUNTIME_MARKER_SCHEMA, ...marker }, null, 2)}\n`, {
44
+ encoding: 'utf8',
45
+ mode: 0o600,
46
+ });
47
+ return true;
48
+ }
49
+ catch (error) {
50
+ warn(`could not write the runtime marker in ${dir}: ${error instanceof Error ? error.message : String(error)}`);
51
+ return false;
52
+ }
53
+ }
54
+ /**
55
+ * Remove the startup marker, best effort.
56
+ *
57
+ * Called from the effect's disposer, so a stopped or disabled row stops claiming
58
+ * to be running: "no marker" is then an honest answer to "is it up?".
59
+ *
60
+ * @param dir - the plugin's data directory.
61
+ */
62
+ export function removeRuntimeMarker(dir) {
63
+ try {
64
+ rmSync(join(dir, RUNTIME_MARKER_FILE), { force: true });
65
+ }
66
+ catch {
67
+ // Removal failing is not worth escalating: the pid in the file is checked
68
+ // by whoever reads it, so a leftover marker cannot be mistaken for a live one.
69
+ }
70
+ }
71
+ //# sourceMappingURL=runtime-marker.js.map
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Ledger record schema: which versions this build can READ, and how each one is
3
+ * upgraded into the canonical in-memory shape.
4
+ *
5
+ * ## Why readers exist instead of one validator
6
+ *
7
+ * A ledger is append-only and long-lived: it outlives plugin versions. If
8
+ * reading were tied to "the current version number", any future schema change
9
+ * would make every previously written line unreadable — the plugin would look
10
+ * like it had lost history, and the loss would be silent.
11
+ *
12
+ * So each version gets a READER that upgrades its own shape into the canonical
13
+ * one. Adding a version means adding a reader and keeping the old ones:
14
+ *
15
+ * 1. bump `RECORD_SCHEMA_VERSION` (what new lines are WRITTEN as);
16
+ * 2. add `READABLE_RECORD_VERSIONS` entry and a `v<N>Reader`;
17
+ * 3. make the OLD reader map its shape up to the new canonical fields.
18
+ *
19
+ * Lines from a version this build does not know are reported as
20
+ * `unsupported-version` rather than `malformed`, so a newer plugin's ledger is
21
+ * visibly "too new" instead of looking corrupt.
22
+ *
23
+ * @module dsh-token-usage-ledger/host/schema
24
+ */
25
+ import type { HealthReport, UsageAttempt, UsageRecord } from '../shared/protocol.js';
26
+ /**
27
+ * Record versions this build can read.
28
+ *
29
+ * Ordered oldest-first. `RECORD_SCHEMA_VERSION` must always appear here.
30
+ */
31
+ export declare const READABLE_RECORD_VERSIONS: readonly number[];
32
+ /** Why one ledger line could not be used. */
33
+ export type RecordRejection =
34
+ /** The line is not a record of any known shape. */
35
+ 'malformed'
36
+ /** The line is a record from a NEWER plugin than this build understands. */
37
+ | 'unsupported-version';
38
+ /** Result of reading one ledger line. */
39
+ export type RecordParseOutcome = {
40
+ readonly ok: true;
41
+ readonly record: UsageRecord;
42
+ } | {
43
+ readonly ok: false;
44
+ readonly reason: RecordRejection;
45
+ };
46
+ /**
47
+ * Parse one ledger line.
48
+ *
49
+ * @param line - one line of the ledger file, without its newline.
50
+ * @returns the canonical record, or why it was rejected.
51
+ */
52
+ export declare function parseRecordLine(line: string): RecordParseOutcome;
53
+ /**
54
+ * Read one already-parsed ledger value.
55
+ *
56
+ * @param value - parsed JSON value of one line.
57
+ * @returns the canonical record, or why it was rejected.
58
+ */
59
+ export declare function readRecordValue(value: unknown): RecordParseOutcome;
60
+ /**
61
+ * Report whether a value is a token bucket set with numeric buckets.
62
+ * @param value - candidate.
63
+ * @returns true when every bucket the aggregation reads is a finite number.
64
+ */
65
+ export declare function isBucketSet(value: unknown): value is UsageRecord['tokens'];
66
+ /**
67
+ * Report whether one attempt entry carries what the aggregation path reads.
68
+ * @param value - candidate.
69
+ * @returns true when the entry is usable.
70
+ */
71
+ export declare function isAttempt(value: unknown): value is UsageAttempt;
72
+ /**
73
+ * Fill the health report's ledger-derived counters for this module's concerns.
74
+ * @param base - the counters the store already tracks.
75
+ * @returns the completed report.
76
+ */
77
+ export declare function withSchemaHealth(base: Omit<HealthReport, 'unsupportedRecords'>): HealthReport;
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Ledger record schema: which versions this build can READ, and how each one is
3
+ * upgraded into the canonical in-memory shape.
4
+ *
5
+ * ## Why readers exist instead of one validator
6
+ *
7
+ * A ledger is append-only and long-lived: it outlives plugin versions. If
8
+ * reading were tied to "the current version number", any future schema change
9
+ * would make every previously written line unreadable — the plugin would look
10
+ * like it had lost history, and the loss would be silent.
11
+ *
12
+ * So each version gets a READER that upgrades its own shape into the canonical
13
+ * one. Adding a version means adding a reader and keeping the old ones:
14
+ *
15
+ * 1. bump `RECORD_SCHEMA_VERSION` (what new lines are WRITTEN as);
16
+ * 2. add `READABLE_RECORD_VERSIONS` entry and a `v<N>Reader`;
17
+ * 3. make the OLD reader map its shape up to the new canonical fields.
18
+ *
19
+ * Lines from a version this build does not know are reported as
20
+ * `unsupported-version` rather than `malformed`, so a newer plugin's ledger is
21
+ * visibly "too new" instead of looking corrupt.
22
+ *
23
+ * @module dsh-token-usage-ledger/host/schema
24
+ */
25
+ import { isCurrency, RECORD_SCHEMA_VERSION } from '../shared/protocol.js';
26
+ /**
27
+ * Record versions this build can read.
28
+ *
29
+ * Ordered oldest-first. `RECORD_SCHEMA_VERSION` must always appear here.
30
+ */
31
+ export const READABLE_RECORD_VERSIONS = [1];
32
+ /**
33
+ * Parse one ledger line.
34
+ *
35
+ * @param line - one line of the ledger file, without its newline.
36
+ * @returns the canonical record, or why it was rejected.
37
+ */
38
+ export function parseRecordLine(line) {
39
+ let value;
40
+ try {
41
+ value = JSON.parse(line);
42
+ }
43
+ catch {
44
+ return { ok: false, reason: 'malformed' };
45
+ }
46
+ return readRecordValue(value);
47
+ }
48
+ /**
49
+ * Read one already-parsed ledger value.
50
+ *
51
+ * @param value - parsed JSON value of one line.
52
+ * @returns the canonical record, or why it was rejected.
53
+ */
54
+ export function readRecordValue(value) {
55
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
56
+ return { ok: false, reason: 'malformed' };
57
+ }
58
+ const raw = value;
59
+ const version = raw['v'];
60
+ if (typeof version !== 'number' || !Number.isSafeInteger(version)) {
61
+ return { ok: false, reason: 'malformed' };
62
+ }
63
+ const reader = READERS[version];
64
+ if (reader === undefined) {
65
+ // Distinguish "newer than me" from "garbage": a v2 line read by a v1 build
66
+ // is not corruption, it is a version this build has never seen.
67
+ return { ok: false, reason: version > RECORD_SCHEMA_VERSION ? 'unsupported-version' : 'malformed' };
68
+ }
69
+ const record = reader(raw);
70
+ return record === undefined ? { ok: false, reason: 'malformed' } : { ok: true, record };
71
+ }
72
+ /** Reader table, keyed by the version the LINE declares. */
73
+ const READERS = {
74
+ 1: readVersion1,
75
+ };
76
+ /**
77
+ * Reader for schema version 1.
78
+ *
79
+ * Strict about every field the aggregation path reads, permissive about the
80
+ * rest, and coercing only `workspaceLabel` (a missing label costs nothing,
81
+ * while dropping the line would lose real usage).
82
+ *
83
+ * @param raw - the parsed line.
84
+ * @returns the canonical record, or undefined when unusable.
85
+ */
86
+ function readVersion1(raw) {
87
+ if (typeof raw['ts'] !== 'number' || !Number.isFinite(raw['ts']))
88
+ return undefined;
89
+ if (typeof raw['sessionId'] !== 'string' || raw['sessionId'].length === 0)
90
+ return undefined;
91
+ if (typeof raw['turn'] !== 'number' || !Number.isSafeInteger(raw['turn']))
92
+ return undefined;
93
+ if (typeof raw['total'] !== 'number' || !Number.isFinite(raw['total']))
94
+ return undefined;
95
+ if (typeof raw['workspace'] !== 'string')
96
+ return undefined;
97
+ if (!isBucketSet(raw['tokens']))
98
+ return undefined;
99
+ if (!Array.isArray(raw['attempts']))
100
+ return undefined;
101
+ for (const attempt of raw['attempts']) {
102
+ if (!isAttempt(attempt))
103
+ return undefined;
104
+ }
105
+ const cost = raw['cost'];
106
+ if (typeof cost !== 'object' || cost === null)
107
+ return undefined;
108
+ const priced = cost;
109
+ if (typeof priced['total'] !== 'number' || !Number.isFinite(priced['total']))
110
+ return undefined;
111
+ if (!isCurrency(priced['currency']))
112
+ return undefined;
113
+ const label = typeof raw['workspaceLabel'] === 'string' ? raw['workspaceLabel'] : raw['workspace'];
114
+ const record = { ...raw, workspaceLabel: label };
115
+ return record;
116
+ }
117
+ /**
118
+ * Report whether a value is a token bucket set with numeric buckets.
119
+ * @param value - candidate.
120
+ * @returns true when every bucket the aggregation reads is a finite number.
121
+ */
122
+ export function isBucketSet(value) {
123
+ if (typeof value !== 'object' || value === null)
124
+ return false;
125
+ const buckets = value;
126
+ for (const key of ['uncachedInput', 'cacheRead', 'cacheWrite', 'output', 'reasoning']) {
127
+ const bucket = buckets[key];
128
+ if (typeof bucket !== 'number' || !Number.isFinite(bucket))
129
+ return false;
130
+ }
131
+ return true;
132
+ }
133
+ /**
134
+ * Report whether one attempt entry carries what the aggregation path reads.
135
+ * @param value - candidate.
136
+ * @returns true when the entry is usable.
137
+ */
138
+ export function isAttempt(value) {
139
+ if (typeof value !== 'object' || value === null)
140
+ return false;
141
+ const attempt = value;
142
+ if (typeof attempt['provider'] !== 'string' || typeof attempt['model'] !== 'string')
143
+ return false;
144
+ if (typeof attempt['total'] !== 'number' || !Number.isFinite(attempt['total']))
145
+ return false;
146
+ if (typeof attempt['cost'] !== 'number' || !Number.isFinite(attempt['cost']))
147
+ return false;
148
+ return isBucketSet(attempt['tokens']);
149
+ }
150
+ /**
151
+ * Fill the health report's ledger-derived counters for this module's concerns.
152
+ * @param base - the counters the store already tracks.
153
+ * @returns the completed report.
154
+ */
155
+ export function withSchemaHealth(base) {
156
+ return { ...base, unsupportedRecords: 0 };
157
+ }
158
+ //# sourceMappingURL=schema.js.map
@@ -0,0 +1,171 @@
1
+ /**
2
+ * Append-only ledger storage.
3
+ *
4
+ * One JSON object per line under the harness home, so the ledger is
5
+ * human-inspectable, append-only, and survives a crash mid-write (a torn final
6
+ * line is skipped and counted, never fatal). Writes are batched onto a
7
+ * `setImmediate` drain so the `session/event` dispatch that produced a record
8
+ * never performs file I/O on the conversation's critical path.
9
+ *
10
+ * Every entry point swallows its own failure and reports it through
11
+ * {@link UsageStore.stats}: the ledger is a diagnostic side-channel and must
12
+ * never be able to fail a Turn.
13
+ *
14
+ * @module dsh-token-usage-ledger/host/store
15
+ */
16
+ import type { HealthReport, UsageRecord } from '../shared/protocol.js';
17
+ /** Directory (under the harness home) that holds the ledger. */
18
+ export declare const LEDGER_DIR = "token-usage";
19
+ /** File name of the append-only ledger. */
20
+ export declare const LEDGER_FILE = "records.jsonl";
21
+ /** Snapshot of the ledger loaded from disk. */
22
+ export interface LedgerSnapshot {
23
+ /** Accepted records, oldest first, de-duplicated by `sessionId` + `turn`. */
24
+ records: UsageRecord[];
25
+ /** Lines skipped because they were not valid records. */
26
+ malformedLines: number;
27
+ /** Lines from a newer plugin version this build cannot read. */
28
+ unsupportedRecords: number;
29
+ /** Lines collapsed because a later line carried the same idempotency key. */
30
+ duplicateLines: number;
31
+ /** True when the record cap was reached and older records were dropped. */
32
+ truncated: boolean;
33
+ }
34
+ /** Diagnostics the store exposes for the dashboard's health strip. */
35
+ export interface StoreStats {
36
+ /** Failed append attempts since process start. */
37
+ writeErrors: number;
38
+ /** Message of the most recent append failure, or `''`. */
39
+ lastWriteError: string;
40
+ /** Records still queued for the next drain. */
41
+ pendingWrites: number;
42
+ /** Lines skipped while parsing the ledger. */
43
+ malformedLines: number;
44
+ /** Ledger file size in bytes, or 0 when absent. */
45
+ bytes: number;
46
+ }
47
+ /** Collaborators the store needs; injected so tests can run without a real clock or logger. */
48
+ export interface StoreOptions {
49
+ /** Directory holding the ledger file. */
50
+ dir: string;
51
+ /** File name inside {@link dir}. */
52
+ file?: string;
53
+ /** Queue bound; oldest records are dropped past it. */
54
+ maxPending?: number;
55
+ /** Sink for the one-line, throttled failure reports. */
56
+ warn?: (message: string) => void;
57
+ }
58
+ /**
59
+ * The ledger: a write queue plus a cached reader.
60
+ *
61
+ * Instances are created per plugin activation and dropped with the fiber; a
62
+ * re-activation re-reads the file, so the ledger — not memory — is the source
63
+ * of truth.
64
+ */
65
+ export declare class UsageStore {
66
+ private readonly dir;
67
+ private readonly file;
68
+ private readonly path;
69
+ private readonly maxPending;
70
+ private readonly warn;
71
+ private queue;
72
+ private drainScheduled;
73
+ private writeErrors;
74
+ private lastWriteError;
75
+ private malformedLines;
76
+ private unsupportedRecords;
77
+ private truncated;
78
+ private droppedRecords;
79
+ /** Set while a failed batch is awaiting its single retry. */
80
+ private retryArmed;
81
+ private warnedOnce;
82
+ private snapshot;
83
+ private snapshotKey;
84
+ private loadInFlight;
85
+ /**
86
+ * @param options - directory, file name, queue bound, and warning sink.
87
+ */
88
+ constructor(options: StoreOptions);
89
+ /** Absolute path of the ledger file. */
90
+ get filePath(): string;
91
+ /**
92
+ * Queue one record for the next append drain.
93
+ *
94
+ * Returns immediately; the caller is on the conversation's dispatch path and
95
+ * must not block. Never throws.
96
+ *
97
+ * @param record - the record to persist.
98
+ */
99
+ enqueue(record: UsageRecord): void;
100
+ /**
101
+ * Flush the queue and wait for it, for shutdown paths and tests.
102
+ * @returns the number of records written, or 0 when the flush failed.
103
+ */
104
+ flush(): Promise<number>;
105
+ /**
106
+ * Append records produced outside the live collector (import/backfill).
107
+ *
108
+ * Waits for the live queue first so the file stays in one append order, then
109
+ * appends the batch in a single write. The caller has already validated the
110
+ * records and checked `(sessionId, turn)` duplicates; this method only reports
111
+ * whether the OS write succeeded. It never throws into the caller's request
112
+ * path — the API maps the returned failure to a structured error.
113
+ *
114
+ * @param records - records to append.
115
+ * @returns the written count, or the write error message on failure.
116
+ */
117
+ appendRecords(records: readonly UsageRecord[]): Promise<{
118
+ written: number;
119
+ error?: string;
120
+ }>;
121
+ /**
122
+ * Load and cache the ledger.
123
+ *
124
+ * The cache is keyed on the file's size and mtime, so a second request after
125
+ * a write re-reads while repeated reads stay cheap. A concurrent caller
126
+ * joins the in-flight read instead of starting a second one.
127
+ *
128
+ * @returns the parsed snapshot; an empty snapshot when the file is absent.
129
+ */
130
+ load(): Promise<LedgerSnapshot>;
131
+ /**
132
+ * Report current diagnostics.
133
+ * @param extra - additional counters owned by the caller.
134
+ * @returns the health report embedded in the summary payload.
135
+ */
136
+ stats(extra: {
137
+ skippedTurns: number;
138
+ }): HealthReport;
139
+ /** Read + parse the ledger, refreshing the cache. */
140
+ private loadOnce;
141
+ /**
142
+ * Stream the ledger into de-duplicated records.
143
+ *
144
+ * Streamed rather than read whole so memory is bounded by the RECORD cap and
145
+ * not by the file size: a large ledger degrades to the newest
146
+ * {@link API_LIMITS.maxRecords} records with `ledgerTruncated` set, instead of
147
+ * silently reporting an empty dashboard. Every line is still visited, so
148
+ * de-duplication and the malformed count stay exact.
149
+ *
150
+ * @returns the snapshot.
151
+ */
152
+ private parseLedger;
153
+ /** Schedule one drain on the next macrotask boundary. */
154
+ private scheduleDrain;
155
+ /**
156
+ * Write every queued record in one append.
157
+ * @returns the number of records written.
158
+ */
159
+ private drain;
160
+ /**
161
+ * Account one append failure, reporting it at most once per process so a
162
+ * broken disk cannot flood the log.
163
+ * @param error - the failure to record.
164
+ */
165
+ private recordWriteError;
166
+ /**
167
+ * Emit one warning line, throttled to a single occurrence per activation.
168
+ * @param message - warning text.
169
+ */
170
+ private report;
171
+ }