@thehammer/danx-session-telemetry 0.1.14 → 0.1.16

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.
@@ -0,0 +1,83 @@
1
+ /**
2
+ * DX-2954 — the TRANSCRIPT-side producer of a dispatch's running set.
3
+ *
4
+ * `dispatch_activities` answers "what is this dispatch running RIGHT NOW" — one
5
+ * row per sub-agent or background script, with `finished_at` NULL while it is
6
+ * still going. This module produces the sub-agent half of that set from the one
7
+ * signal danxbot owns end-to-end: the session-log watcher discovering a
8
+ * sub-agent's transcript file and then tailing it.
9
+ *
10
+ * ## Why the transcript, and where the hooks come in
11
+ *
12
+ * Claude Code's `SubagentStart` / `SubagentStop` hooks carry strictly more (an
13
+ * `agent_type` before the sub-agent has written anything, and — the part this
14
+ * module cannot supply — a FINISH). Those hooks ship from the danxbot plugin in
15
+ * the claude-plugins repo, and DX-3284 builds them, next. They were not built in
16
+ * DX-2954 itself, but not because a plugin change cannot ship from a danxbot
17
+ * card: DX-2954's own `transcript_path` change shipped as claude-plugins
18
+ * `c0c134d`. Keying the running set solely on them before they exist would ship
19
+ * a set that is permanently empty (`subagent_count` 0 on every dispatch, a
20
+ * REGRESSION against the transcript-derived counter this replaced).
21
+ *
22
+ * So the transcript is the producer, and the hooks are an ENRICHMENT layered on
23
+ * the same rows:
24
+ *
25
+ * | Signal | Sub-agent start | Sub-agent finish | Background script |
26
+ * |---|---|---|---|
27
+ * | Transcript (here) | file discovered | dispatch terminal (`finishOpenActivities`) | not visible |
28
+ * | Hooks (DX-3284) | `SubagentStart` | `SubagentStop` | `PostToolUse` start; end at dispatch terminal (no documented completion event) |
29
+ *
30
+ * **Until DX-3284 lands, "running" over-counts.** With no finish signal, every
31
+ * sub-agent this dispatch ever started stays in the running set until the
32
+ * dispatch itself ends, and the silent-too-long warning fires
33
+ * `RUNNING_ACTIVITY_SILENT_AFTER_MS` after a sub-agent that has in fact
34
+ * finished. `SubagentStop` is what closes that gap.
35
+ *
36
+ * ## Why the two producers cannot double-count
37
+ *
38
+ * Every row is an upsert keyed `(dispatch_id, kind, activity_id)`, and BOTH
39
+ * producers derive `activity_id` from the same thing: the sub-agent's transcript
40
+ * file basename. The watcher has it directly; a hook has it as the basename of
41
+ * its `transcript_path`. That is also the key the ledger credits the sub-agent's
42
+ * tokens under, which is how per-sub-agent tokens join to the running set
43
+ * without this table carrying a token column.
44
+ *
45
+ * ## What this module deliberately does NOT do
46
+ *
47
+ * It never reports a FINISH. A transcript gives no "this sub-agent is done"
48
+ * signal — a finished sub-agent's file simply stops growing, which is
49
+ * indistinguishable from a slow one. Guessing a finish from an idle gap would
50
+ * mark a long-thinking sub-agent as complete. So open rows are closed exactly
51
+ * once, at the dispatch's own terminal transition (`finishOpenActivities`),
52
+ * unless DX-3284's `SubagentStop` hook closes a row first.
53
+ */
54
+ import type { ActivityChange } from "./stats-wire.js";
55
+ import type { EntryMeta, SourceDiscoveredInfo } from "./session-log-watcher.js";
56
+ import type { AgentLogEntry } from "./types.js";
57
+ /** What the observer needs from the dispatch's usage accumulator. */
58
+ export interface ActivityObserverDeps {
59
+ /**
60
+ * Queue activity changes onto the next stats write. Called with the full
61
+ * current state of each changed activity — the server's upsert is idempotent,
62
+ * so re-reporting an unchanged field is free and a dropped batch is
63
+ * self-healing on the next write.
64
+ */
65
+ recordActivities: (changes: ActivityChange[]) => void;
66
+ /**
67
+ * DX-2954 — ignore every sub-agent file that already existed when the watcher
68
+ * attached. Set for a dispatch that continues an earlier one's session
69
+ * (`StartCursorPlan.inheritsPredecessorSubagents`): those files are the
70
+ * predecessor's sub-agents, which ended with its process, and reporting them
71
+ * would open a never-closing "running" row per predecessor sub-agent on the
72
+ * new dispatch — inflating `subagent_count` / `running_activity_count` and
73
+ * tripping the silent-too-long warning ten minutes later.
74
+ */
75
+ ignorePreexisting?: boolean;
76
+ }
77
+ export interface ActivityObserver {
78
+ /** Wire to the watcher's `onSourceDiscovered`. */
79
+ onSourceDiscovered: (info: SourceDiscoveredInfo) => void;
80
+ /** Wire to the watcher's `onEntry`. */
81
+ onEntry: (entry: AgentLogEntry, meta: EntryMeta) => void;
82
+ }
83
+ export declare function createActivityObserver(deps: ActivityObserverDeps): ActivityObserver;
@@ -0,0 +1,73 @@
1
+ export function createActivityObserver(deps) {
2
+ // No clock of its own, deliberately. Every stamp this module reports comes from
3
+ // the event that caused it — the watcher's `discoveredAt` for a start, the
4
+ // entry's own `timestamp` for an advance — so there is no wall-clock reading
5
+ // anywhere that a test would need to freeze or that a replay could skew.
6
+ /** Every sub-agent this observer has reported, by its ledger source key. */
7
+ const started = new Map();
8
+ return {
9
+ onSourceDiscovered(info) {
10
+ // Not this dispatch's sub-agent (see `ignorePreexisting`). Never added to
11
+ // `started` either, so its later lines do not stamp activity on a row
12
+ // that does not exist.
13
+ if (deps.ignorePreexisting === true && info.preexisting)
14
+ return;
15
+ const existing = started.get(info.source);
16
+ if (existing) {
17
+ // A second discovery of a source already reported can only ADD an
18
+ // `agentType` the first pass could not read yet (the sub-agent had not
19
+ // written a line naming one). Never re-stamp `startedAt`: the server
20
+ // takes LEAST(startedAt) anyway, but reporting a later start for a
21
+ // sub-agent that has been running since before this watcher attached
22
+ // would be wrong in the payload itself.
23
+ if (existing.agentType === null && info.agentType !== null) {
24
+ existing.agentType = info.agentType;
25
+ deps.recordActivities([{ ...existing }]);
26
+ }
27
+ return;
28
+ }
29
+ const change = {
30
+ kind: "agent",
31
+ activityId: info.source,
32
+ agentType: info.agentType,
33
+ // A sub-agent has no Bash `description`; the field exists for the
34
+ // background-script kind and stays null here rather than being filled
35
+ // with a stand-in a reader would have to distinguish from a real one.
36
+ description: null,
37
+ startedAt: info.discoveredAt,
38
+ lastActivityAt: info.discoveredAt,
39
+ // Never a finish from the transcript — see the module docblock.
40
+ finishedAt: null,
41
+ };
42
+ started.set(info.source, change);
43
+ deps.recordActivities([{ ...change }]);
44
+ },
45
+ onEntry(entry, meta) {
46
+ // DX-2954 — a REPLAY counts as activity here, unlike the stall detector's
47
+ // liveness signal. The two ask different questions: the stall detector asks
48
+ // "is the agent alive NOW" (a re-read proves nothing), while this stamp
49
+ // answers "when did this sub-agent last actually say something", which a
50
+ // re-read line genuinely reports.
51
+ //
52
+ // Which is exactly why the stamp is the ENTRY's OWN timestamp and never a
53
+ // wall clock. Stamping `Date.now()` would make a reattach reset every
54
+ // pre-existing sub-agent's last activity to the moment the collector
55
+ // restarted: the whole replay window would report as fresh, and a sub-agent
56
+ // silent for half an hour would come out of it looking live, so
57
+ // `RUNNING_ACTIVITY_SILENT_AFTER_MS` could never fire for it. That is the
58
+ // one signal this feature has for "ended or stuck" (DX-3246 fixed the same
59
+ // wall-clock-for-entry-time confusion in the boot mark). Even with no
60
+ // replay involved, a wall clock records when the 5s poll NOTICED the line,
61
+ // not when the agent wrote it.
62
+ const change = started.get(meta.source);
63
+ if (!change)
64
+ return;
65
+ // GREATEST, mirroring the server: a line read out of order, or an older
66
+ // line inside a replay window, never drags liveness backwards.
67
+ if (entry.timestamp <= change.lastActivityAt)
68
+ return;
69
+ change.lastActivityAt = entry.timestamp;
70
+ deps.recordActivities([{ ...change }]);
71
+ },
72
+ };
73
+ }
@@ -0,0 +1,227 @@
1
+ /**
2
+ * DX-2963 — a running dispatch's usage, worker side.
3
+ *
4
+ * The worker no longer sums anything. It feeds every transcript line into
5
+ * the ONE shared counter (`UsageLedgerCounter`, per-field maximum per reply)
6
+ * and ships the entries that are new or changed since the last acknowledged
7
+ * write to the server (`applyStats`), which derives every total from the
8
+ * ledger and hands them back. The worker's own view of the totals is what the
9
+ * server last returned — plus, for the token ceiling only, a local estimate of
10
+ * what it has read but the server has not acknowledged yet.
11
+ *
12
+ * Totals are taken from the server ONLY at process start (the first write,
13
+ * sent with no entries if there are none) and from each write's response —
14
+ * never seeded by hand (the reattach hand seeds this replaces).
15
+ *
16
+ * DB-free: runs in the DB-less worker. The sink decides the transport
17
+ * (HTTP on a registered worker, getPool-direct on the dashboard).
18
+ */
19
+ import { UsageLedgerCounter } from "./usage-ledger.js";
20
+ import type { CursorPastEofInfo } from "./session-log-watcher.js";
21
+ import type { AgentLogEntry } from "./types.js";
22
+ import { type ActivityChange, type SourceCursors, type StatsPayload, type StatsResponse, type UsageTotals } from "./stats-wire.js";
23
+ /** Where stats writes go — both dispatch-row sinks implement it. */
24
+ export interface StatsSink {
25
+ applyStats(dispatchId: string, payload: StatsPayload): Promise<StatsResponse>;
26
+ }
27
+ export declare function zeroUsageTotals(): UsageTotals;
28
+ export type FlushOutcome = "ok" | "failed" | "refused";
29
+ export declare class DispatchUsage {
30
+ readonly counter: UsageLedgerCounter;
31
+ private serverTotals;
32
+ private readonly acked;
33
+ private healthy;
34
+ private refused;
35
+ private started;
36
+ private readonly queue;
37
+ /** How to read the watcher's live per-source cursor state. */
38
+ private readCursorState;
39
+ /**
40
+ * Per source, the `delivered` offset as of the last ACKNOWLEDGED write — which
41
+ * is precisely what `acked` means. Seeded from the cursors this process
42
+ * resumed from, so a restart that writes before reading anything re-reports
43
+ * its own resume point instead of regressing it.
44
+ */
45
+ private readonly ackedCursor;
46
+ /**
47
+ * DX-2954 (AC 34324) — the cursors this process STARTED from, reported
48
+ * verbatim for every source the watcher has not opened yet until one write
49
+ * carrying them has landed. See {@link DispatchUsage.buildCursorReports}.
50
+ */
51
+ private startCursors;
52
+ private startCursorsPersisted;
53
+ /** Past-EOF resets to report once, then forget. */
54
+ private pastEof;
55
+ /**
56
+ * DX-2954 — replies this process read as REPLAYS. The server already counted
57
+ * them for THIS dispatch (they are below its stored `acked`), so they must not
58
+ * enter the unacknowledged excess the token-ceiling estimate adds on top of the
59
+ * server totals.
60
+ */
61
+ private readonly replayedMessageIds;
62
+ /** Running-set changes to report on the next write. */
63
+ private pendingActivities;
64
+ /** The session transcript path — the ONE path field the wire carries. */
65
+ private transcriptPath;
66
+ private transcriptPathSent;
67
+ /**
68
+ * DX-2954 — wire the cursor half up at attach.
69
+ *
70
+ * `startCursors` are the cursors this process RESUMED from
71
+ * (`resolveStartCursors`); their `acked` values seed this collector's own
72
+ * acknowledged floor. `readCursorState` reads the watcher's live offsets at
73
+ * each write.
74
+ */
75
+ attachCursors(readCursorState: () => Record<string, {
76
+ startOffset: number;
77
+ delivered: number;
78
+ }>, startCursors: SourceCursors): void;
79
+ /**
80
+ * DX-2954 — a stored cursor was past its file's end; report the reset on the
81
+ * next write so the server records a `transcript_cursor_past_eof` event and
82
+ * permits the one sanctioned backwards move of `acked`.
83
+ */
84
+ recordPastEof(info: CursorPastEofInfo): void;
85
+ /**
86
+ * DX-2954 — queue running-set changes for the next write.
87
+ *
88
+ * Kept COLLAPSED (one entry per `(kind, activityId)`) rather than appended
89
+ * raw, so the queue is bounded by how many activities the dispatch has, not by
90
+ * how much they moved since the last write. A producer reports an activity's
91
+ * full current state every time anything about it changes, and a chatty
92
+ * sub-agent advances its `lastActivityAt` continuously — appending those would
93
+ * grow without bound, eventually exceed `ACTIVITY_BATCH_CAP` and take the
94
+ * WHOLE stats write down (not just its activity part) to describe a handful of
95
+ * activities.
96
+ *
97
+ * `collapseActivityChanges` applies the server's own merge rule, so collapsing
98
+ * here reaches the identical stored row; it is not a lossy summarisation.
99
+ */
100
+ recordActivities(changes: readonly ActivityChange[]): void;
101
+ /**
102
+ * DX-2954 — the session's own transcript path, recorded on the dispatch's
103
+ * `jsonl_path`. Sent once, with the first stats write that carries it; the
104
+ * server also keeps only the first path it is given, so a repeat is harmless.
105
+ */
106
+ setTranscriptPath(path: string): void;
107
+ /**
108
+ * DX-2954 — this write's cursor reports, plus the `delivered` value to promote
109
+ * to `acked` per source once the write is acknowledged.
110
+ *
111
+ * **`acked` deliberately LAGS `delivered` by one write.** A write reports the
112
+ * position it has read to (`delivered`) and the position whose entries a
113
+ * PREVIOUS write already had acknowledged (`acked`); only when THIS write
114
+ * succeeds does its own `delivered` become the next write's `acked`.
115
+ *
116
+ * The lag is not slack — it is what makes the pair safe. A reply's ledger entry
117
+ * can be RAISED after it was first reported (its usage grows as the reply
118
+ * streams), and a delivered line need not produce an entry at all (a
119
+ * `tool_result`), so "the server committed my last write" is NOT the same as
120
+ * "every line I have read is finally accounted for". Reporting `acked` one
121
+ * write behind is the conservative claim that is always true.
122
+ *
123
+ * What it costs: a restart re-reads the last write's window. That is exactly
124
+ * the window `EntryMeta.replay` covers — the ledger re-credits nothing (its
125
+ * excess rule) and every side-effecting subscriber skips it — so the cost is
126
+ * one window of re-read, never a double count or a duplicate side effect.
127
+ *
128
+ * ## The process-start write carries the STARTING cursors (AC 34324)
129
+ *
130
+ * `attachMonitoringStack` deliberately does NOT await `watcher.start()` —
131
+ * file discovery polls for up to 180 s and must not block the spawn — and the
132
+ * process-start stats write fires immediately after it. At that moment the
133
+ * watcher has opened no file, so its live `cursorState()` is empty.
134
+ *
135
+ * So every source in the cursors this process STARTED from that the watcher
136
+ * has not opened yet is reported VERBATIM — the exact `{acked, delivered}`
137
+ * pair it resumed from — until one write carrying them has landed. That is
138
+ * what makes "every attach persists its starting cursors" true on the FIRST
139
+ * write rather than one stats tick (15-30 s) later: a reattach of this row
140
+ * inside its first interval reads them back (start-order rule 1) and starts
141
+ * exactly where this process did, instead of finding no cursor, resolving
142
+ * rule 4 and skipping every line written since spawn. A fresh session's
143
+ * starting cursor is explicit too (`resolveStartCursors` rule 3 returns the
144
+ * main source at 0), and a `--resume`'s is its predecessor's (rule 2).
145
+ *
146
+ * Verbatim is the only honest claim for a source this process has not read:
147
+ * a higher `acked` would let a restart skip the replay window it has not
148
+ * re-credited, a lower one is refused as a regression. For the same reason
149
+ * the start write does not PROMOTE such a source's acknowledged floor — it
150
+ * delivered nothing there — so it stays out of `deliveredAtSend`.
151
+ *
152
+ * The one case with nothing to carry is rule 4 (a continuing dispatch with no
153
+ * cursor for ANY source): its start is "each existing file's end at
154
+ * discovery", which does not exist until discovery runs. Its cursors reach
155
+ * the server on the first write after discovery. Rule 4 is the pre-card
156
+ * deploy transition only — every dispatch since this card stores cursors on
157
+ * its first write — so that bounded window is the one the card accepts.
158
+ */
159
+ private buildCursorReports;
160
+ /**
161
+ * DX-2954 — whether the cursor half has anything new to say. An IDLE dispatch
162
+ * (no new lines, no hook events) must still cost zero writes per tick, which
163
+ * is why a write is not forced merely because cursors EXIST.
164
+ */
165
+ private cursorsMoved;
166
+ /**
167
+ * Feed one watcher entry. Only assistant lines carry usage / tool ids.
168
+ *
169
+ * `replay` (DX-2954) marks a line re-read after a restart. The line STILL goes
170
+ * to the counter — the ledger is idempotent and dropping it would lose usage a
171
+ * restart is meant to recover — but its id is remembered so the local ceiling
172
+ * estimate does not count it twice (see {@link DispatchUsage.unacknowledged}).
173
+ */
174
+ observeEntry(entry: AgentLogEntry, replay?: boolean): void;
175
+ /**
176
+ * Ship every changed entry in capped batches, one after another. The first
177
+ * call always writes (even with nothing to send) so the process takes the
178
+ * server totals at start. A failed batch re-queues itself and every later
179
+ * batch; a refusal (the dispatch went terminal) stops all later writes.
180
+ *
181
+ * DX-2954 — the write also carries the cursor half. A write happens when there
182
+ * are entries, OR the cursors moved, OR there are activity changes, OR it is
183
+ * the process-start write; an idle dispatch still writes nothing. Cursors,
184
+ * activity changes and the transcript path ride the LAST batch only, so a
185
+ * multi-batch backlog does not repeat them and the cursor can never be
186
+ * acknowledged ahead of the entries it covers.
187
+ */
188
+ flush(sink: StatsSink, dispatchId: string): Promise<FlushOutcome>;
189
+ /** The dispatch's totals as the server last returned them. */
190
+ totals(): UsageTotals;
191
+ /** Window tokens (input + output + cache writes) of the server totals. */
192
+ serverWindowTokens(): number;
193
+ /** Whether the most recent stats write succeeded. */
194
+ statsHealthy(): boolean;
195
+ /**
196
+ * The per-field excess of each local reply's maximum over what the server
197
+ * last acknowledged for it.
198
+ *
199
+ * DX-2954 — REPLAYED replies are excluded. The pre-DX-2954 comment here
200
+ * asserted that "every id this process observed was read at or after its
201
+ * starting cursor … so lines re-read on a restart never enter the estimate",
202
+ * which stopped being true the moment replays became a deliberate input: a
203
+ * replayed reply has no entry in `this.acked` at process start, so its FULL
204
+ * usage would be added on top of `serverTotals` that already contain it. That
205
+ * feeds a fabricated total to the token ceiling (`agent-status.ts` uses this
206
+ * estimate precisely when a write did NOT land) and to the context-overflow
207
+ * decision — either can stop a healthy dispatch.
208
+ */
209
+ private unacknowledged;
210
+ /**
211
+ * The dispatch's usage as far as this process knows it: the server totals
212
+ * plus the per-field excess this process has read but the server has not
213
+ * acknowledged. A replay block adds nothing (its excess over the
214
+ * acknowledged total is zero). For a job with no dispatch row (nothing is
215
+ * ever acknowledged) this is exactly the local counter's total.
216
+ */
217
+ estimate(): {
218
+ tokensIn: number;
219
+ tokensOut: number;
220
+ cacheRead: number;
221
+ cacheWrite: number;
222
+ };
223
+ /** Token-ceiling input: window tokens (input + output + cache writes) of {@link estimate}. */
224
+ windowTokensEstimate(): number;
225
+ /** All-field total of {@link estimate}. */
226
+ totalTokensEstimate(): number;
227
+ }