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
9.0 KB
Raw Blame
#!/usr/bin/env -S bun
/**
 * Runtime lifecycle hook: capture prompt/tool/session observations into
 * Brain without writing hook output back to the runtime. Failures are
 * intentionally silent so a hook problem never blocks the agent.
 *
 * Two modes:
 *
 *   - HOOK (default): reads the host payload from stdin. An event whose
 *     capture may need the signal dedup index (see
 *     `lifecycleEventNeedsDedup`) is handed to a detached worker and the
 *     hook returns at once; every other event is captured inline. The
 *     dedup walk reads every `sig-*.md`, which on a slow mount (WSL 9p)
 *     could take longer than the host's 10 s timeout. When it does run
 *     inline (hand-off disabled or failed) it runs under a cooperative
 *     deadline equal to the ceiling (`ceilingSafeguard`), checked between
 *     files, so it stops and the hook exits cleanly before the host kills
 *     it.
 *   - WORKER (`--deferred <spool>`): reads the spooled payload, deletes the
 *     spool, and captures with no host deadline. Workers for one vault run
 *     one at a time, so two deferred events cannot both miss each other's
 *     signal in the dedup index.
 *
 * `OPEN_SECOND_BRAIN_SESSION_CAPTURE_DEFER=0` disables the hand-off and
 * captures every event inline (the pre-1.58.1 behaviour).
 */

