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

36.6 KB
Raw Blame
import { createHash, randomBytes } from 'crypto';
import { link, mkdir, readdir, readFile, rename, unlink } from 'fs/promises';
import { existsSync, mkdirSync, opendirSync, readdirSync, readFileSync, renameSync, rmSync, unlinkSync } from 'fs';
import { dirname, join, resolve } from 'path';
import { WINDOWS_RENAME_RETRY_CODES, writeJsonFileAtomic } from './atomic-json.js';
import { ensurePrivateDir, resolveDataDir } from './paths.js';
import { normalizePlatformSource } from './platform-source.js';
import { logger } from '../utils/logger.js';
import type { AgentRole, InstructionState, WorkStateOutcome } from './work-state-telemetry.js';

/**
 * Durable metadata hand-off from short-lived hooks to the worker.
 *
 * Only metadata (advisor records, SessionEnd, deliverables, usage) is written
 * here. Observation/edit/summary shapes remain readable for upgrade cleanup.
 * Live observer inputs use the non-durable handoff instead. Metadata never waits
 * for the worker. The worker drains the directory in order (boot, a nudge from
 * the hook, an fs.watch of the directory, and a slow safety sweep).
 *
 * Dedupe + ordering design (the simpler of the two correct options):
 * - The filename IS the deterministic key: `<kind>-<key>.json`, key =
 *   a hash of session + platform followed by `tool_use_id` when filename-safe, else
 *   sha256(kind, contentSessionId, canonical payload). A re-delivered event
 *   therefore overwrites its own file — no directory scan on the hook path,
 *   and no window where two hooks racing the same event create two files.
 * - Order lives in the body: `enqueuedAtEpochMs`, monotonic per process and
 *   preserved when an existing entry is overwritten. Readers sort by it (then
 *   by filename) — the drain reads every file anyway.
 *
 * One file per event, never a shared append-only file: concurrent hook
 * processes cannot interleave writes (Windows), and writeJsonFileAtomic makes
 * each file all-or-nothing.
 */

export const HOOK_SPOOL_KINDS = ['observation', 'file_edit', 'summarize', 'session_end', 'subagent_stop', 'advisor_calls', 'deliverables', 'remote_deliverables', 'work_state_telemetry'] as const;
export type HookSpoolKind = typeof HOOK_SPOOL_KINDS[number];
/** Inference kinds are legacy read/wire shapes, not writable spool kinds. */
export type DurableHookSpoolKind = Exclude<HookSpoolKind, 'observation' | 'file_edit' | 'summarize'>;

export interface SpooledObservationPayload {
  contentSessionId: string;
  platformSource: string;
  /** Preserve missing host attribution separately from the legacy DB default. */
  telemetryPlatformSource?: string;
  toolName: string;
  /** Exact host tool name before normalization, retained for configured exclusions. */
  nativeToolName?: string;
  toolInput?: unknown;
  toolResponse?: unknown;
  cwd?: string;
  agentId?: string;
  agentType?: string;
  toolUseId?: string;
  /** When the tool use happened at its source; see ObservationPayload.eventOccurredAtEpochMs. */
  eventOccurredAtEpochMs?: number | null;
}

export interface SpooledSummarizePayload {
  contentSessionId: string;
  platformSource: string;
  lastAssistantMessage: string;
  observedModel?: string;
  observedBilling?: string;
  cwd?: string;
}

export interface SpooledSessionEndPayload {
  contentSessionId: string;
  platformSource: string;
}

/** Claude Code's SubagentStop: one subagent of the session finished. */
export interface SpooledSubagentStopPayload {
  contentSessionId: string;
  platformSource: string;
  agentId: string;
  agentType?: string;
  cwd?: string;
}

export interface SpooledAdvisorCall {
  toolUseId: string;
  advice: string;
  advisorModel?: string | null;
  occurredAtEpoch: number;
  lastUserMessage?: string | null;
  transcriptByteOffset?: number | null;
}

export interface SpooledAdvisorCallsPayload {
  contentSessionId: string;
  platformSource: string;
  cwd?: string;
  transcriptPath?: string;
  calls: SpooledAdvisorCall[];
}

/** One file the Stop hook copied into the project's deliverables bucket (src/shared/deliverables.ts). */
export interface SpooledDeliverable {
  /** Where the agent made it; may be gone by the time anyone looks. */
  sourcePath: string;
  /** The bucket copy: ~/.claude-mem/deliverables/<project>/<stem>-<hash><ext>. */
  bucketPath: string;
  title: string;
  /** work-product.mjs kind: deck, document, page, image, video, spreadsheet, or file. */
  kind: string;
  bytes: number;
  sha256: string;
  /** True when an agent attached it through a work-state field; false when the hook inferred it from a write. */
  declared: boolean;
  list?: string | null;
  field?: string | null;
  toolUseId?: string | null;
  occurredAtEpoch: number;
}

