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

24.0 KB
Raw Blame
import { projectScopeSql, scopedProjects } from './project-read-keys.js';
// Durable raw tool-use rows (schema v51; platform-qualified identity v75).
//
// `pending_messages` is the GENERATION QUEUE: rows are claimed, fed to the
// observer, then deleted. Nothing durable survives it, so raw tool I/O was
// unrecoverable once an observation had been written. `tool_uses` is the
// backup/side index for that same payload — written from the SAME ingest
// choke point (`ingestObservation`), never a second capture path, so the
// transcript-watch JSONL spine stays authoritative for transcripts and this
// table stays a progressive-disclosure side index for tool bodies.
//
// Receipt freeze 2026-09-06: this table carries tool IDENTITY only. Dollars
// live on OpenRouter call-time stamps / the Receipt spend log. `or_generation_id`
// and `or_session_id` are nullable JOIN keys back to those lines — never a
// `cost_usd` / micros column here. See docs/receipt-join.md.
import { Database } from 'bun:sqlite';
import { createHash } from 'crypto';
import { logger } from '../../utils/logger.js';
import { DEFAULT_PLATFORM_SOURCE, normalizePlatformSource } from '../../shared/platform-source.js';
import { isRecursiveMemoryTool } from '../../shared/memory-retrieval-tools.js';
export { isRecursiveMemoryTool } from '../../shared/memory-retrieval-tools.js';

/**
 * Soft cap per stored payload field. The Pro hook envelope already truncates
 * `tool_input` / `tool_response` to 16 KB each on the wire
 * (`cowork/PRO-ENDPOINT-SPEC.md`), but the local worker path does not, and a
 * single Read of a large file would otherwise pin megabytes into a table that
 * — unlike `pending_messages` — is never drained. 64 KB keeps the in-row shape
 * the plan asked for (no blob sidecar) while bounding growth.
 *
 * Truncated values get a `…[truncated: N bytes]` marker so a reader can tell a
 * clipped payload from one that legitimately ends there. A truncated value is
 * NOT valid JSON any more; `get_tool_uses` consumers must tolerate that.
 */
export const MAX_TOOL_PAYLOAD_BYTES = 64 * 1024;

/**
 * claude-mem's own read tools, which must never be backed up into this table.
 *
 * `get_tool_uses` RETURNS raw tool bodies. Recording its own PostToolUse would
 * store those bodies a second time, and disclosing them again would store them
 * a third — the table grows with every read instead of every tool call. The
 * other layers are gated for the same reason at a smaller scale.
 *
 * The same lightweight classifier gates hook/ingest observation generation:
 * retrieval must not create a new paid observation of its own previous output.
 * OpenClaw already drops `memory_*` before it ever reaches the worker
 * (`openclaw/src/index.ts:802`); the prefix is mirrored here so every other
 * adapter gets the same protection.
 */
export interface ToolUseRow {
  id: number;
  tool_use_id: string;
  content_session_id: string;
  memory_session_id: string | null;
  session_db_id: number | null;
  project: string;
  platform_source: string;
  tool_name: string;
  tool_input: string | null;
  tool_response: string | null;
  cwd: string | null;
  prompt_number: number | null;
  agent_type: string | null;
  agent_id: string | null;
  observation_id: number | null;
  or_generation_id: string | null;
  or_session_id: string | null;
  content_hash: string | null;
  created_at: string;
  created_at_epoch: number;
}

/** Metadata disclosed before a caller chooses which raw tool bodies to read. */
export type ToolUseIndexRow = Pick<ToolUseRow,
  'id' | 'tool_use_id' | 'tool_name' | 'project' | 'content_session_id' |
  'memory_session_id' | 'platform_source' | 'agent_id' | 'agent_type' |
  'observation_id' | 'or_generation_id' | 'or_session_id' | 'prompt_number' |
  'created_at' | 'created_at_epoch'> & {
    tool_input_bytes: number;
    tool_response_bytes: number;
  };

export interface UpsertToolUseInput {
  toolUseId: string;
  contentSessionId: string;
  sessionDbId?: number | null;
  memorySessionId?: string | null;
  project: string;
  platformSource?: string;
  toolName: string;
  toolInput?: string | null;
  toolResponse?: string | null;
  cwd?: string | null;
  promptNumber?: number | null;
  agentType?: string | null;
  agentId?: string | null;
  orGenerationId?: string | null;
  orSessionId?: string | null;
  createdAtEpoch?: number;
}

