Skip to content

Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.

TypeScript
35.1 KB
Raw Blame
import { existsSync, readFileSync } from "node:fs";
import { basename, join } from "node:path";

import { delegatedAgentName } from "../agent-identity.ts";
import { appendAuditRecord } from "../reliability/audit.ts";
import { appendLogEvent } from "./log.ts";
import { SESSION_LIFECYCLE_AUDIT_DIR } from "./audit-dirs.ts";
import { brainDirsForWrite } from "./paths.ts";
import { buildCaptureBoundary, type SessionCaptureDecision } from "./capture-boundary.ts";
import { extractFacts, routeExtractedFacts } from "./fact-extract.ts";
import { emitIngestDedupReport } from "./dedup-telemetry.ts";
import {
  buildDedupIndex,
  computeDedupHash,
  loadDedupIndex,
  type DedupIndexEntry,
} from "./dedup-hash.ts";
import type { Safeguard } from "./safeguard.ts";
import { discoverMarkersDetailed, isFeedbackMarker } from "./inline.ts";
import { writeSignal } from "./signal.ts";
import { isoDate, isoSecond } from "./time.ts";
import { BRAIN_LOG_EVENT_KIND, BRAIN_SIGNAL_SOURCE_TYPE } from "./types.ts";
import { isToolResponseError } from "./tool-outcome.ts";
import { validateBrainFeedbackInput } from "./sessions/validate-feedback.ts";
import { resolveSearchConfig } from "../search/index.ts";
import { clearSessionFocus, sessionFocusPath } from "../search/session-focus.ts";
import { resolveSessionHandoff } from "../config.ts";
import { writeHandoffNote, type HandoffNoteResult } from "./handoff.ts";
import { detectAdapter } from "./sessions/registry.ts";
import type { SessionTurn } from "./sessions/types.ts";
import {
  lineageGapSessionIds,
  readLineageLedger,
  recordLineageObservation,
} from "./lineage/ledger.ts";
import { resolveSessionLineageDetailed } from "./lineage/resolve.ts";
import {
  recordWorkIdentityMarker,
  resolveWorkIdentity,
  WORK_IDENTITY_SOURCE,
} from "./lineage/identity.ts";
import { readGitWorkspaceIdentity } from "./git/reader.ts";
import { type DegradationNotice, formatDegradationNotice } from "../integrity/degradation.ts";
import { isCompressionEvidenceEvent, type SessionLineage } from "./lineage/types.ts";
import { refreshAnticipatoryCache } from "./anticipatory-cache.ts";

export interface CaptureSessionLifecycleOptions {
  readonly agent: string;
  readonly now?: Date;
  readonly dryRun?: boolean;
  /**
   * Cooperative deadline for the dedup index walk, the one step whose cost
   * grows with the vault. A hook passes its process ceiling here so a walk
   * that would outlast the host's timeout stops at a file boundary.
   */
  readonly safeguard?: Safeguard;
}

export interface CaptureSessionLifecycleResult {
  readonly event: string;
  readonly session_id?: string;
  /**
   * Host-assigned id of the delegated sub-agent this event closed. Present
   * only on `SubagentStop`, so a flat session's result shape is unchanged.
   */
  readonly agent_id?: string;
  readonly signals_created: number;
  readonly signals_deduped: number;
  readonly tool_replays: number;
  /**
   * Tool calls this event declined to replay because the host reported
   * them as failed. Absent when nothing was declined, so a run with
   * nothing to report keeps its previous shape and a real zero stays
   * distinguishable from a silent skip.
   */
  readonly tool_calls_failed?: number;
  readonly malformed: number;
  /** Capture-boundary verdict for this event (Memory Integrity Suite). */
  readonly boundary_decision: SessionCaptureDecision;
  /** Messages whose text was suppressed before any extraction. */
  readonly suppressed_messages: number;
  readonly facts_extracted: number;
  readonly facts_deduped: number;
  /**
   * Where the audit row landed: the week shard, or the store ledger's
   * name once switched. Absent when a fail-open store write did not land.
   */
  readonly audit_path?: string;
  readonly log_path?: string;
  /**
   * True when the host marked this SessionEnd as interrupted
   * (SIGHUP/SIGTERM/force-quit/restart-drain). Absent for a clean close so
   * the pre-interrupt result shape stays byte-identical (t_c181f92b).
   */
  readonly interrupted?: boolean;
  /**
   * Whether the pre-restart transcript could be consumed on an interrupted
   * close. Absent unless `interrupted` is set; `false` when the transcript
   * was missing/unreadable/empty rather than silently coerced to a clean close.
   */
  readonly transcript_consumed?: boolean;
  /** True when a SessionEnd event cleared that session's bound focus. */
  readonly focus_cleared?: boolean;
  /** Path of the handoff note a SessionEnd event produced (gated). */
  readonly handoff_path?: string;
  /**
   * Session lineage when the session is part of a compression chain
   * (continuity-hygiene-freshness suite). Absent for flat sessions so
   * the pre-lineage result shape stays byte-identical.
   */
  readonly lineage?: SessionLineage;
}