/**
 * Bound on `errors` in one deliverables event: the remote spool schema
 * (hook-spool-remote.ts) admits this many, and the hook keeps to it
 * (deliverables-capture.ts boundedErrors) so a turn with more failures than
 * this never costs the records of the files that did copy.
 */
export const DELIVERABLE_ERRORS_PER_EVENT = 128;

/** The Stop (or SubagentStop) hook's deliverables for one turn, already copied into the bucket. */
export interface SpooledDeliverablesPayload {
  contentSessionId: string;
  platformSource: string;
  cwd: string;
  /** The checkout's primary project key, which names the bucket folder. */
  project: string;
  agentId?: string;
  files: SpooledDeliverable[];
  /** Files that could not be copied (missing, unreadable, over the limit): recorded in the worker log, never dropped silently. */
  errors?: Array<{ sourcePath: string; error: string }>;
}

/** Name and opaque revision of an output on a direct remote worker client's disk. */
export interface RemoteDeliverablesPayload {
  contentSessionId: string;
  platformSource: string;
  files: { name: string; version: string; occurredAtEpoch: number }[];
}
export interface HookSpoolPayloadByKind {
  observation: SpooledObservationPayload;
  file_edit: SpooledObservationPayload;
  summarize: SpooledSummarizePayload;
  session_end: SpooledSessionEndPayload;
  subagent_stop: SpooledSubagentStopPayload;
  advisor_calls: SpooledAdvisorCallsPayload;
  deliverables: SpooledDeliverablesPayload;
  remote_deliverables: RemoteDeliverablesPayload;
  work_state_telemetry: {
    contentSessionId: string;
    platformSource: string;
    eventId: string;
    agentId?: string;
    agentRole?: AgentRole;
    kind: 'instruction' | 'mcp';
    state?: InstructionState;
    tool?: 'read' | 'write';
    outcome?: WorkStateOutcome;
  };
}

export type HookSpoolEntry = {
  [K in HookSpoolKind]: {
    kind: K;
    payload: HookSpoolPayloadByKind[K];
    enqueuedAtEpochMs: number;
  }
}[HookSpoolKind];

/**
 * Durable record of the entries ingest irrevocably accepted (the worker's
 * hook_spool_consumed table). Makes the hand-off exactly-once across
 * restarts: see HookSpool.drain.
 */
export interface HookSpoolConsumedMarkers {
  isConsumed(entryKey: string): boolean;
  markConsumed(entryKey: string, consumedAtEpochMs: number): void;
  clearConsumed(entryKey: string): void;
  pruneConsumedBefore(epochMs: number): void;
}

export interface HookSpoolDrainResult {
  drained: number;
  retained: number;
  quarantined: number;
  expired: number;
}

export interface HookSpoolDrainOptions {
  shouldContinue?: () => boolean;
  verifyUnchanged?: boolean;
  maxEntries?: number;
}

export type HookSpoolAcceptance = boolean | 'rejected' | 'expired';

export function remoteHookSpoolReceivedKey(receipt: string): string {
  return `received_${receipt}`;
}

const ENTRY_FILENAME = /^[a-z_]+-[A-Za-z0-9_-]+\.json$/;
const FILENAME_SAFE_TOOL_USE_ID = /^[A-Za-z0-9_-]{1,128}$/;
const CORRUPT_DIRNAME = 'corrupt';
/**
 * Spool entries carry captured prompts, tool inputs and file paths, so a new entry is written
 * readable by its owner only; the directory that holds them gets the same treatment.
 */
const SPOOL_ENTRY_MODE = 0o600;

const EXPIRED_DIRNAME = 'expired';
/**
 * Files read per parallel batch while draining. Bounded well under common file
 * descriptor limits so a large backlog cannot exhaust them; the batch also caps
 * how many raw payloads are held in memory at once.
 */
const DRAIN_READ_BATCH_SIZE = 64;

/** Corrupt entries whose transient quarantine failure was already logged by this process. */
const reportedTransientQuarantineFailures = new Set<string>();

/**
 * A retained entry (session never became known, ingest keeps failing) older
 * than this stops being retried: it is moved to `expired/` with an error log,
 * never silently deleted.
 */
export const HOOK_SPOOL_RETRY_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;

/**
 * A `session_end` for a session the worker never registered can never succeed:
 * `unknown_session` is returned only when the worker is up and its DB has no
 * such session (a DB outage throws instead, retrying the whole pass), and a
 * session registers within moments of starting or never. This grace window
 * covers just the init race — an init and its end can land in the same
 * instant — past it the drain retires the entry to `expired/` instead of
 * holding it for the full retry window.
 */
