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
/**
 * Grok Build install artifacts, resolved at install time with ABSOLUTE
 * commands.
 *
 * Verified against live grok 0.2.45 (debug log of a real session): grok spawns
 * MCP servers and hook scripts with a restricted PATH that excludes
 * `~/.local/bin`, so a bare `o2b` / `o2b-hook` command fails with ENOENT and no
 * tools/hooks load. The working form is an absolute command - the bun binary
 * (`process.execPath`) running the repo's entry points by absolute path:
 *
 *   - MCP servers go into `~/.grok/config.toml` `[mcp_servers.*]` (grok's
 *     primary, highest-priority source): `bun run <repo>/src/cli/main.ts mcp …`.
 *   - Lifecycle hooks go into `~/.grok/hooks/open-second-brain.json` (grok's
 *     native, always-trusted hooks dir; plugin-provided hooks are NOT
 *     discovered in-session): `bun run <repo>/hooks/<name>.ts`.
 *
 * Both are grok-native sources, not Claude-compat impersonation.
 */

import { join } from "node:path";

import { INSTALL_HOOK_TIMEOUT_SECONDS_DEFAULT } from "../brain/policy/blocks/install.ts";
import { payloadWithRuntimeIdentity, runtimeAgentNameFromPayload } from "./identity.ts";
import { OSB_KEY_FULL, OSB_KEY_WRITER } from "./json-merge.ts";
import type { GrokMcpEntry } from "./grok-config.ts";
import { cliArgs } from "./payload.ts";
import type { McpPayload, McpServerEntry } from "./types.ts";

const REPO_ROOT = join(import.meta.dir, "..", "..", "..");
const MAIN_TS = join(REPO_ROOT, "src", "cli", "main.ts");

/** The bun binary currently running this process - an absolute path. */
function bunBin(): string {
  return process.execPath;
}

export const GROK_HOOKS_FILENAME = "open-second-brain.json";

/** grok's vendor token; combined with the operator's host into a host-qualified
 * identity by {@link runtimeAgentNameFromPayload} (see identity.ts). */
export const GROK_RUNTIME_ID = "grok";

/**
 * The two MCP server tables to write into `config.toml`, derived from the
 * canonical payload: same `args`, but the command becomes
 * `bun run <repo>/src/cli/main.ts` (absolute) instead of the PATH-resolved
 * `o2b` (so grok can spawn it in a session), and `VAULT_AGENT_NAME` is set to
 * grok's own host-qualified id (e.g. `grok-vps-agent`) so the server's identity
 * instruction and any Brain write say it was grok, not the shared operator name.
 */
export function grokMcpServers(payload: McpPayload): Record<string, GrokMcpEntry> {
  const identified = payloadWithRuntimeIdentity(payload, GROK_RUNTIME_ID);
  const toEntry = (entry: McpServerEntry) => ({
    command: bunBin(),
    args: ["run", MAIN_TS, ...cliArgs(entry)],
    env: { ...entry.env },
  });
  return {
    [OSB_KEY_FULL]: toEntry(identified.full),
    [OSB_KEY_WRITER]: toEntry(identified.writer),
  };
}

/** Build the absolute hook command for a hooks/<name>.ts entry point. */
function hookCommand(name: string): string {
  return `${bunBin()} run ${join(REPO_ROOT, "hooks", `${name}.ts`)}`;
}

interface HookGroupSpec {
  readonly matcher?: string;
  readonly hooks: ReadonlyArray<string>;
}

/**
 * Event -> hook mapping, mirroring the Claude Code plugin's behaviour with
 * grok's rules: lifecycle events (SessionStart, UserPromptSubmit, Stop,
 * SessionEnd) reject a `matcher`, so they carry none; PostToolUse keeps a
 * matcher and lists grok's `search_replace` alongside the Claude tool names.
 *
 * "Mirroring" is asserted rather than claimed:
 * `tests/core/install/adapters/grok-hook-parity.test.ts` derives the
 * plugin's own event -> hook-name map out of `hooks/hooks.json` and
 * requires this table to cover it, with every deliberate difference
 * declared there by name and reason. It was a claim for two releases, and
 * for two releases this table was missing `SubagentStop` and `PreToolUse`
 * - so a grok install got no delegated-sub-agent capture at all, which is
 * the headline capability of one of the units that shipped alongside it.
 *
 * The MATCHERS still differ, and only the matchers: grok rejects one on a
 * lifecycle event, so `SessionStart` / `PostCompact` / `PreToolUse` carry
 * none where the plugin narrows them. That is grok's rule, not a reduced
 * hook set - an absent matcher fires on every trigger of the event.
 */