import { spawn } from "node:child_process";
import { createHash, randomBytes } from "node:crypto";
import {
  closeSync,
  fstatSync,
  lstatSync,
  openSync,
  readFileSync,
  unlinkSync,
  writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

import { resolveAgentName } from "../src/core/config.ts";
import {
  captureSessionLifecycleEvent,
  lifecycleEventNeedsDedup,
} from "../src/core/brain/session-lifecycle.ts";
import { hookAuditDir } from "../src/core/brain/paths.ts";
import { removeStaleLockSync } from "../src/core/brain/sync-lockfile.ts";
import { SafeguardTimeoutError, type Safeguard } from "../src/core/brain/safeguard.ts";
import {
  armProcessCeiling,
  ceilingSafeguard,
  resolveHookCeilingMs,
} from "./lib/process-ceiling.ts";
import { appendAuditRecord } from "../src/core/reliability/audit.ts";
import { normalizeHookPayload, readHookInput } from "./lib/stdin.ts";
import { resolveHookTarget } from "./lib/hook-vault.ts";

const DEFERRED_FLAG = "--deferred";
/** A deferred worker has no host deadline, but it must still end. */
const WORKER_CEILING_MS = 10 * 60_000;
/** How long a worker waits for its vault's previous worker. */
const WORKER_LOCK_WAIT_MS = 5 * 60_000;
/** A lock older than this belongs to a worker that died; it is taken over. */
const WORKER_LOCK_STALE_MS = WORKER_CEILING_MS + 60_000;

function audit(vault: string | null, action: string, details: Record<string, unknown>): void {
  if (vault === null) return;
  try {
    appendAuditRecord(hookAuditDir(vault), {
      timestamp: new Date().toISOString(),
      actor: "session-capture",
      action,
      target: "session-capture",
      ok: action !== "hook_ceiling_exceeded",
      details: { hook: "session-capture", ...details },
    });
  } catch {
    // best-effort
  }
}

function deferEnabled(env: Record<string, string | undefined> = process.env): boolean {
  return env["OPEN_SECOND_BRAIN_SESSION_CAPTURE_DEFER"]?.trim() !== "0";
}

/**
 * Spool the payload and start a detached worker on it. Returns false when
 * the hand-off could not be made, so the caller captures inline instead of
 * dropping the event.
 */
function handOff(payload: unknown): boolean {
  let spool: string | undefined;
  try {
    spool = join(tmpdir(), `o2b-capture-${process.pid}-${randomBytes(6).toString("hex")}.json`);
    writeFileSync(spool, JSON.stringify(payload), { mode: 0o600 });
    const child = spawn(process.execPath, ["run", import.meta.path, DEFERRED_FLAG, spool], {
      detached: true,
      stdio: "ignore",
      windowsHide: true,
      env: process.env,
    });
    child.on("error", () => {});
    child.unref();
    return child.pid !== undefined;
  } catch {
    if (spool !== undefined) {
      try {
        unlinkSync(spool);
      } catch {
        // nothing to clean
      }
    }
    return false;
  }
}

function lockPath(vault: string): string {
  const key = createHash("sha256").update(vault).digest("hex").slice(0, 16);
  return join(tmpdir(), `o2b-capture-${key}.lock`);
}

/** Whether a worker lock is older than {@link WORKER_LOCK_STALE_MS}. */
function workerLockAbandoned(st: { readonly mtimeMs: bigint }): boolean {
  return Date.now() - Number(st.mtimeMs) > WORKER_LOCK_STALE_MS;
}

/**
 * Take the per-vault worker lock; returns its release, or null on timeout.
 *
 * A lock older than {@link WORKER_LOCK_STALE_MS} is removed through
 * `removeStaleLockSync`, so of two waiters that both judged it abandoned
 * only one removes it, and the other never removes the lock the first then
 * takes. The release removes the lock only while it is still the file this
 * worker created.
 */
async function acquireWorkerLock(vault: string): Promise<(() => void) | null> {
  const path = lockPath(vault);
  const deadline = Date.now() + WORKER_LOCK_WAIT_MS;
  for (;;) {
    let fd = -1;
    try {
      fd = openSync(path, "wx");
    } catch {
      removeStaleLockSync(path, workerLockAbandoned);
    }
    if (fd >= 0) {
      let mine: { readonly dev: bigint; readonly ino: bigint } | null = null;
      try {
        mine = fstatSync(fd, { bigint: true });
      } catch {
        // unknown identity: release falls back to removing the name
      } finally {
        closeSync(fd);
      }
      return () => {
        try {
          const now = lstatSync(path, { bigint: true });
          if (mine !== null && mine.ino !== 0n && (now.dev !== mine.dev || now.ino !== mine.ino)) {
            return; // taken over and re-acquired by another worker: theirs now
          }
          unlinkSync(path);
        } catch {
          // already gone
        }
      };
    }
    if (Date.now() >= deadline) return null;
    // oxlint-disable-next-line no-await-in-loop -- polling a lock, sequential by design
    await new Promise((r) => setTimeout(r, 100));
  }
}

async function capture(vault: string, payload: unknown, safeguard: Safeguard): Promise<void> {
  // Normalize grok's camelCase payload to the internal snake_case shape so the
  // lifecycle capture reads the same fields it does for Claude Code and Codex.
  try {
    await captureSessionLifecycleEvent(vault, normalizeHookPayload(payload), {
      agent: resolveAgentName(),
      safeguard,
    });
  } catch (err) {
    // The cooperative deadline tripped inside synchronous work (the dedup
    // walk): the same verdict the ceiling timer records, reached from the
    // inside. Nothing was written past the checkpoint.
    if (err instanceof SafeguardTimeoutError) {
      audit(vault, "hook_ceiling_exceeded", { cooperative: true });
      return;
    }
    throw err;
  }
}

async function runWorker(spool: string): Promise<void> {
  let payload: unknown = null;
  try {
    payload = JSON.parse(readFileSync(spool, "utf8"));
  } catch {
    payload = null;
  } finally {
    try {
      unlinkSync(spool);
    } catch {
      // already consumed
    }
  }
  // With no vault the capture lands in the brain store (design D14, task 2.10).
  const target = resolveHookTarget();
  if (target === null || payload === null) return;
  const { vault } = target;
  const disarm = armProcessCeiling({
    ceilingMs: WORKER_CEILING_MS,
    onExpire: () => audit(vault, "hook_ceiling_exceeded", { mode: "deferred" }),
  });
  const safeguard = ceilingSafeguard(WORKER_CEILING_MS);
  const release = await acquireWorkerLock(vault);
  try {
    await capture(vault, payload, safeguard);
  } finally {
    release?.();
    disarm();
  }
}

async function runHook(): Promise<void> {
  // Arm the process self-watchdog so a hung capture (stalled read, slow
  // continuity append) self-terminates at the ceiling instead of orphaning
  // the hook process or blocking the host agent.
  let auditVault: string | null = null;
  const ceilingMs = resolveHookCeilingMs();
  const disarm = armProcessCeiling({
    ceilingMs,
    onExpire: () => audit(auditVault, "hook_ceiling_exceeded", {}),
  });
  const safeguard = ceilingSafeguard(ceilingMs);
  try {
    // With no vault the capture lands in the brain store (design D14, task 2.10).
    const target = resolveHookTarget();
    if (target === null) return;
    const { vault } = target;
    auditVault = vault;
    let payload: unknown;
    try {
      payload = await readHookInput();
    } catch {
      payload = null;
    }
    const normalized = normalizeHookPayload(payload);
    if (deferEnabled() && lifecycleEventNeedsDedup(normalized) && handOff(normalized)) return;
    await capture(vault, normalized, safeguard);
  } finally {
    disarm();
  }
}

async function main(): Promise<void> {
  const flag = process.argv.indexOf(DEFERRED_FLAG);
  const spool = flag >= 0 ? process.argv[flag + 1] : undefined;
  if (spool !== undefined) await runWorker(spool);
  else await runHook();
}

main().catch(() => {
  // Never block the runtime on lifecycle capture failures.
});