interface NormalizedPayload {
  readonly event: string;
  readonly sessionId?: string;
  readonly transcriptPath?: string;
  readonly promptText?: string;
  readonly toolName?: string;
  readonly toolInput?: unknown;
  /**
   * What the host reported the tool call returned. Declared on the hook
   * payload since the grok adapter landed and lifted past here until
   * v1.49.0, which meant a `brain_feedback` call the host REFUSED was
   * still replayed into a signal - a record for a write that never
   * happened. Read only through {@link isToolResponseError}; the response
   * body itself never reaches disk.
   */
  readonly toolResponse?: unknown;
  readonly cwd?: string;
  /**
   * Host-assigned id of the delegated sub-agent a `SubagentStop` event is
   * closing (Claude Code delivers `agent_id` on that event and no other).
   * Its sibling `agent_transcript_path` is deliberately NOT lifted: it is
   * a machine-local host path, this vault syncs between devices, and the
   * sub-agent's turns reach memory through `o2b brain import-session`,
   * which reads the sidechain flag and the id off the transcript itself.
   */
  readonly agentId?: string;
  readonly parentSessionId?: string;
  readonly rootSessionId?: string;
  readonly compressionDepth?: number;
  /** SessionStart discriminator (`startup|resume|clear|compact`). */
  readonly sessionStartSource?: string;
  /** Declared work id the host named (`work_id`), if any. Unit 9. */
  readonly workId?: string;
  /** Declared lane the host named (`lane_id`), if any. Unit 9. */
  readonly laneId?: string;
  /**
   * Host flag: this SessionEnd was an interrupted close
   * (SIGHUP/SIGTERM/force-quit/restart-drain). Absent by default; only
   * `true` is honoured so an omitted field is byte-identical (t_c181f92b).
   */
  readonly interrupted?: boolean;
  readonly malformed: number;
}

/**
 * Whether capturing this event may need the signal dedup index - the
 * one step whose cost grows with the vault: a read and a frontmatter
 * parse of every `Brain/inbox/sig-*.md` and `processed/sig-*.md`. On a
 * WSL 9p mount of a Windows drive with ~4k signals that walk measured
 * 9-12 s, past the 10 s host timeout, and it is synchronous, so the
 * in-process ceiling timer cannot interrupt it either.
 *
 * Deliberately an OVER-approximation, pure and cheap (no I/O): a prompt
 * that carries a feedback marker or any extractable fact (a URL, an
 * e-mail, a unit-bound quantity such as `80%`), a replayed
 * `brain_feedback` call, and an interrupted SessionEnd (whose transcript
 * is re-extracted). The capture boundary may still suppress the text
 * later; deferring an event that turns out to write nothing costs only
 * a background process.
 */
export function lifecycleEventNeedsDedup(payload: unknown): boolean {
  const normalized = normalizePayload(payload);
  if (normalized.toolName === "brain_feedback") return true;
  if (normalized.event === "SessionEnd" && normalized.interrupted === true) return true;
  const text = normalized.promptText;
  if (text === undefined) return false;
  if (discoverMarkersDetailed(text).markers.some(isFeedbackMarker)) return true;
  return extractFacts(text).length > 0;
}