export const HOOK_SPOOL_SESSION_END_UNKNOWN_GRACE_MS = 5 * 60 * 1000;
const LEGACY_SESSION_END_REPLAY_DIRNAME = 'session-end-replay';

export function resolveHookSpoolDirectory(): string {
  return join(resolveDataDir(), 'state', 'hook-spool');
}

export function resolveLegacySessionEndReplayDirectory(): string {
  return join(resolveDataDir(), 'state', LEGACY_SESSION_END_REPLAY_DIRNAME);
}

/** JSON with object keys sorted at every depth, so equal payloads hash equal. */
function canonicalJson(value: unknown): string {
  if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null';
  if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
  const record = value as Record<string, unknown>;
  const keys = Object.keys(record).filter(key => record[key] !== undefined).sort();
  return `{${keys.map(key => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(',')}}`;
}

export function remoteHookSpoolReceipt(entry: HookSpoolEntry): string {
  return `remote_${entry.kind}-${createHash('sha256').update(canonicalJson(entry)).digest('hex')}`;
}

function isRemoteReceipt(entryKey: string): boolean {
  return /^remote_[a-z_]+-[a-f0-9]{64}$/.test(entryKey);
}

export function hookSpoolKeyFor<K extends HookSpoolKind>(kind: K, payload: HookSpoolPayloadByKind[K]): string {
  const toolUseId = (payload as { toolUseId?: unknown }).toolUseId;
  if (typeof toolUseId === 'string' && FILENAME_SAFE_TOOL_USE_ID.test(toolUseId)) {
    // Tool ids are opaque host values; some hosts number them within a
    // session. Scope the durable filename (and consumed marker) like the
    // worker dedup key, so a second session cannot overwrite the first.
    const sessionKey = createHash('sha256')
      .update(payload.contentSessionId)
      .update('\0')
      .update(normalizePlatformSource(payload.platformSource))
      .digest('hex');
    return `${sessionKey}-${toolUseId}`;
  }
  return createHash('sha256')
    .update(kind)
    .update('\0')
    .update(payload.contentSessionId)
    .update('\0')
    .update(canonicalJson(payload))
    .digest('hex');
}

function isNonEmptyString(value: unknown): value is string {
  return typeof value === 'string' && value.length > 0;
}

/** Returns the entry, or a reason it is corrupt. */
function parseHookSpoolEntry(raw: string): HookSpoolEntry | { corruptReason: string } {
  let parsed: unknown;
  try {
    parsed = JSON.parse(raw);
  } catch (error) {
    return { corruptReason: `invalid JSON: ${error instanceof Error ? error.message : String(error)}` };
  }
  if (parsed === null || typeof parsed !== 'object') return { corruptReason: 'not an object' };
  const candidate = parsed as { kind?: unknown; payload?: unknown; enqueuedAtEpochMs?: unknown };
  if (!HOOK_SPOOL_KINDS.includes(candidate.kind as HookSpoolKind)) {
    return { corruptReason: `unknown kind ${JSON.stringify(candidate.kind)}` };
  }
  if (typeof candidate.enqueuedAtEpochMs !== 'number' || !Number.isFinite(candidate.enqueuedAtEpochMs)) {
    return { corruptReason: 'missing enqueuedAtEpochMs' };
  }
  const payload = candidate.payload as Record<string, unknown> | null;
  if (payload === null || typeof payload !== 'object' || !isNonEmptyString(payload.contentSessionId)) {
    return { corruptReason: 'payload missing contentSessionId' };
  }
  const kind = candidate.kind as HookSpoolKind;
  if ((kind === 'observation' || kind === 'file_edit') && !isNonEmptyString(payload.toolName)) {
    return { corruptReason: 'observation payload missing toolName' };
  }
  if (kind === 'summarize' && typeof payload.lastAssistantMessage !== 'string') {
    return { corruptReason: 'summarize payload missing lastAssistantMessage' };
  }
  if (kind === 'subagent_stop' && !isNonEmptyString(payload.agentId)) {
    return { corruptReason: 'subagent_stop payload missing agentId' };
  }
  if (kind === 'advisor_calls' && (!Array.isArray(payload.calls) || payload.calls.length === 0)) {
    return { corruptReason: 'advisor_calls payload has no calls' };
  }
  if (kind === 'remote_deliverables' && (!Array.isArray(payload.files) || !payload.files.length || payload.files.length > 50)) {
    return { corruptReason: 'remote deliverable metadata has no valid file list' };
  }
  if (kind === 'deliverables' && (!Array.isArray(payload.files) || payload.files.length === 0 || !isNonEmptyString(payload.project))) {
    return { corruptReason: 'deliverables payload has no files or no project' };
  }
  if (kind === 'work_state_telemetry' && (
    !isNonEmptyString(payload.eventId)
    || !['main', 'subagent', 'unknown', undefined].includes(payload.agentRole as any)
    || (payload.kind === 'instruction'
      ? !['returned', 'disabled', 'excluded', 'missing', 'unknown'].includes(String(payload.state))
      : payload.kind !== 'mcp' || !['read', 'write'].includes(String(payload.tool))
        || !['ok', 'error', 'excluded', 'disabled', 'unknown'].includes(String(payload.outcome)))
  )) return { corruptReason: 'invalid work-state telemetry shape' };
  return {
    kind,
    payload: { ...payload, platformSource: normalizePlatformSource(payload.platformSource as string | undefined) },
    enqueuedAtEpochMs: candidate.enqueuedAtEpochMs,
  } as HookSpoolEntry;
}

