Skip to content

Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More

3.7 KB
Raw Blame
import type { Database } from 'bun:sqlite';
import { createHash } from 'node:crypto';
import { assertCanonicalDecimal } from './CanonicalContent.js';

export const RESTORE_CATCH_UP_KEY = 'restore_catch_up';

/**
 * The row kinds a restored database pulls back from this device's own pushes,
 * and the local table each one lives in. Own-device work_state and mutation
 * ops are not caught up: they stay ordinary push echoes.
 */
export const RESTORE_CATCH_UP_TABLES = {
  observation: 'observations',
  summary: 'session_summaries',
  prompt: 'user_prompts',
} as const;
export type RestoreCatchUpKind = keyof typeof RESTORE_CATCH_UP_TABLES;
const RESTORE_CATCH_UP_KINDS = Object.keys(RESTORE_CATCH_UP_TABLES) as RestoreCatchUpKind[];

export function isRestoreCatchUpKind(kind: string): kind is RestoreCatchUpKind {
  return Object.hasOwn(RESTORE_CATCH_UP_TABLES, kind);
}

export interface RestoreCatchUp {
  scope: string;
  /**
   * The snapshot's highest allocated row ID per kind. An own-device first
   * revision above it was created after the snapshot was taken.
   */
  idFloors: Record<RestoreCatchUpKind, string>;
  /** The first hub head seen after the restore; catch-up ends there. */
  through?: { epoch: string; headSeq: string };
}

export function restoreCatchUpScope(hubUrl: string, userId: string, deviceId: string): string | undefined {
  const hub = hubUrl.trim().replace(/\/+$/, '');
  if (hub && userId && deviceId) {
    return createHash('sha256').update(JSON.stringify([hub, userId, deviceId])).digest('hex');
  }
}

/** Record the snapshot's original ID floors before carrying the live counters. */
export function stageRestoreCatchUp(db: Database, scope: string | undefined): void {
  // Legacy databases predating Cloud Sync have no pull state to resume.
  if (!db.query("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'sync_state'").get()) return;
  if (!scope) {
    db.run('DELETE FROM sync_state WHERE k = ?', [RESTORE_CATCH_UP_KEY]);
    return;
  }
  const readFloor = db.query('SELECT CAST(seq AS TEXT) AS id FROM sqlite_sequence WHERE name = ?');
  const idFloors = Object.fromEntries(RESTORE_CATCH_UP_KINDS.map(kind => {
    const row = readFloor.get(RESTORE_CATCH_UP_TABLES[kind]) as { id: string } | null;
    return [kind, assertCanonicalDecimal(row?.id ?? '0')];
  })) as RestoreCatchUp['idFloors'];
  const state: RestoreCatchUp = { scope, idFloors };
  db.run('INSERT OR REPLACE INTO sync_state (k, v) VALUES (?, ?)', [RESTORE_CATCH_UP_KEY, JSON.stringify(state)]);
}

function isCanonicalDecimal(value: unknown): value is string {
  try {
    assertCanonicalDecimal(value);
    return true;
  } catch {
    return false;
  }
}

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === 'object' && value !== null && !Array.isArray(value);
}

/** The stored marker, or null when it is not a shape this version writes. */
export function parseRestoreCatchUp(raw: string): RestoreCatchUp | null {
  let value: unknown;
  try {
    value = JSON.parse(raw);
  } catch {
    return null;
  }
  if (!isRecord(value) || typeof value.scope !== 'string' || !isRecord(value.idFloors)) return null;
  const floors = value.idFloors;
  if (!RESTORE_CATCH_UP_KINDS.every(kind => isCanonicalDecimal(floors[kind]))) return null;
  const idFloors = Object.fromEntries(RESTORE_CATCH_UP_KINDS.map(kind => [kind, floors[kind]])) as RestoreCatchUp['idFloors'];
  if (value.through === undefined) return { scope: value.scope, idFloors };
  const through = value.through;
  if (!isRecord(through) || typeof through.epoch !== 'string' || !isCanonicalDecimal(through.headSeq)) return null;
  return { scope: value.scope, idFloors, through: { epoch: through.epoch, headSeq: through.headSeq } };
}