Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,20 @@ All notable changes to codachi are documented here. This project follows
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and
[Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Fixed

- **Parallel sessions no longer re-roll each other's pet** — with two
Claude Code sessions open, each render from one replaced the other's
identity in the shared `state.json`, so pets changed species and
palette mid-session, `events.json` was cleared, and every switch
counted as a new session (inflating `totalSessions` and the tier).
`state.json` now keeps an entry per transcript path under `sessions`,
pruned after a day unseen, and uptime is credited per session. The
top-level fields still mirror the latest session, so older versions
and `codachi stats` read the file as before.

## [0.3.0] — 2026-04-18

### Added
Expand Down
124 changes: 124 additions & 0 deletions src/state.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ vi.mock('node:fs', () => ({
default: {
readFileSync: vi.fn(),
writeFileSync: vi.fn(),
renameSync: vi.fn(),
mkdirSync: vi.fn(),
},
}));
Expand Down Expand Up @@ -243,3 +244,126 @@ describe('tier upgrade detection', () => {
expect(mod.didTierUpgrade()).toBe(false);
});
});

describe('parallel sessions', () => {
// A tiny in-memory disk: atomicWrite writes a temp file then renames it.
let disk: Map<string, string>;

function useDisk(initial: Record<string, unknown> = {}) {
disk = new Map();
for (const [name, data] of Object.entries(initial)) {
disk.set(name, JSON.stringify(data));
}
const base = (p: unknown) => String(p).split('/').pop() as string;
mockReadFileSync.mockImplementation(((p: unknown) => {
const v = disk.get(base(p));
if (v === undefined) throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' });
return v;
}) as typeof fs.readFileSync);
vi.mocked(fs.writeFileSync).mockImplementation(((p: unknown, d: unknown) => {
disk.set(base(p), String(d));
}) as typeof fs.writeFileSync);
vi.mocked(fs.renameSync).mockImplementation(((from: unknown, to: unknown) => {
disk.set(base(to), disk.get(base(from)) as string);
disk.delete(base(from));
}) as typeof fs.renameSync);
}

/** One statusline render, as its own process: fresh module state. */
async function render(transcript: string) {
vi.resetModules();
const m = await import('./state.js');
m.initSession(transcript);
return { animal: m.getSessionAnimalIndex(), palette: m.getSessionPaletteIndex() };
}

const read = (name: string) => JSON.parse(disk.get(name) as string);

it('keeps each session\'s pet and counts each session once', async () => {
useDisk();
const a1 = await render('/tmp/a');
const b1 = await render('/tmp/b');
for (let i = 0; i < 5; i++) {
expect(await render('/tmp/a')).toEqual(a1);
expect(await render('/tmp/b')).toEqual(b1);
}
expect(read('memory.json').totalSessions).toBe(2);
});

it('does not clear events when another session renders', async () => {
useDisk();
await render('/tmp/a');
await render('/tmp/b');
const { clearEvents } = await import('./events.js');
vi.mocked(clearEvents).mockClear();
await render('/tmp/a');
await render('/tmp/b');
expect(clearEvents).not.toHaveBeenCalled();
});

it('mirrors the latest new session at the top level for older readers', async () => {
useDisk();
await render('/tmp/a');
const b = await render('/tmp/b');
await render('/tmp/a');
const state = read('state.json');
expect(state.transcriptPath).toBe('/tmp/b');
expect(state.animalIndex).toBe(b.animal);
expect(state.paletteIndex).toBe(b.palette);
expect(Object.keys(state.sessions).sort()).toEqual(['/tmp/a', '/tmp/b']);
});

it('adopts a session from a file written by an older codachi', async () => {
useDisk({
'state.json': { version: 1, transcriptPath: '/tmp/a', sessionStart: Date.now() - 60000, animalIndex: 3, paletteIndex: 7 },
'memory.json': { version: 1, totalSessions: 4, totalUptimeMin: 0, firstMet: 1, lastSeen: 1 },
});
expect(await render('/tmp/a')).toEqual({ animal: 3, palette: 7 });
expect(read('memory.json').totalSessions).toBe(4);
});

it('credits an adopted older session\'s uptime when a new one starts', async () => {
useDisk({
'state.json': { version: 1, transcriptPath: '/tmp/a', sessionStart: Date.now() - 30 * 60000, animalIndex: 3, paletteIndex: 7 },
'memory.json': { version: 1, totalSessions: 4, totalUptimeMin: 10, firstMet: 1, lastSeen: 1 },
});
await render('/tmp/b');
const mem = read('memory.json');
expect(mem.totalSessions).toBe(5);
expect(mem.totalUptimeMin).toBe(40);
});

it('prunes sessions unseen for a day, crediting their uptime', async () => {
const day = 24 * 60 * 60 * 1000;
const stale = Date.now() - 2 * day;
useDisk({
'state.json': {
version: 1,
sessions: {
'/tmp/old': { sessionStart: stale - 90 * 60000, lastSeen: stale, creditedUntil: stale - 90 * 60000, animalIndex: 1, paletteIndex: 1 },
},
},
'memory.json': { version: 1, totalSessions: 1, totalUptimeMin: 0, firstMet: 1, lastSeen: 1 },
});
await render('/tmp/new');
expect(Object.keys(read('state.json').sessions)).toEqual(['/tmp/new']);
expect(read('memory.json').totalUptimeMin).toBe(90);
});

it('does not rewrite the file on every render of a known session', async () => {
useDisk();
await render('/tmp/a');
vi.mocked(fs.writeFileSync).mockClear();
await render('/tmp/a');
expect(fs.writeFileSync).not.toHaveBeenCalled();
});

it('ignores malformed session entries', async () => {
useDisk({
'state.json': { version: 1, sessions: { '/tmp/a': { animalIndex: 'x' }, '/tmp/b': null } },
});
await render('/tmp/a');
expect(read('memory.json').totalSessions).toBe(1);
expect(Object.keys(read('state.json').sessions)).toEqual(['/tmp/a']);
});
});
138 changes: 118 additions & 20 deletions src/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,39 @@ const STATE_SCHEMA_VERSION = 1;
const MEMORY_SCHEMA_VERSION = 1;