interface HookSpoolFile {
  entry: HookSpoolEntry;
  path: string;
  filename: string;
}

/** Oldest first; the filename breaks ties between same-millisecond enqueues. */
function compareSpoolFiles(a: HookSpoolFile, b: HookSpoolFile): number {
  return a.entry.enqueuedAtEpochMs - b.entry.enqueuedAtEpochMs || a.filename.localeCompare(b.filename);
}

/**
 * Sort the collected entries and keep only the oldest `maxEntries`, returning
 * how many were dropped. The reader calls it as each entry is collected, so a
 * bounded drain never holds more than `maxEntries` parsed payloads even when the
 * spool holds thousands of files.
 */
export function retainOldestEntries(files: HookSpoolFile[], maxEntries: number): number {
  files.sort(compareSpoolFiles);
  if (files.length <= maxEntries) return 0;
  const omitted = files.length - maxEntries;
  files.length = maxEntries;
  return omitted;
}

// Monotonic per process: two enqueues in the same millisecond (advisor-call
// chunks then the summarize, from one Stop hook) keep their call order.
let lastEnqueuedAtEpochMs = 0;

function monotonicNowEpochMs(): number {
  lastEnqueuedAtEpochMs = Math.max(Date.now(), lastEnqueuedAtEpochMs + 1);
  return lastEnqueuedAtEpochMs;
}

export class HookSpool {
  constructor(readonly directory: string = resolveHookSpoolDirectory()) {}

  get corruptDirectory(): string {
    return join(this.directory, CORRUPT_DIRNAME);
  }

  get expiredDirectory(): string {
    return join(this.directory, EXPIRED_DIRNAME);
  }

  /**
   * Writes (or overwrites) this event's file. Returns the file path.
   * `requestedAtEpochMs` is for carrying an existing timestamp over (legacy
   * migration, tests); hooks omit it and get a per-process monotonic now.
   */
  enqueue<K extends DurableHookSpoolKind>(
    kind: K,
    payload: HookSpoolPayloadByKind[K],
    requestedAtEpochMs?: number,
  ): string {
    const normalizedPayload = { ...payload, platformSource: normalizePlatformSource(payload.platformSource) };
    let entryPath = join(this.directory, `${kind}-${hookSpoolKeyFor(kind, normalizedPayload)}.json`);
    const toolUseId = (normalizedPayload as { toolUseId?: unknown }).toolUseId;
    if (typeof toolUseId === 'string' && FILENAME_SAFE_TOOL_USE_ID.test(toolUseId)) {
      const legacyPath = join(this.directory, `${kind}-${toolUseId}.json`);
      try {
        const legacy = parseHookSpoolEntry(readFileSync(legacyPath, 'utf8'));
        if (!('corruptReason' in legacy) && legacy.kind === kind
          && legacy.payload.contentSessionId === normalizedPayload.contentSessionId
          && legacy.payload.platformSource === normalizedPayload.platformSource) {
          // A pre-upgrade file may remain after handoff but before unlink.
          // Keep its key until removal so its durable consumed marker still
          // suppresses re-delivery; another scope must use the new key.
          entryPath = legacyPath;
        }
      } catch {
        // No legacy entry: new enqueues use the session/platform namespace.
      }
    }
    const enqueuedAtEpochMs = this.existingEnqueuedAt(entryPath) ?? requestedAtEpochMs ?? monotonicNowEpochMs();
    ensurePrivateDir(this.directory);
    writeJsonFileAtomic(entryPath, { kind, payload: normalizedPayload, enqueuedAtEpochMs }, { mode: SPOOL_ENTRY_MODE });
    return entryPath;
  }

  /** Readable entries in drain order. Corrupt files are quarantined as a side effect. */
  async entries(): Promise<HookSpoolEntry[]> {
    return (await this.readEntries()).files.map(file => file.entry);
  }