export interface ToolUseQueryFilters {
  project?: string;
  contentSessionId?: string;
  memorySessionId?: string;
  sessionDbId?: number;
  toolName?: string | string[];
  agentId?: string;
  platformSource?: string;
  dateStart?: number;
  dateEnd?: number;
  limit?: number;
  offset?: number;
  orderBy?: 'date_desc' | 'date_asc';
}

/**
 * UTF-8-safe byte truncation. Match the oversized-prompt guard's semantics:
 * retain only whole code points and report the original payload's byte size.
 */
export function truncatePayload(value: string, maxBytes: number = MAX_TOOL_PAYLOAD_BYTES): string {
  const byteLength = Buffer.byteLength(value, 'utf8');
  if (byteLength <= maxBytes) return value;

  // Encode only the retained prefix. Buffer.write stops before a code point
  // that cannot fit, without allocating a copy of the full tool response.
  const buf = Buffer.allocUnsafe(maxBytes);
  const end = buf.write(value, 'utf8');
  return `${buf.subarray(0, end).toString('utf8')}…[truncated: ${byteLength} bytes]`;
}

/**
 * Stable identity of the ORIGINAL (pre-truncation) payload, so a hash still
 * distinguishes two different oversized tool bodies that clip to the same
 * prefix. Same 16-hex shape as `computeObservationContentHash`.
 */
export function computeToolUseContentHash(
  toolName: string,
  toolInput: string | null | undefined,
  toolResponse: string | null | undefined
): string {
  return createHash('sha256')
    .update(toolName || '').update('\x00')
    .update(toolInput || '').update('\x00')
    .update(toolResponse || '')
    .digest('hex')
    .slice(0, 16);
}

/**
 * Creates the raw tool table and upgrades the v51 identity constraint to v75.
 * No FK on `session_db_id` / `observation_id` on purpose: a FK here would let a
 * single orphan row abort the whole constructor migration chain (#3378), and
 * `observation_id` is deliberately linked LATE (after generation), so it cannot
 * be required at insert time.
 */