const HOOK_SPEC: ReadonlyArray<{ event: string; groups: ReadonlyArray<HookGroupSpec> }> = [
  {
    event: "SessionStart",
    groups: [
      {
        hooks: [
          "active-inject",
          "gap-agenda",
          // The opt-in undistilled-backlog nudge (session-mining-economy),
          // in the position the plugin's own SessionStart group lists it:
          // default-off like gap-agenda, fail-open, one context line.
          "backlog-nudge",
          // The opt-in cross-agent log catch-up (actionable-now-batch), in
          // the plugin's own order: default-off, fail-soft exit 0, read-only
          // over Brain/log with its cursor in the vault's derived store.
          "log-catchup",
          // The human view render (brain store, design D7), in the plugin's
          // own order: a no-op off the view writer, hourly on it, fail-open.
          "view-render",
          "session-capture",
        ],
      },
    ],
  },
  {
    event: "UserPromptSubmit",
    groups: [
      {
        hooks: [
          "session-capture",
          "recall-inject",
          "nav-inject",
          "neighbour-updates",
          // The opt-in counterparty brief (dated commitments), in the
          // plugin's own order: default-off like recall-inject, once per
          // session through the injection ledger, one additionalContext
          // envelope at most.
          "counterparty-brief",
        ],
      },
    ],
  },
  {
    event: "PreToolUse",
    groups: [
      {
        hooks: [
          "pretool-orient",
          // The opt-in host-settings backup gate: default OFF and a silent
          // no-op until armed, and its own write-tool check does the
          // narrowing the plugin spells as a matcher (grok's PreToolUse
          // carries none, so a non-write tool call reaches it and is
          // waved through by the hook itself).
          "pretool-host-backup",
        ],
      },
    ],
  },
  {
    event: "PostToolUse",
    groups: [
      { matcher: "brain_feedback", hooks: ["session-capture"] },
      {
        matcher: "Write|Edit|MultiEdit|apply_patch|search_replace",
        hooks: ["post-write-reminder", "subagent-inject"],
      },
    ],
  },
  {
    event: "Stop",
    groups: [
      {
        hooks: [
          "session-capture",
          "stop-log-guardrail",
          // The answer-trust quote check rides the same Stop pipeline: it is
          // annotation-only, fail-open exit 0, and reads the transcript the
          // same way the guardrail does, so grok gets the same unverified-
          // quote annotation Claude Code does.
          "answer-quote-check",
          "hygiene-digest",
        ],
      },
    ],
  },
  // The delegated sub-agent's close. Without it a grok install records the
  // parent's turns and drops every sub-agent's, and a sub-agent transcript
  // reuses the PARENT's session id - so the loss is invisible in the data.
  { event: "SubagentStop", groups: [{ hooks: ["session-capture"] }] },
  { event: "SessionEnd", groups: [{ hooks: ["session-capture", "gap-promote"] }] },
  { event: "PostCompact", groups: [{ hooks: ["active-inject", "session-capture"] }] },
];

/**
 * The `~/.grok/hooks/open-second-brain.json` content, with absolute bun
 * commands. Each hook carries `env.VAULT_AGENT_NAME` set to grok's own
 * host-qualified id (the same value the MCP env gets, derived from the payload's
 * operator name) so the session-capture / guardrail writes attribute to grok,
 * not the shared operator name. Generated at install time (machine-specific
 * paths and identity), so `verify` compares the installed file against this
 * exact output.
 *
 * `hookTimeoutSeconds` is the resolved `install.hook_timeout_seconds`
 * (see `./settings.ts`) and is REQUIRED, like every other input to a
 * generator in this file. It carried a default of
 * {@link INSTALL_HOOK_TIMEOUT_SECONDS_DEFAULT} - the bottom tier of that
 * same ladder - which made "forgot to resolve it" and "the vault
 * configures nothing" produce identical bytes, so a future caller that
 * dropped the argument would silently write the compiled default over the
 * operator's configured value and no test would notice. A vault that
 * configures nothing still regenerates byte-identical output, because the
 * resolver returns that same constant; the difference is that the caller
 * has to have asked.
 */
export function grokHooksJson(payload: McpPayload, hookTimeoutSeconds: number): string {
  const agentName = runtimeAgentNameFromPayload(payload, GROK_RUNTIME_ID);
  const hooks: Record<string, unknown[]> = {};
  for (const { event, groups } of HOOK_SPEC) {
    hooks[event] = groups.map((g) => ({
      ...(g.matcher !== undefined ? { matcher: g.matcher } : {}),
      hooks: g.hooks.map((name) => ({
        type: "command",
        command: hookCommand(name),
        env: { VAULT_AGENT_NAME: agentName },
        timeout: hookTimeoutSeconds,
      })),
    }));
  }
  return JSON.stringify({ hooks }, null, 2) + "\n";
}