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
feat: native Grok Build CLI integration - bundled plugin, hooks, session import (v1.4.0) (#91)
Sol Aitken2e74afe05719
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 3e6eda35..bad73f81 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.3.1",+ "version": "1.4.0","description": "Plugin-first second brain package for AI agents and humans.","author": {"name": "Open Second Brain contributors"diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 58601fc1..7063eb20 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.3.1",+ "version": "1.4.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","skills": "./skills","hooks": "./hooks/hooks.json",diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a0c1500c..f89f431d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,42 @@ All notable changes to this project will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).+## [1.4.0] - 2026-06-12++### Added++- **Native Grok Build (xAI `grok`) integration.** `o2b install --target grok+ --apply` registers the two Open Second Brain MCP servers in+ `${GROK_HOME:-~/.grok}/config.toml` under `[mcp_servers.*]` (grok's+ highest-priority MCP source) and writes lifecycle hooks to+ `${GROK_HOME:-~/.grok}/hooks/open-second-brain.json` (grok's native hooks+ dir), each with an absolute `bun run <repo>/src/cli/main.ts …` command.+ Verified against live grok 0.2.45 (session debug log): grok spawns MCP and+ hook processes with a restricted PATH that excludes `~/.local/bin`, so a bare+ `o2b` command fails to spawn - the absolute form is what actually handshakes+ in a session (71 + 5 MCP tools registered; active-context inject, post-write+ reminder, session capture, and the stop-log guardrail dispatched). The shared+ hook layer normalizes grok's camelCase stdin payload (`hookEventName` /+ `sessionId` / `toolName` / `toolInput`) into the internal shape, detects the+ `grok` runtime, and counts grok's `search_replace` as a file-mutating tool. A+ new `grok` session adapter imports grok's ACP `updates.jsonl` stream into the+ Brain via `o2b brain import-session` (autodetected). The integration uses grok's+ own config, not the `~/.claude/` namespace. See+ [`install/grok.md`](install/grok.md).+- **Per-runtime host-qualified Brain identity.** Every runtime that registers+ the MCP servers (grok, opencode, openclaw, and Codex via `codex mcp add`) now+ attributes its Brain writes to its OWN host-qualified name rather than the+ shared operator `agent_name`. The host segment of the operator name is kept and+ the vendor token is swapped to the runtime's own id (`claude-vps-agent` ->+ `grok-vps-agent` / `opencode-vps-agent`; a name outside the+ `<vendor>-<host>-agent` shape is prefixed with `<runtime>-`). This keeps a+ shared multi-device vault (e.g. Syncthing across a VPS, a dev box, and a Mac)+ able to tell the same runtime apart both across runtimes and across devices.+ The derived name is read from the payload's operator name, so `apply` and+ `verify` produce the identical value and `o2b install --check` reports no drift+ after an apply. For grok, both the `config.toml` MCP env and the hooks file+ carry the same derived name.+## [1.3.1] - 2026-06-11### Fixeddiff --git a/README.md b/README.mdindex 790ccc62..bb840c13 100644--- a/README.md+++ b/README.md@@ -11,7 +11,7 @@ Open Second Brain plugs into [Hermes Agent](https://github.com/NousResearch/herm- **Lives in your Obsidian vault.** Open `Brain/preferences/pref-no-internal-abbrev.md` in Obsidian and you literally see what your agent learned about you - title, status, evidence count, confidence band, body text. Wikilinks, backlinks, graph view all work.- **You own the data.** Plain Markdown on your filesystem. No service to cancel, no cloud account, no schema migration when a vendor pivots. Syncthing to your other machines if you want.- **Memory that learns deterministically.** A `dream` pass turns repeat signals into rules and retires the ones nothing applies any more. Counters and atomic file moves - no LLM inside the algorithm, no surprise hallucinations in your memory.-- **One vault, every agent.** Hermes Agent is the primary integration. Claude Code, OpenAI Codex, Cursor, Aider, OpenClaw, opencode, kiro, Copilot CLI, Gemini CLI, and Pi all plug into the same Brain through MCP.+- **One vault, every agent.** Hermes Agent is the primary integration. Claude Code, OpenAI Codex, Cursor, Aider, OpenClaw, opencode, Grok Build, kiro, Copilot CLI, Gemini CLI, and Pi all plug into the same Brain through MCP.## One vault, many runtimes@@ -21,7 +21,7 @@ flowchart LRHermes["**Hermes Agent**<br/>(primary)"]CC[Claude Code]Codex[OpenAI Codex]- Others["Cursor · Aider · OpenClaw<br/>opencode · kiro · Copilot CLI<br/>Gemini CLI · Pi · any MCP host"]+ Others["Cursor · Aider · OpenClaw<br/>opencode · Grok Build · kiro · Copilot CLI<br/>Gemini CLI · Pi · any MCP host"]Hermes <==> VaultCC <--> Vault@@ -70,6 +70,7 @@ Enable Open Second Brain as the memory provider in `~/.hermes/config.yaml` (`mem| OpenAI Codex | `codex plugin marketplace add ...` - [`install/codex.md`](install/codex.md) || OpenClaw | Native JS plugin, no MCP needed - [`install/openclaw.md`](install/openclaw.md) || opencode | `o2b install --target opencode --apply` (MCP servers + native plugin) - [`install/opencode.md`](install/opencode.md) |+| Grok Build | `o2b install --target grok --apply` (MCP in `config.toml` + native hooks) - [`install/grok.md`](install/grok.md) || Cursor · Aider · kiro · Copilot CLI · Gemini CLI · Pi | `o2b install --target <name> --apply` - see [`install/`](install/) || Any other MCP host | `o2b install --target generic --apply` - [`install/generic.md`](install/generic.md) |diff --git a/docs/brainstorm/grok-native-integration/cli-output/claude.md b/docs/brainstorm/grok-native-integration/cli-output/claude.mdnew file mode 100644index 00000000..acb28685--- /dev/null+++ b/docs/brainstorm/grok-native-integration/cli-output/claude.md@@ -0,0 +1,34 @@+### Variant 1: Native config.toml writer+- **Approach**: Extend the install-adapter registry with a grok adapter that writes the two canonical MCP entries directly into `~/.grok/config.toml` `[mcp_servers.*]` and drops the three lifecycle hooks into `~/.grok/hooks/*.json` (Claude-compatible JSON shape). A grok `SessionAdapter` reads the ACP `updates.jsonl` + `summary.json` stream. No plugin; integration lives entirely in grok's own first-class config surfaces.+- **Trade-offs**:+ - Pro: maximally native to grok's authoritative surfaces; pure-grok users with no `~/.claude` are served directly with zero compat-merge dependency.+ - Pro: `summary.json.parent_session_id` feeds the existing session-lineage work cleanly; hooks get `GROK_HOOK_*`/`CLAUDE_PROJECT_DIR` env for free.+ - Con: config.toml is TOML and the project ships no TOML lib — forces a hand-rolled minimal emitter/patcher for the `[mcp_servers.<name>]` table, which `serializeEntry` does not currently cover (new on-disk shape + drift detection for TOML).+ - Con: produces no marketplace-publishable unit, so goal (b) is unmet; the integration is invisible to `grok plugin`/marketplace tooling.+ - Con: the canonical `McpServerEntry` must be projected into TOML rather than reused as-is, a new serialization seam that can drift from the JSON targets.+- **Complexity**: medium+- **Risk**: medium++### Variant 2: Bundled grok plugin as the first-class unit (opencode-style two-pronged)+- **Approach**: Ship a version-stamped grok plugin asset (mirroring `opencode-plugin-asset.ts`): a directory with `plugin.json`, `.mcp.json` in MCP standard format carrying the two canonical entries, and `hooks/hooks.json` for the three lifecycle hooks. The install adapter places it under `~/.grok/plugins/` and force-enables it (config.toml `[plugins] enabled` / `--trust` path), and a grok `SessionAdapter` imports the ACP session stream. The plugin is the marketplace-publishable unit.+- **Trade-offs**:+ - Pro: hits all four goals — pure-grok install path, marketplace-publishable first-class unit, and heavy reuse of the opencode-plugin-asset pattern + session-adapter registry.+ - Pro: MCP lives in `.mcp.json` (standard JSON) so the canonical `McpServerEntry` is reused verbatim with zero TOML for MCP — strongest DRY/anti-drift posture.+ - Pro: precedent #88 proves the config-write + bundled-plugin + session-adapter shape end to end.+ - Con: plugins are disabled by default — the adapter must reliably force-enable (config.toml `[plugins] enabled` append or `grok plugin install --trust`), a narrow TOML touch and a footgun if skipped, which the verify step must assert against.+ - Con: two delivery artifacts (plugin asset + thin config write) to keep version-synced, slightly more surface than a pure config writer.+- **Complexity**: medium+- **Risk**: low++### Variant 3: Claude-compat piggyback shim+- **Approach**: Lean on grok's auto-merge of `~/.claude.json` MCP and `~/.claude/settings.json` hooks via `[compat.claude]`; for pure-grok users, the existing Claude Code adapter writes those Claude-format files, and the only new code is a grok camelCase hook-stdin branch plus the grok `SessionAdapter`. Smallest possible footprint.+- **Trade-offs**:+ - Pro: minimal new code — reuses the Claude adapter outputs almost entirely; only the stdin parser and session adapter are grok-specific.+ - Con: writing `~/.claude.json` / `~/.claude/settings.json` for a user who runs only grok is exactly the silent workaround the constraints forbid (maximally native, no crutches); it pollutes a foreign vendor's namespace.+ - Con: relies on compat-merge priority (config.toml > Claude > Cursor) staying stable across grok versions — fragile, no first-class ownership/drift tracking.+ - Con: yields no marketplace unit (goal b fails) and is not "first-class native" (goal a is served only by impersonating Claude).+- **Complexity**: small+- **Risk**: high++### Recommended: Variant 2+**Rationale**: Only Variant 2 satisfies all four sub-goals at once — it serves pure-grok users via a real install/enable path, ships the marketplace-publishable first-class plugin, and maximally reuses the existing seams (opencode-plugin-asset, `.mcp.json` standard format preserving the canonical `McpServerEntry`, session-adapter registry, hook lib). Routing MCP through the plugin's `.mcp.json` keeps grok off the TOML path entirely for the canonical payload, avoiding both the hand-rolled emitter that burdens Variant 1 and the namespace-impersonation workaround that disqualifies Variant 3, while #88 already proves the two-pronged shape end to end.diff --git a/docs/brainstorm/grok-native-integration/cli-output/prompt.md b/docs/brainstorm/grok-native-integration/cli-output/prompt.mdnew file mode 100644index 00000000..4ea9ef95--- /dev/null+++ b/docs/brainstorm/grok-native-integration/cli-output/prompt.md@@ -0,0 +1,62 @@+You are brainstorming architectural variants for the following task. Do not write code. Do not write a final design. Only produce variants and a recommendation.++# Task++Ship a first-class, native Open Second Brain integration for the Grok Build CLI (`grok`, xAI; verified against the locally installed grok 0.2.45 and its bundled docs at `~/.grok/docs/user-guide/`). Match the depth of the existing Claude Code, OpenAI Codex, and opencode integrations: register the two Open Second Brain MCP servers, install lifecycle hooks (active-context injection at session start, post-write logging nudge after file-mutating tools, and session capture), and import Grok sessions into the Brain.++The single most important architectural question: given that Grok ALREADY reads Claude Code and Cursor config automatically (see "Grok surface" below), what is the right native delivery strategy that (a) serves pure-grok users who have no `~/.claude`, (b) is the marketplace-publishable first-class unit, (c) maximally reuses the existing install-adapter / session-adapter / hook seams, and (d) adds no do-nothing fallbacks or stubs? Produce 3 distinct architectural variants for HOW to structure and deliver this integration, then recommend one.++# Grok surface (authoritative, grok 0.2.45)++- MCP servers: native `~/.grok/config.toml` `[mcp_servers.<name>]` (TOML; stdio = `command`/`args`/`env`/`enabled`/timeouts, HTTP = `url`/`headers`). CLI helper `grok mcp add <name> --command <cmd> --args ... --env K=V` writes to config.toml but cannot pass args starting with a hyphen. Grok ALSO auto-merges MCP from `~/.claude.json` (Claude format) and `.cursor/mcp.json` via `[compat.<vendor>]`; merge priority config.toml > Claude > Cursor > project `.mcp.json`.+- Hooks: `~/.grok/hooks/*.json` in the Claude-compatible JSON shape `{"hooks":{"<Event>":[{"matcher","hooks":[{"type":"command","command","timeout","env"}]}]}}`. Events: SessionStart, UserPromptSubmit, PreToolUse (only blocking one), PostToolUse, PostToolUseFailure, PermissionDenied, Stop, StopFailure, Notification, SubagentStart/Stop, PreCompact, PostCompact, SessionEnd. Grok auto-reads `~/.claude/settings.json` hooks. stdin payload uses camelCase: `{hookEventName: "pre_tool_use", sessionId, cwd, workspaceRoot, toolName, toolInput, timestamp}` (Claude Code uses snake_case `hook_event_name`/`session_id`/`tool_name`/`tool_input` and a `transcript_path` that grok does NOT provide). Hook env: GROK_HOOK_EVENT, GROK_HOOK_NAME, GROK_SESSION_ID, GROK_WORKSPACE_ROOT, CLAUDE_PROJECT_DIR alias; plugin hooks also get GROK_PLUGIN_ROOT, GROK_PLUGIN_DATA. Matcher tool-name aliases: Bash->run_terminal_command, Edit/Write/MultiEdit->search_replace, Read->read_file, etc.+- Plugins: a directory with optional `plugin.json` manifest plus convention components: `skills/`, `commands/`, `agents/`, `hooks/hooks.json`, `.mcp.json` (MCP standard format), `.lsp.json`. Installed via `grok plugin install <git|user/repo|local path> --trust` into `~/.grok/plugins/` (auto-trusted) or `.grok/plugins/` (needs trust). Plugins are DISABLED by default unless installed with `--trust`, force-enabled via `[plugins] enabled=[...]` in config.toml, or on an explicit config path. Marketplace via `[[marketplace.sources]]` in config.toml or `extraKnownMarketplaces` in `~/.grok/settings.json`. `grok plugin validate`, `grok plugin tag`, `grok inspect --json`.+- Sessions: `~/.grok/sessions/<encoded-cwd>/<session-id>/` (base overridable by `GROK_HOME`). `updates.jsonl` = authoritative newline-delimited ACP session update stream (prompts, responses, tool calls). `summary.json` = metadata incl. `parent_session_id` (lineage), `agent_name`, model id, timestamps, counts. Also `chat_history.jsonl`. `grok export <id>` emits Markdown; `grok sessions list --json`; headless `grok -p ... --output-format json` returns `sessionId`.++# Project context++- Open Second Brain: an agent-owned Markdown second brain. TypeScript on Bun for the core; a Python shim for the Hermes memory provider. `dependencies = []` (no YAML/TOML lib shipped today).+- Recent commits:+ - 3e7e233 fix(hermes): serialize handle_tool_call result to a string (v1.3.1)+ - 96f1ff4 feat: native opencode integration - config-correct install, bundled plugin, session capture (#88)+ - 0340560 feat: Continuity, Hygiene & Freshness Suite - session lineage, memory hygiene (v1.3.0)+- Existing seams to reuse (NOT rebuild):+ - `src/core/install/json-merge.ts`: canonical MCP keys `OSB_KEY_FULL="open-second-brain"`, `OSB_KEY_WRITER="open-second-brain-writer"`; canonical `McpServerEntry` is `{command, args, env?}`; `serializeEntry` injection point already exists for non-default on-disk shapes.+ - `src/core/install/adapters/_json-mcp.ts` + `opencode.ts`: adapter factory with detect/plan/apply/verify/uninstall, manifest-tracked `owned_paths`, drift detection.+ - `src/core/install/opencode-plugin-asset.ts`: version-stamped bundled-plugin asset module pattern.+ - `src/core/brain/sessions/registry.ts` + `opencode.ts`: `SessionAdapter` registry; add an adapter = drop `sessions/<id>.ts` + append to `SESSION_ADAPTERS` + extend `SessionAdapterId`. Detect on structural fields; a newer unknown shape must fail with a versioned PARSE error.+ - `hooks/lib/stdin.ts` + `detect.ts`: shared hook stdin parser + runtime detection used by the Claude Code / Codex layers (currently keyed to Claude snake_case payload).+ - `o2b-hook` PATH shim: `o2b-hook active-inject` renders the active Brain context; opencode and the Claude/Codex layers call it rather than reimplementing vault resolution and quiet-failure semantics.+- The opencode precedent (#88) delivered BOTH a config write (MCP into opencode.json) AND a bundled plugin (hooks/capture) AND a session adapter. Consider whether grok should mirror that two-pronged shape or collapse into one.++# Conventions++- SOLID, KISS, DRY. Everything that can be lifted into a local/global constant is.+- No fallbacks that silently do nothing and mislead: surface errors explicitly. No stubs. No crutches. Maximally native, no workarounds.+- No hardcoded natural-language phrase lists in any language; English-only source; handle other languages abstractly.+- Adapters stay offline-unit-testable (the project's other adapters are tested without the target binary installed).+- TDD: failing test first, then implement.++# Constraints++- Do not fork the shared install/session/hook seams; extend them.+- Do not add a heavy dependency (no new TOML/YAML library) unless a variant makes an explicit, justified case for it.+- One PR, one CHANGELOG version. Version bump via `package.json` + `bun run scripts/sync-version.ts` (mirrors several manifests).+- Reuse the canonical MCP entry payload so grok never drifts from the other targets.++# Required output format++Produce exactly 3 distinct architectural variants. For each variant:++### Variant N: <short name>+- **Approach**: 2-3 sentences describing the variant.+- **Trade-offs**: bullet list of pros and cons.+- **Complexity**: small | medium | large+- **Risk**: low | medium | high++After the three variants, add exactly one recommendation:++### Recommended: Variant N+**Rationale**: 2-3 sentences explaining why this variant over the others, considering the project context and constraints above.++Output nothing outside of these sections.diff --git a/docs/brainstorm/grok-native-integration/design.md b/docs/brainstorm/grok-native-integration/design.mdnew file mode 100644index 00000000..f4b1e468--- /dev/null+++ b/docs/brainstorm/grok-native-integration/design.md@@ -0,0 +1,197 @@+# Grok Build native integration - config.toml MCP, native hooks, session import, hook-payload compat++**Status:** implemented (superseded MCP/hooks delivery; see Correction below)+**Author:** claude-dev-agent (via feature-release-playbook)+**Audience:** implementation+**Kanban:** t_0eda929d (epic) with children t_fc98eef2, t_23cd40bc, t_b69deebd, t_8fdd6077, t_f7111278++## Correction (2026-06-12) - the bundled-plugin approach did NOT work; superseded++The original design (below) shipped MCP and hooks as a bundled grok plugin under+`~/.grok/plugins/open-second-brain/`. Validated against live grok 0.2.45 (session debug+log), that does NOT deliver working tools/hooks in a real session:++- The plugin's `.mcp.json` used a bare `o2b` command. grok spawns MCP servers with a+ restricted PATH that excludes `~/.local/bin`, so `o2b` fails with ENOENT and zero tools+ load. (The earlier "verified, 71 tools" was a false positive: `grok mcp doctor` runs with+ the interactive shell PATH, masking the session-spawn failure.)+- Plugin-provided hooks are not discovered in a session (`hooks: discovery complete+ total_hooks=0`); the plugin `.mcp.json` is also lower priority than `config.toml`.++The shipped, working design (implemented; proven in a real session: 71 + 5 MCP tools+registered, 10 hooks discovered and dispatched):++- **MCP** -> `~/.grok/config.toml` `[mcp_servers.open-second-brain]` /+ `[mcp_servers.open-second-brain-writer]` (grok's primary, highest-priority source), with an+ ABSOLUTE command `bun run <repo>/src/cli/main.ts mcp …` (bun = `process.execPath`, repo and+ vault resolved at install). `src/core/install/grok-config.ts` is a minimal, dependency-free+ TOML editor that ensures/removes only these two tables, preserving all other config.+- **Hooks** -> `~/.grok/hooks/open-second-brain.json` (grok's native, always-trusted hooks+ dir), absolute `bun run <repo>/hooks/<name>.ts` commands. `src/core/install/grok-asset.ts`+ renders both artifacts.+- The bundled plugin (`plugins/grok/`, `grok-plugin-asset.ts`) is removed. The session-import+ adapter (`sessions/grok.ts`) and the hook-payload compat (`hooks/lib/*`) are unchanged - they+ were correct independent of the delivery mechanism.++The sections below are the original (superseded) plugin design, kept for the audit trail.++## Problem statement++Open Second Brain integrates deeply with Claude Code, OpenAI Codex, and opencode (MCP+registration, lifecycle hooks, session import) but has no Grok Build (`grok`, xAI) support.+Grok auto-reads Claude Code and Cursor config, so a user who already runs the Claude Code+integration gets partial pickup, but pure-grok users get nothing, grok sessions are never+imported into the Brain, our hook scripts misparse grok's stdin payload, and there is no+first-class, marketplace-publishable grok unit. This ships a native grok integration matching+the depth of the existing runtimes.++## Scope++- A bundled grok plugin (`plugins/grok/open-second-brain/`): `plugin.json` manifest, `.mcp.json`+ with the two canonical Open Second Brain MCP servers, `hooks/hooks.json` with three lifecycle+ hooks (SessionStart active-context inject, PostToolUse post-write logging nudge, SessionEnd+ session capture). The plugin is the marketplace-publishable unit.+- A `grok` install target (`o2b install --target grok --apply`) that installs the plugin under+ `~/.grok/plugins/open-second-brain/` (auto-trusted), ensures it is enabled, records it in the+ install manifest, reports drift on `verify`, and reverses on `uninstall`.+- A `grok` session adapter that imports `~/.grok/sessions/<cwd>/<id>/updates.jsonl` (ACP stream)+ with lineage from `summary.json` `parent_session_id`, wired through `importSessionPath`.+- Hook-payload compatibility: the shared hook stdin parser learns grok's camelCase payload so+ the hooks run under grok (whether via native `~/.grok/hooks/` or grok's Claude-compat scan).+- Docs: `install/grok.md`, `install.md` table, `README.md` runtime list, `docs/how-it-works.md`+ integration section, `CHANGELOG.md`.++## Out of scope++- Writing `~/.claude.json` / `~/.claude/settings.json` for pure-grok users (Variant 3, rejected:+ impersonates a foreign vendor's namespace).+- A general TOML serialization layer for the MCP payload (Variant 1, rejected). MCP lives in the+ plugin's `.mcp.json` (standard JSON), so the canonical `McpServerEntry` is reused verbatim and+ no TOML touches the MCP payload.+- `grok mcp add` shelling and `grok plugin install` shelling for the install path: rejected to+ keep the adapter offline-unit-testable and free of a hard runtime dependency on the grok+ binary. (`grok` IS used in QA smoke tests, just not as an apply-time dependency.)+- LSP server registration (`.lsp.json`), `commands/`, `agents/` plugin components: not needed.+- PreCompact extraction parity: handled by session capture; revisit if a gap shows in the field.++## Chosen approach++Variant 2 from `variants.md` (consultant-recommended, accepted without override).++The bundled plugin is the single first-class artifact, mirroring the opencode bundled plugin.+`src/core/install/grok-plugin-asset.ts` resolves the bundled plugin tree and a version stamp+(mirroring `opencode-plugin-asset.ts`). The plugin directory holds:++- `plugin.json` - name `open-second-brain`, version mirrored from `package.json` via the+ version-sync script, description, metadata. Passes `grok plugin validate`.+- `.mcp.json` - MCP standard format `{ "mcpServers": { ... } }`. STATIC and vault-agnostic,+ mirroring the repo's existing Claude plugin file `./.mcp.json`: `command`+ `${CLAUDE_PLUGIN_ROOT}/scripts/o2b`, args `["mcp"]` and `["mcp", "--scope", "writer"]`. Grok+ populates `${CLAUDE_PLUGIN_ROOT}` via its documented alias of `GROK_PLUGIN_ROOT`, and `o2b mcp`+ resolves the vault from the persisted config (no `--vault` arg, no install-time generation).+ This is the plugin-scoped MCP form already proven by the Claude integration, NOT the+ `buildPayload` (`--vault <path>`) form the file-config adapters use; the two forms are+ intentionally different and the grok plugin reuses the plugin-scoped one.+- `hooks/hooks.json` - mirrors the repo's existing Claude plugin `./hooks/hooks.json` (same+ `o2b-hook active-inject | post-write-reminder | session-capture` commands, same+ `$CLAUDE_PLUGIN_ROOT`-then-PATH fallback), with grok-specific adjustments:+ - Lifecycle events (`SessionStart`, `SessionEnd`, `UserPromptSubmit`, `Stop`) carry NO+ `matcher` - grok rejects a matcher on those events. Tool events (`PostToolUse`) keep theirs.+ - `PostToolUse` matcher lists both the Claude-style names (`Write|Edit|MultiEdit|apply_patch`)+ and grok's aliased `search_replace`, since grok maps Claude tool names to its own.+ - Session capture is wired on `SessionEnd` (grok's terminal lifecycle event).+ - The commands bake in no vault path, so one bundle serves every vault and the content is+ deterministic for drift detection.++The `grok` install adapter (`src/core/install/adapters/grok.ts`) does NOT use the JSON-MCP+factory for MCP (MCP ships inside the plugin, not in a grok config file). Its plan/apply/verify/+uninstall manage the plugin tree:++- `apply`: copy the bundled plugin tree into `~/.grok/plugins/open-second-brain/` (creating dirs),+ record every written path under the manifest `owned_paths`, and refresh an outdated copy.+ `GROK_HOME` overrides the base dir; honor it. NO `config.toml` touch is needed: verified+ against live grok 0.2.45 that a user-scope plugin under `~/.grok/plugins/<name>/` is+ auto-enabled and auto-trusted (`grok inspect` shows `enabled: true` with its MCP servers and+ hooks active, `grok mcp doctor` starts the server and discovers its tools), with config.toml+ carrying only `[cli]`. The docs' "plugins disabled by default" applies to marketplace and+ project-scope plugins, not user-scope ones. This drops the planned TOML enable helper entirely.+- `verify`: flag a missing, edited, or non-file (stray directory) plugin file as drift, with a+ `o2b install --target grok --apply` fix hint.+- `uninstall`: remove exactly the `owned_paths` and the now-empty plugin directory, leaving+ unrelated grok config untouched.++The `grok` session adapter (`src/core/brain/sessions/grok.ts`) detects on the ACP `updates.jsonl`+structure, yields `SessionTurn`-shaped turns, and resolves lineage from a sibling `summary.json`+`parent_session_id`. A newer/unknown ACP shape fails with a versioned PARSE error.++Hook-payload compat (`hooks/lib/stdin.ts` + `detect.ts`): a single declarative field-mapping+normalizes grok's `{hookEventName, sessionId, cwd, workspaceRoot, toolName, toolInput}` into the+internal shape the Claude/Codex paths use; runtime detection recognizes grok via `GROK_*` env and+payload shape. Where grok omits a Claude field (`transcript_path`), the type stays optional and+the code branches explicitly rather than faking a default.++## Design decisions++- **Plugin is the MCP vehicle, not config.toml.** `.mcp.json` is standard JSON - zero TOML, and+ (per the verified enable finding below) zero `config.toml` touch at all.+- **Reuse the Claude plugin artifacts; the whole plugin tree is static and vault-agnostic.** The+ grok `.mcp.json` and `hooks/hooks.json` mirror the repo's existing `./.mcp.json` and+ `./hooks/hooks.json`. Grok sets `CLAUDE_PLUGIN_ROOT` as an alias for `GROK_PLUGIN_ROOT` and+ reads the Claude-shape hook JSON, so those artifacts work under grok almost verbatim. No+ `buildPayload`, no install-time generation, no vault path baked into the bundle. A unit test+ asserts the grok artifacts stay in sync with their Claude-plugin sources (the only allowed+ divergences are the documented grok adjustments: lifecycle-event matchers removed, `SessionEnd`+ capture), so the two never drift.+- **File-copy install, no `config.toml` touch, no `grok plugin install --trust` shell.** Verified+ on live grok: dropping the tree into `~/.grok/plugins/<name>/` is sufficient (auto-enabled and+ auto-trusted). The adapter stays offline-unit-testable and free of an apply-time grok-binary+ dependency, and the planned TOML enable helper proved unnecessary and was dropped.+- **Hook env vars over payload fields where grok provides both.** `GROK_SESSION_ID` /+ `GROK_WORKSPACE_ROOT` / `CLAUDE_PROJECT_DIR` are stable; the parser prefers them and falls back+ to payload fields, matching how the Claude layer already reads env first.+- **Capture via SessionEnd hook, import via adapter.** The hook only triggers capture; the+ adapter owns parsing `updates.jsonl`. Same separation the opencode spool used, but grok's own+ session store is the source of truth (no spool file to own), so the adapter reads grok's files+ directly.+- **Matcher lists both tool-name spellings.** grok maps Claude names to its own, but listing both+ `Edit|Write|MultiEdit` and `search_replace` makes the hook robust whether grok applies the alias+ before or after matcher evaluation; verified in QA.++## File changes++New:+- `plugins/grok/open-second-brain/plugin.json`, `.mcp.json`, `hooks/hooks.json` - the bundled+ plugin tree (hooks use inline `o2b-hook` commands; no `hooks/bin/` scripts needed).+- `src/core/install/grok-plugin-asset.ts` - renders the grok artifacts from the Claude sources ++ exposes the committed bytes for the adapter.+- `src/core/install/adapters/grok.ts` - the install adapter (plugin-tree lifecycle).+- `src/core/brain/sessions/grok.ts` - the ACP session adapter.+- `tests/core/install/adapters/grok.test.ts`, `tests/core/brain.sessions.grok.test.ts`,+ `tests/plugins/grok-plugin.test.ts`, `tests/hooks/grok-stdin.test.ts` - per-unit tests.+- `tests/fixtures/sessions/grok-minimal.jsonl` (real `updates.jsonl` captured from live grok),+ `tests/fixtures/install/grok/` fixtures.+- `install/grok.md` - install guide.++Modified:+- `src/core/install/registry.ts` (or adapter self-register) - register `grok`.+- `src/core/install/adapters/types.ts` if a target-id union exists - add `grok`.+- `src/core/brain/sessions/registry.ts` (`SESSION_ADAPTERS`) + `types.ts` (`SessionAdapterId`) -+ add `grok`.+- `hooks/lib/stdin.ts`, `hooks/lib/detect.ts` - grok payload normalization + runtime detection.+- The version-sync script's manifest list, if `plugin.json` version must mirror `package.json`.+- `README.md`, `install.md`, `docs/how-it-works.md`, `CHANGELOG.md`.++## Risks and open questions++- Enable semantics: RESOLVED in Phase 2 against live grok 0.2.45. A user-scope plugin under+ `~/.grok/plugins/<name>/` is auto-enabled and auto-trusted with no `config.toml` entry+ (`grok inspect` reports `enabled: true`, MCP + hooks active; `grok mcp doctor` handshakes and+ discovers 71 tools). The planned `[plugins] enabled` TOML helper was therefore dropped.+- `updates.jsonl` ACP event schema: typed from grok's ACP docs but must be pinned to a real+ captured session; the `format`/version gate surfaces a shape mismatch as a versioned error,+ not silent corruption.+- Whether grok applies matcher tool-name aliasing before or after matcher evaluation: the matcher+ lists both spellings to be safe; QA confirms which fires.+- `plugin.json` version mirroring: RESOLVED. `plugins/grok/open-second-brain/plugin.json` was+ added to `scripts/sync-version.ts` JSON_TARGETS (and the CLAUDE.md mirrored-manifest list), so+ CI gates it against `package.json`.diff --git a/docs/brainstorm/grok-native-integration/plan.md b/docs/brainstorm/grok-native-integration/plan.mdnew file mode 100644index 00000000..c184cb97--- /dev/null+++ b/docs/brainstorm/grok-native-integration/plan.md@@ -0,0 +1,62 @@+# Grok Build native integration - implementation plan++One feature branch `feat/grok-native-integration`, atomic conventional commits, TDD per unit+(failing test first). Implementation order is risk-first: build the plugin and prove the+enable-semantics against live grok 0.2.45 before the rest depends on it.++## Tasks++### Task 1: Bundled grok plugin tree + asset module (kanban t_b69deebd)+- **Files**: `plugins/grok/open-second-brain/plugin.json`, `.mcp.json`, `hooks/hooks.json`,+ `hooks/bin/*`; `src/core/install/grok-plugin-asset.ts`; `tests/plugins/grok-plugin.test.ts`.+- **Acceptance**: `grok plugin validate plugins/grok/open-second-brain` passes; `.mcp.json`+ carries the two canonical entries built from the shared `McpServerEntry` payload (no+ duplication); `grok-plugin-asset.ts` returns the tree + version stamp; hooks are fail-soft and+ unit-tested offline with stub stdin + stub `o2b-hook`.+- **Depends on**: none.++### Task 2: Grok install adapter (kanban t_8fdd6077) - DONE+- **Files**: `src/core/install/adapters/grok.ts`; registry registration in the four import+ sites; `tests/core/install/adapters/grok.test.ts`.+- **Acceptance**: `o2b install --target grok --apply` copies the plugin tree into+ `~/.grok/plugins/open-second-brain/` (honoring `GROK_HOME`), records `owned_paths`; `verify`+ flags a missing/edited/non-file plugin file as drift; `uninstall` removes exactly what was+ installed and the now-empty plugin dir; dry-run writes nothing.+- **VERIFIED against live grok 0.2.45**: after a real `apply`, `grok inspect --json` shows the+ plugin `enabled: true` with MCP servers + hooks; `o2b install --target grok --check` reports+ `ok`; `grok mcp doctor` handshakes and discovers the tools. A user-scope plugin is auto-enabled+ and auto-trusted, so no `config.toml` enable helper is needed (planned `grok-config.ts` dropped).+- **Depends on**: Task 1.++### Task 3: Grok hook-payload compatibility (kanban t_23cd40bc)+- **Files**: `hooks/lib/stdin.ts`, `hooks/lib/detect.ts`; `tests/hooks/grok-stdin.test.ts`.+- **Acceptance**: grok's camelCase payload (`hookEventName`/`sessionId`/`cwd`/`workspaceRoot`/+ `toolName`/`toolInput`) normalizes to the internal shape via one declarative mapping; existing+ Claude/Codex payloads still parse unchanged; runtime detection recognizes grok via `GROK_*`+ env + payload shape; a missing `transcript_path` is an explicit typed-optional branch, not a+ faked default; unknown payload fails explicitly.+- **Depends on**: none (integrates with Task 1's hooks at QA).++### Task 4: Grok session import adapter (kanban t_fc98eef2)+- **Files**: `src/core/brain/sessions/grok.ts`; `SESSION_ADAPTERS` + `SessionAdapterId`;+ `tests/core/brain.sessions.grok.test.ts`; `tests/fixtures/sessions/grok-minimal.jsonl`.+- **Acceptance**: adapter `detect()` keys on the ACP `updates.jsonl` structure; iterator yields+ `SessionTurn`-shaped turns; lineage from sibling `summary.json` `parent_session_id`;+ cross-table detect test extended (no adapter collision); a newer ACP shape fails with a+ versioned PARSE error. Fixture captured from a real grok session.+- **Depends on**: none.++### Task 5: Docs (kanban t_f7111278)+- **Files**: `install/grok.md` (new); `install.md`, `README.md`, `docs/how-it-works.md`,+ `CHANGELOG.md`.+- **Acceptance**: every shipped capability documented; full product name throughout; no+ abbreviations, exclamation marks, em-dashes, or AI-authorship markers; any mermaid renders on+ GitHub; known gaps documented (no `transcript_path`; plugins disabled by default until enabled;+ Claude-compat overlap explained). One CHANGELOG entry under the next version header.+- **Depends on**: Tasks 1-4 (docs describe what actually shipped).++## QA (Phase 4, after all tasks)++- `bun test`, `bun run typecheck`, `bun run lint`, `bun run scripts/sync-version.ts --check`.+- Live smoke test against grok 0.2.45: install, `grok inspect --json` shows MCP + hooks, trigger+ a file edit (PostToolUse nudge), end a session and import it into the Brain, `grok mcp list`.diff --git a/docs/brainstorm/grok-native-integration/variants.md b/docs/brainstorm/grok-native-integration/variants.mdnew file mode 100644index 00000000..9399cff9--- /dev/null+++ b/docs/brainstorm/grok-native-integration/variants.md@@ -0,0 +1,64 @@+# Grok Build native integration - brainstorm variants++**Consultant:** Claude Code (`claude -p`), primary, exit 0. Fallback (codex) not needed.+**Orchestrator:** claude-dev-agent (via feature-release-playbook)+**Decision:** Accept the consultant recommendation (Variant 2) without override.++---++## Consultant output (verbatim)++### Variant 1: Native config.toml writer+- **Approach**: Extend the install-adapter registry with a grok adapter that writes the two canonical MCP entries directly into `~/.grok/config.toml` `[mcp_servers.*]` and drops the three lifecycle hooks into `~/.grok/hooks/*.json` (Claude-compatible JSON shape). A grok `SessionAdapter` reads the ACP `updates.jsonl` + `summary.json` stream. No plugin; integration lives entirely in grok's own first-class config surfaces.+- **Trade-offs**:+ - Pro: maximally native to grok's authoritative surfaces; pure-grok users with no `~/.claude` are served directly with zero compat-merge dependency.+ - Pro: `summary.json.parent_session_id` feeds the existing session-lineage work cleanly; hooks get `GROK_HOOK_*`/`CLAUDE_PROJECT_DIR` env for free.+ - Con: config.toml is TOML and the project ships no TOML lib - forces a hand-rolled minimal emitter/patcher for the `[mcp_servers.<name>]` table, which `serializeEntry` does not currently cover (new on-disk shape + drift detection for TOML).+ - Con: produces no marketplace-publishable unit, so goal (b) is unmet; the integration is invisible to `grok plugin`/marketplace tooling.+ - Con: the canonical `McpServerEntry` must be projected into TOML rather than reused as-is, a new serialization seam that can drift from the JSON targets.+- **Complexity**: medium+- **Risk**: medium++### Variant 2: Bundled grok plugin as the first-class unit (opencode-style two-pronged)+- **Approach**: Ship a version-stamped grok plugin asset (mirroring `opencode-plugin-asset.ts`): a directory with `plugin.json`, `.mcp.json` in MCP standard format carrying the two canonical entries, and `hooks/hooks.json` for the three lifecycle hooks. The install adapter places it under `~/.grok/plugins/` and force-enables it (config.toml `[plugins] enabled` / `--trust` path), and a grok `SessionAdapter` imports the ACP session stream. The plugin is the marketplace-publishable unit.+- **Trade-offs**:+ - Pro: hits all four goals - pure-grok install path, marketplace-publishable first-class unit, and heavy reuse of the opencode-plugin-asset pattern + session-adapter registry.+ - Pro: MCP lives in `.mcp.json` (standard JSON) so the canonical `McpServerEntry` is reused verbatim with zero TOML for MCP - strongest DRY/anti-drift posture.+ - Pro: precedent #88 proves the config-write + bundled-plugin + session-adapter shape end to end.+ - Con: plugins are disabled by default - the adapter must reliably force-enable (config.toml `[plugins] enabled` append or `grok plugin install --trust`), a narrow TOML touch and a footgun if skipped, which the verify step must assert against.+ - Con: two delivery artifacts (plugin asset + thin config write) to keep version-synced, slightly more surface than a pure config writer.+- **Complexity**: medium+- **Risk**: low++### Variant 3: Claude-compat piggyback shim+- **Approach**: Lean on grok's auto-merge of `~/.claude.json` MCP and `~/.claude/settings.json` hooks via `[compat.claude]`; for pure-grok users, the existing Claude Code adapter writes those Claude-format files, and the only new code is a grok camelCase hook-stdin branch plus the grok `SessionAdapter`. Smallest possible footprint.+- **Trade-offs**:+ - Pro: minimal new code - reuses the Claude adapter outputs almost entirely; only the stdin parser and session adapter are grok-specific.+ - Con: writing `~/.claude.json` / `~/.claude/settings.json` for a user who runs only grok is exactly the silent workaround the constraints forbid (maximally native, no crutches); it pollutes a foreign vendor's namespace.+ - Con: relies on compat-merge priority (config.toml > Claude > Cursor) staying stable across grok versions - fragile, no first-class ownership/drift tracking.+ - Con: yields no marketplace unit (goal b fails) and is not "first-class native" (goal a is served only by impersonating Claude).+- **Complexity**: small+- **Risk**: high++### Recommended: Variant 2+**Rationale**: Only Variant 2 satisfies all four sub-goals at once - it serves pure-grok users via a real install/enable path, ships the marketplace-publishable first-class plugin, and maximally reuses the existing seams (opencode-plugin-asset, `.mcp.json` standard format preserving the canonical `McpServerEntry`, session-adapter registry, hook lib). Routing MCP through the plugin's `.mcp.json` keeps grok off the TOML path entirely for the canonical payload, avoiding both the hand-rolled emitter that burdens Variant 1 and the namespace-impersonation workaround that disqualifies Variant 3, while #88 already proves the two-pronged shape end to end.++---++## Orchestrator final rationale++Accepted Variant 2 without override. It is the only variant consistent with the project's+explicit constraints (maximally native, no crutches, reuse seams) AND the operator's stated+preference to never impersonate or diverge from a foreign vendor's conventions. Variant 3 is+rejected outright: writing into `~/.claude.json` for a pure-grok user is precisely the kind+of misleading workaround the brief forbids. Variant 1 is native but yields no marketplace+unit and forces a TOML serialization seam for the MCP payload that would drift from every+other target.++The one design fork the recommendation leaves open - how to force-enable the plugin (grok+disables plugins by default) - is resolved in `design.md`: copy the bundle into+`~/.grok/plugins/<name>/` (auto-trusted) and ensure a `[plugins] enabled` entry through a+minimal, offline-testable TOML section/array helper, rather than shelling to `grok plugin+install --trust` (which would add a hard runtime dependency on the grok binary and break the+project's offline-unit-testable-adapter convention). MCP itself stays entirely in the+plugin's `.mcp.json`, so no TOML touches the canonical MCP payload.diff --git a/docs/how-it-works.md b/docs/how-it-works.mdindex fde53777..d6d5c227 100644--- a/docs/how-it-works.md+++ b/docs/how-it-works.md@@ -672,6 +672,7 @@ graph LRHermes -- "mcp_servers.yaml" --> Stdio["o2b mcp (stdio)"]ClaudeCode["Claude Code"] -- "bundled .mcp.json" --> StdioCodex -- "codex mcp add" --> Stdio+ GrokBuild["Grok Build"] -- "config.toml [mcp_servers]" --> StdioOpenClaw -- "native JS plugin" --> InProc["in-process tools"]Stdio --> Vault[(Brain/ on disk)]InProc --> Vault@@ -686,6 +687,14 @@ graph LRplugin-shipped `brain-memory/SKILL.md` automatically.- **Codex** registers the MCP server with `codex mcp add`; the sameskill bundle is loaded automatically.+- **Grok Build** registers MCP in `~/.grok/config.toml` `[mcp_servers.*]`+ (grok's primary source) and lifecycle hooks in `~/.grok/hooks/` (its native+ hooks dir), both with an absolute `bun run …/main.ts` command, via+ `o2b install --target grok`. Verified against live grok 0.2.45: the bare+ `o2b` command does not resolve on grok's session-spawn PATH, so the absolute+ form is required. grok sessions (`~/.grok/sessions/.../updates.jsonl`, an ACP+ stream) import via the `grok` session adapter. See+ [`install/grok.md`](../install/grok.md).- **OpenClaw** runs tools natively in the plugin's Node.js process(no subprocess, by security-scanner requirement).diff --git a/hooks/lib/detect.ts b/hooks/lib/detect.tsindex 3e0214a3..ff67fea1 100644--- a/hooks/lib/detect.ts+++ b/hooks/lib/detect.ts@@ -14,16 +14,25 @@import type { ToolCall } from "./transcript.ts";-// Canonical tool names that mutate files in either runtime.+// Canonical tool names that mutate files across runtimes.// Claude Code: `Write`, `Edit`, `MultiEdit` (native tools — no// `mcp__…__` prefix in transcripts).// Codex: `apply_patch` (custom_tool_call wrapping diffs).+// Grok Build: `search_replace` (grok's own file-edit tool, the name+// it aliases Claude's Edit/Write/MultiEdit to and the name+// that appears in its hook payload and session transcript).//// Codex also supports Edit/Write *aliases* in matchers, but the actual// `name` field in the transcript is always `apply_patch` for file// edits done through it; we still accept Edit/Write to defend against// a future runtime that mirrors the matcher alias into the call name.-const NATIVE_ARTIFACT_NAMES = new Set<string>(["Write", "Edit", "MultiEdit", "apply_patch"]);+const NATIVE_ARTIFACT_NAMES = new Set<string>([+ "Write",+ "Edit",+ "MultiEdit",+ "apply_patch",+ "search_replace",+]);// Tool-name suffixes that count as "the agent logged this turn",// regardless of any runtime-injected MCP prefix.@@ -162,7 +171,7 @@ export function summarizeTurn(* renders byte-identical reminder text to the v0.10.4 baseline, so* a future runtime that breaks both signals never crashes the hook.*/-export type HookRuntime = "claudecode" | "codex" | "unknown";+export type HookRuntime = "claudecode" | "codex" | "grok" | "unknown";const CLAUDE_TRANSCRIPT_NEEDLES = ["/.claude/projects/", "/.claude/sessions/"] as const;const CODEX_TRANSCRIPT_NEEDLE = "/.codex/sessions/";@@ -171,21 +180,35 @@ const CODEX_TRANSCRIPT_NEEDLE = "/.codex/sessions/";* Infer the runtime from a hook payload by shape. First-hit wins,* order matches the design doc:*- * 1. `transcript_path` substring (`/.claude/projects/`, `/.claude/sessions/`).- * 2. `transcript_path` substring (`/.codex/sessions/`).- * 3. Claude Code distinctive triple (`session_id` + `cwd` + `tool_use_id`).- * 4. Codex apply_patch shape (`tool_name === "apply_patch"` with+ * 1. Grok: camelCase payload shape (`hookEventName` / `workspaceRoot`) or a+ * `GROK_*` hook env var. Grok ships no `transcript_path` and uses+ * camelCase keys Claude/Codex never send, so this is unambiguous.+ * 2. `transcript_path` substring (`/.claude/projects/`, `/.claude/sessions/`).+ * 3. `transcript_path` substring (`/.codex/sessions/`).+ * 4. Claude Code distinctive triple (`session_id` + `cwd` + `tool_use_id`).+ * 5. Codex apply_patch shape (`tool_name === "apply_patch"` with* a patch body in `tool_input.input`).- * 5. `"unknown"`.+ * 6. `"unknown"`.*- * Malformed payloads (`null`, primitives, missing fields, wrong types)- * resolve to `"unknown"` without throwing — the hook never crashes on- * detection.+ * `normalizeHookPayload` preserves grok's original camelCase keys, so this+ * works whether it runs before or after normalization. Malformed payloads+ * (`null`, primitives, missing fields, wrong types) resolve to `"unknown"`+ * without throwing — the hook never crashes on detection.*/-export function detectHookRuntime(payload: unknown): HookRuntime {+export function detectHookRuntime(+ payload: unknown,+ env: Record<string, string | undefined> = process.env,+): HookRuntime {if (payload === null || typeof payload !== "object") return "unknown";const p = payload as Record<string, unknown>;+ if (typeof p["hookEventName"] === "string" || typeof p["workspaceRoot"] === "string") {+ return "grok";+ }+ if (env["GROK_HOOK_EVENT"] || env["GROK_SESSION_ID"] || env["GROK_WORKSPACE_ROOT"]) {+ return "grok";+ }+const tp = p["transcript_path"];if (typeof tp === "string") {if (CLAUDE_TRANSCRIPT_NEEDLES.some((n) => tp.includes(n))) {diff --git a/hooks/lib/messages.ts b/hooks/lib/messages.tsindex a44d86ca..6b9d5fe9 100644--- a/hooks/lib/messages.ts+++ b/hooks/lib/messages.ts@@ -42,6 +42,13 @@ function postWriteCadenceLine(runtime: HookRuntime): string {"_or `brain_apply_evidence` before this exec returns; there is_","_no second turn._",].join("\n");+ case "grok":+ return [+ "_Grok Build session: many turns ahead — capture the signal or_",+ "_evidence now rather than batching to end-of-session; long_",+ "_sessions risk forgetting the context that distinguishes one_",+ "_artifact from the next._",+ ].join("\n");case "unknown":return "";}@@ -87,6 +94,8 @@ function stopGuardrailCadenceLine(runtime: HookRuntime): string {return "_This guardrail fires at most once per turn — send another reply (with or without a brain-event call) to clear it._";case "codex":return "_This `codex exec` is about to end — call `brain_feedback` / `brain_apply_evidence` / `brain_note` now or finish silently; no further guardrail will fire._";+ case "grok":+ return "_This guardrail fires at most once per turn — send another reply (with or without a brain-event call) to clear it._";case "unknown":return "";}@@ -96,7 +105,7 @@ export function stopGuardrailReason(runtime: HookRuntime = "unknown"): string {const cadence = stopGuardrailCadenceLine(runtime);const parts: string[] = ["Open Second Brain hook: this turn touched files",- "(Write / Edit / MultiEdit / apply_patch) but did not call any of:",+ "(Write / Edit / MultiEdit / apply_patch / search_replace) but did not call any of:","","- `brain_feedback` — new taste correction the user expressed in this"," turn (one signal per file, see the `brain-memory` skill)",diff --git a/hooks/lib/stdin.ts b/hooks/lib/stdin.tsindex cf5fb4c3..84915032 100644--- a/hooks/lib/stdin.ts+++ b/hooks/lib/stdin.ts@@ -39,9 +39,62 @@ export interface HookPayloadBase {readonly tool_response?: unknown;}+/**+ * Grok Build delivers the hook event with camelCase keys and a snake_case+ * event VALUE (`hookEventName: "session_start"`), where Claude Code and Codex+ * use snake_case keys and a PascalCase value (`hook_event_name:+ * "SessionStart"`). Each tuple maps a grok key to its internal snake_case+ * equivalent; the optional transform reshapes the value. Verified against grok+ * 0.2.45 (`~/.grok/docs/user-guide/10-hooks.md`).+ */+const GROK_KEY_MAP: ReadonlyArray<readonly [string, string, ((v: unknown) => unknown)?]> = [+ ["hookEventName", "hook_event_name", snakeToPascalEvent],+ ["sessionId", "session_id"],+ ["toolName", "tool_name"],+ ["toolInput", "tool_input"],+ ["toolResponse", "tool_response"],+ ["parentSessionId", "parent_session_id"],+];++/**+ * Convert grok's snake_case event value to the canonical PascalCase the rest+ * of the hook layer compares against. Idempotent on a value that is already+ * PascalCase (Claude/Codex), so it is safe to apply unconditionally to the+ * grok-sourced field. Non-strings pass through untouched.+ */+function snakeToPascalEvent(value: unknown): unknown {+ if (typeof value !== "string") return value;+ return value+ .split("_")+ .map((part) => (part.length === 0 ? part : part[0]!.toUpperCase() + part.slice(1)))+ .join("");+}++/**+ * Normalize a raw hook payload into the internal snake_case shape. Grok's+ * camelCase fields are mapped to their snake_case equivalents (filling a key+ * only when it is not already present, so a Claude/Codex payload is returned+ * unchanged); the original keys are preserved so {@link detectHookRuntime} can+ * still recognize the grok shape. A non-object value passes through unchanged.+ */+export function normalizeHookPayload(value: unknown): unknown {+ if (value === null || typeof value !== "object" || Array.isArray(value)) {+ return value;+ }+ const source = value as Record<string, unknown>;+ const result: Record<string, unknown> = { ...source };+ for (const [camelKey, snakeKey, transform] of GROK_KEY_MAP) {+ if (result[snakeKey] === undefined && source[camelKey] !== undefined) {+ result[snakeKey] = transform ? transform(source[camelKey]) : source[camelKey];+ }+ }+ return result;+}+export function asHookPayload(value: unknown): HookPayloadBase {- if (value !== null && typeof value === "object") {- return value as HookPayloadBase;+ const normalized = normalizeHookPayload(value);+ if (normalized !== null && typeof normalized === "object") {+ return normalized as HookPayloadBase;}return {};}diff --git a/hooks/post-write-reminder.ts b/hooks/post-write-reminder.tsindex ec79ff66..1fde0a26 100755--- a/hooks/post-write-reminder.ts+++ b/hooks/post-write-reminder.ts@@ -103,13 +103,16 @@ async function main(): Promise<void> {const runtime = detectHookRuntime(payload);// Session cadence (token-diet, t_9cc4f400): the full reminder- // teaches the contract once per Claude Code session; afterwards a- // <= 200-char nudge keeps the per-edit cost negligible. Codex+ // teaches the contract once per session; afterwards a <= 200-char+ // nudge keeps the per-edit cost negligible. Applies to the+ // multi-turn interactive runtimes (Claude Code, Grok Build). Codex// `codex exec` is one-shot, so steady state never applies there;// unknown runtimes and absent session ids stay on the full text.const sessionId = typeof payload.session_id === "string" ? payload.session_id : "";const steadyState =- runtime === "claudecode" && sessionId.length > 0 && sessionAlreadyReminded(sessionId);+ (runtime === "claudecode" || runtime === "grok") &&+ sessionId.length > 0 &&+ sessionAlreadyReminded(sessionId);const text = steadyState ? postWriteNudge() : postWriteReminder({ toolName, filePath, runtime });diff --git a/hooks/session-capture.ts b/hooks/session-capture.tsindex 7bd633d9..462ace8d 100644--- a/hooks/session-capture.ts+++ b/hooks/session-capture.ts@@ -7,7 +7,7 @@import { resolveAgentName, resolveVault } from "../src/core/config.ts";import { captureSessionLifecycleEvent } from "../src/core/brain/session-lifecycle.ts";-import { readHookInput } from "./lib/stdin.ts";+import { normalizeHookPayload, readHookInput } from "./lib/stdin.ts";async function main(): Promise<void> {const vault = resolveVault();@@ -18,7 +18,9 @@ async function main(): Promise<void> {} catch {payload = null;}- await captureSessionLifecycleEvent(vault, payload, {+ // 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.+ await captureSessionLifecycleEvent(vault, normalizeHookPayload(payload), {agent: resolveAgentName(),});}diff --git a/install.md b/install.mdindex 4d832b3d..a4e989fe 100644--- a/install.md+++ b/install.md@@ -27,6 +27,7 @@ in one command:| Cursor | `o2b install --target cursor --apply` | `install/cursor.md` — JSON-merge; restart Cursor after apply || Aider | `o2b install --target aider --apply` | `install/aider.md` — managed block + sidecar context; no native MCP || opencode | `o2b install --target opencode --apply` | `install/opencode.md` — MCP servers + native plugin |+| Grok Build | `o2b install --target grok --apply` | `install/grok.md` — MCP in `~/.grok/config.toml` + native hooks (absolute command) || kiro | `o2b install --target kiro --apply` | `install/kiro.md` — JSON-merge || GitHub Copilot CLI | `o2b install --target copilot-cli --apply` | `install/copilot-cli.md` — `copilot mcp add` with JSON fallback || Google Gemini CLI | `o2b install --target gemini-cli --apply` | `install/gemini-cli.md` — JSON-merge in `~/.gemini/settings.json` |@@ -101,9 +102,9 @@ Universal:- [ ] a test event written without an explicit `agent` argumentstamps `@<chosen-agent-name>` in `Daily/`, not `@agent`.-MCP-driven runtimes only (Cursor, opencode, kiro, Copilot CLI,-Gemini CLI, Claude Code, Codex, Hermes — not `aider`, `pi`, or-`generic`):+MCP-driven runtimes only (Cursor, opencode, Grok Build, kiro,+Copilot CLI, Gemini CLI, Claude Code, Codex, Hermes — not `aider`,+`pi`, or `generic`):- [ ] all OSB tools advertised by the runtime's MCP listing.diff --git a/install/codex.md b/install/codex.mdindex 65df9298..2027b301 100644--- a/install/codex.md+++ b/install/codex.md@@ -38,11 +38,23 @@ o2b brain init --vault /path/to/vault```bashcodex mcp add open-second-brain \- --env VAULT_AGENT_NAME=<chosen-agent-name> \+ --env VAULT_AGENT_NAME=codex-<host>-agent \--env VAULT_TIMEZONE=<chosen-tz> \-- o2b mcp --vault /path/to/vault```+`VAULT_AGENT_NAME` makes Codex attribute its Brain writes to its OWN+host-qualified identity rather than the shared operator name - so Codex+activity is distinguishable per runtime, and in a shared multi-device vault+also per device.++Build the value by keeping the host segment of your configured `agent_name`+and substituting `codex` as the vendor token: if `agent_name` is+`claude-vps-agent`, use `codex-vps-agent`; on a Mac box named+`claude-mac-agent`, use `codex-mac-agent`. A name that does not fit the+`<vendor>-<host>-agent` shape is prefixed with `codex-` instead. This mirrors+what the `grok` and `opencode` adapters derive automatically.+## 5. Verify```bashdiff --git a/install/grok.md b/install/grok.mdnew file mode 100644index 00000000..4d001570--- /dev/null+++ b/install/grok.md@@ -0,0 +1,114 @@+# Grok Build++`o2b install --target grok --apply` performs a native [Grok Build](https://docs.x.ai/build/overview)+integration in one pass, writing to grok's own primary config locations:++- **MCP servers** - registers `open-second-brain` and `open-second-brain-writer`+ in `${GROK_HOME:-$HOME/.grok}/config.toml` under `[mcp_servers.*]` (grok's+ highest-priority MCP source), each with an absolute command+ (`bun run <repo>/src/cli/main.ts mcp …`). User-authored `[mcp_servers.*]`+ and other config sections are preserved.+- **Lifecycle hooks** - writes `${GROK_HOME:-$HOME/.grok}/hooks/open-second-brain.json`+ (grok's native, always-trusted hooks dir), again with absolute `bun` commands.++Why an absolute command rather than a bare `o2b`: verified against live grok+0.2.45 (the session debug log), grok spawns MCP servers and hook scripts with a+restricted PATH that excludes `~/.local/bin`, so a bare `o2b` fails to spawn and+no tools load. The absolute `bun run …/main.ts` form is what grok actually+launches and handshakes in a session (71 + 5 tools registered, hooks dispatched).++## Install++```bash+o2b install --target grok --apply+```++Start grok (or press `r` in the `/mcps` and `/hooks` modals) to load them.+Confirm with `grok inspect` and, for a live check, `grok mcp doctor+open-second-brain`.++## What it provides++- **MCP servers** - `open-second-brain` (full Brain surface) and+ `open-second-brain-writer` (the always-loaded writer set). grok namespaces+ the tools as `open-second-brain__<tool>` / `open-second-brain-writer__<tool>`+ and the model reaches them through grok's `search_tool` / `use_tool`.+- **Active context inject** - `SessionStart` runs `hooks/active-inject.ts`,+ appending the rendered `Brain/active.md` digest so the agent sees live+ preferences without calling `brain_query` first.+- **Post-write reminder** - after a file-mutating tool (grok's `search_replace`,+ plus the Claude-style `Write` / `Edit` / `MultiEdit` / `apply_patch` aliases)+ `hooks/post-write-reminder.ts` appends the logging nudge.+- **Session capture and the stop-log guardrail** - the `Stop` / `SessionEnd`+ hooks capture the session and check that an artifact turn logged a Brain+ event, mirroring the Claude Code behavior.++Every hook is fail-soft: a missing vault or runtime error never breaks the grok+session.++grok's Brain writes (hook captures and tool calls) attribute to a **grok-specific+identity** derived from your configured `agent_name`: the host segment is kept and+the vendor token is swapped to `grok` (`claude-vps-agent` -> `grok-vps-agent`; a+name that does not fit the `<vendor>-<host>-agent` shape is prefixed with `grok-`).+So grok activity is distinguishable per runtime - and, in a shared multi-device+vault, per device - rather than logged under the shared identity. Both the MCP+env (`config.toml`) and the hooks file carry this same derived name.++## Importing grok sessions++grok stores each session as+`${GROK_HOME:-$HOME/.grok}/sessions/<encoded-cwd>/<id>/updates.jsonl` (an ACP+session-update stream). Import one session, or a directory of them, into the+Brain:++```bash+o2b brain import-session \+ ~/.grok/sessions/<encoded-cwd>/<session-id>/updates.jsonl \+ --vault /path/to/vault+```++Autodetect resolves the `grok` format; pass `--format grok` to force it. The+importer extracts `@osb` markers from messages and replays `brain_feedback`+tool calls (grok's `open-second-brain__brain_feedback` is normalized to the+bare name first).++## Verify++```bash+o2b install --check --target grok+```++Reports drift when the `config.toml` MCP tables or the hooks file differ from+canonical (for example after an Open Second Brain upgrade, or if `bun`/the repo+moved - re-run apply to refresh the absolute paths).++## Uninstall++```bash+o2b uninstall --target grok --apply+```++Removes the two `[mcp_servers.*]` tables from `config.toml` and deletes the+hooks file. Unrelated grok configuration (other MCP servers, `[cli]`,+`[marketplace]`) is left intact.++## Relationship to the Claude Code integration++Grok reads Claude Code configuration for compatibility (MCP from+`~/.claude.json`, hooks from `~/.claude/settings.json`). An operator who already+runs the Open Second Brain Claude Code integration may see some of it picked up+that way. The native `grok` target exists so that operators who run only grok+get a first-class, in-session-working install, and so grok sessions import+**into** the Brain (no compatibility path covers that direction). The+integration uses grok's own `config.toml` and hooks dir - it does not write into+the `~/.claude/` namespace.++## Notes++- Verified against grok 0.2.45 and its bundled docs (`~/.grok/docs/user-guide/`).+- `GROK_HOME` overrides the `~/.grok` base directory; the adapter honors it.+- The absolute `bun`/repo paths are resolved at install time. If you move the+ Open Second Brain checkout or change the `bun` binary, re-run+ `o2b install --target grok --apply`.+- Rules: grok reads `AGENTS.md` and `CLAUDE.md` natively, so vault-level rules+ can travel as project instructions without any Open Second Brain involvement.diff --git a/install/openclaw.md b/install/openclaw.mdindex 92fd0253..f952b789 100644--- a/install/openclaw.md+++ b/install/openclaw.md@@ -64,6 +64,14 @@ The values are stored as JSON, so string values must be valid JSONescaping so bash does not consume the doubles. That's why thearguments look like `'"...".`+The configured `agentName` is the operator base name; OpenClaw does not log+under it verbatim. The per-turn identity reminder derives an+**openclaw-specific identity** from it: the host segment is kept and the vendor+token is swapped to `openclaw` (`claude-vps-agent` -> `openclaw-vps-agent`; a+name outside the `<vendor>-<host>-agent` shape is prefixed with `openclaw-`).+So OpenClaw activity is distinguishable per runtime - and, in a shared+multi-device vault, per device.+## 5. Verify```bashdiff --git a/install/opencode.md b/install/opencode.mdindex 9208c530..10d01a8d 100644--- a/install/opencode.md+++ b/install/opencode.md@@ -25,6 +25,15 @@ o2b install --target opencode --applyRestart `opencode` to load the MCP servers and the plugin.+opencode's Brain writes attribute to an **opencode-specific identity** derived+from your configured `agent_name`: the host segment is kept and the vendor+token is swapped to `opencode` (`claude-vps-agent` -> `opencode-vps-agent`; a+name that does not fit the `<vendor>-<host>-agent` shape is prefixed with+`opencode-`). So opencode activity is distinguishable per runtime - and, in a+shared multi-device vault, per device - rather than logged under the shared+identity. `apply` stamps this on `VAULT_AGENT_NAME` in `opencode.json`; no+manual step is needed.+## What the plugin does- **Active context inject** - appends the rendered `Brain/active.md`diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 1d31f53d..06003892 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -2,7 +2,7 @@"id": "open-second-brain","name": "Open Second Brain","description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",- "version": "1.3.1",+ "version": "1.4.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/openclaw/index.js b/openclaw/index.jsindex ad0c587e..1c85a619 100644--- a/openclaw/index.js+++ b/openclaw/index.js@@ -2370,6 +2370,16 @@ function normalizeAgentArgument(value) {return null;return cleaned;}+var HOST_QUALIFIED_NAME_RE = /^[^-]+-(.+)-agent$/;+function deriveRuntimeAgentName(runtimeId, operatorName) {+ const base = (operatorName ?? "").trim();+ if (base.length === 0)+ return runtimeId;+ const match = HOST_QUALIFIED_NAME_RE.exec(base);+ if (match)+ return `${runtimeId}-${match[1]}-agent`;+ return `${runtimeId}-${base}`;+}// src/core/path-safety.tsimport { dirname as dirname6, posix, relative as relative2, resolve as resolve3, sep } from "node:path";@@ -2387,9 +2397,10 @@ var openclaw_default = definePluginEntry({register(api) {api.on("before_prompt_build", () => {const cfg = api.pluginConfig ?? {};- const agent = normalizeAgentArgument(cfg.agentName ?? null) ?? process.env["VAULT_AGENT_NAME"] ?? resolveAgentName();- if (agent === "agent")+ const operator = normalizeAgentArgument(cfg.agentName ?? null) ?? process.env["VAULT_AGENT_NAME"] ?? resolveAgentName();+ if (operator === "agent")return;+ const agent = deriveRuntimeAgentName("openclaw", operator);return { prependContext: buildReminder(agent, "openclaw") };});api.registerTool({diff --git a/package.json b/package.jsonindex 242c1112..f8335eda 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.3.1",+ "version": "1.4.0","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.","keywords": [diff --git a/plugin.yaml b/plugin.yamlindex b0060cf5..9634a686 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.3.1"+version: "1.4.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex 90447199..a4e11cd9 100644--- a/plugins/codex/.codex-plugin/plugin.json+++ b/plugins/codex/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.3.1",+ "version": "1.4.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex b0060cf5..9634a686 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.3.1"+version: "1.4.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/pyproject.toml b/pyproject.tomlindex 81d4d197..31ac1337 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"# CLI entry points (those moved to `package.json` `bin`).[project]name = "open-second-brain"-version = "1.3.1"+version = "1.4.0"description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."readme = "README.md"requires-python = ">=3.11"diff --git a/src/cli/install/init-interactive.ts b/src/cli/install/init-interactive.tsindex a028f682..ac7890ed 100644--- a/src/cli/install/init-interactive.ts+++ b/src/cli/install/init-interactive.ts@@ -19,6 +19,7 @@ import "../../core/install/adapters/copilot-cli.ts";import "../../core/install/adapters/cursor.ts";import "../../core/install/adapters/gemini-cli.ts";import "../../core/install/adapters/generic.ts";+import "../../core/install/adapters/grok.ts";import "../../core/install/adapters/kiro.ts";import "../../core/install/adapters/opencode.ts";import "../../core/install/adapters/pi.ts";diff --git a/src/cli/install/install.ts b/src/cli/install/install.tsindex ecbfd460..9c2500b5 100644--- a/src/cli/install/install.ts+++ b/src/cli/install/install.ts@@ -31,6 +31,7 @@ import "../../core/install/adapters/copilot-cli.ts";import "../../core/install/adapters/cursor.ts";import "../../core/install/adapters/gemini-cli.ts";import "../../core/install/adapters/generic.ts";+import "../../core/install/adapters/grok.ts";import "../../core/install/adapters/kiro.ts";import "../../core/install/adapters/opencode.ts";import "../../core/install/adapters/pi.ts";diff --git a/src/cli/install/uninstall-target.ts b/src/cli/install/uninstall-target.tsindex 3a744b84..e4616586 100644--- a/src/cli/install/uninstall-target.ts+++ b/src/cli/install/uninstall-target.ts@@ -18,6 +18,7 @@ import "../../core/install/adapters/copilot-cli.ts";import "../../core/install/adapters/cursor.ts";import "../../core/install/adapters/gemini-cli.ts";import "../../core/install/adapters/generic.ts";+import "../../core/install/adapters/grok.ts";import "../../core/install/adapters/kiro.ts";import "../../core/install/adapters/opencode.ts";import "../../core/install/adapters/pi.ts";diff --git a/src/cli/update.ts b/src/cli/update.tsindex 992d1f4b..d4f8d88f 100644--- a/src/cli/update.ts+++ b/src/cli/update.ts@@ -19,6 +19,7 @@ import "../core/install/adapters/copilot-cli.ts";import "../core/install/adapters/cursor.ts";import "../core/install/adapters/gemini-cli.ts";import "../core/install/adapters/generic.ts";+import "../core/install/adapters/grok.ts";import "../core/install/adapters/kiro.ts";import "../core/install/adapters/opencode.ts";import "../core/install/adapters/pi.ts";diff --git a/src/core/agent-identity.ts b/src/core/agent-identity.tsindex 11a80330..20fc307f 100644--- a/src/core/agent-identity.ts+++ b/src/core/agent-identity.ts@@ -53,3 +53,41 @@ export function normalizeAgentArgument(value: string | null | undefined): stringif (PLACEHOLDER_AGENT_VALUES.has(canonical)) return null;return cleaned;}++/**+ * The operator identity template every device follows: `<vendor>-<host>-agent`+ * (e.g. `claude-vps-agent`, `hermes-mac-agent`). Capture group 1 is the host+ * segment, which may itself contain hyphens (`vps-prod`).+ */+const HOST_QUALIFIED_NAME_RE = /^[^-]+-(.+)-agent$/;++/**+ * Derive a runtime's own host-qualified Brain identity from the operator's+ * configured agent name.+ *+ * In a shared multi-device vault (the same Brain synced across, say, a VPS, a+ * dev box, and a Mac) the identity must encode BOTH which runtime wrote an+ * event AND on which device. The operator already names each device with the+ * `<vendor>-<host>-agent` template; a runtime keeps that host segment and+ * substitutes its OWN vendor token (the `runtimeId` argument), so e.g.+ * `claude-vps-agent` becomes `grok-vps-agent` for the grok runtime.+ *+ * This names no other runtime: `runtimeId` is always the caller's own id, and+ * the source vendor token is discarded rather than enumerated. Idempotent when+ * the operator name already carries this runtime's vendor.+ *+ * Names that do not fit the template (no `-agent` suffix, or no host segment)+ * cannot yield a host, so the whole name is prefixed with `<runtimeId>-` to+ * stay unambiguously this runtime's. When no operator name is configured the+ * runtime falls back to its bare id - there is no host to qualify with.+ */+export function deriveRuntimeAgentName(+ runtimeId: string,+ operatorName: string | null | undefined,+): string {+ const base = (operatorName ?? "").trim();+ if (base.length === 0) return runtimeId;+ const match = HOST_QUALIFIED_NAME_RE.exec(base);+ if (match) return `${runtimeId}-${match[1]}-agent`;+ return `${runtimeId}-${base}`;+}diff --git a/src/core/brain/sessions/grok.ts b/src/core/brain/sessions/grok.tsnew file mode 100644index 00000000..2ba91976--- /dev/null+++ b/src/core/brain/sessions/grok.ts@@ -0,0 +1,179 @@+/**+ * Grok Build session adapter.+ *+ * Grok persists each session under+ * `${GROK_HOME:-~/.grok}/sessions/<url-encoded-cwd>/<session-id>/updates.jsonl`+ * as a newline-delimited ACP session-update stream. Every line is+ *+ * {"timestamp": <unix-seconds>, "method": "session/update",+ * "params": {"sessionId": "...", "update": {"sessionUpdate": "<kind>", ...}}}+ *+ * (shapes captured from live grok 0.2.45). The kinds this adapter maps:+ * - `user_message_chunk` / `agent_message_chunk`: `update.content.text` is a+ * fragment of a streamed message. Consecutive chunks of the same role are+ * coalesced into one turn so a message - and any `@osb` marker inside it -+ * is never split across turns.+ * - `tool_call`: `update.title` is the tool name (e.g.+ * `open-second-brain__brain_note`), `update.rawInput` the input,+ * `update.toolCallId` the id. (`tool_call_update` carries only progress /+ * output for the same id, so it is skipped.)+ * Other kinds (`available_commands_update`, `agent_thought_chunk`,+ * `tool_call_update`, `plan`, ...) are skipped: the ACP stream is an evolving+ * protocol, so an unrecognized update kind is ignored rather than failing the+ * import. The structural gate is the first line - it must be a grok+ * `session/update`, or the import throws PARSE.+ */++import { readFileSync } from "node:fs";+import { basename, dirname } from "node:path";++import { SessionImportError } from "./types.ts";+import type { SessionAdapter, SessionTurn } from "./types.ts";++interface GrokUpdate {+ readonly sessionId: string | null;+ readonly kind: string;+ readonly raw: Record<string, unknown>;+ /** ISO-8601 derived from the line's unix-seconds `timestamp`. */+ readonly timestamp: string;+}++function asRecord(value: unknown): Record<string, unknown> | null {+ if (value === null || typeof value !== "object" || Array.isArray(value)) return null;+ return value as Record<string, unknown>;+}++function isoFrom(ts: unknown): string {+ if (typeof ts === "number" && Number.isFinite(ts)) {+ return new Date(ts * 1000).toISOString();+ }+ return new Date(0).toISOString();+}++/** Parse one line into its `session/update` payload, or null if it is not one. */+function parseUpdateLine(line: string): GrokUpdate | null {+ let obj: unknown;+ try {+ obj = JSON.parse(line);+ } catch {+ return null;+ }+ const o = asRecord(obj);+ if (!o || o["method"] !== "session/update") return null;+ const params = asRecord(o["params"]);+ if (!params) return null;+ const update = asRecord(params["update"]);+ if (!update || typeof update["sessionUpdate"] !== "string") return null;+ return {+ sessionId: typeof params["sessionId"] === "string" ? params["sessionId"] : null,+ kind: update["sessionUpdate"],+ raw: update,+ timestamp: isoFrom(o["timestamp"]),+ };+}++function chunkText(update: Record<string, unknown>): string {+ const content = asRecord(update["content"]);+ return content && typeof content["text"] === "string" ? content["text"] : "";+}++/**+ * Grok namespaces MCP tools as `<server>__<tool>` (e.g.+ * `open-second-brain__brain_feedback`); built-in tools (`search_replace`,+ * `run_terminal_command`) carry no `__`. Strip the namespace to the bare tool+ * name so the import's exact-match replay (`name === "brain_feedback"`) fires,+ * matching what every other adapter yields. Built-in names pass through.+ */+function bareToolName(title: string): string {+ const sep = title.lastIndexOf("__");+ return sep === -1 ? title : title.slice(sep + 2);+}++const ROLE_BY_KIND: Readonly<Record<string, "user" | "assistant">> = {+ user_message_chunk: "user",+ agent_message_chunk: "assistant",+};++export const grokAdapter: SessionAdapter = {+ id: "grok",+ defaultAgent: "grok",++ detect(firstLine: string): boolean {+ return parseUpdateLine(firstLine) !== null;+ },++ async *iterate(path: string): AsyncIterable<SessionTurn> {+ const lines = readFileSync(path, "utf8").split("\n");+ const firstNonEmpty = lines.find((l) => l.trim() !== "");+ if (firstNonEmpty === undefined || parseUpdateLine(firstNonEmpty.trim()) === null) {+ throw new SessionImportError(+ "PARSE",+ "grok session: first line is not an ACP session/update; not a grok updates.jsonl stream",+ );+ }++ const sessionId = parseUpdateLine(firstNonEmpty.trim())?.sessionId ?? basename(dirname(path));+ let seq = 0;+ const nextId = (): string => `${sessionId}:${seq++}`;++ // Buffered coalescing of consecutive same-role message chunks.+ let buf: { role: "user" | "assistant"; parts: string[]; timestamp: string } | null = null;+ const flush = (): SessionTurn | null => {+ if (buf === null) return null;+ const turn: SessionTurn = {+ turnId: nextId(),+ timestamp: buf.timestamp,+ role: buf.role,+ text: buf.parts.join(""),+ };+ buf = null;+ return turn;+ };++ for (const rawLine of lines) {+ const trimmed = rawLine.trim();+ if (trimmed === "") continue;+ const parsed = parseUpdateLine(trimmed);+ if (parsed === null) continue;+ const timestamp = parsed.timestamp;++ const role = ROLE_BY_KIND[parsed.kind];+ if (role !== undefined) {+ const text = chunkText(parsed.raw);+ if (buf !== null && buf.role === role) {+ buf.parts.push(text);+ } else {+ const pending = flush();+ if (pending !== null) yield pending;+ buf = { role, parts: [text], timestamp };+ }+ continue;+ }++ // Any non-message update is a turn boundary: flush the buffered message.+ const pending = flush();+ if (pending !== null) yield pending;++ if (parsed.kind === "tool_call") {+ const title = parsed.raw["title"];+ if (typeof title === "string" && title.length > 0) {+ const input = asRecord(parsed.raw["rawInput"]) ?? {};+ const id = parsed.raw["toolCallId"];+ yield {+ turnId: nextId(),+ timestamp,+ role: "assistant",+ toolCalls: [+ { name: bareToolName(title), input, ...(typeof id === "string" ? { id } : {}) },+ ],+ };+ }+ }+ // Every other kind (available_commands_update, agent_thought_chunk,+ // tool_call_update, plan, ...) is intentionally skipped.+ }++ const tail = flush();+ if (tail !== null) yield tail;+ },+};diff --git a/src/core/brain/sessions/registry.ts b/src/core/brain/sessions/registry.tsindex 8feffd53..eeb318d3 100644--- a/src/core/brain/sessions/registry.ts+++ b/src/core/brain/sessions/registry.ts@@ -11,6 +11,7 @@import { claudeAdapter } from "./claude.ts";import { codexAdapter } from "./codex.ts";+import { grokAdapter } from "./grok.ts";import { hermesAdapter } from "./hermes.ts";import { opencodeAdapter } from "./opencode.ts";import type { SessionAdapter, SessionAdapterId } from "./types.ts";@@ -20,6 +21,7 @@ export const SESSION_ADAPTERS: ReadonlyArray<SessionAdapter> = Object.freeze([codexAdapter,hermesAdapter,opencodeAdapter,+ grokAdapter,]);export function isSessionAdapterId(value: string): value is SessionAdapterId {diff --git a/src/core/brain/sessions/types.ts b/src/core/brain/sessions/types.tsindex 92ebe155..e016b862 100644--- a/src/core/brain/sessions/types.ts+++ b/src/core/brain/sessions/types.ts@@ -14,7 +14,7 @@* entry — no other code path needs to change.*/-export type SessionAdapterId = "claude" | "codex" | "hermes" | "opencode";+export type SessionAdapterId = "claude" | "codex" | "hermes" | "opencode" | "grok";export interface SessionToolCall {/** Tool name as emitted by the runtime, e.g. `brain_feedback`. */diff --git a/src/core/install/adapters/_json-mcp.ts b/src/core/install/adapters/_json-mcp.tsindex 62143bf8..bb2178c3 100644--- a/src/core/install/adapters/_json-mcp.ts+++ b/src/core/install/adapters/_json-mcp.ts@@ -14,6 +14,7 @@ import { existsSync, mkdirSync, readFileSync, statSync } from "node:fs";import { dirname } from "node:path";import { atomicWriteFileSync } from "../../fs-atomic.ts";+import { payloadWithRuntimeIdentity } from "../identity.ts";import { mergeMcpServers, removeMcpServers, OSB_KEY_FULL, OSB_KEY_WRITER } from "../json-merge.ts";import { recordEntry, readManifest, removeEntry } from "../manifest.ts";import { deepJsonEquals, expectedPayloadFromEnv, payloadKeyEquals } from "../payload-equals.ts";@@ -68,6 +69,18 @@ export interface JsonMcpAdapterSpec {probeMcp?(env: InstallEnv): boolean | null;/** Fix-hint text for `verify` when drift detected. */readonly fixHintForDrift?: string;+ /**+ * When set, stamp this runtime's own id (`target`) as `VAULT_AGENT_NAME` so+ * its Brain writes attribute to itself rather than inheriting the shared+ * operator name. Opt-in: only real runtime integrations set it; the generic+ * "other MCP host" adapters leave the operator name untouched.+ */+ readonly runtimeIdentity?: boolean;+}++/** Apply the runtime-identity rule to the payload when the spec opted in. */+function identifyPayload(spec: JsonMcpAdapterSpec, payload: McpPayload): McpPayload {+ return spec.runtimeIdentity ? payloadWithRuntimeIdentity(payload, spec.target) : payload;}function readFileOrEmpty(path: string): string {@@ -257,8 +270,14 @@ export function createJsonMcpAdapter(spec: JsonMcpAdapterSpec): InstallAdapter {};},- apply(_plan: InstallPlan, payload: McpPayload, env: InstallEnv, opts: ApplyOpts): ApplyResult {+ apply(+ _plan: InstallPlan,+ rawPayload: McpPayload,+ env: InstallEnv,+ opts: ApplyOpts,+ ): ApplyResult {const path = spec.resolveConfigPath(env);+ const payload = identifyPayload(spec, rawPayload);const onDisk = readOnDisk(spec, env, payload);const manifestEntry = readManifest(env.vault).installs[spec.target];@@ -407,7 +426,7 @@ export function createJsonMcpAdapter(spec: JsonMcpAdapterSpec): InstallAdapter {fix_hint: spec.fixHintForDrift ?? `o2b install --target ${spec.target} --apply`,};}- const expected = expectedPayloadFromEnv(env);+ const expected = identifyPayload(spec, expectedPayloadFromEnv(env));const equals = resolveEntryEquals(spec);if (!equals(block[OSB_KEY_FULL] as Record<string, unknown> | undefined, expected.full) ||diff --git a/src/core/install/adapters/grok.ts b/src/core/install/adapters/grok.tsnew file mode 100644index 00000000..29975189--- /dev/null+++ b/src/core/install/adapters/grok.ts@@ -0,0 +1,204 @@+/**+ * grok adapter - native MCP + hooks registration for Grok Build.+ *+ * Verified against live grok 0.2.45 (debug log of a real session): grok loads+ * MCP from `~/.grok/config.toml` `[mcp_servers.*]` (its primary, highest-+ * priority source) and hooks from `~/.grok/hooks/*.json` (its native,+ * always-trusted dir), spawning each with a restricted PATH. A bundled plugin+ * was tried first but does NOT work: its `.mcp.json` is lower priority and a+ * bare `o2b` command is not on grok's session-spawn PATH (ENOENT, zero tools),+ * and plugin-provided hooks are not discovered in-session. So this adapter:+ *+ * - writes the two Open Second Brain servers into `~/.grok/config.toml`+ * with an absolute command (`bun run <repo>/src/cli/main.ts mcp …`);+ * - writes the lifecycle hooks into `~/.grok/hooks/open-second-brain.json`+ * with absolute bun commands.+ *+ * Both are grok-native sources (not Claude-compat). `GROK_HOME` overrides the+ * `~/.grok` base dir.+ */++import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";+import { dirname, join } from "node:path";++import { atomicWriteFileSync } from "../../fs-atomic.ts";+import { GROK_HOOKS_FILENAME, grokHooksJson, grokMcpServers } from "../grok-asset.ts";+import { hasMcpServers, removeMcpServers, upsertMcpServers } from "../grok-config.ts";+import { OSB_KEY_FULL, OSB_KEY_WRITER } from "../json-merge.ts";+import { readManifest, recordEntry, removeEntry } from "../manifest.ts";+import { expectedPayloadFromEnv } from "../payload-equals.ts";+import { defaultRegistry } from "../registry.ts";+import type {+ ApplyOpts,+ ApplyResult,+ DetectResult,+ InstallEnv,+ InstallPlan,+ ManifestEntry,+ McpPayload,+ UninstallResult,+ VerifyResult,+} from "../types.ts";++const TARGET = "grok";+const LABEL = "Grok Build";+const FIX_HINT = "o2b install --target grok --apply";+const SERVER_NAMES = [OSB_KEY_FULL, OSB_KEY_WRITER] as const;++function grokHome(env: InstallEnv): string {+ const override = env.env["GROK_HOME"];+ return override && override.length > 0 ? override : join(env.home, ".grok");+}++function configPath(env: InstallEnv): string {+ return join(grokHome(env), "config.toml");+}++function hooksPath(env: InstallEnv): string {+ return join(grokHome(env), "hooks", GROK_HOOKS_FILENAME);+}++function readFileOrEmpty(path: string): string {+ try {+ return readFileSync(path, "utf8");+ } catch {+ return "";+ }+}++interface DesiredState {+ readonly nextToml: string;+ readonly currentToml: string;+ readonly hooksContent: string;+ readonly currentHooks: string;+}++/** Compute the target config.toml + hooks content for the current env/payload. */+function desired(payload: McpPayload, env: InstallEnv): DesiredState {+ const currentToml = readFileOrEmpty(configPath(env));+ const currentHooks = readFileOrEmpty(hooksPath(env));+ return {+ currentToml,+ nextToml: upsertMcpServers(currentToml, grokMcpServers(payload)),+ hooksContent: grokHooksJson(payload),+ currentHooks,+ };+}++/** mcp = in sync when our tables are present verbatim; hooks = file matches. */+function syncState(env: InstallEnv): { mcpOk: boolean; hooksOk: boolean; anyPresent: boolean } {+ const toml = readFileOrEmpty(configPath(env));+ const hooks = readFileOrEmpty(hooksPath(env));+ const payload = expectedPayloadFromEnv(env);+ const mcpOk = hasMcpServers(toml, grokMcpServers(payload));+ const hooksOk = hooks === grokHooksJson(payload);+ const anyMcp = SERVER_NAMES.some((n) => toml.includes(`[mcp_servers.${n}]`));+ return { mcpOk, hooksOk, anyPresent: anyMcp || hooks.length > 0 };+}++export const grokAdapter = {+ target: TARGET,+ label: LABEL,++ detect(env: InstallEnv): DetectResult {+ const { mcpOk, hooksOk, anyPresent } = syncState(env);+ const status = !anyPresent ? "not-installed" : mcpOk && hooksOk ? "installed" : "drift";+ return { target: TARGET, status, configPath: configPath(env), notes: [] };+ },++ plan(payload: McpPayload, env: InstallEnv): InstallPlan {+ return {+ target: TARGET,+ steps: [+ {+ kind: "managed-block",+ path: configPath(env),+ preview: `register the open-second-brain MCP servers in ${configPath(env)} (absolute bun command)`,+ },+ {+ kind: "file-copy",+ path: hooksPath(env),+ preview: `write the lifecycle hooks to ${hooksPath(env)}`,+ },+ ],+ postNotes: [+ "grok loads the MCP servers and hooks on the next session start (or press r in the /mcps and /hooks modals).",+ ],+ };+ },++ apply(_plan: InstallPlan, payload: McpPayload, env: InstallEnv, opts: ApplyOpts): ApplyResult {+ const state = desired(payload, env);+ const entry: ManifestEntry = {+ target: TARGET,+ applied_at: env.now.toISOString(),+ operation: "managed-block",+ config_path: configPath(env),+ owned_keys: [...SERVER_NAMES],+ owned_paths: [hooksPath(env)],+ };+ if (opts.dryRun) {+ return { target: TARGET, manifest: entry, steps_executed: 0 };+ }++ let steps = 0;+ if (state.nextToml !== state.currentToml) {+ const cfg = configPath(env);+ if (!existsSync(dirname(cfg))) mkdirSync(dirname(cfg), { recursive: true });+ atomicWriteFileSync(cfg, state.nextToml);+ steps += 1;+ }+ if (state.hooksContent !== state.currentHooks) {+ const hp = hooksPath(env);+ if (!existsSync(dirname(hp))) mkdirSync(dirname(hp), { recursive: true });+ atomicWriteFileSync(hp, state.hooksContent);+ steps += 1;+ }+ recordEntry(env.vault, entry);+ return { target: TARGET, manifest: entry, steps_executed: steps };+ },++ verify(env: InstallEnv): VerifyResult {+ const installed = TARGET in readManifest(env.vault).installs;+ const { mcpOk, hooksOk, anyPresent } = syncState(env);+ if (!installed && !anyPresent) {+ return { target: TARGET, status: "not-installed", details: [], fix_hint: FIX_HINT };+ }+ const details: string[] = [];+ if (!mcpOk) details.push(`config.toml is missing or differs from the canonical MCP servers`);+ if (!hooksOk) details.push(`${hooksPath(env)} is missing or differs from the bundled hooks`);+ if (details.length > 0) {+ return { target: TARGET, status: "drift", details, fix_hint: FIX_HINT };+ }+ return { target: TARGET, status: "ok", details: [], fix_hint: null };+ },++ uninstall(env: InstallEnv, opts: ApplyOpts & { fromSnippet?: boolean }): UninstallResult {+ const removedKeys: string[] = [];+ const removedPaths: string[] = [];+ const skipped: Array<readonly [string, string]> = [];++ const cfg = configPath(env);+ const currentToml = readFileOrEmpty(cfg);+ if (SERVER_NAMES.some((n) => currentToml.includes(`[mcp_servers.${n}]`))) {+ const next = removeMcpServers(currentToml, [...SERVER_NAMES]).replace(/\s*$/, "") + "\n";+ if (!opts.dryRun) atomicWriteFileSync(cfg, next === "\n" ? "" : next);+ removedKeys.push(...SERVER_NAMES);+ }++ const hp = hooksPath(env);+ if (existsSync(hp)) {+ try {+ if (!opts.dryRun) rmSync(hp, { force: true });+ removedPaths.push(hp);+ } catch (e) {+ skipped.push([hp, `could not remove: ${(e as Error).message}`]);+ }+ }++ if (!opts.dryRun && skipped.length === 0) removeEntry(env.vault, TARGET);+ return { target: TARGET, removed_keys: removedKeys, removed_paths: removedPaths, skipped };+ },+};++defaultRegistry.register(grokAdapter);diff --git a/src/core/install/adapters/opencode.ts b/src/core/install/adapters/opencode.tsindex 864bbb08..7acc4186 100644--- a/src/core/install/adapters/opencode.ts+++ b/src/core/install/adapters/opencode.ts@@ -119,6 +119,7 @@ const base = createJsonMcpAdapter({topLevelKey: "mcp",resolveConfigPath: configPath,serializeEntry: serializeOpencodeEntry,+ runtimeIdentity: true,postNotes: ["Restart opencode to load the new MCP servers and the Open Second Brain plugin."],});diff --git a/src/core/install/grok-asset.ts b/src/core/install/grok-asset.tsnew file mode 100644index 00000000..92531318--- /dev/null+++ b/src/core/install/grok-asset.ts@@ -0,0 +1,123 @@+/**+ * 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 { payloadWithRuntimeIdentity, runtimeAgentNameFromPayload } from "./identity.ts";+import { OSB_KEY_FULL, OSB_KEY_WRITER } from "./json-merge.ts";+import type { GrokMcpEntry } from "./grok-config.ts";+import type { McpPayload } 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: {+ args: ReadonlyArray<string>;+ env?: Readonly<Record<string, string>>;+ }) => ({+ command: bunBin(),+ args: ["run", MAIN_TS, ...entry.args],+ 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.+ */+const HOOK_SPEC: ReadonlyArray<{ event: string; groups: ReadonlyArray<HookGroupSpec> }> = [+ { event: "SessionStart", groups: [{ hooks: ["active-inject", "session-capture"] }] },+ { event: "UserPromptSubmit", groups: [{ hooks: ["session-capture"] }] },+ {+ event: "PostToolUse",+ groups: [+ { matcher: "brain_feedback", hooks: ["session-capture"] },+ {+ matcher: "Write|Edit|MultiEdit|apply_patch|search_replace",+ hooks: ["post-write-reminder"],+ },+ ],+ },+ { event: "Stop", groups: [{ hooks: ["session-capture", "stop-log-guardrail"] }] },+ { event: "SessionEnd", groups: [{ hooks: ["session-capture"] }] },+ { 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.+ */+export function grokHooksJson(payload: McpPayload): 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: 10,+ })),+ }));+ }+ return JSON.stringify({ hooks }, null, 2) + "\n";+}diff --git a/src/core/install/grok-config.ts b/src/core/install/grok-config.tsnew file mode 100644index 00000000..4b7223be--- /dev/null+++ b/src/core/install/grok-config.ts@@ -0,0 +1,96 @@+/**+ * Minimal TOML editor for grok's `~/.grok/config.toml` `[mcp_servers.<name>]`+ * tables.+ *+ * `config.toml` is grok's PRIMARY, highest-priority MCP source: verified+ * against live grok 0.2.45 that a server declared here is spawned and+ * handshakes in a real session (the plugin `.mcp.json` source is lower+ * priority and a bare `o2b` command does not resolve on grok's session-spawn+ * PATH). So the grok install target writes the two Open Second Brain servers+ * here, with an absolute command.+ *+ * The project ships `dependencies = []`, so rather than pull in a TOML+ * library this edits by line-section: it only ever writes/removes the exact+ * `[mcp_servers.open-second-brain]` / `[mcp_servers.open-second-brain-writer]`+ * tables and leaves every other section (`[cli]`, `[marketplace]`,+ * `[[marketplace.sources]]`, foreign `[mcp_servers.*]`, ...) byte-for-byte+ * intact. It handles only the value shapes we emit: a string `command`, a+ * string-array `args`, and an optional inline-table `env`.+ */++export interface GrokMcpEntry {+ readonly command: string;+ readonly args: ReadonlyArray<string>;+ readonly env?: Readonly<Record<string, string>>;+}++/** TOML basic-string: wrap in double quotes, escaping backslash then quote. */+function tomlString(value: string): string {+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;+}++function tableHeader(name: string): string {+ return `[mcp_servers.${name}]`;+}++/** Render one `[mcp_servers.<name>]` table (no leading/trailing blank lines). */+export function serializeMcpServerTable(name: string, entry: GrokMcpEntry): string {+ const lines = [tableHeader(name), `command = ${tomlString(entry.command)}`];+ lines.push(`args = [${entry.args.map(tomlString).join(", ")}]`);+ if (entry.env && Object.keys(entry.env).length > 0) {+ const inner = Object.entries(entry.env)+ .map(([k, v]) => `${k} = ${tomlString(v)}`)+ .join(", ");+ lines.push(`env = { ${inner} }`);+ }+ return lines.join("\n") + "\n";+}++/**+ * Remove the named `[mcp_servers.<name>]` sections: a section runs from its+ * header line to the line before the next table/array-of-table header (a line+ * starting with `[`) or end of file. Other sections are preserved verbatim.+ */+export function removeMcpServers(toml: string, names: ReadonlyArray<string>): string {+ const targets = new Set(names.map(tableHeader));+ const out: string[] = [];+ let skipping = false;+ for (const line of toml.split("\n")) {+ if (/^\s*\[/.test(line)) {+ skipping = targets.has(line.trim());+ if (skipping) continue;+ }+ if (skipping) continue;+ out.push(line);+ }+ return out.join("\n");+}++/**+ * Ensure the config text declares exactly the given servers: drop any existing+ * copies of our tables, then append fresh ones. Idempotent - re-running with+ * the same entries returns byte-identical text.+ */+export function upsertMcpServers(+ toml: string,+ entries: Readonly<Record<string, GrokMcpEntry>>,+): string {+ const base = removeMcpServers(toml, Object.keys(entries)).replace(/\s*$/, "");+ const tables = Object.entries(entries)+ .map(([name, entry]) => serializeMcpServerTable(name, entry).trimEnd())+ .join("\n\n");+ return (base.length > 0 ? `${base}\n\n` : "") + tables + "\n";+}++/**+ * True when every expected server table is present verbatim. Drift (an edited+ * command, a removed table, a reformat) yields false so `verify` reports it.+ */+export function hasMcpServers(+ toml: string,+ entries: Readonly<Record<string, GrokMcpEntry>>,+): boolean {+ return Object.entries(entries).every(([name, entry]) =>+ toml.includes(serializeMcpServerTable(name, entry).trimEnd()),+ );+}diff --git a/src/core/install/identity.ts b/src/core/install/identity.tsnew file mode 100644index 00000000..85c36e3e--- /dev/null+++ b/src/core/install/identity.ts@@ -0,0 +1,52 @@+/**+ * Per-runtime Brain identity.+ *+ * Rule: a runtime attributes its Brain writes to ITS OWN, host-qualified name -+ * the runtime's vendor token (the same id it uses as its session-import+ * `defaultAgent` and its install `target`: `opencode`, `grok`, ...) combined+ * with the host segment of the operator's configured `agent_name`. So on a box+ * whose operator name is `claude-vps-agent`, opencode logs as `opencode-vps-agent`+ * and grok as `grok-vps-agent`. See {@link deriveRuntimeAgentName} for the+ * derivation; it names no other runtime and discards the source vendor token.+ *+ * Without this, every runtime that registers the MCP servers would write under+ * the single operator `agent_name` from the shared config, so e.g. opencode+ * would log under whatever that name is (commonly a Claude one) and be+ * indistinguishable - one agent masquerading as another. Host-qualifying the+ * runtime's own id additionally keeps a shared multi-device vault able to tell+ * the same runtime apart across machines.+ *+ * The operator name is read from the payload's own `VAULT_AGENT_NAME` (which+ * `buildPayload` populates from the resolved config), so `apply` and `verify`+ * derive the identical value from the identical input - the install stays+ * idempotent and `--check` reports no drift after an apply.+ */++import { deriveRuntimeAgentName } from "../agent-identity.ts";+import type { McpPayload, McpServerEntry } from "./types.ts";++function withIdentity(entry: McpServerEntry, runtimeId: string): McpServerEntry {+ const name = deriveRuntimeAgentName(runtimeId, entry.env?.["VAULT_AGENT_NAME"]);+ return { ...entry, env: { ...entry.env, VAULT_AGENT_NAME: name } };+}++/**+ * Return a copy of the payload whose `VAULT_AGENT_NAME` is the runtime's own+ * host-qualified id, preserving the other env keys (timezone, ...).+ */+export function payloadWithRuntimeIdentity(payload: McpPayload, runtimeId: string): McpPayload {+ return {+ full: withIdentity(payload.full, runtimeId),+ writer: withIdentity(payload.writer, runtimeId),+ };+}++/**+ * The single host-qualified identity a runtime stamps everywhere (MCP env and,+ * for grok, the hooks env), derived from the payload's operator name. Callers+ * that write more than one artifact (grok writes both config.toml and a hooks+ * file) use this so every artifact agrees on one name.+ */+export function runtimeAgentNameFromPayload(payload: McpPayload, runtimeId: string): string {+ return deriveRuntimeAgentName(runtimeId, payload.full.env?.["VAULT_AGENT_NAME"]);+}diff --git a/src/openclaw/index.ts b/src/openclaw/index.tsindex 8b065a03..e2cd0f7e 100644--- a/src/openclaw/index.ts+++ b/src/openclaw/index.ts@@ -16,7 +16,7 @@ import { discoverConfig, redactMapping, resolveAgentName } from "../core/config.import { doctor } from "../core/doctor.ts";import { buildReminder } from "../core/identity-reminder.ts";import { listVaultPages } from "../core/vault.ts";-import { normalizeAgentArgument } from "../core/agent-identity.ts";+import { deriveRuntimeAgentName, normalizeAgentArgument } from "../core/agent-identity.ts";import { vaultRelative as vaultRelativePath } from "../core/path-safety.ts";interface PluginConfig {@@ -45,11 +45,15 @@ export default definePluginEntry({// stops paying attention to it as the conversation grows.api.on("before_prompt_build", () => {const cfg = (api.pluginConfig ?? {}) as PluginConfig;- const agent =+ const operator =normalizeAgentArgument(cfg.agentName ?? null) ??process.env["VAULT_AGENT_NAME"] ??resolveAgentName();- if (agent === "agent") return undefined;+ if (operator === "agent") return undefined;+ // OpenClaw writes under its OWN host-qualified identity (vendor `openclaw`+ // + the operator's host), not the operator's name - so its Brain activity+ // is distinguishable per runtime and per device, matching grok/opencode.+ const agent = deriveRuntimeAgentName("openclaw", operator);return { prependContext: buildReminder(agent, "openclaw") };});diff --git a/tests/core/agent-identity.test.ts b/tests/core/agent-identity.test.tsnew file mode 100644index 00000000..259b8f34--- /dev/null+++ b/tests/core/agent-identity.test.ts@@ -0,0 +1,62 @@+import { describe, expect, test } from "bun:test";++import { deriveRuntimeAgentName, normalizeAgentArgument } from "../../src/core/agent-identity.ts";++describe("deriveRuntimeAgentName", () => {+ test("keeps the host segment and substitutes the runtime's own vendor token", () => {+ expect(deriveRuntimeAgentName("grok", "claude-dev-agent")).toBe("grok-dev-agent");+ expect(deriveRuntimeAgentName("grok", "hermes-vps-agent")).toBe("grok-vps-agent");+ expect(deriveRuntimeAgentName("opencode", "claude-mac-agent")).toBe("opencode-mac-agent");+ expect(deriveRuntimeAgentName("codex", "claude-vps-agent")).toBe("codex-vps-agent");+ });++ test("preserves a multi-segment host", () => {+ expect(deriveRuntimeAgentName("grok", "claude-vps-prod-agent")).toBe("grok-vps-prod-agent");+ });++ test("is idempotent when the operator name already uses the runtime's vendor", () => {+ expect(deriveRuntimeAgentName("grok", "grok-dev-agent")).toBe("grok-dev-agent");+ });++ test("prefixes names that do not fit the <vendor>-<host>-agent template", () => {+ // No `-agent` suffix, or no host segment: cannot extract a host, so the+ // whole name is prefixed with the runtime id to stay unambiguous.+ expect(deriveRuntimeAgentName("grok", "mybrain")).toBe("grok-mybrain");+ expect(deriveRuntimeAgentName("grok", "claude-vps")).toBe("grok-claude-vps");+ expect(deriveRuntimeAgentName("grok", "agent")).toBe("grok-agent");+ });++ test("falls back to the bare runtime id when no operator name is configured", () => {+ expect(deriveRuntimeAgentName("grok", null)).toBe("grok");+ expect(deriveRuntimeAgentName("grok", undefined)).toBe("grok");+ expect(deriveRuntimeAgentName("grok", "")).toBe("grok");+ expect(deriveRuntimeAgentName("grok", " ")).toBe("grok");+ });++ test("trims surrounding whitespace before deriving", () => {+ expect(deriveRuntimeAgentName("grok", " claude-dev-agent ")).toBe("grok-dev-agent");+ });++ test("names no other runtime: the vendor token is always the caller's own id", () => {+ // Whatever vendor the operator name carries, the result vendor is the+ // runtimeId argument - the function never echoes the source vendor.+ for (const operator of ["claude-dev-agent", "hermes-dev-agent", "codex-dev-agent"]) {+ expect(deriveRuntimeAgentName("grok", operator)).toBe("grok-dev-agent");+ }+ });+});++describe("normalizeAgentArgument", () => {+ test("strips a leading @ and trims", () => {+ expect(normalizeAgentArgument("@claude-dev-agent")).toBe("claude-dev-agent");+ expect(normalizeAgentArgument(" grok-vps-agent ")).toBe("grok-vps-agent");+ });++ test("returns null for empty and placeholder values", () => {+ expect(normalizeAgentArgument(null)).toBeNull();+ expect(normalizeAgentArgument("")).toBeNull();+ expect(normalizeAgentArgument("agent")).toBeNull();+ expect(normalizeAgentArgument("claude")).toBeNull();+ expect(normalizeAgentArgument("claude_code")).toBeNull();+ });+});diff --git a/tests/core/brain.sessions.grok.test.ts b/tests/core/brain.sessions.grok.test.tsnew file mode 100644index 00000000..0067aeb4--- /dev/null+++ b/tests/core/brain.sessions.grok.test.ts@@ -0,0 +1,102 @@+/**+ * Grok Build session adapter.+ *+ * Grok stores each session under+ * `~/.grok/sessions/<encoded-cwd>/<id>/updates.jsonl` as a newline-delimited+ * ACP session-update stream: every line is+ * `{timestamp, method:"session/update", params:{sessionId, update:{sessionUpdate, ...}}}`.+ * The adapter normalizes the relevant update kinds into `SessionTurn`s -+ * `user_message_chunk` / `agent_message_chunk` (coalescing consecutive+ * same-role chunks so a streamed message, and any `@osb` marker in it, stays+ * intact) and `tool_call` (the `title` is the tool name, `rawInput` the input).+ * Noise kinds (`available_commands_update`, `agent_thought_chunk`,+ * `tool_call_update`) are skipped. Shapes captured from live grok 0.2.45.+ */++import { describe, expect, test } from "bun:test";+import { join } from "node:path";++import { grokAdapter } from "../../src/core/brain/sessions/grok.ts";+import { SessionImportError } from "../../src/core/brain/sessions/types.ts";+import type { SessionTurn } from "../../src/core/brain/sessions/types.ts";++const FIXTURE = join(import.meta.dir, "..", "fixtures", "sessions", "grok-minimal.jsonl");++const AVAILABLE_COMMANDS_LINE = JSON.stringify({+ timestamp: 1781213002,+ method: "session/update",+ params: { sessionId: "s1", update: { sessionUpdate: "available_commands_update" } },+});++async function collect(path: string): Promise<SessionTurn[]> {+ const turns: SessionTurn[] = [];+ for await (const t of grokAdapter.iterate(path)) turns.push(t);+ return turns;+}++describe("grok session adapter - detect", () => {+ test("matches a grok ACP session/update first line", () => {+ expect(grokAdapter.detect(AVAILABLE_COMMANDS_LINE)).toBe(true);+ });++ test("rejects other runtimes and garbage", () => {+ expect(grokAdapter.detect(JSON.stringify({ type: "session_meta", originator: "x" }))).toBe(+ false,+ );+ expect(grokAdapter.detect(JSON.stringify({ method: "session/update" }))).toBe(false);+ expect(grokAdapter.detect("not json")).toBe(false);+ expect(grokAdapter.detect("")).toBe(false);+ });+});++describe("grok session adapter - iterate", () => {+ test("normalizes the ACP stream into ordered turns", async () => {+ const turns = await collect(FIXTURE);+ expect(turns.map((t) => t.role)).toEqual(["user", "assistant", "assistant", "assistant"]);+ expect(turns[0]!.text).toBe("Remember to prefer tabs over spaces.");+ // Consecutive agent_message_chunk lines coalesce into one turn.+ expect(turns[1]!.text).toBe("I'll record that.");+ expect(turns[3]!.text).toBe("Done.");+ });++ test("extracts the tool call with the MCP namespace stripped to the bare name", async () => {+ const turns = await collect(FIXTURE);+ const toolTurn = turns.find((t) => t.toolCalls && t.toolCalls.length > 0);+ // grok's `open-second-brain__brain_feedback` normalizes to the bare name+ // so the import's exact-match replay fires, as every other adapter yields.+ expect(toolTurn?.toolCalls?.[0]).toEqual({+ name: "brain_feedback",+ input: {+ topic: "indentation-style",+ signal: "positive",+ principle: "Prefer tabs over spaces.",+ },+ id: "call-abc-0",+ });+ });++ test("skips noise updates (available_commands, thought, tool_call_update)", async () => {+ const turns = await collect(FIXTURE);+ // 1 user + 2 agent message turns + 1 tool turn = 4; nothing from the+ // three noise kinds in the fixture.+ expect(turns.length).toBe(4);+ for (const t of turns) {+ expect(t.text ?? "").not.toContain("durable preference"); // the thought chunk+ }+ });++ test("every turn carries a stable id and an ISO timestamp", async () => {+ const turns = await collect(FIXTURE);+ for (const t of turns) {+ expect(t.turnId.length).toBeGreaterThan(0);+ expect(t.timestamp).toMatch(/^\d{4}-\d{2}-\d{2}T/);+ }+ // ids are unique within the file+ expect(new Set(turns.map((t) => t.turnId)).size).toBe(turns.length);+ });++ test("throws PARSE when the first line is not a grok session/update", async () => {+ const bad = join(import.meta.dir, "..", "fixtures", "sessions", "opencode-minimal.jsonl");+ await expect(collect(bad)).rejects.toBeInstanceOf(SessionImportError);+ });+});diff --git a/tests/core/brain.sessions.registry.test.ts b/tests/core/brain.sessions.registry.test.tsindex f30c2b6c..d9f8d6ff 100644--- a/tests/core/brain.sessions.registry.test.ts+++ b/tests/core/brain.sessions.registry.test.ts@@ -20,6 +20,7 @@ const FIXTURES = {codex: resolve("tests/fixtures/sessions/codex-minimal.jsonl"),hermes: resolve("tests/fixtures/sessions/hermes-minimal.jsonl"),opencode: resolve("tests/fixtures/sessions/opencode-minimal.jsonl"),+ grok: resolve("tests/fixtures/sessions/grok-minimal.jsonl"),};function firstLine(path: string): string {@@ -27,17 +28,18 @@ function firstLine(path: string): string {}describe("registry — single source of adapters", () => {- test("exposes all four adapters", () => {+ test("exposes all five adapters", () => {const ids = SESSION_ADAPTERS.map((a) => a.id).toSorted();- expect(ids).toEqual(["claude", "codex", "hermes", "opencode"]);+ expect(ids).toEqual(["claude", "codex", "grok", "hermes", "opencode"]);});test("owns runtime validation and help choices", () => {- expect(sessionAdapterFormatChoices()).toBe("auto|claude|codex|hermes|opencode");+ expect(sessionAdapterFormatChoices()).toBe("auto|claude|codex|hermes|opencode|grok");expect(isSessionAdapterId("claude")).toBe(true);expect(isSessionAdapterId("codex")).toBe(true);expect(isSessionAdapterId("hermes")).toBe(true);expect(isSessionAdapterId("opencode")).toBe(true);+ expect(isSessionAdapterId("grok")).toBe(true);expect(isSessionAdapterId("copilot")).toBe(false);});@@ -48,6 +50,7 @@ describe("registry — single source of adapters", () => {codex: "codex",hermes: "hermes",opencode: "opencode",+ grok: "grok",});});@@ -56,6 +59,7 @@ describe("registry — single source of adapters", () => {expect(getAdapter("codex").id).toBe("codex");expect(getAdapter("hermes").id).toBe("hermes");expect(getAdapter("opencode").id).toBe("opencode");+ expect(getAdapter("grok").id).toBe("grok");});});@@ -72,6 +76,9 @@ describe("detectAdapter — autodetect across all three formats", () => {test("picks opencode on the opencode fixture", () => {expect(detectAdapter(firstLine(FIXTURES.opencode))?.id).toBe("opencode");});+ test("picks grok on the grok fixture", () => {+ expect(detectAdapter(firstLine(FIXTURES.grok))?.id).toBe("grok");+ });test("no adapter claims a foreign fixture (full cross-table)", () => {for (const [name, path] of Object.entries(FIXTURES)) {diff --git a/tests/core/install/adapters/grok.test.ts b/tests/core/install/adapters/grok.test.tsnew file mode 100644index 00000000..498394f4--- /dev/null+++ b/tests/core/install/adapters/grok.test.ts@@ -0,0 +1,215 @@+/**+ * grok adapter tests.+ *+ * The grok integration registers MCP into `~/.grok/config.toml`+ * `[mcp_servers.*]` (grok's primary source) with an absolute `bun run+ * <repo>/src/cli/main.ts mcp …` command, and lifecycle hooks into+ * `~/.grok/hooks/open-second-brain.json`. Verified against live grok 0.2.45+ * that this is the form grok actually spawns in a session (a bundled plugin+ * with a bare `o2b` command does not load). `GROK_HOME` overrides the base dir.+ */++import { describe, expect, test, beforeEach, afterEach } from "bun:test";+import { mkdtempSync, rmSync, readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { Writable } from "node:stream";++import { grokAdapter } from "../../../../src/core/install/adapters/grok.ts";+import { grokMcpServers, grokHooksJson } from "../../../../src/core/install/grok-asset.ts";+import { hasMcpServers } from "../../../../src/core/install/grok-config.ts";+import { buildPayload } from "../../../../src/core/install/payload.ts";+import { readManifest } from "../../../../src/core/install/manifest.ts";++let vault: string;+let home: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "osb-grok-v-"));+ home = mkdtempSync(join(tmpdir(), "osb-grok-h-"));+});+afterEach(() => {+ for (const d of [vault, home]) {+ try {+ rmSync(d, { recursive: true, force: true });+ } catch {}+ }+});++function env(extraEnv: Record<string, string> = {}) {+ return {+ vault,+ home,+ cwd: home,+ env: { VAULT_AGENT_NAME: "claude-dev-agent", VAULT_TIMEZONE: "UTC", ...extraEnv },+ now: new Date("2026-06-12T12:00:00.000Z"),+ };+}++function applyOpts() {+ const sink = new Writable({+ write(_c, _e, cb) {+ cb();+ },+ });+ return {+ dryRun: false,+ force: false,+ stdout: sink as unknown as NodeJS.WriteStream,+ stderr: sink as unknown as NodeJS.WriteStream,+ };+}++function payload() {+ return buildPayload({ vault, agent_name: "claude-dev-agent", timezone: "UTC" });+}++function grokDir(base = join(home, ".grok")) {+ return base;+}+function configPath(base = join(home, ".grok")) {+ return join(base, "config.toml");+}+function hooksPath(base = join(home, ".grok")) {+ return join(base, "hooks", "open-second-brain.json");+}++function apply(e = env()) {+ return grokAdapter.apply(grokAdapter.plan(payload(), e), payload(), e, applyOpts());+}++describe("grok adapter - config path", () => {+ test("default config is ~/.grok/config.toml", () => {+ expect(grokAdapter.detect(env()).configPath).toBe(configPath());+ });+ test("GROK_HOME override is honoured", () => {+ const gh = mkdtempSync(join(tmpdir(), "osb-grokhome-"));+ expect(grokAdapter.detect(env({ GROK_HOME: gh })).configPath).toBe(configPath(gh));+ try {+ rmSync(gh, { recursive: true, force: true });+ } catch {}+ });+});++describe("grok adapter - apply", () => {+ test("writes both MCP servers into config.toml with an absolute bun command", () => {+ apply();+ const toml = readFileSync(configPath(), "utf8");+ expect(hasMcpServers(toml, grokMcpServers(payload()))).toBe(true);+ expect(toml).toContain("[mcp_servers.open-second-brain]");+ expect(toml).toContain("[mcp_servers.open-second-brain-writer]");+ // absolute command (the running bun), the repo entry point, and the vault.+ expect(toml).toContain(process.execPath);+ expect(toml).toContain("src/cli/main.ts");+ expect(toml).toContain(vault);+ expect(toml).not.toContain('command = "o2b"'); // not the bare PATH form+ });++ test("attributes to a grok-specific identity, not the shared one", () => {+ apply();+ const toml = readFileSync(configPath(), "utf8");+ const hooks = readFileSync(hooksPath(), "utf8");+ expect(toml).toContain('VAULT_AGENT_NAME = "grok-dev-agent"');+ expect(toml).not.toContain('VAULT_AGENT_NAME = "claude-dev-agent"');+ expect(hooks).toContain('"VAULT_AGENT_NAME": "grok-dev-agent"');+ expect(hooks).not.toContain("claude-dev-agent");+ });++ test("writes the lifecycle hooks file verbatim", () => {+ apply();+ expect(readFileSync(hooksPath(), "utf8")).toBe(grokHooksJson(payload()));+ });++ test("manifest records the mcp keys and the hooks path", () => {+ apply();+ const entry = readManifest(vault).installs["grok"];+ expect(entry?.owned_keys).toEqual(["open-second-brain", "open-second-brain-writer"]);+ expect(entry?.owned_paths).toContain(hooksPath());+ });++ test("preserves pre-existing config.toml content", () => {+ mkdirSync(grokDir(), { recursive: true });+ writeFileSync(configPath(), '[cli]\ninstaller = "internal"\n');+ apply();+ const toml = readFileSync(configPath(), "utf8");+ expect(toml).toContain("[cli]");+ expect(toml).toContain('installer = "internal"');+ expect(toml).toContain("[mcp_servers.open-second-brain]");+ });++ test("idempotent re-apply executes no steps", () => {+ apply();+ expect(apply().steps_executed).toBe(0);+ });++ test("dry-run writes nothing", () => {+ grokAdapter.apply(grokAdapter.plan(payload(), env()), payload(), env(), {+ ...applyOpts(),+ dryRun: true,+ });+ expect(existsSync(configPath())).toBe(false);+ expect(existsSync(hooksPath())).toBe(false);+ });++ test("re-apply refreshes a tampered hooks file", () => {+ apply();+ writeFileSync(hooksPath(), "{}\n");+ apply();+ expect(readFileSync(hooksPath(), "utf8")).toBe(grokHooksJson(payload()));+ });+});++describe("grok adapter - lifecycle", () => {+ test("detect/verify report installed+ok after apply", () => {+ apply();+ expect(grokAdapter.detect(env()).status).toBe("installed");+ expect(grokAdapter.verify(env()).status).toBe("ok");+ });++ test("clean home is not-installed", () => {+ expect(grokAdapter.detect(env()).status).toBe("not-installed");+ expect(grokAdapter.verify(env()).status).toBe("not-installed");+ });++ test("verify reports drift when the MCP servers are edited", () => {+ apply();+ const toml = readFileSync(configPath(), "utf8").replace(vault, "/somewhere/else");+ writeFileSync(configPath(), toml);+ expect(grokAdapter.verify(env()).status).toBe("drift");+ });++ test("verify reports drift when the hooks file is missing", () => {+ apply();+ rmSync(hooksPath());+ expect(grokAdapter.verify(env()).status).toBe("drift");+ });++ test("uninstall removes our MCP tables and hooks, keeps foreign config, clears manifest", () => {+ mkdirSync(grokDir(), { recursive: true });+ writeFileSync(+ configPath(),+ '[cli]\ninstaller = "internal"\n\n[mcp_servers.other]\nurl = "x"\n',+ );+ apply();+ const r = grokAdapter.uninstall(env(), applyOpts());+ const toml = readFileSync(configPath(), "utf8");+ expect(toml).toContain("[mcp_servers.other]"); // foreign server kept+ expect(toml).toContain("[cli]");+ expect(toml).not.toContain("[mcp_servers.open-second-brain]");+ expect(existsSync(hooksPath())).toBe(false);+ expect(r.removed_keys).toContain("open-second-brain");+ expect(r.removed_paths).toContain(hooksPath());+ expect(readManifest(vault).installs["grok"]).toBeUndefined();+ });+});++describe("grok adapter - plan", () => {+ test("plan lists the config.toml managed-block and the hooks file-copy", () => {+ const plan = grokAdapter.plan(payload(), env());+ const kinds = plan.steps.map((s) => s.kind);+ expect(kinds).toContain("managed-block");+ expect(kinds).toContain("file-copy");+ expect(plan.steps.map((s) => s.path)).toContain(configPath());+ expect(plan.steps.map((s) => s.path)).toContain(hooksPath());+ });+});diff --git a/tests/core/install/adapters/opencode.test.ts b/tests/core/install/adapters/opencode.test.tsindex 06baddef..b4b110dd 100644--- a/tests/core/install/adapters/opencode.test.ts+++ b/tests/core/install/adapters/opencode.test.ts@@ -41,7 +41,7 @@ function env(extraEnv: Record<string, string> = {}) {vault,home,cwd: home,- env: { VAULT_AGENT_NAME: "a", VAULT_TIMEZONE: "UTC", ...extraEnv },+ env: { VAULT_AGENT_NAME: "claude-dev-agent", VAULT_TIMEZONE: "UTC", ...extraEnv },now: new Date("2026-06-10T12:00:00.000Z"),};}@@ -61,7 +61,7 @@ function applyOpts() {}function payload() {- return buildPayload({ vault, agent_name: "a", timezone: "UTC" });+ return buildPayload({ vault, agent_name: "claude-dev-agent", timezone: "UTC" });}function configPath() {@@ -101,7 +101,9 @@ describe("opencode adapter - apply", () => {expect(full).toEqual({type: "local",command: ["o2b", "mcp", "--vault", vault],- environment: { VAULT_AGENT_NAME: "a", VAULT_TIMEZONE: "UTC" },+ // opencode keeps the operator host ("dev") but swaps the vendor to its+ // own, rather than inheriting the operator name "claude-dev-agent".+ environment: { VAULT_AGENT_NAME: "opencode-dev-agent", VAULT_TIMEZONE: "UTC" },enabled: true,});const writer = parsed.mcp["open-second-brain-writer"];@@ -170,7 +172,7 @@ describe("opencode adapter - legacy mcp.json migration", () => {return {command: "o2b",args: writerOnly ? ["mcp", "--writer-only", "--vault", vault] : ["mcp", "--vault", vault],- env: { VAULT_AGENT_NAME: "a", VAULT_TIMEZONE: "UTC" },+ env: { VAULT_AGENT_NAME: "claude-dev-agent", VAULT_TIMEZONE: "UTC" },};}diff --git a/tests/core/install/grok-asset.test.ts b/tests/core/install/grok-asset.test.tsnew file mode 100644index 00000000..03ae5602--- /dev/null+++ b/tests/core/install/grok-asset.test.ts@@ -0,0 +1,65 @@+/**+ * grok install-artifact helpers: grok attributes its Brain writes to its OWN+ * host-qualified id (vendor `grok` + the operator host, e.g. `grok-dev-agent`)+ * in both the MCP env and the hooks file - it never inherits the operator's+ * vendor token, and both artifacts agree on one derived name.+ */++import { describe, expect, test } from "bun:test";++import { grokHooksJson, grokMcpServers } from "../../../src/core/install/grok-asset.ts";+import type { McpPayload } from "../../../src/core/install/types.ts";++const PAYLOAD: McpPayload = {+ full: {+ command: "o2b",+ args: ["mcp", "--vault", "/v"],+ env: { VAULT_AGENT_NAME: "claude-dev-agent", VAULT_TIMEZONE: "UTC" },+ },+ writer: {+ command: "o2b",+ args: ["mcp", "--writer-only", "--vault", "/v"],+ env: { VAULT_AGENT_NAME: "claude-dev-agent", VAULT_TIMEZONE: "UTC" },+ },+};++describe("grokMcpServers", () => {+ test("uses an absolute bun command and grok's own identity, keeping other env", () => {+ const servers = grokMcpServers(PAYLOAD);+ const full = servers["open-second-brain"]!;+ expect(full.command).toBe(process.execPath);+ expect(full.args).toEqual([+ "run",+ expect.stringContaining("src/cli/main.ts"),+ "mcp",+ "--vault",+ "/v",+ ]);+ // grok keeps the operator host ("dev") but swaps the vendor to its own.+ expect(full.env).toEqual({ VAULT_AGENT_NAME: "grok-dev-agent", VAULT_TIMEZONE: "UTC" });+ expect(servers["open-second-brain-writer"]!.env?.["VAULT_AGENT_NAME"]).toBe("grok-dev-agent");+ });++ test("falls back to the bare vendor id when no operator name is configured", () => {+ const servers = grokMcpServers({+ full: { command: "o2b", args: ["mcp", "--vault", "/v"] },+ writer: { command: "o2b", args: ["mcp", "--writer-only", "--vault", "/v"] },+ });+ expect(servers["open-second-brain"]!.env).toEqual({ VAULT_AGENT_NAME: "grok" });+ });+});++describe("grokHooksJson", () => {+ test("stamps grok's host-qualified id on every hook command's env", () => {+ const parsed = JSON.parse(grokHooksJson(PAYLOAD));+ const commands = Object.values(+ parsed.hooks as Record<string, Array<{ hooks: Array<{ env: Record<string, string> }> }>>,+ )+ .flat()+ .flatMap((g) => g.hooks);+ expect(commands.length).toBeGreaterThan(0);+ for (const h of commands) {+ expect(h.env["VAULT_AGENT_NAME"]).toBe("grok-dev-agent");+ }+ });+});diff --git a/tests/core/install/grok-config.test.ts b/tests/core/install/grok-config.test.tsnew file mode 100644index 00000000..db6d5fe7--- /dev/null+++ b/tests/core/install/grok-config.test.ts@@ -0,0 +1,122 @@+/**+ * Minimal TOML editor for grok's ~/.grok/config.toml [mcp_servers.<name>]+ * tables. The project ships `dependencies = []`, so this handles only the+ * exact shape the grok adapter writes (string command, string[] args, optional+ * inline-table env) and edits by line-section so unrelated config (other+ * [mcp_servers.*], [marketplace], [[marketplace.sources]], [cli]) survives.+ */++import { describe, expect, test } from "bun:test";++import {+ serializeMcpServerTable,+ upsertMcpServers,+ removeMcpServers,+ hasMcpServers,+} from "../../../src/core/install/grok-config.ts";++const ENTRIES = {+ "open-second-brain": {+ command: "/usr/local/bin/bun",+ args: ["run", "/srv/o2b/src/cli/main.ts", "mcp", "--vault", "/v"],+ env: { VAULT_AGENT_NAME: "a" },+ },+ "open-second-brain-writer": {+ command: "/usr/local/bin/bun",+ args: ["run", "/srv/o2b/src/cli/main.ts", "mcp", "--writer-only", "--vault", "/v"],+ },+};++const EXISTING = `[cli]+installer = "internal"++[marketplace]+official_marketplace_auto_installed = true++[[marketplace.sources]]+name = "xAI Official"+git = "https://github.com/xai-org/plugin-marketplace.git"++[mcp_servers.user-linear]+url = "https://mcp.linear.app/mcp"+enabled = true+`;++describe("serializeMcpServerTable", () => {+ test("emits a valid [mcp_servers.<name>] table with command, args, env", () => {+ const t = serializeMcpServerTable("open-second-brain", ENTRIES["open-second-brain"]);+ expect(t).toContain("[mcp_servers.open-second-brain]");+ expect(t).toContain('command = "/usr/local/bin/bun"');+ expect(t).toContain('args = ["run", "/srv/o2b/src/cli/main.ts", "mcp", "--vault", "/v"]');+ expect(t).toContain('env = { VAULT_AGENT_NAME = "a" }');+ });++ test("omits env when absent", () => {+ expect(serializeMcpServerTable("x", { command: "b", args: ["mcp"] })).not.toContain("env =");+ });++ test("escapes quotes and backslashes in strings", () => {+ const t = serializeMcpServerTable("x", { command: 'a"b\\c', args: [] });+ expect(t).toContain('command = "a\\"b\\\\c"');+ });+});++describe("upsertMcpServers", () => {+ test("adds both tables while preserving unrelated config", () => {+ const out = upsertMcpServers(EXISTING, ENTRIES);+ expect(out).toContain("[cli]");+ expect(out).toContain("[[marketplace.sources]]");+ expect(out).toContain("[mcp_servers.user-linear]"); // foreign mcp server untouched+ expect(out).toContain("[mcp_servers.open-second-brain]");+ expect(out).toContain("[mcp_servers.open-second-brain-writer]");+ expect(hasMcpServers(out, ENTRIES)).toBe(true);+ });++ test("is idempotent: re-upsert does not duplicate or drift", () => {+ const once = upsertMcpServers(EXISTING, ENTRIES);+ const twice = upsertMcpServers(once, ENTRIES);+ expect(twice).toBe(once);+ // exactly one header occurrence each+ expect(once.match(/\[mcp_servers\.open-second-brain\]/g)?.length).toBe(1);+ expect(once.match(/\[mcp_servers\.open-second-brain-writer\]/g)?.length).toBe(1);+ });++ test("replaces a stale entry (different command) in place of drift", () => {+ const stale = upsertMcpServers(EXISTING, {+ "open-second-brain": { command: "o2b", args: ["mcp"] },+ "open-second-brain-writer": { command: "o2b", args: ["mcp", "--writer-only"] },+ });+ expect(stale).toContain('command = "o2b"');+ const fixed = upsertMcpServers(stale, ENTRIES);+ expect(fixed).not.toContain('command = "o2b"\n');+ expect(fixed).toContain('command = "/usr/local/bin/bun"');+ expect(hasMcpServers(fixed, ENTRIES)).toBe(true);+ });++ test("works on an empty config", () => {+ const out = upsertMcpServers("", ENTRIES);+ expect(hasMcpServers(out, ENTRIES)).toBe(true);+ });+});++describe("removeMcpServers", () => {+ test("removes only our tables, keeps foreign mcp servers and other sections", () => {+ const withOurs = upsertMcpServers(EXISTING, ENTRIES);+ const removed = removeMcpServers(withOurs, Object.keys(ENTRIES));+ expect(removed).not.toContain("[mcp_servers.open-second-brain]");+ expect(removed).not.toContain("[mcp_servers.open-second-brain-writer]");+ expect(removed).toContain("[mcp_servers.user-linear]");+ expect(removed).toContain("[cli]");+ expect(removed).toContain("[[marketplace.sources]]");+ expect(hasMcpServers(removed, ENTRIES)).toBe(false);+ });+});++describe("hasMcpServers (drift check)", () => {+ test("false when an expected table is missing or altered", () => {+ expect(hasMcpServers(EXISTING, ENTRIES)).toBe(false);+ const out = upsertMcpServers(EXISTING, ENTRIES);+ const tampered = out.replace('"--vault", "/v"', '"--vault", "/other"');+ expect(hasMcpServers(tampered, ENTRIES)).toBe(false);+ });+});diff --git a/tests/fixtures/sessions/grok-minimal.jsonl b/tests/fixtures/sessions/grok-minimal.jsonlnew file mode 100644index 00000000..c8811853--- /dev/null+++ b/tests/fixtures/sessions/grok-minimal.jsonl@@ -0,0 +1,8 @@+{"timestamp":1781213002,"method":"session/update","params":{"sessionId":"019eb891-7ac5-7eb3-9c32-5c20695f8738","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"compact","description":"Compress conversation history","input":null}]}}}+{"timestamp":1781213003,"method":"session/update","params":{"sessionId":"019eb891-7ac5-7eb3-9c32-5c20695f8738","update":{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"Remember to prefer tabs over spaces."}}}}+{"timestamp":1781213004,"method":"session/update","params":{"sessionId":"019eb891-7ac5-7eb3-9c32-5c20695f8738","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The user stated a durable preference."}}}}+{"timestamp":1781213005,"method":"session/update","params":{"sessionId":"019eb891-7ac5-7eb3-9c32-5c20695f8738","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"I'll "}}}}+{"timestamp":1781213005,"method":"session/update","params":{"sessionId":"019eb891-7ac5-7eb3-9c32-5c20695f8738","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"record that."}}}}+{"timestamp":1781213006,"method":"session/update","params":{"sessionId":"019eb891-7ac5-7eb3-9c32-5c20695f8738","update":{"sessionUpdate":"tool_call","toolCallId":"call-abc-0","title":"open-second-brain__brain_feedback","rawInput":{"topic":"indentation-style","signal":"positive","principle":"Prefer tabs over spaces."}}}}+{"timestamp":1781213006,"method":"session/update","params":{"sessionId":"019eb891-7ac5-7eb3-9c32-5c20695f8738","update":{"sessionUpdate":"tool_call_update","toolCallId":"call-abc-0","kind":"other","title":"Recording feedback","content":[{"type":"content","content":{"type":"text","text":"logged"}}]}}}+{"timestamp":1781213007,"method":"session/update","params":{"sessionId":"019eb891-7ac5-7eb3-9c32-5c20695f8738","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Done."}}}}diff --git a/tests/hooks/grok-stdin.test.ts b/tests/hooks/grok-stdin.test.tsnew file mode 100644index 00000000..289f9a58--- /dev/null+++ b/tests/hooks/grok-stdin.test.ts@@ -0,0 +1,131 @@+/**+ * Grok Build hook-payload compatibility.+ *+ * Grok delivers the hook event on stdin with camelCase field names and a+ * snake_case event VALUE (`{hookEventName: "session_start", sessionId,+ * workspaceRoot, toolName, toolInput, ...}`), where Claude Code and Codex use+ * snake_case keys and a PascalCase event value (`{hook_event_name:+ * "SessionStart", session_id, tool_name, tool_input}`). The shared parser+ * normalizes grok into the internal snake_case shape so every downstream hook+ * (active-context inject, post-write reminder, session capture) works under+ * grok unchanged, and runtime detection recognizes grok.+ *+ * Verified against grok 0.2.45 bundled docs (user-guide/10-hooks.md).+ */++import { describe, expect, test } from "bun:test";++import { asHookPayload, normalizeHookPayload } from "../../hooks/lib/stdin.ts";+import { detectHookRuntime, isArtifactToolName } from "../../hooks/lib/detect.ts";+import { isContextEventName } from "../../hooks/lib/context-events.ts";++const GROK_PRE_TOOL = {+ hookEventName: "pre_tool_use",+ sessionId: "abc-123",+ cwd: "/home/u/project",+ workspaceRoot: "/home/u/project",+ toolName: "run_terminal_command",+ toolInput: { command: "npm test" },+ timestamp: "2026-06-11T12:00:00Z",+};++const GROK_SESSION_START = { hookEventName: "session_start", sessionId: "s1", cwd: "/w" };++const CLAUDE_PRE_TOOL = {+ hook_event_name: "PreToolUse",+ session_id: "c-1",+ cwd: "/home/u/project",+ tool_use_id: "tu-1",+ tool_name: "Bash",+ tool_input: { command: "ls" },+ transcript_path: "/home/u/.claude/projects/x/abc.jsonl",+};++describe("normalizeHookPayload - grok camelCase to internal snake_case", () => {+ test("maps the documented grok keys", () => {+ const n = normalizeHookPayload(GROK_PRE_TOOL) as Record<string, unknown>;+ expect(n["hook_event_name"]).toBe("PreToolUse");+ expect(n["session_id"]).toBe("abc-123");+ expect(n["tool_name"]).toBe("run_terminal_command");+ expect(n["tool_input"]).toEqual({ command: "npm test" });+ });++ test("converts the snake_case event value to the canonical PascalCase", () => {+ expect(+ (normalizeHookPayload({ hookEventName: "session_start" }) as Record<string, unknown>)[+ "hook_event_name"+ ],+ ).toBe("SessionStart");+ expect(+ (normalizeHookPayload({ hookEventName: "user_prompt_submit" }) as Record<string, unknown>)[+ "hook_event_name"+ ],+ ).toBe("UserPromptSubmit");+ });++ test("leaves a Claude snake_case payload byte-for-byte equivalent", () => {+ const n = normalizeHookPayload(CLAUDE_PRE_TOOL) as Record<string, unknown>;+ expect(n["hook_event_name"]).toBe("PreToolUse");+ expect(n["session_id"]).toBe("c-1");+ expect(n["tool_name"]).toBe("Bash");+ expect(n["transcript_path"]).toBe("/home/u/.claude/projects/x/abc.jsonl");+ });++ test("passes non-object values through unchanged", () => {+ expect(normalizeHookPayload(null)).toBeNull();+ expect(normalizeHookPayload("x")).toBe("x");+ });+});++describe("asHookPayload - typed access for grok", () => {+ test("exposes grok fields through the snake_case accessors", () => {+ const p = asHookPayload(GROK_PRE_TOOL);+ expect(p.hook_event_name).toBe("PreToolUse");+ expect(p.session_id).toBe("abc-123");+ expect(p.tool_name).toBe("run_terminal_command");+ });++ test("a grok SessionStart payload is recognized as a context event", () => {+ const p = asHookPayload(GROK_SESSION_START);+ expect(p.hook_event_name).toBe("SessionStart");+ expect(isContextEventName(p.hook_event_name ?? "")).toBe(true);+ });++ test("grok omits transcript_path; the field stays undefined, not faked", () => {+ expect(asHookPayload(GROK_PRE_TOOL).transcript_path).toBeUndefined();+ });+});++describe("detectHookRuntime - grok", () => {+ test("detects grok from the camelCase payload shape", () => {+ expect(detectHookRuntime(GROK_PRE_TOOL)).toBe("grok");+ expect(detectHookRuntime(GROK_SESSION_START)).toBe("grok");+ });++ test("detects grok from the GROK_* environment when the payload is opaque", () => {+ expect(detectHookRuntime({}, { GROK_HOOK_EVENT: "session_start" })).toBe("grok");+ });++ test("still detects Claude Code and Codex unchanged", () => {+ expect(detectHookRuntime(CLAUDE_PRE_TOOL, {})).toBe("claudecode");+ expect(+ detectHookRuntime(+ { tool_name: "apply_patch", tool_input: { input: "*** Begin Patch\n" } },+ {},+ ),+ ).toBe("codex");+ });++ test("an opaque payload with no grok signal stays unknown", () => {+ expect(detectHookRuntime({ foo: 1 }, {})).toBe("unknown");+ });+});++describe("artifact tool name - grok", () => {+ test("grok's search_replace counts as a file-mutating tool", () => {+ expect(isArtifactToolName("search_replace")).toBe(true);+ // The cross-runtime names still count.+ expect(isArtifactToolName("Write")).toBe(true);+ expect(isArtifactToolName("apply_patch")).toBe(true);+ });+});diff --git a/tests/openclaw/bundle.test.ts b/tests/openclaw/bundle.test.tsindex a3e5c80d..331272d0 100644--- a/tests/openclaw/bundle.test.ts+++ b/tests/openclaw/bundle.test.ts@@ -70,4 +70,11 @@ describe("openclaw bundle", () => {expect(bundleText).toContain("before_prompt_build");expect(bundleText).toContain("prependContext");});++ test("derives OpenClaw's own host-qualified identity for the reminder", () => {+ // The reminder must attribute to OpenClaw's own vendor token, not the+ // operator name - it routes the operator name through the shared deriver+ // with its own id. (Bundle is not minified, so the call survives verbatim.)+ expect(bundleText).toContain('deriveRuntimeAgentName("openclaw", operator)');+ });});