export async function captureSessionLifecycleEvent(
  vault: string,
  payload: unknown,
  opts: CaptureSessionLifecycleOptions,
): Promise<CaptureSessionLifecycleResult> {
  const now = opts.now ?? new Date();
  const normalized = normalizePayload(payload);
  // The dedup index is a walk of every `Brain/inbox/sig-*.md` (a read and
  // a frontmatter parse per file). On a vault with thousands of signals
  // behind a slow filesystem (WSL's 9p mount of a Windows drive) that walk
  // alone outlasted the UserPromptSubmit hook's host timeout, and it ran
  // for every prompt although almost none carries a marker or a fact.
  // So it is built on first USE - when there is a signal to dedup - and
  // shared by every capture in this event after that. An event that may
  // need it (see `lifecycleEventNeedsDedup`) loads it up front with
  // parallel I/O below; the synchronous build here is the fallback for
  // anything that approximation missed.
  const dedupOpts = opts.safeguard !== undefined ? { safeguard: opts.safeguard } : {};
  let dedup: Map<string, DedupIndexEntry> | undefined;
  const ensureDedup: DedupSource = () => {
    dedup ??= buildDedupIndex(vault, dedupOpts);
    return dedup;
  };
  const counters = {
    signals_created: 0,
    signals_deduped: 0,
    tool_replays: 0,
    malformed: normalized.malformed,
    suppressed_messages: 0,
    facts_extracted: 0,
    facts_deduped: 0,
  };

  // Capture boundary (Memory Integrity Suite): classify FIRST, before
  // any extraction. Ignored sessions produce nothing but the audit
  // row; stateless sessions read but never write; suppressed message
  // text never reaches marker or fact extraction.
  const boundary = buildCaptureBoundary(vault);
  const decision = boundary.sessionDecision(normalized.sessionId, normalized.transcriptPath);
  const mayWrite = decision === "capture";
  if ((mayWrite || opts.dryRun === true) && lifecycleEventNeedsDedup(payload)) {
    dedup = await loadDedupIndex(vault, dedupOpts);
  }

  // Delegation boundary (t_0c6f31ee): `SubagentStop` is the one event that
  // names a sub-agent, and a sub-agent reuses its parent's session id - so
  // without a distinct identity here the dispatched worker's observation
  // reads as the orchestrator's own and the roster cannot tell them apart.
  // Every other event resolves to `opts.agent` exactly as before.
  const capturingAgent =
    normalized.agentId !== undefined
      ? delegatedAgentName(opts.agent, normalized.agentId)
      : opts.agent;
  const captureOpts: CaptureSessionLifecycleOptions =
    capturingAgent === opts.agent ? opts : { ...opts, agent: capturingAgent };

  // Session lineage (continuity-hygiene-freshness): resolve BEFORE
  // recording this session's own ledger observation - the crutch
  // treats prior unlinked history as proof of a parallel session.
  // Read-only resolution runs for every session; the ledger only
  // grows for captured, non-dry runs. Fail-soft throughout.
  let lineage: SessionLineage | undefined;
  /** Continuations that were available and REFUSED. */
  const lineageNotices: DegradationNotice[] = [];
  /**
   * Observations that were made and NOT APPENDED. Kept apart from the
   * abstentions above because they are opposite findings: one says the
   * resolver declined to link, the other says the history the resolver
   * will read next time is missing a line.
   */
  const lineageDrops: DegradationNotice[] = [];
  if (normalized.sessionId !== undefined) {
    try {
      // Unit C: probe the working state ONCE per lifecycle event, at
      // the capture boundary, so the resolver below stays a pure
      // function of its inputs. Two bounded git invocations; a
      // directory outside any repository attests nothing and costs one
      // failed spawn.
      const workspace =
        normalized.cwd !== undefined ? readGitWorkspaceIdentity(normalized.cwd) : null;
      // Unit 9: source the DECLARED work identity here for the same
      // reason the git probe lives here - resolution stays a pure
      // function of its inputs. Absent when nothing declares one, which
      // leaves every rung below exactly as it was.
      const identity = resolveWorkIdentity({
        vault,
        ...(normalized.workId !== undefined ? { payloadWorkId: normalized.workId } : {}),
        ...(normalized.laneId !== undefined ? { payloadLaneId: normalized.laneId } : {}),
        ...(normalized.cwd !== undefined ? { worktree: normalized.cwd } : {}),
        // The same clock the resolver below runs on: the marker rung is
        // the one rung with a freshness bound, and it must age against
        // this event's instant, not against a second reading of the wall
        // clock.
        nowMs: now.getTime(),
      });
      const resolution = resolveSessionLineageDetailed(
        {
          sessionId: normalized.sessionId,
          ...(normalized.parentSessionId !== undefined
            ? { parentSessionId: normalized.parentSessionId }
            : {}),
          ...(normalized.rootSessionId !== undefined
            ? { rootSessionId: normalized.rootSessionId }
            : {}),
          ...(normalized.compressionDepth !== undefined
            ? { compressionDepth: normalized.compressionDepth }
            : {}),
          ...(normalized.cwd !== undefined ? { cwd: normalized.cwd } : {}),
          ...(workspace !== null ? { workspace } : {}),
          ...(identity?.workId !== undefined ? { workId: identity.workId } : {}),
          ...(identity?.laneId !== undefined ? { laneId: identity.laneId } : {}),
        },
        {
          ledger: readLineageLedger(vault),
          // Unit C / block C: a session whose observation the writer
          // lock refused has history the ledger cannot show. Without
          // this the crutch reads it as brand new and stitches it onto
          // an unrelated parallel session in the same directory.
          gapSessionIds: lineageGapSessionIds(vault),
          nowMs: now.getTime(),
          notices: lineageNotices,
        },
      );
      lineage = resolution.lineage;
      if (mayWrite && !opts.dryRun) {
        // The return value carries a NAMED gap when the observation was
        // not appended. Discarding it - which this call site did, as a
        // bare statement - restored the silent failure the widened
        // return type exists to remove: the same audit record that
        // reports a refused continuation can report a lost observation,
        // and the two are the same class of finding.
        const recorded = recordLineageObservation(vault, {
          sessionId: normalized.sessionId,
          at: now.toISOString(),
          ...(normalized.cwd !== undefined ? { cwd: normalized.cwd } : {}),
          event: normalized.event,
          ...(isCompressionEvidenceEvent(normalized.event, normalized.sessionStartSource)
            ? { compressionEvidence: true }
            : {}),
          ...(lineage.source !== "flat" ? { lineage } : {}),
          ...(workspace !== null ? { workspace } : {}),
          ...(identity?.workId !== undefined ? { workId: identity.workId } : {}),
          ...(identity?.laneId !== undefined ? { laneId: identity.laneId } : {}),
        });
        if (recorded.notice !== undefined) lineageDrops.push(recorded.notice);
        recordWorktreeIdentityMarker(vault, normalized.cwd, identity, now.getTime());
      }
    } catch {
      lineage = undefined; // lineage is an enhancement, never a blocker
    }
  }
  const chainLineage = lineage !== undefined && lineage.source !== "flat" ? lineage : undefined;

  let promptText = normalized.promptText;
  if (mayWrite && promptText !== undefined && boundary.suppressMessage(promptText)) {
    counters.suppressed_messages++;
    promptText = undefined;
  }

  if (mayWrite && promptText !== undefined) {
    captureMarkers(vault, normalized, promptText, captureOpts, now, ensureDedup, counters);
    // Fact extraction runs strictly AFTER the boundary: only captured,
    // unsuppressed user text reaches the pattern table.
    const facts = extractFacts(promptText);
    if (facts.length > 0) {
      const routed = routeExtractedFacts(vault, {
        facts,
        agent: capturingAgent,
        now,
        sessionRef: sessionReference(normalized),
        dedup: ensureDedup(),
        ...(opts.dryRun ? { dryRun: true } : {}),
      });
      counters.facts_extracted += routed.created;
      counters.facts_deduped += routed.deduped;
    }
  }

  // A call the host reported as FAILED is not replayed: `brain_feedback`
  // refused to write, and replaying its input would mint the very record
  // the tool declined to create. The decline is counted rather than
  // swallowed, so a run that dropped something says so.
  let toolCallsFailed = 0;
  if (mayWrite && normalized.toolName === "brain_feedback") {
    if (isToolResponseError(normalized.toolResponse)) {
      toolCallsFailed++;
    } else {
      captureToolFeedback(vault, normalized, captureOpts, now, ensureDedup, counters);
    }
  }

  // Session-scoped focus lifecycle (Agent Surface Suite, t_5b478e47):
  // a finished session's bound focus must not leak into the next one.
  // Deliberately NOT gated on the capture boundary (unlike the handoff
  // below): removing the session's own steering state is cleanup, not
  // memory capture, so it applies even for stateless sessions.
  // Fail-soft - focus cleanup can never block lifecycle capture.
  let focusCleared = false;
  if (normalized.event === "SessionEnd" && normalized.sessionId !== undefined && !opts.dryRun) {
    try {
      const searchConfig = resolveSearchConfig({ vault });
      // Clear by file presence, not by activity: an already-expired
      // focus file is still stale state worth removing.
      if (existsSync(sessionFocusPath(searchConfig, normalized.sessionId))) {
        clearSessionFocus(searchConfig, normalized.sessionId);
        focusCleared = true;
      }
    } catch {
      // ignore - lifecycle capture must survive a broken search config
    }
  }

  // Interrupted-session capture (t_c181f92b): when the host flushes an
  // in-flight transcript on SIGHUP/SIGTERM/force-quit/restart-drain and fires
  // SessionEnd with interrupted=true, the in-flight user turns may never have
  // reached per-turn capture. Consume the persisted pre-restart transcript so
  // those turns reach the SAME marker/fact extraction as a live prompt. Only
  // user-authored turns are extracted (matching the fact-extract carve-out -
  // bare assistant output is never auto-captured). Double-counting on resume
  // is prevented by the existing content-keyed dedupe seams (signal
  // dedup_hash + fact dedup index), so re-reading the same turns on a later
  // close suppresses them. Honest: when the transcript cannot be consumed,
  // transcript_consumed is recorded false rather than coerced to a clean
  // close. Fail-soft - a bad transcript never blocks lifecycle capture.
  let transcriptConsumed: boolean | undefined;
  if (
    normalized.event === "SessionEnd" &&
    normalized.interrupted === true &&
    mayWrite &&
    !opts.dryRun
  ) {
    transcriptConsumed = false;
    if (normalized.transcriptPath !== undefined) {
      try {
        const turns = await readTranscriptTurns(normalized.transcriptPath);
        for (const turn of turns) {
          if (turn.role !== "user" || turn.text === undefined) continue;
          if (boundary.suppressMessage(turn.text)) {
            counters.suppressed_messages++;
            continue;
          }
          captureMarkers(vault, normalized, turn.text, captureOpts, now, ensureDedup, counters);
          const facts = extractFacts(turn.text);
          if (facts.length === 0) continue;
          const routed = routeExtractedFacts(vault, {
            facts,
            agent: capturingAgent,
            now,
            sessionRef: sessionReference(normalized),
            dedup: ensureDedup(),
          });
          counters.facts_extracted += routed.created;
          counters.facts_deduped += routed.deduped;
        }
        transcriptConsumed = turns.length > 0;
      } catch {
        // A malformed/unreadable transcript is surfaced honestly (false),
        // never raised into the host.
        transcriptConsumed = false;
      }
    }
  }

  // Handoff note on SessionEnd (Agent Surface Suite, t_28afa4d2):
  // gated by the session_handoff config key (default off) and the
  // capture boundary; reads the recorded transcript through the
  // session adapters. Fail-soft like the rest of lifecycle capture.
  let handoffPath: string | undefined;
  if (
    normalized.event === "SessionEnd" &&
    normalized.transcriptPath !== undefined &&
    mayWrite &&
    !opts.dryRun &&
    resolveSessionHandoff()
  ) {
    try {
      handoffPath = (await writeHandoffNoteFromTranscript(vault, normalized, capturingAgent, now))
        ?.path;
    } catch {
      // ignore - a malformed transcript never blocks lifecycle capture
    }
  }

  // Anticipatory context cache (continuity-hygiene-freshness,
  // t_4cee9df5): piggyback on events that already fire - no daemon, no
  // watcher. TTL debounce lives inside the refresh; suppressed prompt
  // text never reaches the cache (promptText is already cleared above).
  if (
    mayWrite &&
    !opts.dryRun &&
    normalized.sessionId !== undefined &&
    (normalized.event === "UserPromptSubmit" || normalized.event === "PostToolUse")
  ) {
    try {
      refreshAnticipatoryCache(vault, {
        sessionId: normalized.sessionId,
        ...(promptText !== undefined ? { signalText: promptText } : {}),
        now,
      });
    } catch {
      // The cache is an enhancement, never a capture blocker.
    }
  }

  let logPath: string | undefined;
  if (mayWrite && !opts.dryRun) {
    logPath = appendLifecycleLog(vault, normalized, capturingAgent, now, counters);
    // Dedup observability (Unit F): persist the exact-hash drop counts
    // this event produced, keyed by the session being re-ingested.
    // Signals and facts are one count - both are items this event tried
    // to ingest and dropped on a sha-256 collision.
    emitIngestDedupReport(vault, {
      surface: "session_lifecycle",
      sources: [
        {
          ref: normalized.sessionId ?? UNKNOWN_SESSION_REF,
          exactDeduped: counters.signals_deduped + counters.facts_deduped,
        },
      ],
      createdAt: now.toISOString(),
    });
  }

  const auditPath = appendAuditRecord(
    join(brainDirsForWrite(vault).log, SESSION_LIFECYCLE_AUDIT_DIR),
    {
      timestamp: now.toISOString(),
      actor: capturingAgent,
      action: "session_lifecycle_capture",
      target: "Brain/session-lifecycle",
      ok: true,
      details: {
        event: normalized.event,
        ...(normalized.sessionId ? { session_id: normalized.sessionId } : {}),
        ...(normalized.agentId ? { agent_id: normalized.agentId } : {}),
        ...(toolCallsFailed > 0 ? { tool_calls_failed: toolCallsFailed } : {}),
        dry_run: opts.dryRun === true,
        boundary_decision: decision,
        ...(normalized.interrupted === true ? { interrupted: true } : {}),
        ...(transcriptConsumed !== undefined ? { transcript_consumed: transcriptConsumed } : {}),
        ...(chainLineage !== undefined
          ? {
              lineage_root: chainLineage.rootId,
              ...(chainLineage.parentId !== null ? { lineage_parent: chainLineage.parentId } : {}),
              lineage_depth: chainLineage.depth,
              lineage_source: chainLineage.source,
            }
          : {}),
        // Unit C: a continuation that was AVAILABLE and refused. Absent
        // on the ordinary flat path, so a session with nothing to link to
        // keeps its previous audit shape exactly.
        ...(lineageNotices.length > 0
          ? { lineage_abstained: lineageNotices.map(formatDegradationNotice) }
          : {}),
        // Block C: the observation this event tried to record and could
        // not. Absent on every successful append, so the ordinary audit
        // shape is unchanged.
        ...(lineageDrops.length > 0
          ? { lineage_dropped: lineageDrops.map(formatDegradationNotice) }
          : {}),
        ...counters,
      },
    },
    vault,
    // A hook path: a store-only failure is counted device-locally and the
    // capture goes on (design D14 item 1).
    { failOpen: true },
  );

  return {
    event: normalized.event,
    ...(normalized.sessionId ? { session_id: normalized.sessionId } : {}),
    ...(normalized.agentId ? { agent_id: normalized.agentId } : {}),
    signals_created: counters.signals_created,
    signals_deduped: counters.signals_deduped,
    tool_replays: counters.tool_replays,
    ...(toolCallsFailed > 0 ? { tool_calls_failed: toolCallsFailed } : {}),
    malformed: counters.malformed,
    boundary_decision: decision,
    suppressed_messages: counters.suppressed_messages,
    facts_extracted: counters.facts_extracted,
    facts_deduped: counters.facts_deduped,
    ...(auditPath !== "" ? { audit_path: auditPath } : {}),
    ...(logPath ? { log_path: logPath } : {}),
    ...(normalized.interrupted === true ? { interrupted: true } : {}),
    ...(transcriptConsumed !== undefined ? { transcript_consumed: transcriptConsumed } : {}),
    ...(focusCleared ? { focus_cleared: true } : {}),
    ...(handoffPath !== undefined ? { handoff_path: handoffPath } : {}),
    ...(chainLineage !== undefined ? { lineage: chainLineage } : {}),
  };
}

