@fabersep/cache 0.0.0-stage → 0.1.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,518 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { READ_ONLY, cacheHome, loadConfig, projectConfig, resolveProfile, resolveProject } from './config.js';
3
+ import { WARMUP_MESSAGE, claudeBin, claudeVersion, keyBits, modeRefusal, openArgs, runClaude, } from './engines/claude.js';
4
+ import { agyKeyBits, agyVersion, runAgy, UNVERIFIED_MESSAGE } from './engines/agy.js';
5
+ import { keyOf, keyParts } from './key.js';
6
+ import { acquire, unlock } from './lock.js';
7
+ import { isModeVerified, modePolicy } from './measured.js';
8
+ import { baseMessage, buildPacket, packetInFront } from './packet.js';
9
+ import { appendRecord } from './records.js';
10
+ import { Registry } from './registry.js';
11
+ export const ENGINES = ['claude', 'agy', 'codex'];
12
+ export class CacheError extends Error {
13
+ }
14
+ function defaultRunner(opts) {
15
+ return opts.engine === 'agy' ? runAgy(opts) : runClaude(opts);
16
+ }
17
+ export function defaultContext(overrides = {}) {
18
+ const home = overrides.home ?? cacheHome();
19
+ return {
20
+ home,
21
+ config: overrides.config ?? loadConfig(home),
22
+ now: overrides.now ?? (() => Date.now()),
23
+ runner: overrides.runner ?? defaultRunner,
24
+ log: overrides.log ?? ((msg) => process.stderr.write(`faber-cache: ${msg}\n`)),
25
+ };
26
+ }
27
+ function checkEngine(engine) {
28
+ const e = (engine ?? 'claude');
29
+ if (!ENGINES.includes(e))
30
+ throw new CacheError(`unknown engine "${engine}"; known: ${ENGINES.join(', ')}`);
31
+ if (e === 'codex') {
32
+ throw new CacheError('the codex adapter is not built yet (planned for a later release, unverified until measured); use --engine claude or --engine agy');
33
+ }
34
+ return e;
35
+ }
36
+ /** Packet, key and policy for a request; refuses before any engine starts (FR-01.5, FR-01.6). */
37
+ export function prepare(ctx, req, defaultMode = 'fixed', defaultProfile) {
38
+ const projectDir = resolveProject(req.project);
39
+ const engine = checkEngine(req.engine);
40
+ const { name: profileName, profile } = resolveProfile(ctx.config, projectDir, req.profile ?? defaultProfile, req.forceReadOnly);
41
+ const packet = buildPacket(ctx.config, projectDir);
42
+ if (engine === 'agy') {
43
+ const mode = req.mode ?? 'prefix';
44
+ if (mode !== 'prefix')
45
+ throw new CacheError(`unknown mode "${mode}" for agy; agy only supports prefix mode`);
46
+ const engineVersion = agyVersion();
47
+ if (!engineVersion)
48
+ throw new CacheError('Antigravity CLI is not installed or not on PATH (`agy --version` failed)');
49
+ const model = req.model ?? 'default';
50
+ const kp = {
51
+ engine,
52
+ engineVersion,
53
+ model,
54
+ mode,
55
+ profile: profileName,
56
+ tools: profile.tools,
57
+ permissionMode: profile.permissionMode,
58
+ ...agyKeyBits(),
59
+ };
60
+ return {
61
+ projectDir,
62
+ engine,
63
+ engineVersion,
64
+ mode,
65
+ profileName,
66
+ profile,
67
+ model,
68
+ packet,
69
+ key: keyOf(kp, packet),
70
+ parts: keyParts(kp, packet),
71
+ needsWarmup: false,
72
+ breakEven: 1,
73
+ };
74
+ }
75
+ const mode = req.mode ?? defaultMode;
76
+ if (mode !== 'fixed' && mode !== 'default')
77
+ throw new CacheError(`unknown mode "${mode}"; use fixed or default`);
78
+ const refusal = modeRefusal(mode);
79
+ if (refusal)
80
+ throw new CacheError(refusal);
81
+ const model = req.model ?? projectConfig(ctx.config, projectDir).model ?? ctx.config.model;
82
+ const engineVersion = claudeVersion();
83
+ if (!engineVersion)
84
+ throw new CacheError('Claude Code is not installed or not on PATH (`claude --version` failed)');
85
+ const kp = {
86
+ engine,
87
+ engineVersion,
88
+ model,
89
+ mode,
90
+ profile: profileName,
91
+ tools: profile.tools,
92
+ permissionMode: profile.permissionMode,
93
+ ...keyBits(mode),
94
+ };
95
+ const policy = modePolicy(engine, mode);
96
+ return {
97
+ projectDir,
98
+ engine,
99
+ engineVersion,
100
+ mode,
101
+ profileName,
102
+ profile,
103
+ model,
104
+ packet,
105
+ key: keyOf(kp, packet),
106
+ parts: keyParts(kp, packet),
107
+ needsWarmup: policy.needsWarmup,
108
+ breakEven: policy.breakEven,
109
+ };
110
+ }
111
+ export function isFresh(ctx, entry) {
112
+ if (!entry)
113
+ return false;
114
+ return ctx.now() - entry.lastRead <= (ctx.config.lifetimeMin - ctx.config.marginMin) * 60_000;
115
+ }
116
+ function prefixOf(u) {
117
+ return u ? u.input + u.cacheWrite + u.cacheRead : 0;
118
+ }
119
+ function record(ctx, p, fields) {
120
+ const rec = {
121
+ at: new Date(ctx.now()).toISOString(),
122
+ project: p.projectDir,
123
+ profile: p.profileName,
124
+ mode: p.mode,
125
+ engine: p.engine,
126
+ engineVersion: p.engineVersion,
127
+ model: p.model,
128
+ tools: p.profile.tools ? p.profile.tools.join(',') : 'all',
129
+ key: p.key,
130
+ fromSession: null,
131
+ session: null,
132
+ first: null,
133
+ total: null,
134
+ refPrefix: null,
135
+ readShare: null,
136
+ ownTokens: null,
137
+ cacheMiss: false,
138
+ ...fields,
139
+ };
140
+ appendRecord(ctx.home, rec);
141
+ return rec;
142
+ }
143
+ /** Build (and warm) a key's base under its lock, or return the fresh one (FR-02, FR-03). */
144
+ async function ensureBase(ctx, p, req, force = false) {
145
+ const reg = new Registry(ctx.home);
146
+ const lockFile = reg.keyLock(p.key);
147
+ if (!(await acquire(lockFile, ctx.config.limits.lockWaitSec * 1000))) {
148
+ ctx.log(`lock wait for ${p.key} timed out; running with no base`);
149
+ return { fallback: 'lock-timeout' };
150
+ }
151
+ try {
152
+ const existing = reg.get(p.key);
153
+ if (!force && isFresh(ctx, existing))
154
+ return { entry: existing };
155
+ const common = { engine: p.engine, mode: p.mode, profile: p.profile, model: p.model, cwd: p.projectDir, signal: req.signal, onSpawn: req.onSpawn };
156
+ const built = await ctx.runner({ ...common, stdin: baseMessage(p.packet) });
157
+ record(ctx, p, {
158
+ kind: 'build',
159
+ base: 'with-base',
160
+ session: built.session,
161
+ first: built.first,
162
+ total: built.total,
163
+ costUsd: built.costUsd ?? null,
164
+ refPrefix: prefixOf(built.first),
165
+ outcome: built.ok ? 'ok' : built.stopped ? 'stopped' : 'error',
166
+ error: built.error,
167
+ });
168
+ if (!built.ok || !built.session)
169
+ throw new CacheError(`building the base failed: ${built.error ?? 'no session id'}`);
170
+ let warm = null;
171
+ let refPrefix = prefixOf(built.first);
172
+ if (p.needsWarmup) {
173
+ for (let attempt = 1; attempt <= 2 && !warm; attempt++) {
174
+ const w = await ctx.runner({ ...common, stdin: WARMUP_MESSAGE, resume: built.session });
175
+ record(ctx, p, {
176
+ kind: 'warmup',
177
+ base: 'with-base',
178
+ fromSession: built.session,
179
+ session: w.session,
180
+ first: w.first,
181
+ total: w.total,
182
+ refPrefix: prefixOf(w.first),
183
+ outcome: w.ok ? 'ok' : w.stopped ? 'stopped' : 'error',
184
+ error: w.error,
185
+ attempt,
186
+ });
187
+ if (w.ok && w.session) {
188
+ warm = w.session;
189
+ refPrefix = prefixOf(w.first);
190
+ }
191
+ else if (w.stopped) {
192
+ break;
193
+ }
194
+ }
195
+ if (!warm) {
196
+ ctx.log(`warm-up failed twice on base ${built.session}; nothing registered, running with no base`);
197
+ return { fallback: 'warmup-failed' };
198
+ }
199
+ }
200
+ const now = ctx.now();
201
+ const entry = {
202
+ key: p.key,
203
+ project: p.projectDir,
204
+ profile: p.profileName,
205
+ mode: p.mode,
206
+ engine: p.engine,
207
+ engineVersion: p.engineVersion,
208
+ model: p.model,
209
+ baseSession: built.session,
210
+ warmSession: warm,
211
+ created: now,
212
+ lastRead: now,
213
+ uses: 0,
214
+ refPrefix,
215
+ parts: p.parts,
216
+ };
217
+ reg.put(entry);
218
+ return { entry };
219
+ }
220
+ finally {
221
+ unlock(lockFile);
222
+ }
223
+ }
224
+ async function runNoBase(ctx, p, req, task, base) {
225
+ const out = await ctx.runner({
226
+ engine: p.engine,
227
+ mode: p.mode,
228
+ profile: p.profile,
229
+ model: p.model,
230
+ cwd: p.projectDir,
231
+ stdin: packetInFront(p.packet, task),
232
+ maxTurns: req.maxTurns,
233
+ signal: req.signal,
234
+ onSpawn: req.onSpawn,
235
+ });
236
+ const rec = record(ctx, p, {
237
+ kind: 'run',
238
+ base,
239
+ session: out.session,
240
+ first: out.first,
241
+ total: out.total,
242
+ costUsd: out.costUsd ?? null,
243
+ ownTokens: out.first ? out.first.input + out.first.cacheWrite : null,
244
+ outcome: out.ok ? 'ok' : out.stopped ? 'stopped' : 'error',
245
+ error: out.error,
246
+ task: task.slice(0, 120),
247
+ });
248
+ return { task, reply: out.reply, ok: out.ok, error: out.error, record: rec };
249
+ }
250
+ /** Prefix-mode run (FR-07.3, AC-26, AC-27): packet first, no base session stored. */
251
+ async function runPrefix(ctx, p, req, task) {
252
+ const verified = isModeVerified(p.engine, p.mode, ctx.config.bar);
253
+ const unverified = !verified;
254
+ if (unverified)
255
+ ctx.log(UNVERIFIED_MESSAGE);
256
+ const out = await ctx.runner({
257
+ engine: p.engine,
258
+ mode: p.mode,
259
+ profile: p.profile,
260
+ model: p.model,
261
+ cwd: p.projectDir,
262
+ stdin: packetInFront(p.packet, task),
263
+ maxTurns: req.maxTurns,
264
+ signal: req.signal,
265
+ onSpawn: req.onSpawn,
266
+ });
267
+ const refPrefix = prefixOf(out.first);
268
+ const share = out.first && refPrefix > 0 ? Math.round((out.first.cacheRead / refPrefix) * 1000) / 1000 : null;
269
+ const miss = out.ok && verified && share !== null && share < ctx.config.bar;
270
+ if (miss)
271
+ ctx.log(`cache miss: prefix run read ${out.first?.cacheRead} of ${refPrefix} tokens (${Math.round((share ?? 0) * 100)}%)`);
272
+ const rec = record(ctx, p, {
273
+ kind: 'run',
274
+ base: 'prefix',
275
+ fromSession: null,
276
+ session: out.session,
277
+ first: out.first,
278
+ total: out.total,
279
+ costUsd: out.costUsd ?? null,
280
+ refPrefix: refPrefix || null,
281
+ readShare: share,
282
+ ownTokens: out.first ? out.first.input + out.first.cacheWrite : null,
283
+ cacheMiss: miss,
284
+ outcome: out.ok ? 'ok' : out.stopped ? 'stopped' : 'error',
285
+ error: out.error,
286
+ task: task.slice(0, 120),
287
+ ...(unverified ? { unverified: true, note: UNVERIFIED_MESSAGE } : {}),
288
+ });
289
+ return { task, reply: out.reply, ok: out.ok, error: out.error, record: rec };
290
+ }
291
+ async function runFork(ctx, p, req, task, entry, retried = false) {
292
+ const from = entry.warmSession ?? entry.baseSession;
293
+ const out = await ctx.runner({
294
+ engine: p.engine,
295
+ mode: p.mode,
296
+ profile: p.profile,
297
+ model: p.model,
298
+ cwd: p.projectDir,
299
+ stdin: task,
300
+ resume: from,
301
+ maxTurns: req.maxTurns,
302
+ signal: req.signal,
303
+ onSpawn: req.onSpawn,
304
+ });
305
+ const reg = new Registry(ctx.home);
306
+ if (out.resumeError && !retried) {
307
+ // FR-03.5: the engine cannot resume the session; replace the entry and fork the new base.
308
+ ctx.log(`session ${from} can no longer be resumed; rebuilding the base`);
309
+ reg.forget(p.key);
310
+ const rebuilt = await ensureBase(ctx, p, req, true);
311
+ if ('fallback' in rebuilt)
312
+ return runNoBase(ctx, p, req, task, rebuilt.fallback);
313
+ return runFork(ctx, p, req, task, rebuilt.entry, true);
314
+ }
315
+ if (out.ok)
316
+ reg.touch(p.key, ctx.now());
317
+ const share = out.first && entry.refPrefix ? Math.round((out.first.cacheRead / entry.refPrefix) * 1000) / 1000 : null;
318
+ const miss = out.ok && share !== null && share < ctx.config.bar;
319
+ if (miss)
320
+ ctx.log(`cache miss: the fork read ${out.first?.cacheRead} of ${entry.refPrefix} prefix tokens (${Math.round((share ?? 0) * 100)}%)`);
321
+ const rec = record(ctx, p, {
322
+ kind: 'run',
323
+ base: 'with-base',
324
+ fromSession: from,
325
+ session: out.session,
326
+ first: out.first,
327
+ total: out.total,
328
+ refPrefix: entry.refPrefix,
329
+ readShare: share,
330
+ ownTokens: out.first ? out.first.input + out.first.cacheWrite : null,
331
+ cacheMiss: miss,
332
+ outcome: out.ok ? 'ok' : out.stopped ? 'stopped' : 'error',
333
+ error: out.error,
334
+ task: task.slice(0, 120),
335
+ });
336
+ return { task, reply: out.reply, ok: out.ok, error: out.error, record: rec };
337
+ }
338
+ /** One task (FR-05.1): fork a fresh base, build one when it pays, or run with the packet in front. */
339
+ export async function runTask(ctx, req, task) {
340
+ const p = prepare(ctx, req);
341
+ if (p.mode === 'prefix')
342
+ return runPrefix(ctx, p, req, task);
343
+ const reg = new Registry(ctx.home);
344
+ const entry = reg.get(p.key);
345
+ if (isFresh(ctx, entry))
346
+ return runFork(ctx, p, req, task, entry);
347
+ let build;
348
+ if (req.uses !== undefined) {
349
+ build = req.uses >= p.breakEven;
350
+ }
351
+ else if (p.breakEven <= 1) {
352
+ build = true;
353
+ }
354
+ else {
355
+ const seen = reg.seenAt(p.key);
356
+ build = seen !== undefined && ctx.now() - seen <= ctx.config.lifetimeMin * 60_000;
357
+ if (!build)
358
+ reg.markSeen(p.key, ctx.now());
359
+ }
360
+ if (!build)
361
+ return runNoBase(ctx, p, req, task, 'no-base');
362
+ const got = await ensureBase(ctx, p, req);
363
+ if ('fallback' in got)
364
+ return runNoBase(ctx, p, req, task, got.fallback);
365
+ return runFork(ctx, p, req, task, got.entry);
366
+ }
367
+ /** A fan-out (FR-05.3): build and warm once, then fork every task with a parallel limit. */
368
+ export async function runTasks(ctx, req, tasks) {
369
+ if (tasks.length === 0)
370
+ return [];
371
+ const p = prepare(ctx, req);
372
+ if (p.mode === 'prefix') {
373
+ const results = new Array(tasks.length);
374
+ let next = 0;
375
+ const worker = async () => {
376
+ while (next < tasks.length) {
377
+ const i = next++;
378
+ results[i] = await runPrefix(ctx, p, req, tasks[i]);
379
+ }
380
+ };
381
+ const width = Math.max(1, Math.min(ctx.config.limits.parallel, tasks.length));
382
+ await Promise.all(Array.from({ length: width }, worker));
383
+ return results;
384
+ }
385
+ const got = await ensureBase(ctx, p, req);
386
+ const results = new Array(tasks.length);
387
+ let next = 0;
388
+ const worker = async () => {
389
+ while (next < tasks.length) {
390
+ const i = next++;
391
+ results[i] = 'fallback' in got
392
+ ? await runNoBase(ctx, p, req, tasks[i], got.fallback)
393
+ : await runFork(ctx, p, req, tasks[i], got.entry);
394
+ }
395
+ };
396
+ const width = Math.max(1, Math.min(ctx.config.limits.parallel, tasks.length));
397
+ await Promise.all(Array.from({ length: width }, worker));
398
+ return results;
399
+ }
400
+ /** `faber-cache warm` (FR-04.5): one build ahead of a batch, never a schedule. */
401
+ export async function warm(ctx, req) {
402
+ if (req.engine === 'agy') {
403
+ throw new CacheError('agy runs in prefix mode and has no base session to warm; run tasks directly with --engine agy');
404
+ }
405
+ const p = prepare(ctx, req, 'fixed');
406
+ const got = await ensureBase(ctx, p, req);
407
+ if ('fallback' in got)
408
+ throw new CacheError(`no base built: ${got.fallback}`);
409
+ return got.entry;
410
+ }
411
+ function shellQuote(s) {
412
+ return /^[A-Za-z0-9_./:=,@+-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`;
413
+ }
414
+ function refuseNoFork(engine) {
415
+ if (engine === 'agy')
416
+ throw new CacheError('agy has no fork, so there is no interactive open for it (FR-06.4)');
417
+ if (engine === 'codex')
418
+ throw new CacheError('the Codex adapter is not in v0.1; interactive open needs its fork, unverified until measured');
419
+ }
420
+ /** The interactive fork of the warm default-prompt base, built first if needed (FR-06.1). */
421
+ export async function planOpen(ctx, req) {
422
+ refuseNoFork(req.engine);
423
+ const p = prepare(ctx, req, 'default', 'interactive');
424
+ const got = await ensureBase(ctx, p, req);
425
+ if ('fallback' in got)
426
+ throw new CacheError(`no base to open: ${got.fallback}`);
427
+ const session = got.entry.warmSession ?? got.entry.baseSession;
428
+ const bin = claudeBin();
429
+ const args = openArgs(p.mode, p.profile, p.model, session);
430
+ const command = `cd ${shellQuote(p.projectDir)} && ${[bin, ...args].map(shellQuote).join(' ')}`;
431
+ return { cwd: p.projectDir, bin, args, command, entry: got.entry, prepared: p };
432
+ }
433
+ /** Launch the interactive fork in this terminal (FR-06.3): last read updated, one open record. */
434
+ export async function launchOpen(ctx, plan) {
435
+ const reg = new Registry(ctx.home);
436
+ reg.touch(plan.entry.key, ctx.now());
437
+ record(ctx, plan.prepared, {
438
+ kind: 'open',
439
+ base: 'with-base',
440
+ fromSession: plan.entry.warmSession ?? plan.entry.baseSession,
441
+ refPrefix: plan.entry.refPrefix,
442
+ outcome: 'ok',
443
+ });
444
+ return new Promise((resolve) => {
445
+ const child = spawn(plan.bin, plan.args, { cwd: plan.cwd, stdio: 'inherit' });
446
+ child.on('error', () => resolve(1));
447
+ child.on('close', (code) => resolve(code ?? 0));
448
+ });
449
+ }
450
+ /** `faber-cache status` (FR-12.2): the current key and every registered base of the project. */
451
+ export function status(ctx, req) {
452
+ const p = prepare(ctx, req);
453
+ const bases = new Registry(ctx.home).load().bases;
454
+ const rows = Object.values(bases)
455
+ .filter((e) => e.project === p.projectDir)
456
+ .sort((a, b) => b.lastRead - a.lastRead)
457
+ .map((e) => ({
458
+ key: e.key,
459
+ engine: e.engine,
460
+ profile: e.profile,
461
+ mode: e.mode,
462
+ model: e.model,
463
+ engineVersion: e.engineVersion,
464
+ fresh: isFresh(ctx, e),
465
+ uses: e.uses,
466
+ lastReadMinAgo: Math.round((ctx.now() - e.lastRead) / 6000) / 10,
467
+ warm: e.warmSession !== null,
468
+ current: e.key === p.key,
469
+ }));
470
+ return { project: p.projectDir, currentKey: p.key, rows };
471
+ }
472
+ /** FR-11.5 / AC-57: three independent single-turn agy runs with the same packet at 0, 1 and 10 min. */
473
+ export async function measureAgy(ctx, req, opts = {}) {
474
+ const delaysMin = opts.delaysMin ?? [0, 1, 10];
475
+ const sleep = opts.sleep ?? ((ms) => new Promise((res) => setTimeout(res, ms)));
476
+ const fullReq = { ...req, engine: 'agy', mode: 'prefix' };
477
+ const p = prepare(ctx, fullReq);
478
+ const prompts = [
479
+ 'Reply with the single word: ready',
480
+ 'Reply with the single word: check-one',
481
+ 'Reply with the single word: check-two',
482
+ ];
483
+ const runs = [];
484
+ for (let i = 0; i < delaysMin.length; i++) {
485
+ const waitMin = i === 0 ? delaysMin[0] : Math.max(0, delaysMin[i] - delaysMin[i - 1]);
486
+ if (waitMin > 0)
487
+ await sleep(waitMin * 60_000);
488
+ const res = await runPrefix(ctx, p, fullReq, prompts[i] ?? `Reply with the single word: check-${i}`);
489
+ runs.push({
490
+ index: i + 1,
491
+ delayMin: delaysMin[i],
492
+ at: res.record.at,
493
+ ok: res.ok,
494
+ session: res.record.session,
495
+ first: res.record.first,
496
+ total: res.record.total,
497
+ refPrefix: res.record.refPrefix,
498
+ readShare: res.record.readShare,
499
+ error: res.error,
500
+ });
501
+ }
502
+ const later = runs.slice(1).filter((r) => r.ok && r.readShare !== null);
503
+ const meanReadShare = later.length
504
+ ? Math.round((later.reduce((sum, r) => sum + (r.readShare ?? 0), 0) / later.length) * 1000) / 1000
505
+ : null;
506
+ const passed = runs.length >= 3 && later.length === runs.length - 1 && later.every((r) => (r.readShare ?? 0) >= ctx.config.bar);
507
+ return {
508
+ engine: 'agy',
509
+ mode: 'prefix',
510
+ engineVersion: p.engineVersion,
511
+ model: p.model,
512
+ date: new Date(ctx.now()).toISOString().slice(0, 10),
513
+ runs,
514
+ passed,
515
+ meanReadShare,
516
+ };
517
+ }
518
+ export { READ_ONLY };
@@ -0,0 +1,25 @@
1
+ import { RunRecord, Usage } from './records.js';
2
+ /**
3
+ * Price weights relative to one fresh input token, the same for every current Claude model:
4
+ * a cache write costs 1.25x (five-minute lifetime) or 2x (one hour), a cache read 0.1x, output 5x.
5
+ */
6
+ export declare const WEIGHTS: {
7
+ readonly input: 1;
8
+ readonly write5m: 1.25;
9
+ readonly write1h: 2;
10
+ readonly read: 0.1;
11
+ readonly output: 5;
12
+ };
13
+ /** A usage's cost in input-token equivalents. */
14
+ export declare function inputEquivalents(u: Usage | null | undefined): number;
15
+ /**
16
+ * Dollars per input-token equivalent, from the records whose engine-reported cost is their own
17
+ * (builds and runs that resume nothing), or null when there are none.
18
+ */
19
+ export declare function usdPerEquivalent(records: RunRecord[]): number | null;
20
+ /**
21
+ * A conservative estimate of what a fork saved against sending the packet fresh: the tokens its
22
+ * first request read from cache, priced as plain input instead of a cache read. It leaves out the
23
+ * cache-write premium a fresh session would also pay, so the real saving is larger (see bench/).
24
+ */
25
+ export declare function forkSaving(r: RunRecord): number;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Price weights relative to one fresh input token, the same for every current Claude model:
3
+ * a cache write costs 1.25x (five-minute lifetime) or 2x (one hour), a cache read 0.1x, output 5x.
4
+ */
5
+ export const WEIGHTS = { input: 1, write5m: 1.25, write1h: 2, read: 0.1, output: 5 };
6
+ /** A usage's cost in input-token equivalents. */
7
+ export function inputEquivalents(u) {
8
+ if (!u)
9
+ return 0;
10
+ const w1h = Math.min(u.cacheWrite1h ?? 0, u.cacheWrite);
11
+ return (u.input * WEIGHTS.input +
12
+ (u.cacheWrite - w1h) * WEIGHTS.write5m +
13
+ w1h * WEIGHTS.write1h +
14
+ u.cacheRead * WEIGHTS.read +
15
+ u.output * WEIGHTS.output);
16
+ }
17
+ /**
18
+ * Dollars per input-token equivalent, from the records whose engine-reported cost is their own
19
+ * (builds and runs that resume nothing), or null when there are none.
20
+ */
21
+ export function usdPerEquivalent(records) {
22
+ let usd = 0;
23
+ let eq = 0;
24
+ for (const r of records) {
25
+ if (typeof r.costUsd !== 'number' || !r.total)
26
+ continue;
27
+ usd += r.costUsd;
28
+ eq += inputEquivalents(r.total);
29
+ }
30
+ return usd > 0 && eq > 0 ? usd / eq : null;
31
+ }
32
+ /**
33
+ * A conservative estimate of what a fork saved against sending the packet fresh: the tokens its
34
+ * first request read from cache, priced as plain input instead of a cache read. It leaves out the
35
+ * cache-write premium a fresh session would also pay, so the real saving is larger (see bench/).
36
+ */
37
+ export function forkSaving(r) {
38
+ return (r.first?.cacheRead ?? 0) * (WEIGHTS.input - WEIGHTS.read);
39
+ }
@@ -0,0 +1,26 @@
1
+ import { EngineStatus } from './engines/claude.js';
2
+ export interface ModeReport {
3
+ engine: string;
4
+ mode: string;
5
+ state: 'measured' | 'partly measured' | 'unmeasured' | 're-check' | 'no cache guarantee';
6
+ needsWarmup: boolean | null;
7
+ breakEven: number | null;
8
+ measuredOn: string | null;
9
+ note: string;
10
+ }
11
+ export interface MissReport {
12
+ at: string;
13
+ project: string;
14
+ key: string;
15
+ readShare: number | null;
16
+ differs: string[];
17
+ }
18
+ export interface DoctorReport {
19
+ engines: EngineStatus[];
20
+ settings: {
21
+ excludeDynamicSystemPromptSections: boolean;
22
+ };
23
+ modes: ModeReport[];
24
+ misses: MissReport[];
25
+ }
26
+ export declare function doctor(home: string, bar?: number): DoctorReport;
@@ -0,0 +1,84 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { agyStatus, agyVersion, UNVERIFIED_MESSAGE } from './engines/agy.js';
3
+ import { claudeStatus, claudeVersion, excludeDynamicOn } from './engines/claude.js';
4
+ import { loadConfig } from './config.js';
5
+ import { breakEven, loadMeasured, major } from './measured.js';
6
+ import { readRecords } from './records.js';
7
+ /** Engine adapters and their modes; Codex is planned for a later release. */
8
+ const MODES = [
9
+ { engine: 'claude', mode: 'fixed', note: 'headless runs' },
10
+ { engine: 'claude', mode: 'default', note: 'headless runs with --mode default' },
11
+ { engine: 'claude', mode: 'open', note: 'interactive open (OQ-04)' },
12
+ { engine: 'agy', mode: 'prefix', note: UNVERIFIED_MESSAGE },
13
+ { engine: 'codex', mode: 'fork', note: 'adapter planned for a later release' },
14
+ ];
15
+ function otherEngine(engine, bin) {
16
+ const out = spawnSync(bin, ['--version'], { encoding: 'utf8' });
17
+ if (out.error || out.status !== 0) {
18
+ return { engine, installed: false, version: null, loggedIn: null, message: 'not installed' };
19
+ }
20
+ const version = (out.stdout.match(/\d+\.\d+\.\d+/) ?? [out.stdout.trim()])[0];
21
+ return { engine, installed: true, version, loggedIn: null, message: 'installed; its adapter is planned for a later release' };
22
+ }
23
+ /** Compare a flagged run with the build of the base it forked (FR-09.4). */
24
+ function explainMiss(miss, all) {
25
+ let baseSession = miss.fromSession;
26
+ const warm = all.find((r) => r.kind === 'warmup' && r.session === miss.fromSession);
27
+ if (warm)
28
+ baseSession = warm.fromSession;
29
+ const build = all.find((r) => r.kind === 'build' && r.session === baseSession);
30
+ if (!build)
31
+ return ['the base build record is missing, so nothing could be compared'];
32
+ const differs = [];
33
+ const fields = [
34
+ ['tools', 'tool set'],
35
+ ['model', 'model'],
36
+ ['engineVersion', 'engine version'],
37
+ ['mode', 'mode'],
38
+ ['profile', 'profile'],
39
+ ['key', 'base key'],
40
+ ];
41
+ for (const [field, label] of fields) {
42
+ if (miss[field] !== build[field])
43
+ differs.push(`${label}: base ${String(build[field])}, run ${String(miss[field])}`);
44
+ }
45
+ if (!differs.length) {
46
+ differs.push('no recorded setting differs; look for a session-start hook or other text that lands before the base ends, or a base past its lifetime');
47
+ }
48
+ return differs;
49
+ }
50
+ export function doctor(home, bar = loadConfig(home).bar) {
51
+ const claude = claudeStatus();
52
+ const agy = agyStatus();
53
+ const engines = [claude, agy, otherEngine('codex', process.env.FABER_CACHE_CODEX_BIN || 'codex')];
54
+ const measured = loadMeasured();
55
+ const records = readRecords(home);
56
+ const currentByEngine = {
57
+ claude: claude.installed ? claudeVersion() : null,
58
+ agy: agy.installed ? agyVersion() : null,
59
+ };
60
+ const modes = MODES.map(({ engine, mode, note }) => {
61
+ const m = measured[engine]?.[mode];
62
+ if (!m)
63
+ return { engine, mode, state: 'unmeasured', needsWarmup: null, breakEven: null, measuredOn: null, note };
64
+ let state = m.complete ? (m.readShare < bar ? 'no cache guarantee' : 'measured') : 'partly measured';
65
+ let why = m.note ?? note;
66
+ const current = currentByEngine[engine] ?? null;
67
+ const missOnNewVersion = records.some((r) => r.engine === engine && r.mode === mode && r.cacheMiss && r.engineVersion !== m.engineVersion);
68
+ if (current && major(current) !== major(m.engineVersion)) {
69
+ state = 're-check';
70
+ why = `measured on ${m.engineVersion}, now ${current} (new major version)`;
71
+ }
72
+ else if (missOnNewVersion) {
73
+ const v = records.filter((r) => r.engine === engine && r.mode === mode && r.cacheMiss && r.engineVersion !== m.engineVersion).pop();
74
+ state = 're-check';
75
+ why = `runs on ${v?.engineVersion} read under the bar; measured on ${m.engineVersion}`;
76
+ }
77
+ return { engine, mode, state, needsWarmup: m.needsWarmup, breakEven: breakEven(m), measuredOn: `${m.date}, ${m.engineVersion}`, note: why };
78
+ });
79
+ const misses = records
80
+ .filter((r) => r.cacheMiss)
81
+ .slice(-20)
82
+ .map((r) => ({ at: r.at, project: r.project, key: r.key, readShare: r.readShare, differs: explainMiss(r, records) }));
83
+ return { engines, settings: { excludeDynamicSystemPromptSections: excludeDynamicOn() }, modes, misses };
84
+ }