/** * Session persistence — appends each event in `session.log` to a * per-session JSONL file under `~/.moxxy/sessions/`, and maintains an * `index.json` of session metadata so `moxxy resume` can list and * pick a prior session without scanning every event file. * * Layout: * ~/.moxxy/sessions/ * .json per-session metadata sidecar (one per session) * .jsonl one MoxxyEvent per line * * Each session writes only its OWN `.json` sidecar (write-temp-rename), so * two concurrent moxxy processes can't drop each other's row the way a shared * `index.json` read-modify-write would. `readIndex` assembles the sidecars (and * a legacy `index.json`, if present, for back-compat). JSONL appends are * best-effort (lose at most the last in-flight event on a crash). */ import { type MoxxyEvent, type SessionId } from '@moxxy/sdk'; import type { EventLogLike, EventPage, SessionMeta, SessionSource } from '@moxxy/sdk'; import { type Logger } from '../logger.js'; export type { EventLogLike, EventPage, SessionMeta, SessionSource } from '@moxxy/sdk'; export { SESSION_SOURCES } from '@moxxy/sdk'; /** Schema version of the per-session metadata file (`.json`). Bump when the * shape changes incompatibly; readers tolerate a missing/older version. */ export declare const SESSION_META_VERSION = 1; export interface SessionPersistenceOpts { readonly sessionId: SessionId; readonly cwd: string; /** Override the storage root. Defaults to `~/.moxxy/sessions`. */ readonly dir?: string; /** Currently-active provider name — captured into the index for the picker. */ readonly providerName?: string; /** Currently-active model id — captured into the index for the picker. */ readonly modelId?: string; /** Originating channel — persisted into the sidecar so the workspace list can * be derived from a single source (see {@link SessionSource}). */ readonly source?: SessionSource; /** * Structured logger for persistence-degradation warnings. Defaults to a * stderr JSON logger — event-log write failures are the session's source * of truth going dark, so they must be loud even when nothing injects one. */ readonly logger?: Logger; } export declare function defaultSessionsDir(): string; /** * Attaches a listener that streams every appended event to disk and * keeps the index in sync. Returns an `unsubscribe` callback the * caller should run on shutdown. */ export declare class SessionPersistence { private readonly dir; private readonly id; private readonly logPath; private meta; private indexUpdateScheduled; /** Handle for the in-flight debounce timer, so `flush()` can cancel it. */ private indexTimer; /** * In-flight writes are serialized through this mutex so the file * stays append-ordered even when events arrive faster than the disk * can flush. */ private writeQueue; /** * Single-flight guard for the sidecar (`writeIndex`) write. The debounced * timer and an explicit `flush()` can both call `writeIndex()` concurrently; * without serialization two `writeFileAtomic`s would race on `metaPath` and * the on-disk result would be last-rename-wins between two `this.meta` * snapshots non-deterministically. Chaining them makes the latest meta win * deterministically and drops the redundant work. */ private indexWriteChain; /** * Memoized one-time setup: `mkdir -p` the sessions dir and create the empty * `.jsonl` (so resume lists the session before any event). Awaited by both * `attach` and `writeIndex` so an early debounced index flush can't race the * initial creation — but it runs the open+close syscalls ONCE, not on every * 250ms flush as before. */ private ready; private closed; private readonly logger; /** * Latched while event-log writes are failing. Doubles as the warn-once * gate: only the first failure of a streak logs; a subsequent successful * write clears the latch (and re-arms the warning). */ private writeDegraded; constructor(opts: SessionPersistenceOpts); /** * Subscribe to the log; returns the unsubscribe callback. The first * call also writes the initial index row so `moxxy resume` lists * the session before any events arrive. * * Also subscribes to the log's `clear()`, truncating the JSONL in * lockstep so a `/new` wipe can't resurrect on `--resume`. The * session keeps its id and file: post-reset events restart at seq 0 * in the same (now empty) JSONL, matching how the in-memory log * reuses the same Session object. */ attach(log: EventLogLike): () => void; /** * Force the pending (debounced) index write to happen now and resolve once * the meta sidecar is on disk. Cancels the in-flight debounce timer so the * write isn't also re-run on its original schedule. Intended for awaitable * shutdown: `detach()` only *schedules* the final write (an `unref`'d timer * an immediate `process.exit` can drop), whereas `await flush()` guarantees * it completed. The steady-state debounce in `scheduleIndexWrite` is * untouched, so calling this mid-session just collapses the next write early. */ flush(): Promise; /** * Resolve once every event-log write queued so far has settled. Appends are * enqueued fire-and-forget (`enqueueAppend`), so callers that need to observe * the on-disk result of prior appends — graceful shutdown, or a test that * mutates the filesystem between writes — await this to drain the queue * rather than guessing at timing. Enqueues a no-op at the tail of the same * mutex, so it can only resolve after all earlier appends/truncates have run. */ settleWrites(): Promise; /** * Manually update header fields (provider/model) when the user * switches mid-session. The /model picker calls this so the index * reflects the active model when the session is resumed. */ updateHeader(patch: { providerName?: string; modelId?: string; }): void; private enqueueAppend; /** * True while event-log writes are failing (history is no longer being * persisted). Cleared automatically by the next successful write. */ get degraded(): boolean; private noteWriteOk; private noteWriteFailure; /** * Mirror a `log.clear()` on disk: truncate the JSONL and reset the * sidecar's counters. Rides the same write queue as appends, so * pre-clear appends flush first and post-clear appends land in the * fresh (empty) file — ordering matches the in-memory log exactly. */ private enqueueTruncate; private scheduleIndexWrite; /** * Serialize the sidecar write through `indexWriteChain` so a debounced write * and a concurrent `flush()` never race on `metaPath`; resolves once THIS * call's write (or a later one that supersedes it) has settled. */ private writeIndex; private doWriteIndex; /** One-time, memoized: `mkdir -p` the dir + create the empty `.jsonl`, then * ADOPT a pre-existing file's stable identity: `startedAt` (so the derived * "created" time doesn't jump on every resume), `source` (when the caller * didn't pass one), and the UI-owned `title`/`groupId` (so the first runner * write doesn't drop a rename/move made while no runner was attached). On * failure the latch is cleared so a later flush retries. */ private ensureReady; private applyLogStats; } /** * Read the session index by assembling per-session metadata files (`.json`), * then hydrating each one's first prompt from its `.jsonl`. Sessions whose * `.jsonl` is missing are dropped. Sorted most-recent-activity first. This is the * heavier, jsonl-hydrated read used by `moxxy resume`; the workspace list uses * the cheap {@link listSessionMetas} instead. */ export declare function readIndex(dir?: string): Promise; /** * The {@link readIndex} row of ONE session, or null when the index has none. * Reads every small metadata file (so duplicates resolve exactly as in the * index) but only this session's event log, never the other sessions' logs: * opening one conversation must not cost the whole history on disk. */ export declare function readSessionMeta(sessionId: string, dir?: string): Promise; /** * Restore a previously-persisted session's events. Returns the full * event array suitable for passing into `new EventLog(events)`. * * Skips malformed lines — corrupt JSON and valid-JSON-but-wrong-shape * alike (see {@link isMoxxyEventShape}); a single bad append shouldn't * make the rest of the conversation unreadable — and then RE-SEQUENCES * the survivors to contiguous `seq` 0..n-1, preserving order and ids. * This matters twice over: * * - Mirror replay: `EventLog.ingest` accepts only `seq === length`, so * a gap left by one corrupt middle line would silently truncate every * attached client's history at that point. * - Future appends: `EventLog.append` mints `seq = events.length`, so a * gapped seed would mint colliding/out-of-order seqs. * * When anything was skipped or re-sequenced, the file is atomically * rewritten with the repaired events so the NEXT resume starts clean — * otherwise post-resume appends (seq = n-gap..) would interleave with the * stale higher on-disk seqs forever. Safe ordering-wise: restore runs * before `SessionPersistence.attach`, so no append queue is live yet. * Note: compaction/elision events referencing seqs after a gap shift by * the gap size — an accepted, logged trade-off versus losing all * post-gap history. */ export declare function restoreEvents(sessionId: string, dir?: string, logger?: Logger): Promise; /** * Read ONE page of a persisted session's events without re-materializing the * whole conversation into a live {@link EventLog}. Backs the runner's * `session.loadHistory` so a thin client (the desktop) can page history from * the runner's authoritative JSONL instead of its own NDJSON mirror. * * Paging is newest-first, walking backwards: * - `before == null` — the NEWEST page: the last `limit` events on disk. * - `before == N` — the page of (up to) `limit` events strictly OLDER than * `seq === N` (the events immediately preceding the cursor). Pass the * previous page's `prevCursor` here to step one page further back. * * The returned `events` are always in ascending `seq` order (oldest-first * WITHIN the page) so a caller can prepend a page to an in-order transcript. * `prevCursor` is the `seq` of the page's oldest event, or `null` once the * first persisted event is included (no older page remains). * * Corrupt and wrong-shape lines are skipped (matching {@link restoreEvents}); unlike * `restoreEvents` this is a READ-ONLY reader — it never rewrites the file, so * it preserves the JSONL exactly (no atomic-write / mutex needed: there is no * mutation). Paging keys on each event's on-disk `seq`. Determinism holds for a * MONOTONICALLY-INCREASING seq sequence — including a gapped-but-increasing one * (the append path guarantees this; the next resume re-sequences to contiguous * 0..n-1 anyway). DUPLICATE / non-strictly-increasing seqs are only reachable * via external file corruption, and a backward `prevCursor` walk over them can * drop events page-size-dependently until that next resume repairs the log. * * A missing log file is treated as an EMPTY history (`{ events: [], prevCursor: * null }`), not an error — a freshly-created session whose JSONL hasn't been * written yet must page as empty rather than throw. */ export declare function readEventPage(sessionId: string, opts: { before: number | null; limit: number; }, dir?: string): Promise; /** * Slice one newest-first page out of an ascending-`seq` event array. Pure + * exported so the runner can reuse the EXACT paging semantics when it serves a * page out of its in-memory log instead of disk — the two paths must agree * byte-for-byte or a client crossing between them (in-memory → disk fallback) * would see a discontinuity. `events` MUST be ordered oldest-first (the on-disk * / append order); `before`/`limit` follow {@link readEventPage}. */ export declare function pageEvents(events: ReadonlyArray, before: number | null, limit: number): EventPage; /** * Seed a session's event log from an external event list IFF the session has no * log on disk yet. This is the migration that makes the runner's authoritative * log the home of a chat whose history previously lived ONLY in a thin client's * own mirror (the desktop's NDJSON chat store) — after it runs, `loadHistory` * serves that chat from the runner like any other. * * Idempotent and NON-destructive: if `.jsonl` already exists AND is * NON-EMPTY this is a no-op returning `false`, so a session the runner already * owns is NEVER overwritten. A 0-byte log IS seeded: `persistence.attach` * creates an empty `.jsonl` on every spawn (even a session with zero * events), so an existence-only guard would skip exactly the legacy chats this * migration targets — and an empty file holds no history, so seeding over it * loses nothing. Events are re-sequenced to contiguous `seq` 0..n-1 (order + ids * preserved) so the seeded log satisfies {@link EventLog}'s seq invariants when * it is later restored. Written temp+rename so a crash mid-seed can't leave a * half-written log. Returns `true` iff it wrote the log. */ export declare function seedSessionLog(sessionId: string, events: ReadonlyArray, dir?: string): Promise; /** * Remove a session entirely: its event log (`.jsonl`) and its single * metadata file (`.json`). This is the SINGLE deletion mechanism — a session * exists iff its `.json` does, so erasing it removes the session from every * surface's derived list with no second copy to resurrect it. */ export declare function deleteSession(sessionId: string, dir?: string): Promise; /** Persist (or clear, when blank) a user-set session title — the rename path. */ export declare function setSessionTitle(sessionId: string, title: string, dir?: string): Promise; /** Persist (or clear, when null) a session's explicit desk/workspace membership. */ export declare function setSessionGroup(sessionId: string, groupId: string | null, dir?: string): Promise; /** * Seed a session's `.json` (+ empty `.jsonl`) so a freshly-created session * appears in the derived workspace list IMMEDIATELY, before its runner spawns * and attaches. Idempotent: if a metadata file already exists this is a no-op, * so it never clobbers a live session. The runner adopts the seeded * `startedAt`/`source`/`groupId`/`title` on attach. */ export declare function seedSessionMeta(sessionId: string, cwd: string, source: SessionSource, dir?: string, groupId?: string | null): Promise; export interface ListSessionMetasOptions { readonly hydrateStale?: boolean; } /** * List every session from its `.json` sidecar (mtime-cached). By default * this is the cheap read the workspace list/search can call frequently. Callers * that need to survive stale legacy sidecars can opt into targeted `.jsonl` * hydration for rows whose counters/name seed are empty. */ export declare function listSessionMetas(dir?: string, opts?: ListSessionMetasOptions): Promise; //# sourceMappingURL=persistence.d.ts.map