/**
 * Persist a live declaration as this worktree's marker (Unit 9), so the
 * next session here resolves the same work item even when its host says
 * nothing. Only a declaration that came from the payload or the
 * environment is written: re-writing what the marker itself supplied
 * would be a read echoed back as a write.
 *
 * Fail-soft in its own right, like the anticipatory cache below it - the
 * marker is a convenience for a LATER session, and a state directory
 * that cannot be written must not cost this one its capture.
 *
 * Skipping the marker-sourced case is also what gives the marker rung's
 * freshness bound its meaning: the recorded instant is the last time
 * something ACTUALLY declared this identity, so an inherited one cannot
 * keep refreshing itself and stay live forever.
 */
function recordWorktreeIdentityMarker(
  vault: string,
  worktree: string | undefined,
  identity: ReturnType<typeof resolveWorkIdentity>,
  nowMs: number,
): void {
  if (worktree === undefined || identity === null) return;
  if (identity.source === WORK_IDENTITY_SOURCE.marker) return;
  try {
    recordWorkIdentityMarker(vault, worktree, identity, { nowMs });
  } catch {
    // The marker is an enhancement, never a capture blocker.
  }
}

/**
 * Read the recorded transcript via the session adapters and write a
 * handoff note. Trust model: `transcript_path` is produced by the host
 * runtime itself (Claude Code / Hermes hand their own transcript path
 * to their own hook); it is not user-typed input, which is why no
 * inside-vault check applies - transcripts live in host directories.
 */
