@spike1292/claude-memory 0.0.0-stage → 0.14.0
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/LICENSE +21 -0
- package/README.md +412 -2
- package/hooks/distill-session.mjs +74 -0
- package/hooks/graph-staleness-check.mjs +25 -0
- package/hooks/hooks.json +94 -0
- package/hooks/insights-surface.mjs +48 -0
- package/hooks/lib/distill-session.mjs +1560 -0
- package/hooks/lib/dupe-report.mjs +61 -0
- package/hooks/lib/env-shell.mjs +92 -0
- package/hooks/lib/graph-staleness-check.mjs +394 -0
- package/hooks/lib/hook-io.mjs +715 -0
- package/hooks/lib/insights-surface.mjs +165 -0
- package/hooks/lib/memory-link-lint.mjs +499 -0
- package/hooks/lib/memory-recall.mjs +219 -0
- package/hooks/lib/omp.mjs +103 -0
- package/hooks/lib/opencode.mjs +231 -0
- package/hooks/lib/paths.mjs +452 -0
- package/hooks/lib/semantic-index-refresh.mjs +155 -0
- package/hooks/lib/validate-note.mjs +218 -0
- package/hooks/lib/vault-env.sh +110 -0
- package/hooks/memory-link-lint.mjs +65 -0
- package/hooks/memory-recall.mjs +251 -0
- package/hooks/semantic-index-refresh.mjs +23 -0
- package/hooks/session-context.mjs +9 -0
- package/hooks/validate-note.mjs +52 -0
- package/hooks/vault-memory-sync.sh +154 -0
- package/omp/index.js +1 -0
- package/opencode/index.js +1 -0
- package/package.json +51 -4
- package/scripts/claude-memory.mjs +31 -0
- package/scripts/doctor-perf.mjs +121 -0
- package/scripts/doctor.sh +558 -0
- package/scripts/env.mjs +6 -0
- package/scripts/lib/claude-memory.mjs +168 -0
- package/scripts/lib/doctor-perf.mjs +434 -0
- package/scripts/lib/hook-stats.mjs +864 -0
- package/scripts/lib/lexical.mjs +85 -0
- package/scripts/lib/memory-adopt.mjs +69 -0
- package/scripts/lib/memory-audit-checks.mjs +344 -0
- package/scripts/lib/memory-eval.mjs +381 -0
- package/scripts/lib/memory-mark.mjs +135 -0
- package/scripts/lib/memory-mcp.mjs +142 -0
- package/scripts/lib/memory-merge.mjs +316 -0
- package/scripts/lib/memory-mine.mjs +108 -0
- package/scripts/lib/memory-promote.mjs +207 -0
- package/scripts/lib/memory-prune.mjs +84 -0
- package/scripts/lib/memory-semantic.mjs +999 -0
- package/scripts/lib/memory-setup.mjs +170 -0
- package/scripts/lib/memory-synth-vault.mjs +538 -0
- package/scripts/lib/model-default.mjs +7 -0
- package/scripts/lib/models.mjs +58 -0
- package/scripts/lib/prune-logs.mjs +130 -0
- package/scripts/lib/recall-stats.mjs +354 -0
- package/scripts/lib/share-modules.mjs +70 -0
- package/scripts/lib/slim-install.mjs +162 -0
- package/scripts/lib/vault-mcp.mjs +405 -0
- package/scripts/memory-adopt.mjs +160 -0
- package/scripts/memory-audit-checks.mjs +375 -0
- package/scripts/memory-eval.mjs +753 -0
- package/scripts/memory-mark.mjs +39 -0
- package/scripts/memory-mcp.mjs +35 -0
- package/scripts/memory-merge.mjs +55 -0
- package/scripts/memory-prune.mjs +44 -0
- package/scripts/memory-semantic.mjs +1192 -0
- package/scripts/memory-setup.mjs +33 -0
- package/scripts/memory-synth-vault.mjs +251 -0
- package/scripts/prune-logs.mjs +42 -0
- package/scripts/share-modules.mjs +79 -0
- package/scripts/slim-install.mjs +55 -0
- package/scripts/vault-mcp.mjs +50 -0
- package/stubs/onnxruntime-web/index.mjs +11 -0
- package/stubs/onnxruntime-web/package.json +12 -0
- package/stubs/sharp/index.mjs +11 -0
- package/stubs/sharp/package.json +12 -0
|
@@ -0,0 +1,864 @@
|
|
|
1
|
+
// The `--hooks` half of /memory:doctor: what every hook did, and how long it took. The CLI entry
|
|
2
|
+
// is scripts/doctor-perf.mjs. It is the continuous version of the one-off hand measurements
|
|
3
|
+
// CLAUDE.md quotes for the ported gates (43-58 ms) and the shell link lint (74 ms vs 10.9 s) —
|
|
4
|
+
// see CLAUDE.md's hook-cost section.
|
|
5
|
+
//
|
|
6
|
+
// Read-only, and the same hard rule as its two siblings: no server, no model, no index write, no
|
|
7
|
+
// file written at all.
|
|
8
|
+
//
|
|
9
|
+
// It must also read lines written before any field it reports existed, so every metric is counted
|
|
10
|
+
// over the lines that HAVE the key rather than treating a missing one as a zero.
|
|
11
|
+
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import { table } from './doctor-perf.mjs';
|
|
15
|
+
import { logFiles, readLines, percentile, DEFAULT_DAYS } from './recall-stats.mjs';
|
|
16
|
+
import { mocs } from '../../hooks/lib/memory-link-lint.mjs';
|
|
17
|
+
import { COST_EVENT } from '../../hooks/lib/hook-io.mjs';
|
|
18
|
+
|
|
19
|
+
export { DEFAULT_DAYS };
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* @typedef {{
|
|
23
|
+
* t?: string, slug?: string | null, hook?: string, event?: string,
|
|
24
|
+
* ms?: number, outcome?: string, reason?: string, session?: string, child?: boolean, machine?: boolean,
|
|
25
|
+
* bytes?: number, pruned?: number,
|
|
26
|
+
* inTok?: number, cacheWriteTok?: number, cacheReadTok?: number, outTok?: number, usd?: number,
|
|
27
|
+
* }} HookLine
|
|
28
|
+
*/
|
|
29
|
+
/** @typedef {{ chars?: number, abstained?: boolean, t?: string, slug?: string, pruned?: number }} RecallSize */
|
|
30
|
+
|
|
31
|
+
// `<family>-YYYY-MM-DD.jsonl` — the window's own dates, read back off the filenames that define it.
|
|
32
|
+
const DATE_IN_NAME = /-(\d{4}-\d{2}-\d{2})\.jsonl$/;
|
|
33
|
+
/**
|
|
34
|
+
* @typedef {{
|
|
35
|
+
* hook: string,
|
|
36
|
+
* n: number,
|
|
37
|
+
* latencies: number[],
|
|
38
|
+
* outcomes: Map<string, number>,
|
|
39
|
+
* reasons: Map<string, Map<string, number>>,
|
|
40
|
+
* worker: boolean,
|
|
41
|
+
* }} HookRow
|
|
42
|
+
*/
|
|
43
|
+
|
|
44
|
+
// A hook that runs at half its declared timeout is not failing, and is one slow vault away from
|
|
45
|
+
// failing. Half is the point at which a number is worth printing rather than a threshold anything
|
|
46
|
+
// acts on — nothing here retunes a timeout, it only says which one is close.
|
|
47
|
+
export const NEAR_FRACTION = 0.5;
|
|
48
|
+
|
|
49
|
+
// The one hook that is not Node and does not log: hooks/vault-memory-sync.sh moves files and
|
|
50
|
+
// repoints symlinks in a live vault and is under an explicit do-not-port fence. Naming it here is
|
|
51
|
+
// the difference between "this hook is not measured" and "this hook did not run", which is exactly
|
|
52
|
+
// the distinction the outcome column exists to make everywhere else.
|
|
53
|
+
export const UNLOGGED = 'vault-memory-sync (bash, not instrumented)';
|
|
54
|
+
|
|
55
|
+
// Bytes per token. A rule of thumb, not a tokeniser: adding one would mean a dependency shipped
|
|
56
|
+
// into every user's plugin cache to put a second decimal on a number nobody acts on at that
|
|
57
|
+
// precision. 4 is the conventional English figure and these strings are English prose with a few
|
|
58
|
+
// wikilinks. Everything derived from it is LABELLED an estimate, everywhere it is printed — the
|
|
59
|
+
// distiller's figures beside them are measured, and the two must never read alike.
|
|
60
|
+
export const BYTES_PER_TOKEN = 4;
|
|
61
|
+
|
|
62
|
+
// Injected context is spent before the user has typed anything: it is the session's opening cost.
|
|
63
|
+
// The threshold only produces a warning line — here and in costReport(), for one MEMORY.md loaded
|
|
64
|
+
// per start. Nothing caps a list or changes a budget, which is deliberately somebody else's ticket.
|
|
65
|
+
export const INJECTED_TOKEN_BUDGET = 2000;
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Estimated tokens for a byte count. Null in, null out — a hook that injected nothing must not
|
|
69
|
+
* average in as a zero beside hooks that were never measured.
|
|
70
|
+
*
|
|
71
|
+
* @param {number | null | undefined} bytes
|
|
72
|
+
* @returns {number | null}
|
|
73
|
+
*/
|
|
74
|
+
export function estTokens(bytes) {
|
|
75
|
+
return typeof bytes === 'number' && Number.isFinite(bytes) && bytes >= 0
|
|
76
|
+
? Math.round(bytes / BYTES_PER_TOKEN)
|
|
77
|
+
: null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// graph-staleness-check is observed at its gate only. Its background run is the `claude` binary,
|
|
81
|
+
// which cannot log for itself, and nothing may be put in front of it to do so: graphgen.lock holds
|
|
82
|
+
// that process's pid, and a wrapper that died would free the lock while the work carried on — two
|
|
83
|
+
// concurrent re-indexes, which is what the lock is for.
|
|
84
|
+
export const NO_WORKER_LINE = 'graph-staleness-check (its background run is timed by nothing)';
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Every hook's declared timeout, read from the manifest AT RUNTIME.
|
|
88
|
+
*
|
|
89
|
+
* The limits are never copied into a log line or into this file: a duplicated timeout drifts
|
|
90
|
+
* silently, and the drift would show up as near-misses that are not, or as none where there are.
|
|
91
|
+
*
|
|
92
|
+
* Keyed by `<hook>` AND by `<hook> · <event>`, because the manifest declares a limit per event and
|
|
93
|
+
* the report now has a row per event. The per-hook key is the tighter of them, kept as the fallback
|
|
94
|
+
* for a line whose event is missing; a row that knows its event reads its own budget, so a Stop at
|
|
95
|
+
* 5 s and a SessionEnd at 15 s are never judged against each other's.
|
|
96
|
+
*
|
|
97
|
+
* @param {string} manifest
|
|
98
|
+
* @returns {Map<string, number>}
|
|
99
|
+
*/
|
|
100
|
+
export function timeouts(manifest) {
|
|
101
|
+
/** @type {Map<string, number>} */
|
|
102
|
+
const out = new Map();
|
|
103
|
+
let json;
|
|
104
|
+
try {
|
|
105
|
+
json = JSON.parse(fs.readFileSync(manifest, 'utf8'));
|
|
106
|
+
} catch {
|
|
107
|
+
return out; // no manifest, no timeout column — never a throw
|
|
108
|
+
}
|
|
109
|
+
for (const [event, group] of Object.entries(json?.hooks ?? {})) {
|
|
110
|
+
for (const matcher of Array.isArray(group) ? group : []) {
|
|
111
|
+
for (const h of matcher?.hooks ?? []) {
|
|
112
|
+
const m = /hooks\/([\w.-]+)\.(?:mjs|sh)/.exec(String(h?.command ?? ''));
|
|
113
|
+
const secs = Number(h?.timeout);
|
|
114
|
+
if (!m || !Number.isFinite(secs)) continue;
|
|
115
|
+
out.set(`${m[1]} · ${event}`, secs);
|
|
116
|
+
const prev = out.get(m[1]);
|
|
117
|
+
out.set(m[1], prev === undefined ? secs : Math.min(prev, secs));
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return out;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Fold the lines into one row per hook, with gate and worker kept apart.
|
|
126
|
+
*
|
|
127
|
+
* They are two different measurements of the same hook and averaging them would be meaningless:
|
|
128
|
+
* a gate decides in milliseconds and detaches, a worker is the minutes of headless `claude` or
|
|
129
|
+
* re-index that follows. Only the gate runs against a timeout.
|
|
130
|
+
*
|
|
131
|
+
* The log is MACHINE-WIDE — every project appends to the same daily file — so a slug filters it
|
|
132
|
+
* and the report says how much it dropped, rather than quietly reporting another project's numbers.
|
|
133
|
+
*
|
|
134
|
+
* @param {readonly HookLine[]} lines
|
|
135
|
+
* @param {string | null} [slug]
|
|
136
|
+
* @param {number} [logDays] how many daily log files the window read — the honest denominator for
|
|
137
|
+
* a per-day rate, since a day nothing was logged has no file and cannot be counted from lines
|
|
138
|
+
*/
|
|
139
|
+
export function summarize(lines, slug = null, logDays = 0, extraPruned = 0) {
|
|
140
|
+
const seen = lines.length;
|
|
141
|
+
// BEFORE the slug filter, deliberately, and the one figure here that is not scoped. A retention
|
|
142
|
+
// pass is machine-wide: it deletes every project's files, and the line recording it carries
|
|
143
|
+
// whichever slug happened to trigger it. Scoped, the project that LOST the history was the one
|
|
144
|
+
// told nothing — 300 deleted files reported as 0 (measured 2026-08-21).
|
|
145
|
+
const pruned =
|
|
146
|
+
lines.reduce((a, l) => a + (typeof l.pruned === 'number' ? l.pruned : 0), 0) + extraPruned;
|
|
147
|
+
lines = slug ? lines.filter((l) => l.slug === slug) : lines;
|
|
148
|
+
/** @type {Map<string, HookRow>} */
|
|
149
|
+
const hooks = new Map();
|
|
150
|
+
let untimed = 0;
|
|
151
|
+
let childLines = 0;
|
|
152
|
+
let machineLines = 0;
|
|
153
|
+
// Counted in the loop, not taken from `lines.length`: an extract line is a cost record for one
|
|
154
|
+
// API call and is not an invocation of anything.
|
|
155
|
+
let invocations = 0;
|
|
156
|
+
// hook -> session -> bytes injected in that session. Not a flat list of runs: the report's
|
|
157
|
+
// headline is what a SESSION pays, and a hook that fires twice in one session pays twice.
|
|
158
|
+
/** @type {Map<string, Map<string, number>>} */
|
|
159
|
+
const perSession = new Map();
|
|
160
|
+
/** @type {Set<string>} */
|
|
161
|
+
const measured = new Set();
|
|
162
|
+
/** @type {Map<string, number>} */
|
|
163
|
+
const unsized = new Map();
|
|
164
|
+
/** @type {HookLine[]} */
|
|
165
|
+
const extracts = [];
|
|
166
|
+
/** @type {HookLine[]} */
|
|
167
|
+
const judges = [];
|
|
168
|
+
/** @type {Set<string>} */
|
|
169
|
+
const sessions = new Set();
|
|
170
|
+
/** @type {Set<string>} */
|
|
171
|
+
const days = new Set();
|
|
172
|
+
|
|
173
|
+
for (const l of lines) {
|
|
174
|
+
if (l.child) childLines++;
|
|
175
|
+
if (l.machine) machineLines++;
|
|
176
|
+
// A headless or scheduled run's session id is not a person's session, and counting it would
|
|
177
|
+
// inflate the denominator of every per-session figure below.
|
|
178
|
+
const notPerson = l.child || l.machine;
|
|
179
|
+
if (l.session && !notPerson) sessions.add(l.session);
|
|
180
|
+
// NOT used as the per-day denominator any more — see `logDays`, which report() passes in from
|
|
181
|
+
// the files it actually read. Kept only because a day with lines is still a day the log covers.
|
|
182
|
+
if (l.t) days.add(l.t.slice(0, 10));
|
|
183
|
+
const worker = l.event === 'worker';
|
|
184
|
+
const name = l.hook || '(unnamed)';
|
|
185
|
+
|
|
186
|
+
// The mean-of-sessions form below rejects per-line counting — folding a headless `claude`
|
|
187
|
+
// run's own SessionStart in roughly doubled every count on a synthetic 12-session log (an
|
|
188
|
+
// injector that fired in 3 sessions reported 15 runs). Full argument:
|
|
189
|
+
// docs/decisions/2026-08-31-hook-stats-injected-context.md.
|
|
190
|
+
//
|
|
191
|
+
// A session where the hook RAN and injected nothing is a real zero and counts as one — mixing
|
|
192
|
+
// it with "did not run" would show an occasional injector as costing every session.
|
|
193
|
+
//
|
|
194
|
+
// An absent `bytes` means either "injected nothing" or "written before this field existed",
|
|
195
|
+
// indistinguishable, so a hook's older lines read as zeros until they age out of the window (a
|
|
196
|
+
// week). Counted separately below as `unsized` rather than silently folded into the average.
|
|
197
|
+
const cost = l.event === COST_EVENT.extract || l.event === COST_EVENT.judge;
|
|
198
|
+
if (!notPerson && l.session && !worker && !cost) {
|
|
199
|
+
const by = perSession.get(name) ?? new Map();
|
|
200
|
+
by.set(l.session, (by.get(l.session) ?? 0) + (typeof l.bytes === 'number' ? l.bytes : 0));
|
|
201
|
+
perSession.set(name, by);
|
|
202
|
+
if (typeof l.bytes === 'number') measured.add(name);
|
|
203
|
+
else unsized.set(name, (unsized.get(name) ?? 0) + 1);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// An `extract` line is a COST RECORD for one API call, not a hook invocation: it belongs to the
|
|
207
|
+
// cost section and nowhere else. Counted as an invocation it took distill-session's 15 s
|
|
208
|
+
// timeout with it and reported every 40-second API call as a near-breach of a limit it is not
|
|
209
|
+
// subject to — inside a worker that is already detached.
|
|
210
|
+
if (cost) {
|
|
211
|
+
(l.event === COST_EVENT.judge ? judges : extracts).push(l);
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
invocations++;
|
|
215
|
+
|
|
216
|
+
// Keyed by hook AND EVENT. distill-session runs on both Stop and SessionEnd, and they are not
|
|
217
|
+
// the same measurement: Stop fires at the end of every assistant turn and is gated hard, so
|
|
218
|
+
// hundreds of cheap decisions were burying the one SessionEnd run per session that reads the
|
|
219
|
+
// transcript and forks. Merged, the p95 and the near-timeout share for the only hook with a
|
|
220
|
+
// 15 s timeout described the path that cannot breach it.
|
|
221
|
+
const key = `${name} · ${l.event || '(no event)'}`;
|
|
222
|
+
const row =
|
|
223
|
+
hooks.get(key) ??
|
|
224
|
+
/** @type {HookRow} */ ({
|
|
225
|
+
hook: name,
|
|
226
|
+
n: 0,
|
|
227
|
+
latencies: [],
|
|
228
|
+
outcomes: new Map(),
|
|
229
|
+
reasons: new Map(),
|
|
230
|
+
worker,
|
|
231
|
+
});
|
|
232
|
+
row.n++;
|
|
233
|
+
if (typeof l.ms === 'number') row.latencies.push(l.ms);
|
|
234
|
+
else untimed++;
|
|
235
|
+
const o = l.outcome ?? '(none)';
|
|
236
|
+
row.outcomes.set(o, (row.outcomes.get(o) ?? 0) + 1);
|
|
237
|
+
if (l.reason) {
|
|
238
|
+
const by = row.reasons.get(o) ?? new Map();
|
|
239
|
+
by.set(l.reason, (by.get(l.reason) ?? 0) + 1);
|
|
240
|
+
row.reasons.set(o, by);
|
|
241
|
+
}
|
|
242
|
+
hooks.set(key, row);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
return {
|
|
246
|
+
invocations,
|
|
247
|
+
untimed,
|
|
248
|
+
childLines,
|
|
249
|
+
machineLines,
|
|
250
|
+
pruned,
|
|
251
|
+
first: lines.find((l) => l.t)?.t ?? null,
|
|
252
|
+
last: [...lines].reverse().find((l) => l.t)?.t ?? null,
|
|
253
|
+
hooks: [...hooks.entries()].sort((a, b) => b[1].n - a[1].n),
|
|
254
|
+
injected: [...perSession.entries()]
|
|
255
|
+
.filter(([name]) => measured.has(name))
|
|
256
|
+
.map((/** @type {[string, Map<string, number>]} */ [name, by]) => ({
|
|
257
|
+
name,
|
|
258
|
+
sessions: [...by.values()],
|
|
259
|
+
}))
|
|
260
|
+
.sort((a, b) => b.sessions.length - a.sessions.length),
|
|
261
|
+
// Lines for a measured hook that carried no `bytes`. Indistinguishable from "injected nothing",
|
|
262
|
+
// so they are counted as zeros and their number is printed beside the figures they drag down.
|
|
263
|
+
unsized: [...unsized.entries()]
|
|
264
|
+
.filter(([name]) => measured.has(name))
|
|
265
|
+
.reduce((a, [, n]) => a + n, 0),
|
|
266
|
+
extracts,
|
|
267
|
+
judges,
|
|
268
|
+
sessions: sessions.size,
|
|
269
|
+
days: logDays || days.size,
|
|
270
|
+
slug,
|
|
271
|
+
otherProjects: seen - lines.length,
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* The retention sentence, or nothing at all.
|
|
277
|
+
*
|
|
278
|
+
* The one thing in this report that DELETED the data the report reads. Without it the only
|
|
279
|
+
* evidence is the absence of files, which reads identically to a machine that never logged — and
|
|
280
|
+
* a project whose lines were the ones deleted lands in render()'s no-invocations arm, so this has
|
|
281
|
+
* to be reachable from both.
|
|
282
|
+
*
|
|
283
|
+
* @param {{ pruned: number }} s
|
|
284
|
+
* @returns {string[]}
|
|
285
|
+
*/
|
|
286
|
+
function prunedSection(s) {
|
|
287
|
+
if (!s.pruned) return [];
|
|
288
|
+
return [
|
|
289
|
+
'',
|
|
290
|
+
`retention deleted ${s.pruned} dated log file(s) while this window was being logged —`,
|
|
291
|
+
'machine-wide: one pass deletes for every project and both families.',
|
|
292
|
+
];
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* How many of a hook's invocations ran within NEAR_FRACTION of its timeout.
|
|
297
|
+
*
|
|
298
|
+
* `null` when there is no declared timeout to compare against — a worker line, or a hook the
|
|
299
|
+
* manifest does not name. A missing limit must not print as zero near-misses, which reads as
|
|
300
|
+
* "measured, and fine".
|
|
301
|
+
*
|
|
302
|
+
* @param {readonly number[]} latencies
|
|
303
|
+
* @param {number | undefined} timeoutSeconds
|
|
304
|
+
* @returns {number | null}
|
|
305
|
+
*/
|
|
306
|
+
export function nearTimeout(latencies, timeoutSeconds) {
|
|
307
|
+
// Both halves are "not measured", and both must print as "-". A row with a declared timeout and
|
|
308
|
+
// no timings at all — every line written by a version that dropped `ms` — would otherwise show
|
|
309
|
+
// p50/p95/max as "-" beside a confident 0, which reads as measured and fine.
|
|
310
|
+
if (!Number.isFinite(timeoutSeconds) || !latencies.length) return null;
|
|
311
|
+
const limit = /** @type {number} */ (timeoutSeconds) * 1000 * NEAR_FRACTION;
|
|
312
|
+
return latencies.filter((ms) => ms >= limit).length;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** @param {number | null} v @param {number} [digits] @returns {string} */
|
|
316
|
+
const num = (v, digits = 0) => (v === null ? '-' : v.toFixed(digits));
|
|
317
|
+
|
|
318
|
+
// Reasons are often raw exception messages, and an ENOENT carries an absolute path: the vault
|
|
319
|
+
// root, the NOTE FILENAME, and the OS username inside it. This report tells the reader it holds
|
|
320
|
+
// nothing identifying but the project slug and invites them to paste it into an issue, so the
|
|
321
|
+
// redaction has to happen before it is printed. The log file on disk keeps the full message — it is
|
|
322
|
+
// local, and it is what someone debugging their own machine actually needs.
|
|
323
|
+
//
|
|
324
|
+
// THREE passes, in this order, and the order is the whole design. A path with a SPACE in it is the
|
|
325
|
+
// common case here rather than an edge case — vaults live under `~/My Vault`, `~/Google Drive`,
|
|
326
|
+
// `Library/Mobile Documents/…` — and the bare rule alone turned `open '/Users/bob/My Vault/x.md'`
|
|
327
|
+
// into `<path> Vault<path>`, publishing the vault directory's name.
|
|
328
|
+
//
|
|
329
|
+
// 1. a QUOTED path, taken whole, spaces and all;
|
|
330
|
+
// 2. a quoted path with NO CLOSING QUOTE, which is what logHook's 200-char cap leaves behind on a
|
|
331
|
+
// long path — without this one, pass 3 gets it and the leak reopens;
|
|
332
|
+
// 3. the bare rule, on whatever is left.
|
|
333
|
+
//
|
|
334
|
+
// Each pass only sees what the ones before it did not take.
|
|
335
|
+
//
|
|
336
|
+
// Deliberately blunt: over-redacting a reason costs a word, under-redacting it publishes a private
|
|
337
|
+
// file path. Windows paths are not matched, and are not reachable — these messages come from Node's
|
|
338
|
+
// `fs` errors on paths these hooks pass in as absolute POSIX.
|
|
339
|
+
/** @param {string} text @returns {string} */
|
|
340
|
+
export function redact(text) {
|
|
341
|
+
return (
|
|
342
|
+
String(text)
|
|
343
|
+
.replace(/(['"`])(?:~|\.{0,2})?\/[^'"`]*\1/g, '$1<path>$1')
|
|
344
|
+
// An UNTERMINATED quoted path, which is what `logHook`'s 200-char cap leaves behind: the
|
|
345
|
+
// closing quote is gone, the pass above stops matching, and the bare rule below then publishes
|
|
346
|
+
// the spaced segments it was added to hide. A deep iCloud vault path passes 200 characters on
|
|
347
|
+
// its own.
|
|
348
|
+
.replace(/(['"`])(?:~|\.{0,2})?\/[^'"`]*$/g, '$1<path>')
|
|
349
|
+
.replace(/(?:~|\.{0,2})?\/[^\s'"`)\]]*/g, '<path>')
|
|
350
|
+
);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* The commonest reason behind one (hook, outcome) row, and how many others there were.
|
|
355
|
+
*
|
|
356
|
+
* @param {HookRow} row
|
|
357
|
+
* @param {string} outcome
|
|
358
|
+
* @returns {string}
|
|
359
|
+
*/
|
|
360
|
+
function reasonFor(row, outcome) {
|
|
361
|
+
const by = [...(row.reasons.get(outcome) ?? new Map()).entries()].sort((a, b) => b[1] - a[1]);
|
|
362
|
+
if (!by.length) return '-';
|
|
363
|
+
const [text] = by[0];
|
|
364
|
+
const others = by.slice(1).reduce((a, [, c]) => a + c, 0);
|
|
365
|
+
return others ? `${redact(text)} (+${others} other)` : redact(text);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* The hook section body.
|
|
370
|
+
*
|
|
371
|
+
* @param {ReturnType<typeof summarize>} s
|
|
372
|
+
* @param {Map<string, number>} limits
|
|
373
|
+
* @param {readonly RecallSize[]} [recall] injecting recall decisions, from the recall log family
|
|
374
|
+
* @returns {string}
|
|
375
|
+
*/
|
|
376
|
+
export function render(s, limits, recall = []) {
|
|
377
|
+
// No invocations does not mean no report: extract lines are cost records rather than invocations,
|
|
378
|
+
// so a window can hold real spend and no gate lines at all. Say so, then let the sections below
|
|
379
|
+
// print what they do have.
|
|
380
|
+
//
|
|
381
|
+
// The retention sentence is in BOTH arms, and this is the arm that needs it most: a window with
|
|
382
|
+
// no lines for this project is exactly what retention produces, and the early return used to
|
|
383
|
+
// answer "no hook has run for this project yet" while a pass had just deleted its history.
|
|
384
|
+
if (!s.invocations)
|
|
385
|
+
return [
|
|
386
|
+
s.otherProjects
|
|
387
|
+
? `not measured: none of the ${s.otherProjects} logged invocations in this window belong ` +
|
|
388
|
+
`to ${s.slug}. The log is machine-wide; no hook has run for this project yet.`
|
|
389
|
+
: 'not measured: no hook invocations logged in this window.',
|
|
390
|
+
...prunedSection(s),
|
|
391
|
+
...injectedSection(s, recall),
|
|
392
|
+
...costSection(s),
|
|
393
|
+
].join('\n');
|
|
394
|
+
|
|
395
|
+
const window = s.first && s.last ? ` (${s.first.slice(0, 10)} … ${s.last.slice(0, 10)})` : '';
|
|
396
|
+
const out = [
|
|
397
|
+
s.slug
|
|
398
|
+
? `${s.invocations} invocations for ${s.slug}${window}` +
|
|
399
|
+
(s.otherProjects
|
|
400
|
+
? ` — ${s.otherProjects} more in this window belong to other projects`
|
|
401
|
+
: '')
|
|
402
|
+
: `${s.invocations} invocations, every project on this machine${window}`,
|
|
403
|
+
'',
|
|
404
|
+
table(
|
|
405
|
+
['hook', 'n', 'p50 ms', 'p95 ms', 'max ms', 'timeout', `≥${NEAR_FRACTION * 100}% of it`],
|
|
406
|
+
s.hooks.map(([name, r]) => {
|
|
407
|
+
// The row's own event first — the manifest declares a limit per event — then the per-hook
|
|
408
|
+
// fallback for a line whose event is missing. A worker row is not the hook and has none.
|
|
409
|
+
const limit = r.worker ? undefined : (limits.get(name) ?? limits.get(r.hook));
|
|
410
|
+
const near = nearTimeout(r.latencies, limit);
|
|
411
|
+
return [
|
|
412
|
+
name,
|
|
413
|
+
r.n,
|
|
414
|
+
num(percentile(r.latencies, 50), 1),
|
|
415
|
+
num(percentile(r.latencies, 95), 1),
|
|
416
|
+
num(percentile(r.latencies, 100), 1),
|
|
417
|
+
limit === undefined ? '-' : `${limit}s`,
|
|
418
|
+
near === null ? '-' : near,
|
|
419
|
+
];
|
|
420
|
+
}),
|
|
421
|
+
),
|
|
422
|
+
'',
|
|
423
|
+
'ms is the WHOLE process, from node startup, because that is what the timeout applies to.',
|
|
424
|
+
'One row per hook AND EVENT: distill-session on Stop is a cheap decision fired every assistant',
|
|
425
|
+
'turn, and on SessionEnd it is the run that reads the transcript — merged, the cheap one buries',
|
|
426
|
+
'the one that can breach a timeout. A "· worker" row is the detached background run rather than',
|
|
427
|
+
'the hook, so it has no timeout and its duration is the distillation or the re-index itself.',
|
|
428
|
+
'',
|
|
429
|
+
'THE SAMPLE IS CENSORED AT THE TIMEOUT. A hook killed at its limit is killed by a signal and',
|
|
430
|
+
'writes no line, so a real breach is INVISIBLE here and the last column counts only how close',
|
|
431
|
+
'the survivors ran. Read a hook that stops appearing, or whose n falls, as the breach.',
|
|
432
|
+
'',
|
|
433
|
+
'outcomes',
|
|
434
|
+
// The REASON column, not just the count. Every call site records one and nothing printed it,
|
|
435
|
+
// so the first question an `error` row raises — "error saying what?" — could only be answered
|
|
436
|
+
// by hand-reading the JSONL. The commonest reason per row is shown; `+N other` says when the
|
|
437
|
+
// row is not of one mind.
|
|
438
|
+
table(
|
|
439
|
+
['hook', 'outcome', 'n', 'commonest reason'],
|
|
440
|
+
s.hooks.flatMap(([name, r]) =>
|
|
441
|
+
[...r.outcomes.entries()]
|
|
442
|
+
.sort((a, b) => b[1] - a[1])
|
|
443
|
+
.map(([o, n]) => [name, o, n, reasonFor(r, o)]),
|
|
444
|
+
),
|
|
445
|
+
),
|
|
446
|
+
'',
|
|
447
|
+
'ran = did its work · spawned = handed it to a detached child · child-guard = it fired inside',
|
|
448
|
+
"a headless claude run a hook started, or in Claude Code's own Stop loop · debounced = it",
|
|
449
|
+
'stood down: its own timer, a line count below the threshold, or a lock somebody else holds ·',
|
|
450
|
+
'noop-missing-dep = what it needs is absent, so it',
|
|
451
|
+
'can do nothing at all — sometimes permanently and correctly, when that thing is an OPTIONAL',
|
|
452
|
+
'integration this install never set up · error = it threw, or the work it started never ran.',
|
|
453
|
+
'',
|
|
454
|
+
'A HIGH SKIP RATE IS NOT A FAULT BY ITSELF — read it against what the hook is for.',
|
|
455
|
+
'`distill-session · Stop` is a crash fallback and stands down on nearly every assistant turn, so',
|
|
456
|
+
'100% debounced there is the healthy state. It IS a finding where work was expected: a',
|
|
457
|
+
'`· SessionEnd` row that never spawns, or a `graph-staleness-check` debounced by a lock nothing',
|
|
458
|
+
'releases. Either way the hook says nothing and exits 0, which is why the column exists.',
|
|
459
|
+
];
|
|
460
|
+
|
|
461
|
+
if (s.untimed)
|
|
462
|
+
out.push('', `${s.untimed} of ${s.invocations} invocations carry no ms — not counted above.`);
|
|
463
|
+
|
|
464
|
+
// A headless `claude` run fires SessionStart itself, so a single distillation adds four hook
|
|
465
|
+
// invocations that no user ever saw. Counted, not hidden: they are real runs, they are just not
|
|
466
|
+
// sessions, and "nine invocations per session" is the denominator someone will divide by.
|
|
467
|
+
if (s.childLines)
|
|
468
|
+
out.push(
|
|
469
|
+
'',
|
|
470
|
+
`${s.childLines} of ${s.invocations} were fired by a background \`claude\` run, not by a`,
|
|
471
|
+
'session — one distillation or graph regen fires SessionStart again on its way through.',
|
|
472
|
+
);
|
|
473
|
+
if (s.machineLines)
|
|
474
|
+
out.push(
|
|
475
|
+
'',
|
|
476
|
+
`${s.machineLines} of ${s.invocations} were fired by a machine-driven run (MEMORY_MACHINE_RUN),`,
|
|
477
|
+
'not by a person — left out of every per-session figure.',
|
|
478
|
+
);
|
|
479
|
+
|
|
480
|
+
out.push(...prunedSection(s));
|
|
481
|
+
|
|
482
|
+
out.push('', `not in this table: ${UNLOGGED}, and ${NO_WORKER_LINE}.`);
|
|
483
|
+
out.push(...injectedSection(s, recall));
|
|
484
|
+
out.push(...costSection(s));
|
|
485
|
+
return out.join('\n');
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/**
|
|
489
|
+
* What the hooks put INTO the context window, before the user has typed anything.
|
|
490
|
+
*
|
|
491
|
+
* Estimated, and said so on every line: bytes / BYTES_PER_TOKEN, no tokeniser. Recall is folded in
|
|
492
|
+
* from its OWN log family, which already records injected characters — it gains no `bytes` field,
|
|
493
|
+
* because two sources for one number is how they come to disagree.
|
|
494
|
+
*
|
|
495
|
+
* Recall's records carry no session id (they never have), so its column is a per-session AVERAGE
|
|
496
|
+
* over the sessions the hook log saw, not a per-session breakdown. Named as an average rather than
|
|
497
|
+
* quietly presented as one.
|
|
498
|
+
*
|
|
499
|
+
* @param {ReturnType<typeof summarize>} s
|
|
500
|
+
* @param {readonly RecallSize[]} recall
|
|
501
|
+
* @returns {string[]}
|
|
502
|
+
*/
|
|
503
|
+
function injectedSection(s, recall) {
|
|
504
|
+
const rows = s.injected.map(({ name, sessions }) => {
|
|
505
|
+
const toks = sessions.map((b) => /** @type {number} */ (estTokens(b)));
|
|
506
|
+
return {
|
|
507
|
+
name,
|
|
508
|
+
sessions: toks.length,
|
|
509
|
+
injecting: toks.filter((t) => t > 0).length,
|
|
510
|
+
p50: percentile(toks, 50),
|
|
511
|
+
p95: percentile(toks, 95),
|
|
512
|
+
toks,
|
|
513
|
+
};
|
|
514
|
+
});
|
|
515
|
+
|
|
516
|
+
const recallChars = recall
|
|
517
|
+
.filter((r) => !r.abstained && typeof r.chars === 'number')
|
|
518
|
+
.map((r) => /** @type {number} */ (r.chars));
|
|
519
|
+
const recallToks = recallChars.map((c) => /** @type {number} */ (estTokens(c)));
|
|
520
|
+
|
|
521
|
+
if (!rows.length && !recallToks.length)
|
|
522
|
+
return [
|
|
523
|
+
'',
|
|
524
|
+
'injected context: not measured — no hook in this window recorded what it injected.',
|
|
525
|
+
];
|
|
526
|
+
|
|
527
|
+
const mean = (/** @type {readonly number[]} */ v) =>
|
|
528
|
+
v.length ? Math.round(v.reduce((a, b) => a + b, 0) / v.length) : null;
|
|
529
|
+
|
|
530
|
+
/** @type {string[]} */
|
|
531
|
+
const body = [''];
|
|
532
|
+
// Only when there is something to put in it. A bare header over an empty table, followed by
|
|
533
|
+
// "~0 tokens across 0 injector(s)", reads as a measured zero — in a report whose whole thesis is
|
|
534
|
+
// that a measured zero and an unmeasured one must never look alike.
|
|
535
|
+
if (rows.length)
|
|
536
|
+
body.push(
|
|
537
|
+
'injected context (ESTIMATED tokens, bytes / ' + BYTES_PER_TOKEN + ' — no tokeniser)',
|
|
538
|
+
// Both numbers, always. "injected in 2 of 40 sessions, mean 380" and "40 of 40, mean 380"
|
|
539
|
+
// are different findings, and a mean with no denominator cannot tell them apart — which is
|
|
540
|
+
// how the per-session total below came to assert a cost most sessions never paid.
|
|
541
|
+
table(
|
|
542
|
+
['hook', 'sessions', 'injected in', 'mean tok', 'p50 tok', 'p95 tok'],
|
|
543
|
+
rows.map((r) => [
|
|
544
|
+
r.name,
|
|
545
|
+
r.sessions,
|
|
546
|
+
r.injecting,
|
|
547
|
+
num(mean(r.toks)),
|
|
548
|
+
num(r.p50),
|
|
549
|
+
num(r.p95),
|
|
550
|
+
]),
|
|
551
|
+
),
|
|
552
|
+
'Averaged over every session the hook RAN in, including the ones where it injected nothing —',
|
|
553
|
+
'so this is what a session actually pays, not what it pays on the sessions where it fires.',
|
|
554
|
+
);
|
|
555
|
+
else body.push('SessionStart injectors: not measured in this window.');
|
|
556
|
+
|
|
557
|
+
if (s.unsized)
|
|
558
|
+
body.push(
|
|
559
|
+
'',
|
|
560
|
+
`${s.unsized} line(s) above carry no size and are counted as injecting nothing. One encoding`,
|
|
561
|
+
'covers two meanings — a hook that really injected nothing, and a line written before this',
|
|
562
|
+
'field existed — and nothing can tell them apart. The first is correct data; to whatever',
|
|
563
|
+
'extent the second is in there, these figures are an under-statement.',
|
|
564
|
+
);
|
|
565
|
+
|
|
566
|
+
if (recallToks.length) {
|
|
567
|
+
const total = recallToks.reduce((a, b) => a + b, 0);
|
|
568
|
+
body.push(
|
|
569
|
+
'',
|
|
570
|
+
`recall injected ~${total} tok across ${recallToks.length} prompt(s) in this window` +
|
|
571
|
+
(s.sessions
|
|
572
|
+
? `, ~${Math.round(total / s.sessions)} per session averaged over the ${s.sessions} ` +
|
|
573
|
+
'session(s) the hook log saw'
|
|
574
|
+
: ''),
|
|
575
|
+
'Recall is read from its own recall-*.jsonl records, which carry no session id — so that is',
|
|
576
|
+
'an average over sessions, not a per-session figure.',
|
|
577
|
+
);
|
|
578
|
+
} else {
|
|
579
|
+
body.push('', 'recall: not measured — no injecting recall decisions in this window.');
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
// Summed across hooks as a mean over each hook's own sessions, not compared per session — the
|
|
583
|
+
// naive per-session form billed an occasional injector to every session (synthetic-log example
|
|
584
|
+
// and the fix: docs/decisions/2026-08-31-hook-stats-injected-context.md).
|
|
585
|
+
//
|
|
586
|
+
// Recall is excluded: it is per prompt, not per session, and adding it would double-count a long
|
|
587
|
+
// session.
|
|
588
|
+
//
|
|
589
|
+
// ponytail: each term is a mean over the sessions ITS OWN hook ran in, so if two injectors ran in
|
|
590
|
+
// different subsets this is a sum over populations that do not coincide. Both fire at every
|
|
591
|
+
// SessionStart today, so they do; the label says "on AVERAGE" rather than claiming more.
|
|
592
|
+
const perSession = rows.reduce((a, r) => a + (mean(r.toks) ?? 0), 0);
|
|
593
|
+
// Inside the same guard as the table. Round 2 added that guard against exactly this sentence and
|
|
594
|
+
// then left it printing from the other branch: with only recall measured the report said
|
|
595
|
+
// "not measured" and, four lines later, "~0 tokens per session across 0 injector(s)".
|
|
596
|
+
if (rows.length)
|
|
597
|
+
body.push(
|
|
598
|
+
'',
|
|
599
|
+
`~${perSession} estimated tokens of SessionStart context per session on AVERAGE, across ` +
|
|
600
|
+
`${rows.length} injector(s).`,
|
|
601
|
+
);
|
|
602
|
+
if (rows.length && perSession > INJECTED_TOKEN_BUDGET)
|
|
603
|
+
body.push(
|
|
604
|
+
`WARNING: that is over the ${INJECTED_TOKEN_BUDGET}-token line this report draws. Read the`,
|
|
605
|
+
'p50 column before acting on it: one hook that injects a great deal rarely moves this mean a',
|
|
606
|
+
'long way while most sessions pay far less. Capping a list is a separate change — this only',
|
|
607
|
+
'says the number.',
|
|
608
|
+
);
|
|
609
|
+
// Measured once, by hand, because logging it needs a second appender written in shell and that
|
|
610
|
+
// hook is under a do-not-port fence: its heredoc is 1079 bytes of template before variable
|
|
611
|
+
// expansion — the body INCLUDING the newline that ends its last line, which is what the hook
|
|
612
|
+
// actually prints. Near-fixed, which is why measuring once is enough — but it is a 2026-11-01
|
|
613
|
+
// measurement of a template and it moves when the template is edited.
|
|
614
|
+
body.push(
|
|
615
|
+
'',
|
|
616
|
+
`Not counted: ${UNLOGGED} injects a near-fixed memory block — measured by hand at 1079 B,`,
|
|
617
|
+
`about ${estTokens(1079)} more estimated tokens per session.`,
|
|
618
|
+
);
|
|
619
|
+
return body;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/**
|
|
623
|
+
* What the distiller's headless run really cost — MEASURED, not estimated, and labelled so.
|
|
624
|
+
*
|
|
625
|
+
* The figures come from the CLI's own JSON envelope. They are dominated by cache traffic rather
|
|
626
|
+
* than by the transcript: a throwaway prompt measured 9 input tokens against 18,078 cache-creation
|
|
627
|
+
* and 22,363 cache-read, at $0.0389 (2026-08-20). That is why nothing here is derived from length.
|
|
628
|
+
*
|
|
629
|
+
* The reversal judge (#156) is a second paid call in a run with merge pairs, so it is a second
|
|
630
|
+
* table: its per-call row divides by the runs that called it, never by every distillation.
|
|
631
|
+
*
|
|
632
|
+
* @param {ReturnType<typeof summarize>} s
|
|
633
|
+
* @returns {string[]}
|
|
634
|
+
*/
|
|
635
|
+
function costSection(s) {
|
|
636
|
+
return [
|
|
637
|
+
...(s.extracts.length
|
|
638
|
+
? costTable(s.extracts, s.days, 'extract')
|
|
639
|
+
: [
|
|
640
|
+
'',
|
|
641
|
+
'distiller cost: not measured — no extract line in this window. A distillation that was',
|
|
642
|
+
'debounced, found no CLI, or failed before the call writes no cost at all, by design.',
|
|
643
|
+
]),
|
|
644
|
+
...(s.judges.length
|
|
645
|
+
? costTable(s.judges, s.days, 'judge')
|
|
646
|
+
: [
|
|
647
|
+
'',
|
|
648
|
+
'reversal judge cost: not measured — no judge line in this window. A run without merge',
|
|
649
|
+
'pairs makes no judge call.',
|
|
650
|
+
]),
|
|
651
|
+
];
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
/**
|
|
655
|
+
* @param {HookLine[]} lines
|
|
656
|
+
* @param {number} days
|
|
657
|
+
* @param {keyof typeof COST_EVENT} kind
|
|
658
|
+
* @returns {string[]}
|
|
659
|
+
*/
|
|
660
|
+
function costTable(lines, days, kind) {
|
|
661
|
+
const judge = kind === 'judge';
|
|
662
|
+
|
|
663
|
+
// PER FIELD, counting only the lines that carry it. parseEnvelope writes the finite figures it
|
|
664
|
+
// found and omits the rest — the API drops `cache_creation_input_tokens` when nothing was cached
|
|
665
|
+
// — so treating an absent key as 0 while still counting the run halved the per-run figure for the
|
|
666
|
+
// one run that WAS measured, under a heading that says MEASURED. Same rule the rest of this
|
|
667
|
+
// reader follows: absent is not zero.
|
|
668
|
+
/** @param {keyof HookLine} k @returns {{ total: number, n: number }} */
|
|
669
|
+
const col = (k) => {
|
|
670
|
+
/** @type {number[]} */
|
|
671
|
+
const v = [];
|
|
672
|
+
for (const l of lines) {
|
|
673
|
+
const x = l[k];
|
|
674
|
+
if (typeof x === 'number' && Number.isFinite(x)) v.push(x);
|
|
675
|
+
}
|
|
676
|
+
return { total: v.reduce((a, b) => a + b, 0), n: v.length };
|
|
677
|
+
};
|
|
678
|
+
const cols = /** @type {const} */ (['inTok', 'cacheWriteTok', 'cacheReadTok', 'outTok']).map(col);
|
|
679
|
+
const usd = col('usd');
|
|
680
|
+
/** @param {{ total: number, n: number }} c @param {number} [digits] */
|
|
681
|
+
const per = (c, digits = 0) => (c.n ? (c.total / c.n).toFixed(digits) : '-');
|
|
682
|
+
const runs = lines.length;
|
|
683
|
+
const partial = [...cols, usd].filter((c) => c.n && c.n < runs).length;
|
|
684
|
+
const absent = [...cols, usd].filter((c) => !c.n).length;
|
|
685
|
+
|
|
686
|
+
// A run that was billed and then failed is IN these totals, and must be: the money was spent.
|
|
687
|
+
// But it wrote no notes, so folding it silently into "per run" prices a distillation using runs
|
|
688
|
+
// that did not distil — the exact fold the extract line's `outcome` was added to prevent, one
|
|
689
|
+
// level down. The log tells them apart; so must the report.
|
|
690
|
+
const errored = lines.filter((l) => l.outcome === 'error').length;
|
|
691
|
+
|
|
692
|
+
return [
|
|
693
|
+
'',
|
|
694
|
+
(judge
|
|
695
|
+
? `reversal judge cost (MEASURED, from the CLI's own usage figures) — ${runs} call(s)`
|
|
696
|
+
: `distiller cost (MEASURED, from the CLI's own usage figures) — ${runs} run(s)`) +
|
|
697
|
+
(errored ? `, ${errored} of which failed after being billed` : ''),
|
|
698
|
+
table(
|
|
699
|
+
['', 'in', 'cache write', 'cache read', 'out', 'USD'],
|
|
700
|
+
[
|
|
701
|
+
['total', ...cols.map((c) => (c.n ? c.total : '-')), usd.n ? usd.total.toFixed(4) : '-'],
|
|
702
|
+
[
|
|
703
|
+
judge
|
|
704
|
+
? `per call (÷${runs} run(s) with a judge call)`
|
|
705
|
+
: `per run (÷${runs} extract run(s))`,
|
|
706
|
+
...cols.map((c) => per(c)),
|
|
707
|
+
per(usd, 4),
|
|
708
|
+
],
|
|
709
|
+
// Divided by the number of DAILY LOG FILES the window read, which is the number of days
|
|
710
|
+
// anything was logged at all — not the days the distiller happened to run, and not a
|
|
711
|
+
// calendar span. A fortnight's spend over the one day it ran is not a daily rate, and the
|
|
712
|
+
// denominator is printed so nobody has to guess which one was used.
|
|
713
|
+
days
|
|
714
|
+
? [
|
|
715
|
+
`per day (÷${days} log day(s))`,
|
|
716
|
+
...cols.map((c) => (c.n ? Math.round(c.total / days) : '-')),
|
|
717
|
+
usd.n ? (usd.total / days).toFixed(4) : '-',
|
|
718
|
+
]
|
|
719
|
+
: ['per day', '-', '-', '-', '-', '-'],
|
|
720
|
+
],
|
|
721
|
+
),
|
|
722
|
+
...(partial
|
|
723
|
+
? [
|
|
724
|
+
`${partial} column(s) are missing from SOME runs and are averaged over only the runs that`,
|
|
725
|
+
'carried them — an absent figure is never counted as a zero.',
|
|
726
|
+
]
|
|
727
|
+
: []),
|
|
728
|
+
...(absent
|
|
729
|
+
? [`${absent} column(s) print "-": no run in this window reported that figure at all.`]
|
|
730
|
+
: []),
|
|
731
|
+
...(errored && judge
|
|
732
|
+
? ['The failed calls are included: they cost money, and their merge pairs were not judged.']
|
|
733
|
+
: []),
|
|
734
|
+
...(errored && !judge
|
|
735
|
+
? [
|
|
736
|
+
'The failed runs are included: they cost money. They wrote no notes, so "per run" is not',
|
|
737
|
+
'the price of a distillation while any are in the window.',
|
|
738
|
+
]
|
|
739
|
+
: []),
|
|
740
|
+
...(judge
|
|
741
|
+
? []
|
|
742
|
+
: [
|
|
743
|
+
'Cache traffic dominates, and it is a near-fixed cost of the headless session rather than a',
|
|
744
|
+
'function of transcript length — a longer session is not a proportionally dearer distillation.',
|
|
745
|
+
]),
|
|
746
|
+
];
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
/**
|
|
750
|
+
* The whole `--hooks` report, as one string.
|
|
751
|
+
*
|
|
752
|
+
* @param {{
|
|
753
|
+
* logDir: string,
|
|
754
|
+
* manifest: string,
|
|
755
|
+
* days?: number,
|
|
756
|
+
* slug?: string | null,
|
|
757
|
+
* }} options
|
|
758
|
+
* @returns {string}
|
|
759
|
+
*/
|
|
760
|
+
export function report({ logDir, manifest, days = DEFAULT_DAYS, slug = null }) {
|
|
761
|
+
const files = logFiles(logDir, days, 'hooks');
|
|
762
|
+
// Recall's own family, for the injected-context section only. It records injected CHARACTERS and
|
|
763
|
+
// is not given a `bytes` field, because one number with two sources is one number that will
|
|
764
|
+
// disagree with itself. Scoped by the same slug for the same reason every other figure here is.
|
|
765
|
+
const recallLines = /** @type {RecallSize[]} */ (readLines(logFiles(logDir, days, 'recall')));
|
|
766
|
+
const recall = recallLines.filter((r) => !slug || r.slug === slug);
|
|
767
|
+
// `pruned` is unscoped by project like the sum inside summarize() and for the same reason
|
|
768
|
+
// (CLAUDE.md's retention section) — it rides on whichever line the day's first append happened
|
|
769
|
+
// to be, which can be a RECALL line for a session that crosses UTC midnight with recall armed.
|
|
770
|
+
//
|
|
771
|
+
// Bounded by the HOOKS window's oldest day: `logFiles()` slices by file COUNT and the recall
|
|
772
|
+
// family is sparser (it logs only when armed), so its seven newest files can reach back months
|
|
773
|
+
// further than the seven newest hook files — unbounded, a pass from January was once reported as
|
|
774
|
+
// "while this window was being logged" over last week's dates. `files[0]` is that oldest file
|
|
775
|
+
// (`logFiles()` sorts and slices off the end); `null` when there are no hook files at all, so
|
|
776
|
+
// nothing to bound against — an empty string there would let every recall line back in.
|
|
777
|
+
const from = files.length
|
|
778
|
+
? /** @type {RegExpExecArray} */ (DATE_IN_NAME.exec(path.basename(files[0])))[1]
|
|
779
|
+
: null;
|
|
780
|
+
// readLines() is shared with the recall reader and is typed for ITS record. The cast below is the
|
|
781
|
+
// only thing telling tsc these are hook lines — without it every field type-checks against a
|
|
782
|
+
// shape with no `hook`, `outcome` or `event` in it, and a rename in logHook() would pass.
|
|
783
|
+
const summary = summarize(
|
|
784
|
+
/** @type {HookLine[]} */ (/** @type {unknown} */ (readLines(files))),
|
|
785
|
+
slug,
|
|
786
|
+
files.length,
|
|
787
|
+
recallLines
|
|
788
|
+
.filter((r) => from !== null && (r.t ?? '') >= from)
|
|
789
|
+
.reduce((a, r) => a + (typeof r.pruned === 'number' ? r.pruned : 0), 0),
|
|
790
|
+
);
|
|
791
|
+
const head = files.length
|
|
792
|
+
? `${files.length} log file(s), most recent first: ${files
|
|
793
|
+
.slice(-3)
|
|
794
|
+
.reverse()
|
|
795
|
+
.map((f) => path.basename(f))
|
|
796
|
+
.join(', ')}`
|
|
797
|
+
: `no hook logs in ${logDir} — nothing has been logged there in this window. That is a` +
|
|
798
|
+
' session that has not run yet, a cleared logs/, a window too narrow, or a directory the' +
|
|
799
|
+
' hooks cannot write (they swallow exactly that).';
|
|
800
|
+
return `\nhook analytics\n${`${head}\n\n${render(summary, timeouts(manifest), recall)}`.replace(/^(?=.)/gm, ' ')}\n`;
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
/**
|
|
804
|
+
* What each `Memory/<slug>/MEMORY.md` costs to load: ESTIMATED tokens per session start, and how
|
|
805
|
+
* often that slug starts. Same `status\tmessage\tfix` lines and the same naming rule as
|
|
806
|
+
* capReport() — only this project is named. #109: the cap answers "will it be truncated?", this
|
|
807
|
+
* answers "what does loading it cost?", and a file can pass the first while failing the second.
|
|
808
|
+
* Rationale and the 2,000 figure: docs/decisions/2026-10-10-moc-cost-budget.md.
|
|
809
|
+
*
|
|
810
|
+
* @param {{ vaultDir: string, slug: string, logDir: string }} options
|
|
811
|
+
* @returns {string[]}
|
|
812
|
+
*/
|
|
813
|
+
export function costReport({ vaultDir, slug, logDir }) {
|
|
814
|
+
const all = mocs(vaultDir).filter((m) => !m.empty);
|
|
815
|
+
if (!all.length) return [];
|
|
816
|
+
const files = logFiles(logDir, Infinity, 'hooks');
|
|
817
|
+
/** @type {Map<string, Set<string>>} */
|
|
818
|
+
const starts = new Map();
|
|
819
|
+
for (const l of /** @type {HookLine[]} */ (/** @type {unknown} */ (readLines(files)))) {
|
|
820
|
+
if (l.event !== 'SessionStart' || !l.session || !l.slug || l.child || l.machine) continue;
|
|
821
|
+
if (!starts.has(l.slug)) starts.set(l.slug, new Set());
|
|
822
|
+
/** @type {Set<string>} */ (starts.get(l.slug)).add(l.session);
|
|
823
|
+
}
|
|
824
|
+
const rows = all.map((m) => {
|
|
825
|
+
const tok = /** @type {number} */ (estTokens(m.bytes));
|
|
826
|
+
const n = starts.get(m.slug)?.size ?? 0;
|
|
827
|
+
return { slug: m.slug, tok, n, perDay: n && files.length ? n / files.length : null };
|
|
828
|
+
});
|
|
829
|
+
// No log files is unmeasured; log files with no start for this slug are a counted zero.
|
|
830
|
+
const none = files.length ? 'no start logged' : 'unmeasured';
|
|
831
|
+
const rate = (/** @type {number} */ v) => (v < 0.05 ? '<0.1/day' : `${Number(v.toFixed(1))}/day`);
|
|
832
|
+
const k = (/** @type {number} */ v) => Math.round(v).toLocaleString('en-US');
|
|
833
|
+
const budget = `soft budget ${k(INJECTED_TOKEN_BUDGET)}`;
|
|
834
|
+
const fix =
|
|
835
|
+
'loaded in full at every session start. Move detail from the MOC into the notes; nothing trims it automatically.';
|
|
836
|
+
|
|
837
|
+
/** @type {string[]} */
|
|
838
|
+
const out = [];
|
|
839
|
+
const mine = rows.find((r) => r.slug === slug);
|
|
840
|
+
if (mine) {
|
|
841
|
+
const freq =
|
|
842
|
+
mine.perDay === null
|
|
843
|
+
? files.length
|
|
844
|
+
? `no start logged in ${files.length} logged day(s)`
|
|
845
|
+
: 'start frequency unmeasured — no hook logs'
|
|
846
|
+
: `${mine.n} start${mine.n === 1 ? '' : 's'} in ${files.length} logged day(s) (${rate(mine.perDay)}), ~${k(mine.tok * mine.perDay)} tok/day`;
|
|
847
|
+
const msg = `this project's MEMORY.md: ~${k(mine.tok)} tok per session start (ESTIMATED, bytes / ${BYTES_PER_TOKEN}) — ${freq}; ${budget}`;
|
|
848
|
+
out.push(mine.tok > INJECTED_TOKEN_BUDGET ? `warn\t${msg}\t${fix}` : `ok\t${msg}`);
|
|
849
|
+
}
|
|
850
|
+
const others = rows.filter((r) => r !== mine).sort((a, b) => b.tok - a.tok);
|
|
851
|
+
if (others.length) {
|
|
852
|
+
const figs = others
|
|
853
|
+
.map((r) => `~${k(r.tok)} tok × ${r.perDay === null ? none : rate(r.perDay)}`)
|
|
854
|
+
.join(', ');
|
|
855
|
+
const over = others.filter((r) => r.tok > INJECTED_TOKEN_BUDGET).length;
|
|
856
|
+
out.push(
|
|
857
|
+
over
|
|
858
|
+
? `warn\t${over} of ${others.length} other MEMORY.md over the soft budget — ${figs}\t` +
|
|
859
|
+
'other projects are not named — this report gets pasted into issues. Run /memory:doctor from each one.'
|
|
860
|
+
: `ok\t${others.length} other MEMORY.md under the soft budget — ${figs}`,
|
|
861
|
+
);
|
|
862
|
+
}
|
|
863
|
+
return out;
|
|
864
|
+
}
|