// ── Session state ────────────────────────────────────
//
// Several Claude Code sessions can render at once, and they all share this
// file, so each session's identity lives in its own entry of `sessions`,
// keyed by transcript path. The top-level fields mirror the most recently
// started session: they are what codachi wrote before `sessions` existed,
// so older versions and `codachi stats` keep reading them unchanged.

interface SessionEntry {
sessionStart: number;
/** Last render, refreshed at most once per SEEN_REFRESH_MS. */
lastSeen: number;
/** Up to when this session's uptime has been added to memory. */
creditedUntil: number;
animalIndex: number;
paletteIndex: number;
}

interface DiskState {
version?: number;
transcriptPath?: string;
sessionStart?: number;
animalIndex?: number;
paletteIndex?: number;
sessions?: Record<string, SessionEntry>;
}

/** Sessions not rendered for this long are pruned (and their uptime credited). */
const SESSION_TTL_MS = 24 * 60 * 60 * 1000;
/** Upper bound on remembered sessions, oldest by lastSeen dropped first. */
const MAX_SESSIONS = 50;
/** How stale lastSeen may get before a render rewrites the file. */
const SEEN_REFRESH_MS = 60 * 1000;

function loadJSON<T>(file: string): T | null {
try { return JSON.parse(fs.readFileSync(file, 'utf8')) as T; }
catch (err) {
Expand All @@ -46,24 +70,103 @@ function saveJSON(file: string, data: unknown): void {
}

let diskState: DiskState = {};
/** The entry for the session this process renders. */
let current: SessionEntry | null = null;

function isEntry(e: unknown): e is SessionEntry {
const o = e as SessionEntry;
return !!o && typeof o === 'object'
&& Number.isFinite(o.sessionStart) && Number.isFinite(o.lastSeen)
&& Number.isFinite(o.creditedUntil)
&& Number.isInteger(o.animalIndex) && Number.isInteger(o.paletteIndex);
}

/** The valid entries of a loaded file, adopting a pre-`sessions` top level. */
function loadSessions(state: DiskState): Record<string, SessionEntry> {
const out: Record<string, SessionEntry> = {};
const raw = state.sessions;
if (raw && typeof raw === 'object') {
for (const [k, e] of Object.entries(raw)) if (isEntry(e)) out[k] = e;
}
// A file from an older codachi (or rewritten by one) carries its session
// only at the top level; keep that session's identity rather than re-roll.
const tp = state.transcriptPath;
if (tp && !out[tp] && Number.isFinite(state.sessionStart)
&& Number.isInteger(state.animalIndex) && Number.isInteger(state.paletteIndex)) {
const start = state.sessionStart as number;
out[tp] = {
sessionStart: start,
lastSeen: Date.now(),
// Nothing has credited this session's uptime yet: an older codachi
// only does that when the next session starts.
creditedUntil: start,
animalIndex: state.animalIndex as number,
paletteIndex: state.paletteIndex as number,
};
}
return out;
}

/** Add a session's not-yet-credited uptime to memory, in whole minutes. */
function creditUptime(m: PetMemory, e: SessionEntry): void {
const mins = Math.floor((e.lastSeen - e.creditedUntil) / 60000);
if (mins > 0) {
m.totalUptimeMin += mins;
e.creditedUntil += mins * 60000;
}
}

/** Drop sessions unseen for SESSION_TTL_MS, then the oldest beyond MAX_SESSIONS. */
function pruneSessions(sessions: Record<string, SessionEntry>, m: PetMemory, now: number): void {
for (const [k, e] of Object.entries(sessions)) {
if (now - e.lastSeen > SESSION_TTL_MS) {
creditUptime(m, e);
delete sessions[k];
}
}
const keys = Object.keys(sessions).sort((a, b) => sessions[a].lastSeen - sessions[b].lastSeen);
for (const k of keys.slice(0, Math.max(0, keys.length - MAX_SESSIONS))) {
creditUptime(m, sessions[k]);
delete sessions[k];
}
}

export function initSession(transcriptPath?: string): void {
diskState = migrateState(loadJSON<DiskState>(STATE_FILE));
const isSameSession = transcriptPath && diskState.transcriptPath === transcriptPath;
const sessions = loadSessions(diskState);
const now = Date.now();
const key = transcriptPath ?? '';
const existing = transcriptPath ? sessions[key] : undefined;

if (!isSameSession) {
// New session: update memory, reset state, clear stale events
updateMemory();
clearEvents();
diskState = {
version: STATE_SCHEMA_VERSION,
transcriptPath: transcriptPath ?? '',
sessionStart: Date.now(),
if (existing) {
current = existing;
if (now - existing.lastSeen < SEEN_REFRESH_MS && diskState.sessions) return;
existing.lastSeen = now;
} else {
// A session this file has never seen: count it, give it an identity,
// and clear stale events. Other sessions' entries are left alone.
const m = loadMemory();
for (const e of Object.values(sessions)) creditUptime(m, e);
pruneSessions(sessions, m, now);
countSession(m);
current = {
sessionStart: now,
lastSeen: now,
creditedUntil: now,
animalIndex: Math.floor(Math.random() * 5),
paletteIndex: Math.floor(Math.random() * 10),
};
saveJSON(STATE_FILE, diskState);
sessions[key] = current;
clearEvents();
diskState = {
transcriptPath: key,
sessionStart: current.sessionStart,
animalIndex: current.animalIndex,
paletteIndex: current.paletteIndex,
};
}
diskState = { ...diskState, version: STATE_SCHEMA_VERSION, sessions };
saveJSON(STATE_FILE, diskState);
}

/** Forward-compatible state loader. Unknown/future versions fall back to defaults. */
Expand All @@ -81,16 +184,16 @@ function migrateState(raw: DiskState | null): DiskState {
return raw;
}

export function getSessionAnimalIndex(): number { return diskState.animalIndex ?? 0; }
export function getSessionPaletteIndex(): number { return diskState.paletteIndex ?? 0; }
export function getSessionAnimalIndex(): number { return current?.animalIndex ?? 0; }
export function getSessionPaletteIndex(): number { return current?.paletteIndex ?? 0; }

export function animTick(speedSec: number = 1.5): number {
return Math.floor(Date.now() / (speedSec * 1000));
}
export function moodTick(): number { return Math.floor(Date.now() / 10000); }

export function sessionUptime(): string {
const start = diskState.sessionStart ?? Date.now();
const start = current?.sessionStart ?? Date.now();
const ms = Date.now() - start;
const mins = Math.floor(ms / 60000);
if (mins < 1) return '<1m';
Expand Down Expand Up @@ -182,15 +285,10 @@ function loadMemory(): PetMemory {
};
}

function updateMemory(): void {
// Called when a NEW session starts — save stats from previous session
const m = loadMemory();
/** Count one new session in memory (already loaded and credited) and save it. */
function countSession(m: PetMemory): void {
m.totalSessions += 1;
m.lastSeen = Date.now();
// Uptime from previous session (approximate)
if (diskState.sessionStart) {
m.totalUptimeMin += Math.floor((Date.now() - diskState.sessionStart) / 60000);
}

// Check for tier upgrade
const oldTier = m.lastShownTier ?? 'stranger';
Expand Down