async function writeHandoffNoteFromTranscript(
  vault: string,
  normalized: NormalizedPayload,
  agent: string,
  now: Date,
): Promise<HandoffNoteResult | null> {
  const path = normalized.transcriptPath!;
  const turns = await readTranscriptTurns(path);
  if (turns.length === 0) return null;
  return writeHandoffNote(vault, {
    turns,
    sessionId: normalized.sessionId ?? basename(path),
    agent,
    now,
    sourcePaths: [path],
  });
}

/**
 * Read a recorded transcript through the session adapters. Returns an empty
 * array (never throws) when the path is missing, unrecognised, or empty - the
 * callers treat "no turns" as "nothing to consume". Trust model matches
 * {@link writeHandoffNoteFromTranscript}: the path is host-produced, not
 * user-typed, so no inside-vault check applies.
 */
async function readTranscriptTurns(path: string): Promise<SessionTurn[]> {
  try {
    if (!existsSync(path)) return [];
    const text = readFileSync(path, "utf8");
    const nl = text.indexOf("\n");
    const adapter = detectAdapter(nl < 0 ? text : text.slice(0, nl));
    if (adapter === null) return [];
    const turns: SessionTurn[] = [];
    for await (const turn of adapter.iterate(path)) turns.push(turn);
    return turns;
  } catch {
    return [];
  }
}