  hasEntries(): boolean {
    try {
      const directory = opendirSync(this.directory);
      try {
        for (let entry = directory.readSync(); entry; entry = directory.readSync()) {
          if (entry.isFile() && ENTRY_FILENAME.test(entry.name)) return true;
        }
      } finally { directory.closeSync(); }
    } catch (error) {
      if (!['ENOENT', 'ENOTDIR'].includes((error as NodeJS.ErrnoException).code ?? '')) {
        logger.warn('HOOK', 'Could not inspect pending hook spool files', {},
          error instanceof Error ? error : new Error(String(error)));
      }
    }
    return false;
  }

  enqueueRemote(entry: HookSpoolEntry, consumedMarkers: HookSpoolConsumedMarkers): string {
    const receipt = remoteHookSpoolReceipt(entry);
    const receivedKey = remoteHookSpoolReceivedKey(receipt);
    if (!consumedMarkers.isConsumed(receipt) && !consumedMarkers.isConsumed(receivedKey)) {
      ensurePrivateDir(this.directory);
      writeJsonFileAtomic(join(this.directory, `${receipt}.json`), entry, { mode: SPOOL_ENTRY_MODE });
      consumedMarkers.markConsumed(receivedKey, Date.now());
    }
    return receipt;
  }

  /**
   * Hands each entry to `accept` in order; an accepted entry is unlinked.
   *
   * With `consumedMarkers`, the hand-off is EXACTLY-ONCE AT THE HANDOFF POINT
   * across restarts. `accept` receives a synchronous `markHandedOff()` that
   * ingest calls the instant the entry is irrevocably accepted (enqueued into
   * the SessionManager / recorded in the DB) and before it kicks any async,
   * provider-bound work (ensureGeneratorRunning). markHandedOff writes the
   * entry's consumed marker to the worker DB synchronously (bun:sqlite), so no
   * provider call can precede it.
   * - Crash before markHandedOff (ingest declined, threw, or died first): no
   *   marker, the file is still there ⇒ the next drain ingests it. No loss.
   * - Crash after markHandedOff, before the unlink: the next drain finds the
   *   marker and removes the file without ingesting it again. No double paid
   *   send.
   * Once markHandedOff has run, the entry counts as accepted even if `accept`
   * later throws or returns false — retrying it would send it twice. The
   * marker is cleared once the file is gone.
   */
  async drain(
    accept: (entry: HookSpoolEntry, markHandedOff: () => void) => HookSpoolAcceptance | Promise<HookSpoolAcceptance>,
    consumedMarkers?: HookSpoolConsumedMarkers,
    options: HookSpoolDrainOptions = {},
  ): Promise<HookSpoolDrainResult> {
    const { files, quarantined: initiallyQuarantined, omitted } = await this.readEntries(options.maxEntries);
    let quarantined = initiallyQuarantined;
    let drained = 0;
    let retained = omitted;
    let expired = 0;

    // A marker outlives its file only when a crash hit between unlink and clear.
    consumedMarkers?.pruneConsumedBefore(Date.now() - HOOK_SPOOL_RETRY_WINDOW_MS);

    // A session's summary and its end wait behind an observation of that
    // session ingest has not accepted yet, so they never overtake the work they
    // close. Nothing else waits: observations are what create a session, so
    // holding them behind a summary kept for an unknown session would keep the
    // session from ever being created.
    const sessionsWithRetainedObservations = new Set<string>();
    for (const [index, file] of files.entries()) {
      if (options.shouldContinue && !options.shouldContinue()) {
        retained += files.length - index;
        break;
      }
      const entryKey = file.filename.replace(/\.json$/, '');
      if (consumedMarkers?.isConsumed(entryKey)) {
        logger.info('HOOK', 'Hook spool entry was already handed to ingest before a restart; removing it without ingesting again', {
          kind: file.entry.kind,
          contentSessionId: file.entry.payload.contentSessionId,
          file: file.filename,
        });
        if (await this.unlinkEntry(file)) {
          if (!isRemoteReceipt(entryKey)) consumedMarkers.clearConsumed(entryKey);
          drained++;
        } else {
          retained++;
        }
        continue;
      }

      const sessionKey = JSON.stringify([file.entry.payload.contentSessionId, file.entry.payload.platformSource]);
      if ((file.entry.kind === 'summarize' || file.entry.kind === 'session_end') && sessionsWithRetainedObservations.has(sessionKey)) {
        retained++;
        continue;
      }

      let handedOff = false;
      const markHandedOff = (): void => {
        if (handedOff) return;
        handedOff = true;
        try {
          consumedMarkers?.markConsumed(entryKey, Date.now());
        } catch (error) {
          // Never throw into ingest: the entry IS enqueued and its generator
          // kick must still run. Without the marker a crash before the unlink
          // below would ingest it again — say so loudly.
          logger.error('HOOK', 'Could not record a hook spool hand-off marker; a crash before the file is removed would ingest it twice', {
            kind: file.entry.kind,
            contentSessionId: file.entry.payload.contentSessionId,
            file: file.filename,
          }, error instanceof Error ? error : new Error(String(error)));
        }
      };
      let accepted: HookSpoolAcceptance;
      try {
        accepted = await accept(file.entry, markHandedOff);
      } catch (error) {
        logger.warn('HOOK', handedOff
          ? 'Hook spool entry failed after ingest accepted it; removing it (a retry would send it twice)'
          : 'Hook spool entry failed to ingest; keeping it for the next drain', {
          kind: file.entry.kind,
          contentSessionId: file.entry.payload.contentSessionId,
          file: file.filename,
        }, error instanceof Error ? error : new Error(String(error)));
        accepted = false;
      }
      if (handedOff) accepted = true;

      if (accepted === 'rejected') {
        if (await this.unlinkTransferredEntry(file, 'Remote worker permanently rejected this capture event')) quarantined++;
        else retained++;
        continue;
      }

      if (accepted === 'expired') {
        // Ingest's verdict: this entry can never succeed (it was not handed
        // off — no marker was written). Retire it the way the retry window
        // does, to expired/, never silently deleted.
        if (await this.expireIfPastWindow(file, HOOK_SPOOL_SESSION_END_UNKNOWN_GRACE_MS, 'unknown-session grace window')) {
          expired++;
        } else {
          retained++;
        }
        continue;
      }

      if (!accepted) {
        // Never handed off (no marker was written): the next drain retries it.
        if (await this.expireIfPastWindow(file, HOOK_SPOOL_RETRY_WINDOW_MS, 'retry window')) {
          expired++;
        } else {
          if (file.entry.kind === 'observation' || file.entry.kind === 'file_edit') sessionsWithRetainedObservations.add(sessionKey);
          retained++;
        }
        continue;
      }

      if (await this.unlinkEntry(file, options.verifyUnchanged)) {
        // A remote sender can retry after its acknowledgement was lost.
        if (!isRemoteReceipt(entryKey)) consumedMarkers?.clearConsumed(entryKey);
        drained++;
      } else {
        // The marker stays: the next drain removes the file without re-ingesting it.
        retained++;
      }
    }

    return { drained, retained, quarantined, expired };
  }