export function createToolUsesSchema(db: Database): void {
  db.run(`
    CREATE TABLE IF NOT EXISTS tool_uses (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      tool_use_id TEXT NOT NULL,
      content_session_id TEXT NOT NULL,
      memory_session_id TEXT,
      session_db_id INTEGER,
      project TEXT NOT NULL,
      platform_source TEXT NOT NULL DEFAULT '${DEFAULT_PLATFORM_SOURCE}',
      tool_name TEXT NOT NULL,
      tool_input TEXT,
      tool_response TEXT,
      cwd TEXT,
      prompt_number INTEGER,
      agent_type TEXT,
      agent_id TEXT,
      observation_id INTEGER,
      or_generation_id TEXT,
      or_session_id TEXT,
      content_hash TEXT,
      created_at TEXT NOT NULL,
      created_at_epoch INTEGER NOT NULL,
      UNIQUE(platform_source, content_session_id, tool_use_id)
    )
  `);

  // v75: host IDs are only unique within a platform, as sdk_sessions and the
  // committed-result marker already reflect. Rebuild the old inline UNIQUE
  // constraint while preserving every stored column, rowid and derived index.
  db.transaction(() => {
    const schema = db.query("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'tool_uses'")
      .get() as { sql: string };
    const oldIdentity = /UNIQUE\s*\(\s*content_session_id\s*,\s*tool_use_id\s*\)/i;
    if (!oldIdentity.test(schema.sql)) return;
    const dependents = db.query(`SELECT sql FROM sqlite_master
      WHERE tbl_name = 'tool_uses' AND type IN ('index', 'trigger') AND sql IS NOT NULL`)
      .all() as Array<{ sql: string }>;
    const sequence = db.query("SELECT seq FROM sqlite_sequence WHERE name = 'tool_uses'")
      .get() as { seq: number } | null;
    db.run(schema.sql
      .replace(/^CREATE TABLE\s+(?:"tool_uses"|tool_uses)\s*\(/i, 'CREATE TABLE tool_uses_platform_new (')
      .replace(oldIdentity, 'UNIQUE(platform_source, content_session_id, tool_use_id)'));
    db.run('INSERT INTO tool_uses_platform_new SELECT * FROM tool_uses');
    db.run('DROP TABLE tool_uses');
    db.run('ALTER TABLE tool_uses_platform_new RENAME TO tool_uses');
    // The external-content FTS table still holds exactly these same rowids.
    // Restore its triggers without replaying inserts or deleting its documents.
    for (const dependent of dependents) db.run(dependent.sql);
    if (sequence) db.run("UPDATE sqlite_sequence SET seq = MAX(seq, ?) WHERE name = 'tool_uses'", [sequence.seq]);
  }).immediate();

  db.run('CREATE INDEX IF NOT EXISTS idx_tool_uses_project ON tool_uses(project)');
  db.run('CREATE INDEX IF NOT EXISTS idx_tool_uses_project_nocase_created ON tool_uses(project COLLATE NOCASE, created_at_epoch DESC, id DESC)');
  db.run('CREATE INDEX IF NOT EXISTS idx_tool_uses_memory_session ON tool_uses(memory_session_id)');
  db.run('CREATE INDEX IF NOT EXISTS idx_tool_uses_content_session ON tool_uses(content_session_id)');
  db.run('CREATE INDEX IF NOT EXISTS idx_tool_uses_session_db_id ON tool_uses(session_db_id)');
  db.run('CREATE INDEX IF NOT EXISTS idx_tool_uses_tool_name ON tool_uses(tool_name)');
  db.run('CREATE INDEX IF NOT EXISTS idx_tool_uses_created_at_epoch ON tool_uses(created_at_epoch)');
  db.run('CREATE INDEX IF NOT EXISTS idx_tool_uses_observation_id ON tool_uses(observation_id)');
  db.run('CREATE INDEX IF NOT EXISTS idx_tool_uses_or_generation_id ON tool_uses(or_generation_id)');
}

/**
 * Idempotent write. A replayed PostToolUse (hook retry, transcript re-scan)
 * carries the same `(platform_source, content_session_id, tool_use_id)` and must not duplicate;
 * it refreshes the payload instead, because the replay may be the first one to
 * carry a `tool_response`. Fields the replay does not carry are preserved via
 * COALESCE — notably `observation_id`, which is linked later.
 *
 * Returns the row id, or null when the caller gave no `tool_use_id` (a tool
 * event with no stable identity cannot be de-duplicated, so it is skipped
 * rather than inserted as an unbounded duplicate).
 */
export function upsertToolUse(db: Database, input: UpsertToolUseInput): number | null {
  if (!input.toolUseId || !input.contentSessionId || !input.toolName) return null;
  if (isRecursiveMemoryTool(input.toolName)) return null;

  const createdAtEpoch = input.createdAtEpoch ?? Date.now();
  const createdAt = new Date(createdAtEpoch).toISOString();
  const contentHash = computeToolUseContentHash(input.toolName, input.toolInput, input.toolResponse);

  const toolInput = input.toolInput != null ? truncatePayload(input.toolInput) : null;
  const toolResponse = input.toolResponse != null ? truncatePayload(input.toolResponse) : null;

  const row = (db.prepare(`
    INSERT INTO tool_uses (
      tool_use_id, content_session_id, memory_session_id, session_db_id, project,
      platform_source, tool_name, tool_input, tool_response, cwd, prompt_number,
      agent_type, agent_id, or_generation_id, or_session_id, content_hash,
      created_at, created_at_epoch
    )
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ON CONFLICT(platform_source, content_session_id, tool_use_id) DO UPDATE SET
      memory_session_id = CASE WHEN tool_uses.observation_id IS NULL
        THEN COALESCE(excluded.memory_session_id, tool_uses.memory_session_id)
        ELSE tool_uses.memory_session_id END,
      session_db_id     = COALESCE(excluded.session_db_id, tool_uses.session_db_id),
      project           = CASE WHEN excluded.project != '' THEN excluded.project ELSE tool_uses.project END,
      platform_source   = excluded.platform_source,
      tool_input        = COALESCE(excluded.tool_input, tool_uses.tool_input),
      tool_response     = COALESCE(excluded.tool_response, tool_uses.tool_response),
      cwd               = COALESCE(excluded.cwd, tool_uses.cwd),
      prompt_number     = COALESCE(excluded.prompt_number, tool_uses.prompt_number),
      agent_type        = COALESCE(excluded.agent_type, tool_uses.agent_type),
      agent_id          = COALESCE(excluded.agent_id, tool_uses.agent_id),
      or_generation_id  = COALESCE(excluded.or_generation_id, tool_uses.or_generation_id),
      or_session_id     = COALESCE(excluded.or_session_id, tool_uses.or_session_id),
      content_hash      = excluded.content_hash
    RETURNING id
  `).all(
    input.toolUseId,
    input.contentSessionId,
    input.memorySessionId ?? null,
    input.sessionDbId ?? null,
    input.project ?? '',
    normalizePlatformSource(input.platformSource),
    input.toolName,
    toolInput,
    toolResponse,
    input.cwd ?? null,
    input.promptNumber ?? null,
    input.agentType ?? null,
    input.agentId ?? null,
    input.orGenerationId ?? null,
    input.orSessionId ?? null,
    contentHash,
    createdAt,
    createdAtEpoch
  ) as { id: number }[])[0] ?? null;

  return row ? row.id : null;
}

/**
 * Late link, called once the observer has actually stored observations for the
 * batch these tool uses were claimed into. `observation_id` is only ever set
 * when it is still NULL: the first observation that consumed a tool use owns
 * the link, and a later batch that happens to re-claim the same id must not
 * steal it. `memory_session_id` is backfilled at the same time because it does
 * not exist yet at ingest.
 *
 * Returns the number of rows updated.
 */
export function linkToolUsesToObservation(
  db: Database,
  params: {
    contentSessionId: string;
    platformSource?: string;
    toolUseIds: string[];
    observationId: number;
    memorySessionId?: string | null;
  }
): number {
  const ids = params.toolUseIds.filter(id => typeof id === 'string' && id.length > 0);
  if (ids.length === 0) return 0;

  const placeholders = ids.map(() => '?').join(',');
  const result = db.prepare(`
    UPDATE tool_uses
    SET observation_id = COALESCE(observation_id, ?),
        memory_session_id = CASE WHEN observation_id IS NULL
          THEN COALESCE(?, memory_session_id)
          ELSE COALESCE(memory_session_id, ?)
        END
    WHERE content_session_id = ?
      AND platform_source = ?
      AND tool_use_id IN (${placeholders})
      AND (observation_id IS NULL OR observation_id = ?)
  `).run(
    params.observationId,
    params.memorySessionId ?? null,
    params.memorySessionId ?? null,
    params.contentSessionId,
    normalizePlatformSource(params.platformSource),
    ...ids,
    params.observationId
  );

  return Number(result.changes ?? 0);
}

function mapPlatformFilter(platformSource: string | undefined): { clause: string; param: string } | null {
  if (!platformSource) return null;
  return {
    clause: `COALESCE(NULLIF(platform_source, ''), '${DEFAULT_PLATFORM_SOURCE}') = ?`,
    param: normalizePlatformSource(platformSource),
  };
}

/**
 * Default row ceiling for `getToolUsesByIds` when the caller omits `limit`.
 *
 * The route caps the id array, but `tool_use_id` is only unique per
 * `(platform_source, content_session_id, tool_use_id)` — `upsertToolUse` stores the same id under
 * a new session as a distinct row — so the id cap alone does not bound the row
 * count. An omitted `limit` must not mean "every matching row", or a single
 * accepted id can still page hundreds of raw payloads.
 */
export const TOOL_USES_BATCH_DEFAULT_ROWS = 100;

/**
 * Layer-4 fetch: full tool bodies for an explicitly filtered set of ids.
 *
 * Accepts BOTH numeric `tool_uses.id` (what `queryToolUses` / the search index
 * hand back) and string `tool_use_id` (what a transcript or an observation ref
 * carries), because callers legitimately hold either one.
 *
 * The result is always bounded: an explicit `limit` wins, and an omitted `limit`
 * falls back to `TOOL_USES_BATCH_DEFAULT_ROWS` rather than returning every row.
 */
export function getToolUsesByIds(
  db: Database,
  ids: Array<number | string>,
  options: { limit?: number; project?: string; projects?: string[]; platformSource?: string; contentSessionId?: string } = {}
): ToolUseRow[] {
  const numericIds: number[] = [];
  const stringIds: string[] = [];
  for (const id of ids) {
    if (typeof id === 'number' && Number.isInteger(id)) {
      numericIds.push(id);
      continue;
    }
    if (typeof id === 'string' && id.trim().length > 0) {
      // A numeric-looking string is ambiguous; match it on BOTH columns rather
      // than guessing, since tool_use_id values are opaque provider strings.
      const asNumber = Number(id);
      if (Number.isInteger(asNumber) && String(asNumber) === id.trim()) numericIds.push(asNumber);
      stringIds.push(id.trim());
    }
  }

  if (numericIds.length === 0 && stringIds.length === 0) return [];

  const idClauses: string[] = [];
  const params: Array<string | number> = [];
  if (numericIds.length > 0) {
    idClauses.push(`id IN (${numericIds.map(() => '?').join(',')})`);
    params.push(...numericIds);
  }
  if (stringIds.length > 0) {
    idClauses.push(`tool_use_id IN (${stringIds.map(() => '?').join(',')})`);
    params.push(...stringIds);
  }

  const conditions = [`(${idClauses.join(' OR ')})`];

  const projects = scopedProjects(options);
  if (projects.length) {
    const scope = projectScopeSql('tool_uses', projects, { includeMerged: false });
    conditions.push(scope.sql); params.push(...scope.params);
  }
  if (options.contentSessionId) {
    conditions.push('content_session_id = ?');
    params.push(options.contentSessionId);
  }
  const platform = mapPlatformFilter(options.platformSource);
  if (platform) {
    conditions.push(platform.clause);
    params.push(platform.param);
  }

  const rowLimit = options.limit && options.limit > 0 ? Math.floor(options.limit) : TOOL_USES_BATCH_DEFAULT_ROWS;

  return db.prepare(`
    SELECT * FROM tool_uses
    WHERE ${conditions.join(' AND ')}
    ORDER BY created_at_epoch DESC
    LIMIT ${rowLimit}
  `).all(...params) as ToolUseRow[];
}

/** Bounded full-row listing for callers that explicitly need stored bodies. */
export function queryToolUses(db: Database, filters: ToolUseQueryFilters = {}): ToolUseRow[] {
  return queryToolUseRows(db, filters, '*') as ToolUseRow[];
}

/**
 * Keep raw payloads inside SQLite for the progressive-disclosure index. Count
 * BLOB bytes, not TEXT characters, so Unicode and embedded NULs agree with
 * the sizes an explicit body fetch returns.
 */
export function queryToolUseIndex(db: Database, filters: ToolUseQueryFilters = {}): ToolUseIndexRow[] {
  return queryToolUseRows(db, filters, `
    id, tool_use_id, tool_name, project, content_session_id, memory_session_id,
    platform_source, agent_id, agent_type, observation_id, or_generation_id,
    or_session_id, prompt_number, created_at, created_at_epoch,
    COALESCE(length(CAST(tool_input AS BLOB)), 0) AS tool_input_bytes,
    COALESCE(length(CAST(tool_response AS BLOB)), 0) AS tool_response_bytes
  `) as ToolUseIndexRow[];
}

function queryToolUseRows(db: Database, filters: ToolUseQueryFilters, projection: string): unknown[] {
  const conditions: string[] = [];
  const params: Array<string | number> = [];

  if (filters.project) {
    conditions.push('project COLLATE NOCASE = ?');
    params.push(filters.project);
  }
  if (filters.contentSessionId) {
    conditions.push('content_session_id = ?');
    params.push(filters.contentSessionId);
  }
  if (filters.memorySessionId) {
    conditions.push('memory_session_id = ?');
    params.push(filters.memorySessionId);
  }
  if (typeof filters.sessionDbId === 'number') {
    conditions.push('session_db_id = ?');
    params.push(filters.sessionDbId);
  }
  if (filters.toolName) {
    const names = Array.isArray(filters.toolName) ? filters.toolName : [filters.toolName];
    if (names.length > 0) {
      conditions.push(`tool_name IN (${names.map(() => '?').join(',')})`);
      params.push(...names);
    }
  }
  if (filters.agentId) {
    conditions.push('agent_id = ?');
    params.push(filters.agentId);
  }
  const platform = mapPlatformFilter(filters.platformSource);
  if (platform) {
    conditions.push(platform.clause);
    params.push(platform.param);
  }
  if (typeof filters.dateStart === 'number') {
    conditions.push('created_at_epoch >= ?');
    params.push(filters.dateStart);
  }
  if (typeof filters.dateEnd === 'number') {
    conditions.push('created_at_epoch <= ?');
    params.push(filters.dateEnd);
  }

  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
  const order = filters.orderBy === 'date_asc' ? 'ASC' : 'DESC';
  const limit = Math.min(Math.max(Math.floor(filters.limit ?? 50), 1), 500);
  const offset = Math.max(Math.floor(filters.offset ?? 0), 0);

  return db.prepare(`
    SELECT ${projection} FROM tool_uses
    ${whereClause}
    ORDER BY created_at_epoch ${order}, id ${order}
    LIMIT ${limit} OFFSET ${offset}
  `).all(...params);
}

/**
 * Receipt's headline number: usage COUNT by tool, never a dollar figure.
 * `COUNT(DISTINCT tool_use_id)` per the frozen join contract, so a row that got
 * upserted twice still counts once.
 */
export function countToolUses(
  db: Database,
  filters: ToolUseQueryFilters = {}
): Array<{ tool_name: string; uses: number }> {
  const conditions: string[] = [];
  const params: Array<string | number> = [];

  if (filters.project) {
    conditions.push('project COLLATE NOCASE = ?');
    params.push(filters.project);
  }
  if (filters.contentSessionId) {
    conditions.push('content_session_id = ?');
    params.push(filters.contentSessionId);
  }
  if (filters.agentId) {
    conditions.push('agent_id = ?');
    params.push(filters.agentId);
  }
  if (typeof filters.dateStart === 'number') {
    conditions.push('created_at_epoch >= ?');
    params.push(filters.dateStart);
  }
  if (typeof filters.dateEnd === 'number') {
    conditions.push('created_at_epoch <= ?');
    params.push(filters.dateEnd);
  }

  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';

  return db.prepare(`
    SELECT tool_name, COUNT(DISTINCT tool_use_id) AS uses
    FROM tool_uses
    ${whereClause}
    GROUP BY tool_name
    ORDER BY uses DESC, tool_name ASC
  `).all(...params) as Array<{ tool_name: string; uses: number }>;
}

/** Diagnostic helper used by the worker health/stat surfaces. */
export function toolUsesTableExists(db: Database): boolean {
  const row = db
    .query("SELECT name FROM sqlite_master WHERE type='table' AND name='tool_uses'")
    .get() as { name: string } | null;
  if (!row) {
    logger.debug('DB', 'tool_uses table not present');
    return false;
  }
  return true;
}

/**
 * Opt-in retention for the raw tool I/O index. Deletes rows older than
 * `retentionDays` that are linked to an observation that still exists, because
 * that observation carries the distilled result. `observation_id` is not a
 * foreign key, so deleting an observation leaves the link behind: a row whose
 * observation is gone is, like a row with no `observation_id` at all, the only
 * copy of that I/O and is never touched. `retentionDays` of 0 keeps
 * everything. Freed pages are reused by SQLite; returning disk space to the OS
 * is the job of VACUUM / auto_vacuum, not of this purge.
 *
 * Returns the number of rows removed.
 */
export function purgeLinkedToolUses(db: Database, retentionDays: number, nowEpoch: number = Date.now()): number {
  if (!Number.isSafeInteger(retentionDays) || retentionDays <= 0) return 0;
  try {
    if (!toolUsesTableExists(db)) return 0;
    const cutoffEpoch = nowEpoch - retentionDays * 24 * 60 * 60 * 1000;
    db
      .prepare(
        `DELETE FROM tool_uses
          WHERE observation_id IS NOT NULL
            AND created_at_epoch < ?
            AND EXISTS (SELECT 1 FROM observations WHERE observations.id = tool_uses.observation_id)`
      )
      .run(cutoffEpoch);
    // Bun's run().changes includes FTS shadow-table writes from triggers.
    const { changes } = db.query('SELECT changes() AS changes').get() as { changes: number };
    if (changes > 0) {
      logger.info('DB', 'Purged tool_uses rows past retention that are already linked to an observation', {
        rows: changes,
        retentionDays,
      });
    }
    return changes;
  } catch (error) {
    logger.warn('DB', 'tool_uses retention purge failed', {},
      error instanceof Error ? error : new Error(String(error)));
    return 0;
  }
}