function normalizePayload(payload: unknown): NormalizedPayload {
  if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
    return { event: "unknown", malformed: 1 };
  }
  const record = payload as Record<string, unknown>;
  const event =
    readNonEmptyString(record["hook_event_name"]) ??
    readNonEmptyString(record["event"]) ??
    "unknown";
  const sessionId = readNonEmptyString(record["session_id"]);
  const transcriptPath = readNonEmptyString(record["transcript_path"]);
  const cwd = readNonEmptyString(record["cwd"]);
  const parentSessionId = readNonEmptyString(record["parent_session_id"]);
  const rootSessionId = readNonEmptyString(record["root_session_id"]);
  const compressionDepthRaw = record["compression_depth"];
  const compressionDepth =
    typeof compressionDepthRaw === "number" &&
    Number.isInteger(compressionDepthRaw) &&
    compressionDepthRaw >= 0
      ? compressionDepthRaw
      : undefined;
  const sessionStartSource = readNonEmptyString(record["source"]);
  const workId = readNonEmptyString(record["work_id"]);
  const laneId = readNonEmptyString(record["lane_id"]);
  const agentId = readNonEmptyString(record["agent_id"]);
  return {
    event,
    ...(sessionId ? { sessionId } : {}),
    ...(agentId ? { agentId } : {}),
    ...(transcriptPath ? { transcriptPath } : {}),
    ...(cwd ? { cwd } : {}),
    ...(parentSessionId ? { parentSessionId } : {}),
    ...(rootSessionId ? { rootSessionId } : {}),
    ...(compressionDepth !== undefined ? { compressionDepth } : {}),
    ...(sessionStartSource ? { sessionStartSource } : {}),
    ...(workId ? { workId } : {}),
    ...(laneId ? { laneId } : {}),
    ...(record["interrupted"] === true ? { interrupted: true } : {}),
    ...(extractPromptText(record) ? { promptText: extractPromptText(record)! } : {}),
    ...(readNonEmptyString(record["tool_name"])
      ? { toolName: readNonEmptyString(record["tool_name"])! }
      : {}),
    ...("tool_input" in record ? { toolInput: record["tool_input"] } : {}),
    ...("tool_response" in record ? { toolResponse: record["tool_response"] } : {}),
    malformed: 0,
  };
}