  /** True when the file is gone (removed here, or by a concurrent drain). */
  private async unlinkEntry(file: HookSpoolFile, verifyUnchanged: boolean = false): Promise<boolean> {
    if (verifyUnchanged) return this.unlinkTransferredEntry(file);
    try {
      await unlink(file.path);
      return true;
    } catch (error) {
      // ENOENT: a concurrent drain (another worker process) already removed it.
      if ((error as NodeJS.ErrnoException).code === 'ENOENT') return true;
      logger.warn('HOOK', 'Hook spool entry was ingested but could not be removed', {
        kind: file.entry.kind,
        file: file.filename,
      }, error instanceof Error ? error : new Error(String(error)));
      return false;
    }
  }

  private async unlinkTransferredEntry(file: HookSpoolFile, rejectionReason?: string): Promise<boolean> {
    const claimedPath = join(this.directory, `${file.entry.kind}-ack-${randomBytes(16).toString('hex')}.json`);
    try {
      // Claim atomically so a concurrent hook's replacement is never unlinked.
      await rename(file.path, claimedPath);
    } catch (error) {
      if ((error as NodeJS.ErrnoException).code === 'ENOENT') return true;
      logger.warn('HOOK', 'Could not claim an acknowledged spool file; retaining it', {},
        error instanceof Error ? error : new Error(String(error)));
      return false;
    }
    try {
      const current = parseHookSpoolEntry(await readFile(claimedPath, 'utf8'));
      if (!('corruptReason' in current) && canonicalJson(current) === canonicalJson(file.entry)) {
        if (rejectionReason) {
          await mkdir(this.corruptDirectory, { recursive: true });
          await rename(claimedPath, join(this.corruptDirectory, file.filename));
          logger.error('HOOK', rejectionReason, { file: file.filename, corruptDirectory: this.corruptDirectory });
        } else await unlink(claimedPath);
        return true;
      }
      try {
        await link(claimedPath, file.path);
        await unlink(claimedPath);
      } catch (error) {
        // A newer writer may own the original path; keep this unacknowledged version too.
        if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {
          logger.warn('HOOK', 'Could not restore a replaced spool file; its claimed copy remains queued', {},
            error instanceof Error ? error : new Error(String(error)));
        }
      }
    } catch (error) {
      logger.warn('HOOK', 'Could not remove an acknowledged spool file; retaining it for retry', {},
        error instanceof Error ? error : new Error(String(error)));
    }
    return false;
  }

