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

31.9 KB
Raw Blame
import path from 'path';
import { recordSessionPrompt } from '../../cli/handlers/session-init.js';
import { fileEditHandler } from '../../cli/handlers/file-edit.js';
import { ensureWorkerRunning, workerHttpRequest } from '../../shared/worker-utils.js';
import { DATA_DIR } from '../../shared/paths.js';
import { logger } from '../../utils/logger.js';
import { getProjectContext } from '../../utils/project-name.js';
import { writeAgentsMd } from '../../utils/agents-md-utils.js';
import { getValueByPath, resolveFieldSpec, resolveFields, matchesRule, recordTimeEpochMs } from './field-utils.js';
import { expandHomePath, shouldSuppressNativeCodexAgentsContext } from './config.js';
import type { TranscriptSchema, WatchTarget, SchemaEvent } from './types.js';
import { normalizePlatformSource } from '../../shared/platform-source.js';
import { projectsQueryString } from '../../shared/project-list.js';
import { spoolHookEvent } from '../../cli/spool-hook-event.js';
import { ingestObservation, ingestSummarize } from '../worker/http/shared.js';

const AGENT_ID_IN_PATH =
  /agent-transcripts[/\\]([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:[/\\]|$)/i;

/** Prefer the explicit watch field; fall back to `agent-transcripts/<uuid>/` in the path. */
export function resolveWatchAgentId(watch: WatchTarget): string | undefined {
  const explicit = typeof watch.agentId === 'string' ? watch.agentId.trim() : '';
  if (explicit && explicit !== '*') return explicit;
  const match = watch.path.match(AGENT_ID_IN_PATH);
  return match?.[1];
}

/**
 * How observations and summaries reach the worker. The worker's own watcher
 * ingests in-process; the standalone `transcript watch` command has no ingest
 * context, so it uses the common live hook handoff.
 */
export type TranscriptObservationTransport = 'in-process' | 'spool';

interface PendingTool {
  toolName: string;
  toolInput?: unknown;
}

interface SessionState {
  sessionId: string;
  platformSource: string;
  cwd?: string;
  project?: string;
  lastUserMessage?: string;
  lastAssistantMessage?: string;
  pendingTools?: Map<string, PendingTool>;
  isSubagent?: boolean;
}

/**
 * What the watcher keeps per transcript file across restarts: the working
 * directory its session last reported, and the tool calls still waiting for
 * their results. Some hosts write the directory once, on the session's first
 * line (DeepSeek Harness), so a watcher that resumes mid-file would otherwise
 * never learn it; and a result retried after a restart still needs its tool's
 * name and input. The processor reads both as a fallback and updates them.
 * The real host session identity is re-read from the header on resume.
 */
export interface TranscriptFileContext {
  /** False once the path holds another file than the one this context was saved from. */
  isCurrent?: () => boolean;
  cwd?: string;
  /** Outstanding tool calls by session key, then tool id: the file's newest MAX_PENDING_TOOLS_PER_FILE. */
  pendingTools?: Record<string, Record<string, { toolName: string; toolInput?: unknown }>>;
  /** Real host identity from the header, including non-UUID session IDs. */
  sessionId?: string;
  /** Every session this file's lines fed, content session id → platform source. */
  sessions?: Map<string, string>;
}

/** How many subagent rollouts the processor remembers past their last turn. */
const MAX_REMEMBERED_SUBAGENT_SESSIONS = 4096;

/**
 * How many transcript sessions the processor keeps in memory. A transcript
 * that crashes, is truncated, or uses a schema with no session_end never ends
 * its session, so without a cap that state would live for the worker's
 * lifetime. Reason for 4096 (memory protection): each entry is a few short
 * strings, its last user and assistant message, and at most
 * MAX_PENDING_TOOLS_PER_FILE tools per file; the number matches
 * MAX_REMEMBERED_SUBAGENT_SESSIONS, the marker set that already outlives these
 * sessions, and is far above the transcripts one worker tails at once, so a
 * live session is evicted only after thousands of newer ones were used.
 */
const MAX_REMEMBERED_TRANSCRIPT_SESSIONS = 4096;

/**
 * Trim the least recently used sessions that have no outstanding tools, never
 * the one named by keepKey (the session the caller is about to use). A session
 * with a pending tool call is never dropped to satisfy the cap; it waits for
 * its own cleanup so an interrupted turn keeps the context it needs.
 * Map order is use order: callers move a session to the end on each use.
 * Returns how many sessions were evicted.
 */
export function evictIdleSessions<T extends { pendingTools?: { size: number } }>(
  sessions: Map<string, T>,
  max: number,
  keepKey?: string,
): number {
  let evicted = 0;
  for (const [key, session] of sessions) {
    if (sessions.size <= max) break;
    if (key === keepKey) continue;
    if ((session.pendingTools?.size ?? 0) === 0) {
      sessions.delete(key);
      evicted++;
    }
  }
  return evicted;
}

/**
 * Outstanding tool calls a file keeps, the newest: calls whose result never
 * comes (an interrupted turn, a schema with no matching result event) would
 * otherwise pile up in the watch state, inputs and all.
 */
const MAX_PENDING_TOOLS_PER_FILE = 64;

export class TranscriptEventProcessor {
  constructor(
    private observationTransport: TranscriptObservationTransport = 'in-process',
    private maxRememberedTranscriptSessions: number = MAX_REMEMBERED_TRANSCRIPT_SESSIONS,
  ) {}

  /** In least-recently-used order: getOrCreateSession moves a session to the end on each use. */
  private sessions = new Map<string, SessionState>();
  /** Set while every session over the cap is busy, so that is reported once, not per event. */
  private sessionCapExceededReported = false;
  /** Ownership is in-memory only; durable snapshots below contain each file's tools. */
  private fileContexts = new Set<TranscriptFileContext>();
  private fileSessionKeys = new WeakMap<TranscriptFileContext, Set<string>>();
  registerFileContext(file: TranscriptFileContext): void { this.fileContexts.add(file); }

  private pendingToolOwners = new WeakMap<PendingTool, TranscriptFileContext>();
  /**
   * Session keys of confirmed subagent rollouts. Codex ends a session per
   * turn but marks the rollout only on its first line, so the marker has to
   * outlive the turn state session_end drops. Oldest forgotten first.
   */
  private subagentSessionKeys = new Set<string>();

  /** A replaced transcript lends neither its outstanding tools nor its directory to the new file. */
  resetFileContext(file: TranscriptFileContext): void {
    for (const key of this.sessionKeysOf(file)) {
      const session = this.sessions.get(key);
      if (session && session.cwd === file.cwd) session.cwd = undefined;
    }
    this.retireFileContext(file);
    file.cwd = undefined;
    file.sessionId = undefined;
  }

  /** A transcript that is gone: its outstanding tool calls are dropped, and it lends none to other files. */
  retireFileContext(file: TranscriptFileContext): void {
    for (const key of this.sessionKeysOf(file)) {
      const tools = this.sessions.get(key)?.pendingTools;
      for (const [id, tool] of tools ?? []) {
        if (this.pendingToolOwners.get(tool) === file) tools!.delete(id);
      }
    }
    this.fileContexts.delete(file);
    this.fileSessionKeys.delete(file);
    file.pendingTools = {};
  }

  private sessionKeysOf(file: TranscriptFileContext): Set<string> {
    return new Set([...Object.keys(file.pendingTools ?? {}), ...(this.fileSessionKeys.get(file) ?? [])]);
  }

  async processEntry(
    entry: unknown,
    watch: WatchTarget,
    schema: TranscriptSchema,
    sessionIdOverride?: string | null,
    file?: TranscriptFileContext
  ): Promise<void> {
    if (file) this.registerFileContext(file);
    for (const event of schema.events) {
      if (!matchesRule(entry, event.match, schema)) continue;
      await this.handleEvent(entry, watch, schema, event, sessionIdOverride ?? undefined, file);
    }
  }

  private getSessionKey(watch: WatchTarget, sessionId: string): string {
    return `${watch.name}:${sessionId}`;
  }

  private getOrCreateSession(watch: WatchTarget, sessionId: string): SessionState {
    const key = this.getSessionKey(watch, sessionId);
    let session = this.sessions.get(key);
    if (session) {
      // Move it to the end so eviction goes by last use, not creation.
      this.sessions.delete(key);
      this.sessions.set(key, session);
      return session;
    }
    session = {
      sessionId,
      platformSource: normalizePlatformSource(watch.name),
      ...(this.subagentSessionKeys.has(key) ? { isSubagent: true } : {}),
    };
    this.sessions.set(key, session);
    this.enforceSessionCap(key);
    return session;
  }

  private enforceSessionCap(keepKey: string): void {
    const cap = this.maxRememberedTranscriptSessions;
    const evicted = evictIdleSessions(this.sessions, cap, keepKey);
    if (evicted > 0) {
      logger.debug('TRANSCRIPT', 'Evicted idle transcript sessions over cap', { evicted, cap, remaining: this.sessions.size });
    }
    if (this.sessions.size <= cap) {
      this.sessionCapExceededReported = false;
    } else if (!this.sessionCapExceededReported) {
      this.sessionCapExceededReported = true;
      logger.warn('TRANSCRIPT', 'Transcript sessions over cap: every older session has a pending tool, none evicted', { cap, remaining: this.sessions.size });
    }
  }

  private rememberSubagentSession(key: string): void {
    this.subagentSessionKeys.delete(key);
    this.subagentSessionKeys.add(key);
    if (this.subagentSessionKeys.size > MAX_REMEMBERED_SUBAGENT_SESSIONS) {
      const oldest = this.subagentSessionKeys.values().next().value;
      if (oldest !== undefined) this.subagentSessionKeys.delete(oldest);
    }
  }

  /**
   * Learn a rollout's session context (cwd, subagent marker) from its first
   * line without ingesting anything. A tail that resumes past that line (a
   * worker restart, or startAtEnd on a rollout already running) never reads
   * it otherwise, and a subagent-only watch would drop the whole rollout.
   */
  async primeSessionContext(
    entry: unknown,
    watch: WatchTarget,
    schema: TranscriptSchema,
    sessionIdOverride?: string | null,
    file?: TranscriptFileContext
  ): Promise<void> {
    for (const event of schema.events) {
      if (event.action !== 'session_context' || !matchesRule(entry, event.match, schema)) continue;
      await this.handleEvent(entry, watch, schema, event, sessionIdOverride ?? undefined, file);
    }
  }

  private resolveSessionId(
    entry: unknown,
    watch: WatchTarget,
    schema: TranscriptSchema,
    event: SchemaEvent,
    sessionIdOverride?: string
  ): string | null {
    const ctx = { watch, schema } as any;
    const fieldSpec = event.fields?.sessionId ?? (schema.sessionIdPath ? { path: schema.sessionIdPath } : undefined);
    const resolved = resolveFieldSpec(fieldSpec, entry, ctx);
    if (typeof resolved === 'string' && resolved.trim()) return resolved;
    if (typeof resolved === 'number') return String(resolved);
    if (sessionIdOverride && sessionIdOverride.trim()) return sessionIdOverride;
    return null;
  }

  private resolveCwd(
    entry: unknown,
    watch: WatchTarget,
    schema: TranscriptSchema,
    event: SchemaEvent,
    session: SessionState
  ): string | undefined {
    const ctx = { watch, schema, session } as any;
    const fieldSpec = event.fields?.cwd ?? (schema.cwdPath ? { path: schema.cwdPath } : undefined);
    const resolved = resolveFieldSpec(fieldSpec, entry, ctx);
    if (typeof resolved === 'string' && resolved.trim()) return resolved;
    if (watch.workspace) return watch.workspace;
    return session.cwd;
  }

  private resolveProject(
    entry: unknown,
    watch: WatchTarget,
    schema: TranscriptSchema,
    event: SchemaEvent,
    session: SessionState
  ): string | undefined {
    const ctx = { watch, schema, session } as any;
    const fieldSpec = event.fields?.project ?? (schema.projectPath ? { path: schema.projectPath } : undefined);
    const resolved = resolveFieldSpec(fieldSpec, entry, ctx);
    if (typeof resolved === 'string' && resolved.trim()) return resolved;
    if (watch.project) return watch.project;
    if (session.cwd) return getProjectContext(session.cwd).primary;
    return session.project;
  }

  private async handleEvent(
    entry: unknown,
    watch: WatchTarget,
    schema: TranscriptSchema,
    event: SchemaEvent,
    sessionIdOverride?: string,
    file?: TranscriptFileContext
  ): Promise<void> {
    const sessionId = this.resolveSessionId(entry, watch, schema, event, file?.sessionId ?? sessionIdOverride);
    if (!sessionId) {
      logger.debug('TRANSCRIPT', 'Skipping event without sessionId', { event: event.name, watch: watch.name });
      return;
    }
    if (file) file.sessionId = sessionId;

    const session = this.getOrCreateSession(watch, sessionId);
    const sessionKey = this.getSessionKey(watch, sessionId);
    if (file) {
      (file.sessions ??= new Map()).set(sessionId, session.platformSource);
      const keys = this.fileSessionKeys.get(file) ?? new Set<string>();
      keys.add(sessionKey);
      this.fileSessionKeys.set(file, keys);
    }
    if (file?.pendingTools?.[sessionKey]) {
      session.pendingTools ??= new Map();
      for (const [id, tool] of Object.entries(file.pendingTools[sessionKey])) {
        this.pendingToolOwners.set(tool, file);
        if (!session.pendingTools.has(id)) session.pendingTools.set(id, tool);
      }
    }
    // After a restart the watcher resumes mid-file, past the line that carried
    // the session's working directory: start from the one saved for the file.
    if (!session.cwd && file?.cwd) session.cwd = file.cwd;
    const cwd = this.resolveCwd(entry, watch, schema, event, session);
    if (cwd) session.cwd = cwd;
    const project = this.resolveProject(entry, watch, schema, event, session);
    if (project) session.project = project;

    // Codex writes the subagent marker on the first (session_meta) line, as an
    // object; learn it from whichever line carries it so later ingest events
    // can be gated. Its presence is the test, not its contents.
    if (watch.subagentSource && !session.isSubagent) {
      const marker = getValueByPath(entry, watch.subagentSource.path);
      if (marker !== undefined && marker !== null) {
        session.isSubagent = true;
        this.rememberSubagentSession(this.getSessionKey(watch, sessionId));
      }
    }

    // When native hooks own top-level sessions, ingest only confirmed subagent
    // rollouts. session_context still runs so a later marker line can flip the
    // session on; session_end still runs so the suppressed session is dropped
    // from the map instead of lingering.
    if (
      watch.subagentOnly &&
      !session.isSubagent &&
      event.action !== 'session_context' &&
      event.action !== 'session_end'
    ) {
      return;
    }

    const fields = resolveFields(event.fields, entry, { watch, schema, session: session as unknown as Record<string, unknown> });
    // The line's own time, not the read's: a restart re-reads old lines now,
    // and only this tells them from new work in a session the user deleted.
    const eventOccurredAtEpochMs = recordTimeEpochMs(entry);

    if (event.action === 'session_context') this.applySessionContext(session, fields);
    // Whatever directory the session now has is the file's, for the next restart.
    if (file && session.cwd) file.cwd = session.cwd;

    try {
      switch (event.action) {
        case 'session_context':
          break;
        case 'session_init':
          await this.handleSessionInit(session, fields, eventOccurredAtEpochMs);
          if (watch.context?.updateOn?.includes('session_start')) {
            await this.updateContext(session, watch);
          }
          break;
        case 'user_message': {
          // A user turn is anchored like a hook-captured prompt. Kept only in
          // memory, it left the session at prompt 0, so the observer got a
          // continuation with no user request and the batch was dropped (#3653).
          const prompt = this.resolveMessageText(fields.message) ?? this.resolveMessageText(fields.prompt);
          if (prompt) await this.anchorUserPrompt(session, prompt, eventOccurredAtEpochMs);
          break;
        }
        case 'assistant_message':
          session.lastAssistantMessage = this.resolveMessageText(fields.message) ?? session.lastAssistantMessage;
          break;
        case 'tool_use':
          await this.handleToolUse(session, watch, fields, eventOccurredAtEpochMs, file);
          break;
        case 'tool_result':
          await this.handleToolResult(session, watch, fields, eventOccurredAtEpochMs, file);
          break;
        case 'observation':
          await this.sendObservation(session, watch, fields, eventOccurredAtEpochMs);
          break;
        case 'file_edit':
          await this.sendFileEdit(session, fields, eventOccurredAtEpochMs);
          break;
        case 'session_end':
          await this.handleSessionEnd(session, watch);
          break;
        default:
          break;
      }
    } finally {
      if (file) this.snapshotPendingTools(file, session, sessionKey, event.action === 'session_end');
    }
  }

  /**
   * Records the session's outstanding tool calls that this file made in the
   * file's durable snapshot (saved with the watch state), and keeps only the
   * file's newest MAX_PENDING_TOOLS_PER_FILE: older ones are forgotten here
   * and in the session.
   */
  private snapshotPendingTools(file: TranscriptFileContext, session: SessionState, sessionKey: string, sessionEnded: boolean): void {
    const pending: Record<string, PendingTool> = sessionEnded ? {} : { ...file.pendingTools?.[sessionKey] };
    for (const [id, tool] of session.pendingTools ?? []) {
      if (this.pendingToolOwners.get(tool) === file) pending[id] = tool;
    }
    file.pendingTools = { ...file.pendingTools, [sessionKey]: pending };
    if (Object.keys(pending).length === 0) delete file.pendingTools[sessionKey];

    // Oldest first: a snapshot keeps its keys in insertion order.
    const held = Object.entries(file.pendingTools).flatMap(([key, tools]) => Object.keys(tools).map(id => [key, id] as const));
    for (const [key, id] of held.slice(0, Math.max(0, held.length - MAX_PENDING_TOOLS_PER_FILE))) {
      const tools = file.pendingTools[key];
      const forgotten = tools[id];
      delete tools[id];
      if (Object.keys(tools).length === 0) delete file.pendingTools[key];
      const sessionTools = this.sessions.get(key)?.pendingTools;
      if (sessionTools?.get(id) === forgotten) sessionTools.delete(id);
    }
  }

  private applySessionContext(session: SessionState, fields: Record<string, unknown>): void {
    const cwd = typeof fields.cwd === 'string' ? fields.cwd : undefined;
    const project = typeof fields.project === 'string' ? fields.project : undefined;
    if (cwd) session.cwd = cwd;
    if (project) session.project = project;
  }

  /**
   * Normalize visible message text. Reasoning and other non-text blocks are
   * not the assistant's answer. A message with no visible text must not
   * replace the preceding answer; strings retain their existing behavior.
   */
  private resolveMessageText(value: unknown): string | undefined {
    if (typeof value === 'string') return value;
    if (!Array.isArray(value)) return undefined;
    const parts: string[] = [];
    for (const block of value) {
      if (!block || typeof block !== 'object') continue;
      const { type, text } = block as { type?: unknown; text?: unknown };
      if (type !== undefined && type !== 'text' && type !== 'input_text' && type !== 'output_text') continue;
      if (typeof text === 'string' && text.length > 0) parts.push(text);
    }
    return parts.length > 0 ? parts.join('\n') : undefined;
  }

  private async handleSessionInit(session: SessionState, fields: Record<string, unknown>, eventOccurredAtEpochMs: number | null): Promise<void> {
    const prompt = this.resolveMessageText(fields.prompt) ?? '';
    await this.anchorUserPrompt(session, prompt, eventOccurredAtEpochMs);
  }

  /**
   * Record the turn's user prompt through the init path the hooks use, so the
   * worker has a user_prompts row for it. A failed handoff is skipped; the
   * transcript remains source evidence, not a backlog for later inference.
   */
  private async anchorUserPrompt(session: SessionState, prompt: string, eventOccurredAtEpochMs: number | null): Promise<void> {
    if (prompt) {
      session.lastUserMessage = prompt;
    }
    const cwd = session.cwd;
    if (!cwd) {
      this.skipWithoutCwd(session, 'user prompt');
      return;
    }

    try {
      await recordSessionPrompt({
        sessionId: session.sessionId,
        cwd,
        prompt,
        platform: session.platformSource,
        eventOccurredAtEpochMs,
      });
    } catch (error: unknown) {
      logger.warn('TRANSCRIPT', 'Skipping user prompt after failed live handoff', { sessionId: session.sessionId }, error instanceof Error ? error : undefined);
    }
  }

  /**
   * A turn of a session whose working directory is not known yet is skipped.
   * The worker's own directory is not a stand-in: it would key the prompt or
   * observation to the worker's own data dir (`.claude-mem`) and check project
   * exclusions against it. Once the session or its file reports a directory,
   * its turns go through.
   */
  private skipWithoutCwd(session: SessionState, what: string): void {
    logger.debug('TRANSCRIPT', `Skipping a ${what}: the session has no known working directory yet`, {
      sessionId: session.sessionId,
    });
  }

  private async handleToolUse(session: SessionState, watch: WatchTarget, fields: Record<string, unknown>, eventOccurredAtEpochMs: number | null, file?: TranscriptFileContext): Promise<void> {
    const toolId = typeof fields.toolId === 'string' ? fields.toolId : undefined;
    const toolName = typeof fields.toolName === 'string' ? fields.toolName : undefined;
    const toolInput = this.maybeParseJson(fields.toolInput);
    const toolResponse = this.maybeParseJson(fields.toolResponse);

    if (toolName && toolResponse !== undefined) {
      await this.sendObservation(session, watch, {
        toolName,
        toolInput,
        toolResponse,
        toolUseId: toolId,
      }, eventOccurredAtEpochMs);
    } else if (toolName && toolId) {
      if (!session.pendingTools) session.pendingTools = new Map();
      const tool: PendingTool = { toolName, toolInput };
      if (file) this.pendingToolOwners.set(tool, file);
      session.pendingTools.set(toolId, tool);
    }
  }

  private async handleToolResult(session: SessionState, watch: WatchTarget, fields: Record<string, unknown>, eventOccurredAtEpochMs: number | null, file?: TranscriptFileContext): Promise<void> {
    const toolId = typeof fields.toolId === 'string' ? fields.toolId : undefined;
    let toolName = typeof fields.toolName === 'string' ? fields.toolName : undefined;
    const toolResponse = this.maybeParseJson(fields.toolResponse);
    let toolInput = this.maybeParseJson(fields.toolInput);

    const fileTools = file?.pendingTools?.[this.getSessionKey(watch, session.sessionId)];
    const cached = toolId ? session.pendingTools?.get(toolId) : undefined;
    let owner = file;
    let pending = file
      ? (toolId ? fileTools?.[toolId] : undefined) ?? (cached && this.pendingToolOwners.get(cached) === file ? cached : undefined)
      : cached;
    if (!pending && file && toolId) {
      // A result can land in another file of the same session. Its tool call is
      // borrowed only from a single holder that still is the file it was saved
      // from: two holders of one id are not guessed between. The id is checked
      // first, since isCurrent() stats the file.
      const candidates = Array.from(this.fileContexts).flatMap(context => {
        const tool = context.pendingTools?.[this.getSessionKey(watch, session.sessionId)]?.[toolId];
        return tool && context.isCurrent?.() !== false ? [{ context, tool }] : [];
      });
      if (candidates.length === 1) {
        owner = candidates[0].context;
        pending = candidates[0].tool;
      }
    }
    if (pending) {
      if (!toolName) toolName = pending.toolName;
      if (toolInput === undefined) toolInput = pending.toolInput;
    }

    if (toolName) {
      await this.sendObservation(session, watch, {
        toolName,
        toolInput,
        toolResponse,
        toolUseId: toolId,
      }, eventOccurredAtEpochMs);
      if (toolId) {
        if (session.pendingTools && session.pendingTools.get(toolId) === pending) session.pendingTools.delete(toolId);
        const ownerTools = owner?.pendingTools?.[this.getSessionKey(watch, session.sessionId)];
        if (ownerTools) delete ownerTools[toolId];
      }
    } else {
      logger.debug('TRANSCRIPT', 'Dropping tool_result with no resolvable toolName', {
        sessionId: session.sessionId,
        toolId,
      });
    }
  }

  private async sendObservation(session: SessionState, watch: WatchTarget, fields: Record<string, unknown>, eventOccurredAtEpochMs: number | null): Promise<void> {
    const toolName = typeof fields.toolName === 'string' ? fields.toolName : undefined;
    if (!toolName) return;
    if (!session.cwd) {
      this.skipWithoutCwd(session, 'observation');
      return;
    }

    const toolInput = this.maybeParseJson(fields.toolInput);
    const payload = {
      contentSessionId: session.sessionId,
      cwd: session.cwd,
      toolName,
      // Freeform patch calls need the same recognized field as structured
      // patch inputs after ingest JSON-encodes them for file evidence.
      toolInput: toolName === 'apply_patch' && typeof toolInput === 'string' ? { patch: toolInput } : toolInput,
      toolResponse: this.maybeParseJson(fields.toolResponse),
      platformSource: session.platformSource,
      toolUseId: typeof fields.toolUseId === 'string' ? fields.toolUseId : undefined,
      agentId: resolveWatchAgentId(watch),
      eventOccurredAtEpochMs,
    };
    if (this.observationTransport === 'spool') {
      try {
        spoolHookEvent('observation', payload);
      } catch (error) {
        logger.warn('TRANSCRIPT', 'Skipping transcript event after failed live handoff', { sessionId: session.sessionId }, error instanceof Error ? error : undefined);
      }
      return;
    }

    let accepted = false;
    try {
      const result = await ingestObservation(payload, { markHandedOff: () => { accepted = true; } });
      if (!result.ok) throw new Error(result.reason);
    } catch (error) {
      // A generator kick can fail after queueObservation accepted the event.
      // That event is already owned by the worker and must not be replayed.
      if (accepted) {
        logger.warn('TRANSCRIPT', 'Observation accepted before generator kick failed', {
          sessionId: session.sessionId,
        }, error instanceof Error ? error : undefined);
        return;
      }
      logger.warn('TRANSCRIPT', 'Skipping observation after failed live handoff', { sessionId: session.sessionId }, error instanceof Error ? error : undefined);
    }
  }

  private async sendFileEdit(session: SessionState, fields: Record<string, unknown>, eventOccurredAtEpochMs: number | null): Promise<void> {
    const filePath = typeof fields.filePath === 'string' ? fields.filePath : undefined;
    if (!filePath) return;
    if (!session.cwd) {
      this.skipWithoutCwd(session, 'file edit');
      return;
    }

    try {
      await fileEditHandler.execute({
        sessionId: session.sessionId,
        cwd: session.cwd,
        filePath,
        edits: Array.isArray(fields.edits) ? fields.edits : undefined,
        platform: session.platformSource,
        eventOccurredAtEpochMs,
      });
    } catch (error) {
      logger.warn('TRANSCRIPT', 'Skipping transcript event after failed live handoff', { sessionId: session.sessionId }, error instanceof Error ? error : undefined);
    }
  }

  private maybeParseJson(value: unknown): unknown {
    if (typeof value !== 'string') return value;
    const trimmed = value.trim();
    if (!trimmed) return value;
    if (!(trimmed.startsWith('{') || trimmed.startsWith('['))) return value;
    try {
      return JSON.parse(trimmed);
    } catch (error) {
      logger.debug('TRANSCRIPT', 'Field looked like JSON but did not parse; using raw string', {
        preview: trimmed.slice(0, 120),
      }, error instanceof Error ? error : undefined);
      return value;
    }
  }

  private async handleSessionEnd(session: SessionState, watch: WatchTarget): Promise<void> {
    // A suppressed top-level session reaches here only to be cleaned up; its
    // summary and context belong to the native hooks, not the transcript watch.
    if (!watch.subagentOnly || session.isSubagent) {
      await this.queueSummary(session);
      await this.updateContext(session, watch);
    }
    session.pendingTools?.clear();
    const key = this.getSessionKey(watch, session.sessionId);
    this.sessions.delete(key);
  }

  private async queueSummary(session: SessionState): Promise<void> {
    if (this.observationTransport === 'spool') {
      try {
        spoolHookEvent('summarize', {
          contentSessionId: session.sessionId,
          platformSource: session.platformSource,
          lastAssistantMessage: session.lastAssistantMessage ?? '',
          ...(session.cwd ? { cwd: session.cwd } : {}),
        });
      } catch (error) {
        logger.warn('TRANSCRIPT', 'Skipping transcript event after failed live handoff', { sessionId: session.sessionId }, error instanceof Error ? error : undefined);
      }
      return;
    }
    // The worker's watcher shares the ingest context with observations. HTTP
    // cannot tell a rejected queue operation from a failed generator kick
    // after acceptance; the synchronous handoff marks that boundary exactly.
    let accepted = false;
    try {
      await ingestSummarize({
        contentSessionId: session.sessionId,
        platformSource: session.platformSource,
        lastAssistantMessage: session.lastAssistantMessage ?? '',
        ...(session.cwd ? { cwd: session.cwd } : {}),
      }, undefined, { markHandedOff: () => { accepted = true; } });
    } catch (error) {
      if (accepted) {
        logger.warn('TRANSCRIPT', 'Summary accepted before generator kick failed', {
          sessionId: session.sessionId,
        }, error instanceof Error ? error : undefined);
        return;
      }
      logger.warn('TRANSCRIPT', 'Skipping summary after failed live handoff', { sessionId: session.sessionId }, error instanceof Error ? error : undefined);
    }
  }

  private async updateContext(session: SessionState, watch: WatchTarget): Promise<void> {
    if (!watch.context) return;
    if (watch.context.mode !== 'agents') return;
    if (shouldSuppressNativeCodexAgentsContext(watch)) return;

    const workerReady = await ensureWorkerRunning();
    if (!workerReady) return;

    const cwd = session.cwd ?? watch.workspace;
    if (!cwd) return;

    const context = getProjectContext(cwd);
    const projectsQuery = projectsQueryString(context.allProjects);

    const contextUrl = `/api/context/inject?${projectsQuery}&platformSource=${encodeURIComponent(session.platformSource)}`;
    const agentsPath = expandHomePath(watch.context.path ?? `${cwd}/AGENTS.md`);

    const resolvedAgentsPath = path.resolve(agentsPath);
    const allowedRoots = [path.resolve(cwd), path.resolve(DATA_DIR)];
    const isPathSafe = allowedRoots.some(root => resolvedAgentsPath.startsWith(root + path.sep) || resolvedAgentsPath === root);
    if (!isPathSafe) {
      logger.warn('SECURITY', 'Rejected path traversal attempt in watch.context.path', {
        original: watch.context.path,
        resolved: resolvedAgentsPath,
        allowedRoots
      });
      return;
    }

    let response: Awaited<ReturnType<typeof workerHttpRequest>>;
    try {
      response = await workerHttpRequest(contextUrl);
    } catch (error: unknown) {
      logger.warn('TRANSCRIPT', 'Failed to fetch AGENTS.md context', {
        error: error instanceof Error ? error.message : String(error)
      });
      return;
    }

    if (!response.ok) return;

    const content = (await response.text()).trim();
    if (!content) return;

    writeAgentsMd(agentsPath, content);
    logger.debug('TRANSCRIPT', 'Updated AGENTS.md context', { agentsPath, watch: watch.name });
  }
}