function extractPromptText(record: Record<string, unknown>): string | undefined {
  const direct = readNonEmptyString(record["prompt"]);
  if (direct) return direct;
  const message = record["message"];
  if (typeof message === "string" && message.trim().length > 0) return message;
  if (message !== null && typeof message === "object") {
    const content = (message as Record<string, unknown>)["content"];
    if (typeof content === "string" && content.trim().length > 0) return content;
  }
  return undefined;
}

function captureMarkers(
  vault: string,
  payload: NormalizedPayload,
  text: string,
  opts: CaptureSessionLifecycleOptions,
  now: Date,
  dedup: DedupSource,
  counters: MutableCounters,
): void {
  const discovery = discoverMarkersDetailed(text);
  counters.malformed += discovery.malformed;
  for (const marker of discovery.markers) {
    // Feedback markers only: loop / set markers are never turned into
    // signals here (loops live-derive, set markers apply via write-back).
    if (!isFeedbackMarker(marker)) continue;
    const dedupHash = computeDedupHash({
      topic: marker.topic,
      signal: marker.signal,
      principle: marker.principle,
      ...(marker.scope ? { scope: marker.scope } : {}),
    });
    emitSignal(vault, payload, opts, now, dedup, counters, {
      topic: marker.topic,
      signal: marker.signal,
      principle: marker.principle,
      ...(marker.scope ? { scope: marker.scope } : {}),
      agent: marker.agent ?? opts.agent,
      ...(marker.note ? { raw: marker.note } : {}),
      dedupHash,
    });
  }
}