  /**
   * Moves an entry older than `windowMs` to `expired/`, with an error log.
   * True when the file is gone (moved here, or by a concurrent drain).
   */
  private async expireIfPastWindow(file: HookSpoolFile, windowMs: number, windowDescription: string): Promise<boolean> {
    const ageMs = Date.now() - file.entry.enqueuedAtEpochMs;
    if (ageMs <= windowMs) return false;

    const details = {
      kind: file.entry.kind,
      contentSessionId: file.entry.payload.contentSessionId,
      ageMinutes: Math.round(ageMs / 60_000),
      ageHours: Math.round(ageMs / 3_600_000),
      file: file.filename,
      expiredDirectory: this.expiredDirectory,
    };
    try {
      await mkdir(this.expiredDirectory, { recursive: true });
      await rename(file.path, join(this.expiredDirectory, file.filename));
    } catch (error) {
      // ENOENT: a concurrent drain (another worker process) already moved it.
      if ((error as NodeJS.ErrnoException).code === 'ENOENT') return true;
      logger.error('HOOK', `Hook spool entry is past its ${windowDescription} but could not be moved to expired/; keeping it`, details,
        error instanceof Error ? error : new Error(String(error)));
      return false;
    }
    logger.error('HOOK', `Hook spool entry was never accepted within its ${windowDescription}; moved to expired/`, details);
    return true;
  }

  private existingEnqueuedAt(entryPath: string): number | null {
    if (!existsSync(entryPath)) return null;
    try {
      const existing = parseHookSpoolEntry(readFileSync(entryPath, 'utf-8'));
      return 'corruptReason' in existing ? null : existing.enqueuedAtEpochMs;
    } catch (error) {
      // The drain may unlink it between existsSync and readFileSync; a fresh
      // timestamp is then correct.
      logger.debug('HOOK', 'Could not read existing hook spool entry; writing a fresh one', { entryPath },
        error instanceof Error ? error : new Error(String(error)));
      return null;
    }
  }

  private async quarantine(filename: string, reason: string): Promise<boolean> {
    const source = join(this.directory, filename);
    try {
      await mkdir(this.corruptDirectory, { recursive: true });
      await rename(source, join(this.corruptDirectory, filename));
      reportedTransientQuarantineFailures.delete(source);
      logger.error('HOOK', 'Quarantined corrupt hook spool entry', {
        file: filename,
        reason,
        corruptDirectory: this.corruptDirectory,
      });
      return true;
    } catch (error) {
      // ENOENT: a concurrent drain (another worker process) already moved it.
      const code = (error as NodeJS.ErrnoException).code ?? '';
      if (code === 'ENOENT') {
        reportedTransientQuarantineFailures.delete(source);
        return false;
      }
      // Another process (antivirus, an indexer) holds the file open; a later drain retries it.
      if (WINDOWS_RENAME_RETRY_CODES.has(code)) {
        if (!reportedTransientQuarantineFailures.has(source)) {
          reportedTransientQuarantineFailures.add(source);
          logger.warn('HOOK', 'Corrupt hook spool entry is locked; leaving it in place and retrying on a later drain', {
            file: filename,
            reason,
          }, error instanceof Error ? error : new Error(String(error)));
        }
        return false;
      }
      logger.error('HOOK', 'Corrupt hook spool entry could not be quarantined; leaving it in place', {
        file: filename,
        reason,
      }, error instanceof Error ? error : new Error(String(error)));
      return false;
    }
  }

  /** A reported locked file that has left the spool no longer needs suppressing. */
  private forgetReportedQuarantineFailuresNotIn(filenames: readonly string[]): void {
    if (reportedTransientQuarantineFailures.size === 0) return;
    const spoolDirectory = resolve(this.directory);
    const listedPaths = new Set(filenames.map(filename => join(this.directory, filename)));
    for (const reportedPath of reportedTransientQuarantineFailures) {
      if (resolve(dirname(reportedPath)) === spoolDirectory && !listedPaths.has(reportedPath)) {
        reportedTransientQuarantineFailures.delete(reportedPath);
      }
    }
  }

