@caveman-ai/cli 1.3.4 → 2.0.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.
@@ -0,0 +1,447 @@
1
+ // Learn autopilot: a native SessionEnd hook starts a detached, low-priority
2
+ // `caveman learn autopilot run`, which refreshes the learn report at most once
3
+ // per throttle window. A later SessionStart surfaces ONE user-visible line when
4
+ // that refresh found a new, big token sink. Shared by the full CLI and
5
+ // native-hook-fast, so it imports nothing from index.ts.
6
+ //
7
+ // Every state file lives under $CAVEMAN_HOME/runtime. Writes go through a
8
+ // temp file created O_EXCL + rename (rename replaces a planted symlink instead
9
+ // of following it) and refuse a symlinked parent; reads refuse symlinks. All
10
+ // hook-side entry points are fail-silent.
11
+ import { spawn, spawnSync } from "node:child_process";
12
+ import { closeSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeSync } from "node:fs";
13
+ import { homedir, setPriority } from "node:os";
14
+ import { dirname, join } from "node:path";
15
+ import { fileURLToPath } from "node:url";
16
+ const ANNOUNCE_CLASSES = new Set(["reducible", "recurring_context"]);
17
+ const ANNOUNCE_MIN_TOKENS_PER_TURN = 2000;
18
+ // Doctor findings that break what the agent loads qualify with no token rate.
19
+ const ANNOUNCE_DOCTOR_PREFIXES = ["memory_health:broken_imports:", "memory_health:memory_truncation:"];
20
+ const SEEN_CAP = 500;
21
+ // A claimed nudge whose output never reached the host (killed hook, delegate
22
+ // timeout) is shown once more after this long. One re-show, never more.
23
+ const NUDGE_RESHOW_MS = 10 * 60_000;
24
+ function caveHome() {
25
+ return process.env.CAVEMAN_HOME ?? join(homedir(), ".caveman");
26
+ }
27
+ function runtimeDir() {
28
+ return join(caveHome(), "runtime");
29
+ }
30
+ export function autopilotPaths() {
31
+ const dir = runtimeDir();
32
+ return {
33
+ state: join(dir, "learn-autopilot.json"),
34
+ lock: join(dir, "learn-autopilot.lock"),
35
+ nudge: join(dir, "learn-autopilot-nudge.json"),
36
+ inflight: join(dir, "learn-autopilot-nudge.inflight.json"),
37
+ announced: join(dir, "learn-autopilot-announced.json"),
38
+ // Autopilot's own reports home: its scans run with whatever cwd and env the
39
+ // last SessionEnd hook had, so they never overwrite the canonical report,
40
+ // dated snapshots or trend history a user's own run writes.
41
+ reports: join(dir, "learn-autopilot"),
42
+ };
43
+ }
44
+ export function autopilotThrottleMs() {
45
+ const hours = Number(process.env.CAVEMAN_LEARN_AUTOPILOT_HOURS ?? "6");
46
+ return (Number.isFinite(hours) && hours > 0 ? hours : 6) * 3_600_000;
47
+ }
48
+ export function autopilotTimeoutSeconds() {
49
+ const value = Number(process.env.CAVE_LEARN_TIMEOUT ?? "120");
50
+ return Number.isFinite(value) && value > 0 ? Math.floor(value) : 120;
51
+ }
52
+ function staleLockMs() {
53
+ return (autopilotTimeoutSeconds() + 60) * 1000;
54
+ }
55
+ // Precedence: env (explicit either way) → config.json `learnAutopilot` →
56
+ // CI/test runners (off unless forced by env) → on.
57
+ export function autopilotEnabled() {
58
+ const env = process.env.CAVEMAN_LEARN_AUTOPILOT?.trim().toLowerCase();
59
+ if (env)
60
+ return { enabled: !["0", "false", "off", "no"].includes(env), source: "env" };
61
+ try {
62
+ const config = JSON.parse(readFileSync(join(homedir(), ".caveman-cloud", "config.json"), "utf8"));
63
+ if (typeof config.learnAutopilot === "boolean")
64
+ return { enabled: config.learnAutopilot, source: "config" };
65
+ }
66
+ catch { /* default below */ }
67
+ const ci = process.env.CI;
68
+ if ((ci && ci !== "0" && ci.toLowerCase() !== "false") || process.env.NODE_TEST_CONTEXT)
69
+ return { enabled: false, source: "ci" };
70
+ return { enabled: true, source: "default" };
71
+ }
72
+ function readJson(path) {
73
+ try {
74
+ if (!lstatSync(path).isFile())
75
+ return undefined;
76
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
77
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : undefined;
78
+ }
79
+ catch {
80
+ return undefined;
81
+ }
82
+ }
83
+ function writeJson(path, value) {
84
+ const dir = dirname(path);
85
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
86
+ if (lstatSync(dir).isSymbolicLink())
87
+ throw new Error("refusing symlinked state directory");
88
+ const temp = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
89
+ const fd = openSync(temp, "wx", 0o600);
90
+ try {
91
+ writeSync(fd, `${JSON.stringify(value)}\n`);
92
+ }
93
+ finally {
94
+ closeSync(fd);
95
+ }
96
+ try {
97
+ renameSync(temp, path);
98
+ }
99
+ catch (error) {
100
+ try {
101
+ unlinkSync(temp);
102
+ }
103
+ catch { /* already gone */ }
104
+ throw error;
105
+ }
106
+ }
107
+ export function readAutopilotState() {
108
+ return readJson(autopilotPaths().state) ?? {};
109
+ }
110
+ function pidAlive(pid) {
111
+ if (!Number.isInteger(pid) || pid <= 0)
112
+ return false;
113
+ try {
114
+ process.kill(pid, 0);
115
+ return true;
116
+ }
117
+ catch (error) {
118
+ return error.code === "EPERM";
119
+ }
120
+ }
121
+ function lockHeld() {
122
+ const { lock } = autopilotPaths();
123
+ try {
124
+ const stat = lstatSync(lock);
125
+ if (Date.now() - stat.mtimeMs > staleLockMs())
126
+ return false;
127
+ const pid = Number(readFileSync(lock, "utf8").split("\n")[0]);
128
+ return pidAlive(pid);
129
+ }
130
+ catch {
131
+ return false;
132
+ }
133
+ }
134
+ // ponytail: stale-lock takeover is unlink-then-O_EXCL; two takers racing on
135
+ // the same stale lock can both proceed once. Harmless (one extra scan).
136
+ function acquireLock() {
137
+ const { lock } = autopilotPaths();
138
+ mkdirSync(dirname(lock), { recursive: true, mode: 0o700 });
139
+ for (let attempt = 0; attempt < 2; attempt++) {
140
+ try {
141
+ const fd = openSync(lock, "wx", 0o600);
142
+ writeSync(fd, `${process.pid}\n${new Date().toISOString()}\n`);
143
+ closeSync(fd);
144
+ return true;
145
+ }
146
+ catch (error) {
147
+ if (error.code !== "EEXIST" || lockHeld())
148
+ return false;
149
+ try {
150
+ unlinkSync(lock);
151
+ }
152
+ catch {
153
+ return false;
154
+ }
155
+ }
156
+ }
157
+ return false;
158
+ }
159
+ function releaseLock() {
160
+ try {
161
+ unlinkSync(autopilotPaths().lock);
162
+ }
163
+ catch { /* already gone */ }
164
+ }
165
+ function due(state, now = Date.now()) {
166
+ const last = Date.parse(state.last_attempt_at ?? "");
167
+ return !Number.isFinite(last) || now - last >= autopilotThrottleMs();
168
+ }
169
+ // Hook side (SessionEnd). Only small file reads before the spawn; the child
170
+ // is detached, stdio-ignored, unref'd and lowered to idle priority, so the host
171
+ // never waits on it and a killed hook process group does not take it down.
172
+ export function maybeSpawnAutopilot(cliPath = join(dirname(fileURLToPath(import.meta.url)), "index.js")) {
173
+ try {
174
+ if (!autopilotEnabled().enabled || !due(readAutopilotState()) || lockHeld())
175
+ return false;
176
+ const child = spawn(process.execPath, [cliPath, "learn", "autopilot", "run"], {
177
+ detached: true,
178
+ stdio: "ignore",
179
+ windowsHide: true,
180
+ env: process.env,
181
+ });
182
+ child.on("error", () => { });
183
+ if (child.pid) {
184
+ try {
185
+ setPriority(child.pid, 19);
186
+ }
187
+ catch { /* best effort */ }
188
+ }
189
+ child.unref();
190
+ return true;
191
+ }
192
+ catch {
193
+ return false;
194
+ }
195
+ }
196
+ function compactTokens(n) {
197
+ if (n >= 10_000)
198
+ return `${Math.round(n / 1000)}k`;
199
+ if (n >= 1000)
200
+ return `${(n / 1000).toFixed(1)}k`;
201
+ return String(Math.round(n));
202
+ }
203
+ function sinksOf(value) {
204
+ const sinks = value && typeof value === "object" ? value.sinks : undefined;
205
+ return Array.isArray(sinks) ? sinks : undefined;
206
+ }
207
+ // nudgeLine leads with the biggest new finding; memory-file findings
208
+ // ride along as a count, or lead when they are all that is new.
209
+ export function nudgeLine(fresh) {
210
+ const clean = (title) => title.replace(/[\u0000-\u001f\u007f]+/g, " ").trim().slice(0, 80);
211
+ const sinks = fresh.filter((item) => !item.doctor);
212
+ const doctor = fresh.filter((item) => item.doctor);
213
+ const findings = (n) => `${n} memory-file finding${n === 1 ? "" : "s"}`;
214
+ if (sinks.length === 0) {
215
+ const more = doctor.length > 1 ? ` (+${doctor.length - 1} more)` : "";
216
+ const where = doctor[0].repo ? ` (${clean(doctor[0].repo)})` : "";
217
+ return `caveman learn: memory files${where} — ${clean(doctor[0].title)}${more}. Run \`caveman learn --all\` to review.`;
218
+ }
219
+ const top = sinks[0];
220
+ const lead = sinks.length === 1 ? "new finding" : `${sinks.length} new findings, biggest`;
221
+ const extra = doctor.length > 0 ? `, plus ${findings(doctor.length)}` : "";
222
+ // A recurring_context sink is a pasted block averaged over all messages, not
223
+ // something loaded with each one.
224
+ const where = top.class === "recurring_context" ? "per message on average" : "in every message";
225
+ return `caveman learn: ${lead} — ${clean(top.title)} (~${compactTokens(top.tokens_per_turn)} tokens ${where}, estimate)${extra}. Run \`caveman learn\` to review.`;
226
+ }
227
+ export const AUTOPILOT_PROXY_TOO_OLD = "proxy too old for autopilot (needs learn capabilities)";
228
+ const REQUIRED_CAPS = ["no_remember", "reports_home", "memory_health"];
229
+ // proxySupportsAutopilot probes `learn capabilities`. A proxy that predates it
230
+ // ignores --no-remember/--reports-home, so an unattended scan would write
231
+ // cavemem and the canonical report; such a proxy never scans.
232
+ function proxySupportsAutopilot(proxyBin, state) {
233
+ let key;
234
+ try {
235
+ const info = statSync(proxyBin);
236
+ key = `${proxyBin}:${info.mtimeMs}:${info.size}`;
237
+ }
238
+ catch {
239
+ key = `${proxyBin}:missing`;
240
+ }
241
+ if (state.proxy_caps?.key === key)
242
+ return state.proxy_caps.ok;
243
+ let ok = false;
244
+ try {
245
+ const probe = spawnSync(proxyBin, ["learn", "capabilities"], {
246
+ encoding: "utf8", env: process.env, timeout: 10_000, killSignal: "SIGKILL", stdio: ["ignore", "pipe", "ignore"], windowsHide: true,
247
+ });
248
+ const caps = probe.status === 0 ? JSON.parse(probe.stdout) : undefined;
249
+ ok = caps?.schema === "caveman.learn.capabilities.v1" && REQUIRED_CAPS.every((cap) => caps[cap] === true);
250
+ }
251
+ catch {
252
+ ok = false;
253
+ }
254
+ state.proxy_caps = { key, ok };
255
+ return ok;
256
+ }
257
+ // Child side (`caveman learn autopilot run`). Holds the lock for the whole
258
+ // scan; the proxy is SIGKILLed at the learn timeout. Returns an exit code.
259
+ export function runAutopilot(proxyBin) {
260
+ if (!autopilotEnabled().enabled || !acquireLock())
261
+ return 0;
262
+ const paths = autopilotPaths();
263
+ try {
264
+ const state = readAutopilotState();
265
+ if (!due(state))
266
+ return 0;
267
+ state.last_attempt_at = new Date().toISOString();
268
+ if (!proxySupportsAutopilot(proxyBin, state)) {
269
+ state.last_error = AUTOPILOT_PROXY_TOO_OLD;
270
+ writeJson(paths.state, state);
271
+ return 1;
272
+ }
273
+ writeJson(paths.state, state);
274
+ const result = spawnSync(proxyBin, ["learn", "scan", "--write-report", "--no-remember", "--reports-home", paths.reports], {
275
+ encoding: "utf8",
276
+ env: process.env,
277
+ timeout: autopilotTimeoutSeconds() * 1000,
278
+ killSignal: "SIGKILL",
279
+ maxBuffer: 64 * 1024 * 1024,
280
+ stdio: ["ignore", "pipe", "pipe"],
281
+ windowsHide: true,
282
+ });
283
+ if (result.error || result.status !== 0) {
284
+ const timedOut = result.error?.code === "ETIMEDOUT";
285
+ state.last_error = timedOut
286
+ ? `scan timed out after ${autopilotTimeoutSeconds()}s`
287
+ : (result.stderr || result.error?.message || `scan exited ${result.status}`).trim().split("\n").pop().slice(0, 300);
288
+ writeJson(paths.state, state);
289
+ return 1;
290
+ }
291
+ let sinks;
292
+ try {
293
+ sinks = sinksOf(JSON.parse(result.stdout));
294
+ }
295
+ catch { /* read the written report */ }
296
+ sinks ??= sinksOf(readJson(join(paths.reports, "reports", "caveman-learn.json")));
297
+ if (!sinks) {
298
+ state.last_error = "scan produced no readable report";
299
+ writeJson(paths.state, state);
300
+ return 1;
301
+ }
302
+ const doctorFinding = (sink) => typeof sink.sink_id === "string"
303
+ && ANNOUNCE_DOCTOR_PREFIXES.some((prefix) => sink.sink_id.startsWith(prefix));
304
+ const big = sinks
305
+ .filter((sink) => doctorFinding(sink) || (typeof sink.sink_id === "string" && typeof sink.class === "string" && ANNOUNCE_CLASSES.has(sink.class)
306
+ && typeof sink.tokens_per_turn === "number" && sink.tokens_per_turn >= ANNOUNCE_MIN_TOKENS_PER_TURN))
307
+ .map((sink) => ({
308
+ sink_id: sink.sink_id,
309
+ title: typeof sink.title === "string" ? sink.title : sink.sink_id,
310
+ tokens_per_turn: typeof sink.tokens_per_turn === "number" ? sink.tokens_per_turn : 0,
311
+ ...(typeof sink.class === "string" ? { class: sink.class } : {}),
312
+ doctor: doctorFinding(sink),
313
+ ...(typeof sink.evidence?.repo === "string" ? { repo: sink.evidence.repo } : {}),
314
+ }))
315
+ .sort((a, b) => Number(a.doctor) - Number(b.doctor) || b.tokens_per_turn - a.tokens_per_turn);
316
+ const baseline = state.seen === undefined;
317
+ const seen = new Set(state.seen ?? []);
318
+ const fresh = big.filter((sink) => !seen.has(sink.sink_id));
319
+ // The first scan only records a baseline: autopilot announces what is NEW.
320
+ // A still-unclaimed nudge is left alone and its successors stay unseen, so
321
+ // they are announced after it rather than silently absorbed.
322
+ const pendingExists = readJson(paths.nudge) !== undefined;
323
+ if (baseline || !pendingExists) {
324
+ if (!baseline && fresh.length > 0) {
325
+ const nudge = { line: nudgeLine(fresh), sink_ids: fresh.map((sink) => sink.sink_id), created_at: new Date().toISOString() };
326
+ writeJson(paths.nudge, nudge);
327
+ }
328
+ for (const sink of fresh)
329
+ seen.add(sink.sink_id);
330
+ }
331
+ state.seen = [...seen].slice(-SEEN_CAP);
332
+ state.last_scan_at = new Date().toISOString();
333
+ delete state.last_error;
334
+ writeJson(paths.state, state);
335
+ return 0;
336
+ }
337
+ catch {
338
+ return 1;
339
+ }
340
+ finally {
341
+ releaseLock();
342
+ }
343
+ }
344
+ // Hook side (SessionStart). At most one nudge is in flight at a time:
345
+ // - an unconfirmed in-flight nudge younger than NUDGE_RESHOW_MS belongs to
346
+ // another session start, so a pending newer nudge waits behind it;
347
+ // - an older one is re-shown once (reshown), and dropped after that;
348
+ // - otherwise the pending nudge is claimed with one atomic rename.
349
+ // The in-flight record carries the claimer's token; confirmLearnNudge(token)
350
+ // marks it announced only for that claimer, once the line reached the host.
351
+ // Only fresh sessions (startup / clear) announce; resume, compact and fork
352
+ // never do.
353
+ export function claimLearnNudge(source, token) {
354
+ if (source !== "startup" && source !== "clear")
355
+ return undefined;
356
+ try {
357
+ if (!autopilotEnabled().enabled)
358
+ return undefined;
359
+ const paths = autopilotPaths();
360
+ const claimed = `${paths.inflight}.${process.pid}.claim`;
361
+ let nudge;
362
+ const held = readJson(paths.inflight);
363
+ if (held) {
364
+ const age = Date.now() - Date.parse(held.claimed_at ?? "");
365
+ // age < 0 = clock went backwards; treat as expired rather than block.
366
+ if (Number.isFinite(age) && age >= 0 && age < NUDGE_RESHOW_MS)
367
+ return undefined;
368
+ if (!held.reshown) {
369
+ renameSync(paths.inflight, claimed); // one concurrent re-claimer wins
370
+ nudge = { ...held, reshown: true };
371
+ }
372
+ else {
373
+ try {
374
+ unlinkSync(paths.inflight);
375
+ }
376
+ catch { /* another session dropped it */ }
377
+ }
378
+ }
379
+ if (!nudge) {
380
+ renameSync(paths.nudge, claimed);
381
+ nudge = readJson(claimed);
382
+ }
383
+ if (!nudge || typeof nudge.line !== "string" || !nudge.line) {
384
+ try {
385
+ unlinkSync(claimed);
386
+ }
387
+ catch { /* best effort */ }
388
+ return undefined;
389
+ }
390
+ // In-flight first, then drop the claim file: a failed write must not lose
391
+ // the line, it only forfeits the re-show.
392
+ try {
393
+ writeJson(paths.inflight, { ...nudge, token, claimed_at: new Date().toISOString() });
394
+ }
395
+ catch { /* shown once, unconfirmable */ }
396
+ try {
397
+ unlinkSync(claimed);
398
+ }
399
+ catch { /* best effort */ }
400
+ return nudge.line.replace(/[\u0000-\u001f\u007f]+/g, " ").slice(0, 300);
401
+ }
402
+ catch {
403
+ return undefined;
404
+ }
405
+ }
406
+ // confirmLearnNudge runs once the claimed line has reached the host's stdout.
407
+ // It only confirms the in-flight record this claimer's token owns.
408
+ export function confirmLearnNudge(token) {
409
+ try {
410
+ const paths = autopilotPaths();
411
+ const nudge = readJson(paths.inflight);
412
+ if (!nudge || !token || nudge.token !== token)
413
+ return;
414
+ unlinkSync(paths.inflight);
415
+ writeJson(paths.announced, { ...nudge, announced_at: new Date().toISOString() });
416
+ }
417
+ catch { /* status only */ }
418
+ }
419
+ function ago(iso, now) {
420
+ const at = Date.parse(iso ?? "");
421
+ if (!Number.isFinite(at))
422
+ return "never";
423
+ const minutes = Math.max(0, Math.round((now - at) / 60_000));
424
+ const rel = minutes < 60 ? `${minutes}m ago` : minutes < 2880 ? `${Math.round(minutes / 60)}h ago` : `${Math.round(minutes / 1440)}d ago`;
425
+ return `${iso} (${rel})`;
426
+ }
427
+ export function autopilotStatusText(now = Date.now()) {
428
+ const enabled = autopilotEnabled();
429
+ const state = readAutopilotState();
430
+ const paths = autopilotPaths();
431
+ const announced = readJson(paths.announced);
432
+ const pending = readJson(paths.nudge);
433
+ const lastAttempt = Date.parse(state.last_attempt_at ?? "");
434
+ const next = !Number.isFinite(lastAttempt) || now - lastAttempt >= autopilotThrottleMs()
435
+ ? "next session end"
436
+ : new Date(lastAttempt + autopilotThrottleMs()).toISOString();
437
+ const lines = [
438
+ `learn autopilot: ${enabled.enabled ? "on" : "off"} (${enabled.source === "env" ? "CAVEMAN_LEARN_AUTOPILOT" : enabled.source === "ci" ? "CI/test run" : enabled.source})`,
439
+ ` last scan: ${ago(state.last_scan_at, now)}${lockHeld() ? " · scan running now" : ""}`,
440
+ ` next scan: ${enabled.enabled ? next : "disabled"}`,
441
+ ` last error: ${state.last_error ?? "none"}`,
442
+ ` last shown: ${announced?.line ? `${announced.line} (${announced.announced_at ?? "?"})` : "nothing yet"}`,
443
+ ];
444
+ if (pending?.line)
445
+ lines.push(` waiting to show: ${pending.line}`);
446
+ return `${lines.join("\n")}\n`;
447
+ }
@@ -0,0 +1,132 @@
1
+ // Renders the proxy's optional `trends` block (caveman.learn.v1): week-over-week
2
+ // change per UTC ISO week from scanned sessions. Observation only: medians and
3
+ // pooled shares with n, no currency, and a trend is never a saving. Older
4
+ // proxies omit the block; every renderer returns [] then.
5
+ const BARS = "▁▂▃▄▅▆▇█";
6
+ const COMPACT_KEYS = ["tokens_per_session", "peak_context_pct", "dumbzone_turn_pct"];
7
+ export function learnSparkline(series) {
8
+ const values = series.filter((value) => typeof value === "number");
9
+ if (values.length === 0)
10
+ return "·".repeat(series.length);
11
+ const lo = Math.min(...values);
12
+ const span = Math.max(...values) - lo;
13
+ return series
14
+ .map((value) => typeof value !== "number" ? "·" : BARS[span === 0 ? 0 : Math.round(((value - lo) / span) * (BARS.length - 1))])
15
+ .join("");
16
+ }
17
+ // trendSpark sets the week in progress apart ("▃▅▆┊█"): it is plotted but
18
+ // never the compared week.
19
+ function trendSpark(trends, metric) {
20
+ const spark = learnSparkline(metric.series);
21
+ return trends.weeks.at(-1)?.in_progress && spark.length > 1 ? `${spark.slice(0, -1)}┊${spark.slice(-1)}` : spark;
22
+ }
23
+ function compactNumber(value) {
24
+ if (value >= 1_000_000)
25
+ return `${(value / 1_000_000).toFixed(1).replace(/\.0$/, "")}M`;
26
+ if (value >= 10_000)
27
+ return `${(value / 1_000).toFixed(1).replace(/\.0$/, "")}k`;
28
+ return Math.round(value).toLocaleString("en-US");
29
+ }
30
+ function trendValue(value, unit) {
31
+ if (value === undefined || !Number.isFinite(value))
32
+ return "—";
33
+ if (unit === "tokens")
34
+ return compactNumber(value);
35
+ if (unit === "pct")
36
+ return `${value.toFixed(1).replace(/\.0$/, "")}%`;
37
+ if (unit === "per_100_turns")
38
+ return `${value.toFixed(1).replace(/\.0$/, "")} per 100 messages`;
39
+ if (unit === "points")
40
+ return `-${Math.round(value)} points`;
41
+ return String(value);
42
+ }
43
+ // shortDate renders YYYY-MM-DD as "Sep 21".
44
+ export function shortDate(day) {
45
+ const at = new Date(`${day}T00:00:00Z`);
46
+ return Number.isNaN(at.getTime())
47
+ ? day
48
+ : at.toLocaleDateString("en-US", { month: "short", day: "numeric", timeZone: "UTC" });
49
+ }
50
+ function currentWeekName(trends) {
51
+ const week = trends.weeks.find((item) => item.week === trends.current_week);
52
+ return week?.start ? `week of ${shortDate(week.start)}` : trends.current_week;
53
+ }
54
+ // Share metrics show the change in percentage points; a relative percent of a
55
+ // percent reads as a much bigger move than it is.
56
+ function trendDelta(metric) {
57
+ const sign = (value) => (value > 0 ? "+" : "");
58
+ if (metric.unit === "pct" && metric.current !== undefined && metric.prior !== undefined) {
59
+ const diff = metric.current - metric.prior;
60
+ const points = diff.toFixed(1).replace(/\.0$/, "");
61
+ return `${sign(diff)}${points} point${Math.abs(diff) === 1 ? "" : "s"} `;
62
+ }
63
+ return metric.delta_pct === undefined ? "" : `${sign(metric.delta_pct)}${Math.round(metric.delta_pct)}% `;
64
+ }
65
+ function trendDirection(metric) {
66
+ return metric.direction === "insufficient_data" ? "not enough data" : metric.direction;
67
+ }
68
+ // learnTrendLines is the compact 2-4 line section shown after the score.
69
+ export function learnTrendLines(trends) {
70
+ if (!trends?.metrics?.length)
71
+ return [];
72
+ const metrics = COMPACT_KEYS
73
+ .map((key) => trends.metrics.find((metric) => metric.key === key))
74
+ .filter((metric) => metric !== undefined);
75
+ if (metrics.length === 0)
76
+ return [];
77
+ const head = `last ${trends.weeks.length} weeks`;
78
+ const width = Math.max(...metrics.map((metric) => metric.label.length));
79
+ const sessions = metrics[0].current_sessions;
80
+ return [
81
+ ...metrics.map((metric, index) => `${index === 0 ? head : " ".repeat(head.length)} ${metric.label.padEnd(width)} ${trendSpark(trends, metric)} ${trendDelta(metric)}${metric.direction === "insufficient_data" ? "" : "· "}${trendDirection(metric)}`),
82
+ `${" ".repeat(head.length)} ${currentWeekName(trends)} (${sessions.toLocaleString("en-US")} session${sessions === 1 ? "" : "s"}) vs the ${trends.prior_weeks} weeks before`,
83
+ `${" ".repeat(head.length)} a trend is not a saving, and it does not show the cause`,
84
+ ];
85
+ }
86
+ // learnTrendTable is the --all / --md view: every metric, plus score history
87
+ // and sink movers when saved reports exist.
88
+ export function learnTrendTable(trends, markdown) {
89
+ if (!trends?.metrics?.length)
90
+ return [];
91
+ const header = ["measure", `last ${trends.weeks.length} weeks`, currentWeekName(trends), `${trends.prior_weeks} weeks before`, "change", "sessions"];
92
+ const rows = trends.metrics.map((metric) => [
93
+ metric.label,
94
+ trendSpark(trends, metric),
95
+ trendValue(metric.current, metric.unit),
96
+ trendValue(metric.prior, metric.unit),
97
+ metric.direction === "insufficient_data"
98
+ ? "not enough data"
99
+ : `${trendDelta(metric)}${metric.direction}`,
100
+ `${metric.current_sessions.toLocaleString("en-US")} vs ${metric.prior_sessions.toLocaleString("en-US")}`,
101
+ ]);
102
+ const lines = [markdown ? "### Trends" : "trends"];
103
+ if (markdown) {
104
+ lines.push(`| ${header.join(" | ")} |`, `|${header.map(() => "---").join("|")}|`, ...rows.map((row) => `| ${row.join(" | ")} |`));
105
+ }
106
+ else {
107
+ const widths = header.map((_, col) => Math.max(...[header, ...rows].map((row) => row[col].length)));
108
+ for (const row of [header, ...rows])
109
+ lines.push(row.map((cell, col) => cell.padEnd(widths[col])).join(" ").trimEnd());
110
+ }
111
+ const weeks = trends.weeks
112
+ .map((week) => `${shortDate(week.start)}${week.in_progress ? " (still running)" : week.partial ? "*" : ""} (${week.sessions.toLocaleString("en-US")})`)
113
+ .join(" · ");
114
+ lines.push(`weeks start Monday, UTC (sessions in brackets; * only partly scanned; ┊ still running, never compared): ${weeks}`, `token counts use the middle session of each week; percentages count all messages together; weeks under ${trends.min_sessions} sessions show no value; changes under ${trends.dead_band_pct}% count as flat`, trends.note);
115
+ const history = trends.score?.history ?? [];
116
+ if (history.length >= 2) {
117
+ lines.push(`Setup Score history: ${history.map((point) => `${shortDate(point.date)} ${point.score}`).join(" → ")}`);
118
+ }
119
+ const movers = trends.movers;
120
+ if (movers) {
121
+ const fmt = (mover) => {
122
+ const delta = mover.delta_tokens_per_turn;
123
+ return `${mover.title} (${delta > 0 ? "+" : delta < 0 ? "-" : ""}${compactNumber(Math.abs(delta))} per message, ${mover.status})`;
124
+ };
125
+ const since = `${shortDate(movers.since)} (${movers.days} day${movers.days === 1 ? "" : "s"} ago)`;
126
+ if (movers.grew?.length)
127
+ lines.push(`grew since ${since}: ${movers.grew.map(fmt).join("; ")}`);
128
+ if (movers.shrank?.length)
129
+ lines.push(`shrank since ${since}: ${movers.shrank.map(fmt).join("; ")}`);
130
+ }
131
+ return markdown ? lines.map((line, index) => (index === 0 || line.startsWith("|") ? line : `- ${line}`)) : lines;
132
+ }