function captureToolFeedback(
  vault: string,
  payload: NormalizedPayload,
  opts: CaptureSessionLifecycleOptions,
  now: Date,
  dedup: DedupSource,
  counters: MutableCounters,
): void {
  const validated = validateBrainFeedbackInput(payload.toolInput);
  if (!validated.ok) {
    counters.malformed++;
    return;
  }
  counters.tool_replays++;
  const input = validated.value;
  const dedupHash = computeDedupHash({
    topic: input.topic,
    signal: input.signal,
    principle: input.principle,
    ...(input.scope ? { scope: input.scope } : {}),
  });
  emitSignal(vault, payload, opts, now, dedup, counters, {
    topic: input.topic,
    signal: input.signal,
    principle: input.principle,
    ...(input.scope ? { scope: input.scope } : {}),
    agent: input.agent ?? opts.agent,
    ...(input.raw ? { raw: input.raw } : {}),
    dedupHash,
  });
}

/** The event's shared dedup index, built on first call (see `ensureDedup`). */
type DedupSource = () => Map<string, DedupIndexEntry>;

interface SignalPayload {
  readonly topic: string;
  readonly signal: "positive" | "negative";
  readonly principle: string;
  readonly scope?: string;
  readonly agent: string;
  readonly raw?: string;
  readonly dedupHash: string;
}

interface MutableCounters {
  signals_created: number;
  signals_deduped: number;
  tool_replays: number;
  malformed: number;
  suppressed_messages: number;
  facts_extracted: number;
  facts_deduped: number;
}

function emitSignal(
  vault: string,
  payload: NormalizedPayload,
  opts: CaptureSessionLifecycleOptions,
  now: Date,
  dedup: DedupSource,
  counters: MutableCounters,
  signal: SignalPayload,
): void {
  const index = dedup();
  if (index.has(signal.dedupHash)) {
    counters.signals_deduped++;
    return;
  }
  if (opts.dryRun) return;
  const sessionRef = sessionReference(payload);
  const result = writeSignal(vault, {
    topic: signal.topic,
    signal: signal.signal,
    agent: signal.agent,
    principle: signal.principle,
    created_at: isoSecond(now),
    date: isoDate(now),
    slug: signal.topic,
    ...(signal.scope ? { scope: signal.scope } : {}),
    source: [`[[${sessionRef}]]`],
    source_type: BRAIN_SIGNAL_SOURCE_TYPE.session,
    dedup_hash: signal.dedupHash,
    session_ref: sessionRef,
    ...(signal.raw ? { raw: signal.raw } : {}),
  });
  index.set(signal.dedupHash, { id: result.id, path: result.path });
  counters.signals_created++;
}

function appendLifecycleLog(
  vault: string,
  payload: NormalizedPayload,
  agent: string,
  now: Date,
  counters: MutableCounters,
): string {
  return appendLogEvent(
    vault,
    {
      timestamp: isoSecond(now),
      eventType: BRAIN_LOG_EVENT_KIND.sessionLifecycle,
      body: {
        agent,
        event: payload.event,
        ...(payload.sessionId ? { session_id: payload.sessionId } : {}),
        signals_created: String(counters.signals_created),
        signals_deduped: String(counters.signals_deduped),
        tool_replays: String(counters.tool_replays),
        malformed: String(counters.malformed),
        suppressed_messages: String(counters.suppressed_messages),
        facts_extracted: String(counters.facts_extracted),
        facts_deduped: String(counters.facts_deduped),
      },
      // A hook path: a store-only failure is counted device-locally and the
      // capture goes on (design D14 item 1).
    },
    { failOpen: true },
  ).logPath;
}

/** Stand-in session identity when the host payload carries none. */
const UNKNOWN_SESSION_REF = "unknown";

function sessionReference(payload: NormalizedPayload): string {
  return `session:${payload.sessionId ?? UNKNOWN_SESSION_REF}#${payload.event}`;
}

function readNonEmptyString(value: unknown): string | undefined {
  return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
}