@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,42 @@
1
+ export interface BaseEntry {
2
+ key: string;
3
+ project: string;
4
+ profile: string;
5
+ mode: string;
6
+ engine: string;
7
+ engineVersion: string;
8
+ model: string;
9
+ baseSession: string;
10
+ /** The session tasks fork: the warm-up when the mode needs one, else null (fork the base). */
11
+ warmSession: string | null;
12
+ created: number;
13
+ lastRead: number;
14
+ uses: number;
15
+ /** The reference first-request prefix for the read share (FR-09.2). */
16
+ refPrefix: number;
17
+ /** What the key was made of, for `doctor` (FR-09.4). */
18
+ parts: Record<string, unknown>;
19
+ }
20
+ interface RegistryFile {
21
+ bases: Record<string, BaseEntry>;
22
+ /** First no-base call per key, for the second-call rule (FR-04.4). */
23
+ seen: Record<string, number>;
24
+ }
25
+ /** The host-local registry (FR-03.1), written atomically under its own lock. */
26
+ export declare class Registry {
27
+ readonly home: string;
28
+ readonly file: string;
29
+ readonly lockFile: string;
30
+ constructor(home: string);
31
+ keyLock(key: string): string;
32
+ load(): RegistryFile;
33
+ get(key: string): BaseEntry | undefined;
34
+ private update;
35
+ put(entry: BaseEntry): void;
36
+ touch(key: string, now: number, used?: boolean): void;
37
+ /** Replace an entry the engine can no longer resume; the next build overwrites it. */
38
+ forget(key: string): void;
39
+ markSeen(key: string, now: number): void;
40
+ seenAt(key: string): number | undefined;
41
+ }
42
+ export {};
@@ -0,0 +1,69 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import { withLockSync } from './lock.js';
4
+ /** The host-local registry (FR-03.1), written atomically under its own lock. */
5
+ export class Registry {
6
+ home;
7
+ file;
8
+ lockFile;
9
+ constructor(home) {
10
+ this.home = home;
11
+ this.file = path.join(home, 'registry.json');
12
+ this.lockFile = path.join(home, 'locks', 'registry.lock');
13
+ }
14
+ keyLock(key) {
15
+ return path.join(this.home, 'locks', `${key}.lock`);
16
+ }
17
+ load() {
18
+ try {
19
+ const raw = JSON.parse(fs.readFileSync(this.file, 'utf8'));
20
+ return { bases: raw.bases ?? {}, seen: raw.seen ?? {} };
21
+ }
22
+ catch {
23
+ return { bases: {}, seen: {} };
24
+ }
25
+ }
26
+ get(key) {
27
+ return this.load().bases[key];
28
+ }
29
+ update(change) {
30
+ withLockSync(this.lockFile, () => {
31
+ const data = this.load();
32
+ change(data);
33
+ fs.mkdirSync(this.home, { recursive: true });
34
+ const tmp = `${this.file}.${process.pid}.tmp`;
35
+ fs.writeFileSync(tmp, JSON.stringify(data, null, 1) + '\n');
36
+ fs.renameSync(tmp, this.file);
37
+ });
38
+ }
39
+ put(entry) {
40
+ this.update((d) => {
41
+ d.bases[entry.key] = entry;
42
+ delete d.seen[entry.key];
43
+ });
44
+ }
45
+ touch(key, now, used = true) {
46
+ this.update((d) => {
47
+ const e = d.bases[key];
48
+ if (!e)
49
+ return;
50
+ e.lastRead = now;
51
+ if (used)
52
+ e.uses += 1;
53
+ });
54
+ }
55
+ /** Replace an entry the engine can no longer resume; the next build overwrites it. */
56
+ forget(key) {
57
+ this.update((d) => {
58
+ delete d.bases[key];
59
+ });
60
+ }
61
+ markSeen(key, now) {
62
+ this.update((d) => {
63
+ d.seen[key] = now;
64
+ });
65
+ }
66
+ seenAt(key) {
67
+ return this.load().seen[key];
68
+ }
69
+ }
@@ -0,0 +1,31 @@
1
+ export interface StatsRow {
2
+ project: string;
3
+ profile: string;
4
+ engine: string;
5
+ mode: string;
6
+ runs: number;
7
+ runsWithBase: number;
8
+ meanReadShare: number | null;
9
+ underBar: number;
10
+ builds: number;
11
+ buildCacheWrite: number;
12
+ warmups: number;
13
+ warmupCacheWrite: number;
14
+ /** Stable-part tokens read from cache instead of sent fresh (FR-09.3). */
15
+ savedTokens: number;
16
+ /** What the group cost, in input-token equivalents: builds, warm-ups and runs. */
17
+ paidEquivalents: number;
18
+ /** Conservative saving against sending the context fresh to every run, net of builds and warm-ups. */
19
+ savedEquivalents: number;
20
+ /** savedEquivalents / (paid + saved); null with no fork. */
21
+ savedShare: number | null;
22
+ /** Dollars, priced from the engine's own cost of the runs that resume nothing; null when unknown. */
23
+ paidUsd: number | null;
24
+ savedUsd: number | null;
25
+ }
26
+ export declare function computeStats(home: string, opts?: {
27
+ project?: string;
28
+ since?: string;
29
+ }): StatsRow[];
30
+ /** The plain-language stats block for one project, profile, engine and mode. */
31
+ export declare function formatStatsRow(r: StatsRow): string;
@@ -0,0 +1,91 @@
1
+ import { readRecords } from './records.js';
2
+ import { resolveProject } from './config.js';
3
+ import { forkSaving, inputEquivalents, usdPerEquivalent } from './cost.js';
4
+ export function computeStats(home, opts = {}) {
5
+ const project = opts.project ? resolveProject(opts.project) : undefined;
6
+ const since = opts.since ? Date.parse(opts.since) : undefined;
7
+ if (opts.since && Number.isNaN(since))
8
+ throw new Error(`--since: not a date: ${opts.since}`);
9
+ const groups = new Map();
10
+ for (const r of readRecords(home)) {
11
+ if (project && r.project !== project)
12
+ continue;
13
+ if (since !== undefined && Date.parse(r.at) < since)
14
+ continue;
15
+ const g = [r.project, r.profile, r.engine, r.mode].join('\u0000');
16
+ const list = groups.get(g) ?? [];
17
+ list.push(r);
18
+ groups.set(g, list);
19
+ }
20
+ const rows = [];
21
+ for (const list of groups.values()) {
22
+ const runs = list.filter((r) => r.kind === 'run');
23
+ const withBase = runs.filter((r) => (r.base === 'with-base' || r.base === 'prefix') && r.readShare !== null && r.outcome === 'ok');
24
+ const builds = list.filter((r) => r.kind === 'build' && r.outcome === 'ok');
25
+ const warmups = list.filter((r) => r.kind === 'warmup');
26
+ const head = list[0];
27
+ const paid = list.reduce((n, r) => n + inputEquivalents(r.total), 0);
28
+ const overhead = [...builds, ...warmups].reduce((n, r) => n + inputEquivalents(r.total), 0);
29
+ const forks = runs.filter((r) => r.base === 'with-base' && r.outcome === 'ok');
30
+ const saved = forks.length ? forks.reduce((n, r) => n + forkSaving(r), 0) - overhead : 0;
31
+ const rate = usdPerEquivalent(list);
32
+ rows.push({
33
+ project: head.project,
34
+ profile: head.profile,
35
+ engine: head.engine,
36
+ mode: head.mode,
37
+ runs: runs.length,
38
+ runsWithBase: withBase.length,
39
+ meanReadShare: withBase.length ? round3(withBase.reduce((n, r) => n + (r.readShare ?? 0), 0) / withBase.length) : null,
40
+ underBar: runs.filter((r) => r.cacheMiss).length,
41
+ builds: builds.length,
42
+ buildCacheWrite: builds.reduce((n, r) => n + (r.first?.cacheWrite ?? 0), 0),
43
+ warmups: warmups.length,
44
+ warmupCacheWrite: warmups.reduce((n, r) => n + (r.first?.cacheWrite ?? 0), 0),
45
+ savedTokens: withBase.reduce((n, r) => n + (r.first?.cacheRead ?? 0), 0),
46
+ paidEquivalents: Math.round(paid),
47
+ savedEquivalents: Math.round(saved),
48
+ savedShare: forks.length && paid + saved > 0 ? round3(saved / (paid + saved)) : null,
49
+ paidUsd: rate === null ? null : round4(paid * rate),
50
+ savedUsd: rate === null || !forks.length ? null : round4(saved * rate),
51
+ });
52
+ }
53
+ return rows.sort((a, b) => a.project.localeCompare(b.project) || a.profile.localeCompare(b.profile));
54
+ }
55
+ function round3(x) {
56
+ return Math.round(x * 1000) / 1000;
57
+ }
58
+ function round4(x) {
59
+ return Math.round(x * 10000) / 10000;
60
+ }
61
+ function plural(n, word) {
62
+ return `${n} ${word}${n === 1 ? '' : 's'}`;
63
+ }
64
+ function short(n) {
65
+ return n >= 10_000 ? `${Math.round(n / 1000)}K` : String(Math.round(n));
66
+ }
67
+ function dollars(n) {
68
+ return `$${n.toFixed(Math.abs(n) < 1 ? 4 : 2)}`;
69
+ }
70
+ /** The plain-language stats block for one project, profile, engine and mode. */
71
+ export function formatStatsRow(r) {
72
+ const share = r.meanReadShare === null ? 'n/a' : `${Math.round(r.meanReadShare * 100)}%`;
73
+ const lines = [
74
+ `${r.project} (${r.engine}, ${r.mode} mode, ${r.profile} profile)`,
75
+ ` runs: ${r.runs}, ${r.runsWithBase} of them started from the warm base; ${plural(r.builds, 'base build')}, ${plural(r.warmups, 'warm-up')}`,
76
+ ` cache: on average a run read ${share} of its project context from cache` +
77
+ (r.underBar ? `; ${r.underBar} read less than expected (faber-cache doctor says why)` : ''),
78
+ ];
79
+ const paid = r.paidUsd === null ? `${short(r.paidEquivalents)} input-token equivalents` : dollars(r.paidUsd);
80
+ if (r.savedShare === null) {
81
+ lines.push(` cost: paid ${paid}; no run has started from a base yet, so nothing saved`);
82
+ }
83
+ else if (r.savedEquivalents <= 0) {
84
+ lines.push(` cost: paid ${paid}; too few runs per base so far to pay back building it`);
85
+ }
86
+ else {
87
+ const saved = r.savedUsd === null ? `${short(r.savedEquivalents)} input-token equivalents` : dollars(r.savedUsd);
88
+ lines.push(` saved: at least ${saved} (${Math.round(r.savedShare * 100)}%) against sending the context fresh to every run; paid ${paid}`);
89
+ }
90
+ return lines.join('\n');
91
+ }
@@ -0,0 +1,2 @@
1
+ /** The installed package version, read from package.json (dist/src/ -> ../../package.json). */
2
+ export declare function getPackageVersion(): string;
@@ -0,0 +1,22 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ let cached;
5
+ /** The installed package version, read from package.json (dist/src/ -> ../../package.json). */
6
+ export function getPackageVersion() {
7
+ if (cached)
8
+ return cached;
9
+ try {
10
+ const here = path.dirname(fileURLToPath(import.meta.url));
11
+ const raw = JSON.parse(fs.readFileSync(path.resolve(here, '../../package.json'), 'utf8'));
12
+ if (typeof raw.version === 'string' && raw.version.trim()) {
13
+ cached = raw.version.trim();
14
+ return cached;
15
+ }
16
+ }
17
+ catch {
18
+ // Fallback below
19
+ }
20
+ cached = '0.0.0';
21
+ return cached;
22
+ }
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@fabersep/cache",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "private": false,
5
+ "description": "Pay for your project's context once, not once per Claude Code session: a warm base session and a fork per task.",
6
+ "license": "Apache-2.0",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/fabersep/cache.git"
10
+ },
11
+ "homepage": "https://github.com/fabersep/cache#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/fabersep/cache/issues"
14
+ },
15
+ "keywords": ["fabersep", "ai-agents", "prompt-caching", "claude-code", "mcp", "fork"],
16
+ "type": "module",
17
+ "bin": {
18
+ "faber-cache": "dist/src/cli.js"
19
+ },
20
+ "exports": {
21
+ ".": "./dist/src/index.js"
22
+ },
23
+ "files": ["dist/src", "data", "LICENSE", "README.md"],
24
+ "engines": {
25
+ "node": ">=20"
26
+ },
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "scripts": {
31
+ "build": "tsc -p tsconfig.json",
32
+ "prepublishOnly": "npm run build",
33
+ "test": "npm run build && node --test dist/test/*.test.js",
34
+ "bench": "npm run build && node bench/ab.mjs"
35
+ },
36
+ "devDependencies": {
37
+ "@types/node": "^22.10.2",
38
+ "typescript": "^5.8.3"
39
+ }
40
+ }