  /**
   * Reads the spool without holding the event loop. Files are read in bounded
   * parallel batches, so a backlog left by a worker outage is read quickly
   * without opening more than `DRAIN_READ_BATCH_SIZE` files at once.
   */
  private async readEntries(maxEntries: number = Number.POSITIVE_INFINITY): Promise<{ files: HookSpoolFile[]; quarantined: number; omitted: number }> {
    if (!existsSync(this.directory)) return { files: [], quarantined: 0, omitted: 0 };

    let filenames: string[];
    try {
      filenames = (await readdir(this.directory)).filter(filename => ENTRY_FILENAME.test(filename));
    } catch (error) {
      logger.warn('HOOK', 'Could not list hook spool entries', { directory: this.directory },
        error instanceof Error ? error : new Error(String(error)));
      return { files: [], quarantined: 0, omitted: 0 };
    }
    this.forgetReportedQuarantineFailuresNotIn(filenames);

    const files: HookSpoolFile[] = [];
    let quarantined = 0;
    let omitted = 0;
    // Parse inside each read so a batch never holds more than one batch of raw
    // payloads at once; a bounded drain keeps at most `maxEntries` parsed
    // entries, so the batch shrinks with the caller's limit instead of
    // dominating it.
    const batchSize = Math.max(1, Math.min(DRAIN_READ_BATCH_SIZE, maxEntries));
    for (let start = 0; start < filenames.length; start += batchSize) {
      const batch = filenames.slice(start, start + batchSize);
      const reads = await Promise.all(batch.map(async (filename): Promise<{ file: HookSpoolFile } | { corrupt: string; filename: string } | null> => {
        const entryPath = join(this.directory, filename);
        let raw: string;
        try {
          raw = await readFile(entryPath, 'utf-8');
        } catch (error) {
          // ENOENT: drained by a concurrent pass after the listing. Anything
          // else is retried on the next pass.
          if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
            logger.warn('HOOK', 'Could not read hook spool entry; will retry', { file: filename },
              error instanceof Error ? error : new Error(String(error)));
          }
          return null;
        }
        const parsed = parseHookSpoolEntry(raw);
        if ('corruptReason' in parsed) return { corrupt: parsed.corruptReason, filename };
        return { file: { entry: parsed, path: entryPath, filename } };
      }));

      for (const read of reads) {
        if (read === null) continue;
        if ('corrupt' in read) {
          if (await this.quarantine(read.filename, read.corrupt)) quarantined++;
          continue;
        }
        // Rewritten with a valid entry: a later corrupt write here is a new failure to report.
        reportedTransientQuarantineFailures.delete(read.file.path);
        files.push(read.file);
        if (files.length > maxEntries) omitted += retainOldestEntries(files, maxEntries);
      }
    }

    files.sort(compareSpoolFiles);
    return { files, quarantined, omitted };
  }
}

/**
 * One-time boot migration from the retired DeferredSessionEndQueue
 * (`state/session-end-replay/<sha256>.json` holding
 * `{contentSessionId, platformSource, requestedAtEpoch}`): each readable entry
 * becomes a `session_end` spool entry, malformed ones are quarantined into the
 * spool's corrupt directory, and the legacy directory is removed.
 */
export function migrateLegacySessionEndReplay(
  spool: HookSpool,
  legacyDirectory: string = resolveLegacySessionEndReplayDirectory(),
): number {
  if (!existsSync(legacyDirectory)) return 0;

  let migrated = 0;
  for (const filename of readdirSync(legacyDirectory)) {
    if (!filename.endsWith('.json') || filename.startsWith('.')) continue;
    const legacyPath = join(legacyDirectory, filename);
    let entry: { contentSessionId?: unknown; platformSource?: unknown; requestedAtEpoch?: unknown } | null = null;
    try {
      entry = JSON.parse(readFileSync(legacyPath, 'utf-8'));
    } catch (error) {
      logger.error('HOOK', 'Legacy SessionEnd replay entry is unreadable', { file: legacyPath },
        error instanceof Error ? error : new Error(String(error)));
    }
    if (entry && isNonEmptyString(entry.contentSessionId)) {
      spool.enqueue('session_end', {
        contentSessionId: entry.contentSessionId,
        platformSource: normalizePlatformSource(typeof entry.platformSource === 'string' ? entry.platformSource : undefined),
      }, typeof entry.requestedAtEpoch === 'number' && Number.isFinite(entry.requestedAtEpoch) ? entry.requestedAtEpoch : Date.now());
      unlinkSync(legacyPath);
      migrated++;
      continue;
    }
    mkdirSync(spool.corruptDirectory, { recursive: true });
    renameSync(legacyPath, join(spool.corruptDirectory, `legacy-session-end-${filename}`));
    logger.error('HOOK', 'Quarantined malformed legacy SessionEnd replay entry', {
      file: filename,
      corruptDirectory: spool.corruptDirectory,
    });
  }

  // Everything meaningful was migrated or quarantined above; what remains is
  // at most an interrupted atomic-write temp file.
  rmSync(legacyDirectory, { recursive: true, force: true });
  if (migrated > 0) {
    logger.info('HOOK', 'Migrated legacy SessionEnd replay entries into the hook spool', { count: migrated });
  }
  return migrated;
}