Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.45.20.0 feat(claw-test): grok e2e install harness — runner, door, CI job, TTY scenario (#4137)

Garry Tan3ebda1fc8791
diff --git a/.github/workflows/heavy-tests.yml b/.github/workflows/heavy-tests.yml
index 404716ae3f..0ce022d07d 100644
--- a/.github/workflows/heavy-tests.yml
+++ b/.github/workflows/heavy-tests.yml
@@ -18,6 +18,11 @@ on:
# label so we don't fan out on unrelated label changes.
types: [labeled, synchronize, reopened]
workflow_dispatch:
+ inputs:
+ run_grok_door:
+ description: 'Run the grok-door job (pre-secret posture: label or this input only)'
+ type: boolean
+ default: false
permissions:
contents: read
@@ -122,11 +127,20 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 20
env:
- # Open the hermes opt-in door here so binary/auth absence — not the
- # opt-in var — is what skips (same posture as the claude/codex doors).
+ # Open the hermes/grok opt-in doors here so binary/auth absence — not
+ # the opt-in var — is what skips (same posture as the claude/codex
+ # doors). The grok door's keyless tier additionally self-skips without
+ # a grok binary, which a stock runner does not have.
GBRAIN_REAL_HERMES_E2E: '1'
+ GBRAIN_REAL_GROK_E2E: '1'
+ # Pin so a provisioned runner's grok version-shape test asserts against
+ # the supported version (and a colliding community `grok` binary fails
+ # loud instead of running the keyless tier confusingly).
+ GROK_VERSION: "1.0.4"
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ with:
+ persist-credentials: false
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
with:
bun-version: 1.3.13
@@ -141,7 +155,8 @@ jobs:
for f in \
test/e2e/bootstrap-real-claude.serial.test.ts \
test/e2e/bootstrap-real-codex.serial.test.ts \
- test/e2e/install-real-hermes.serial.test.ts; do
+ test/e2e/install-real-hermes.serial.test.ts \
+ test/e2e/install-real-grok.serial.test.ts; do
[ -f "$f" ] && files+=("$f")
done
if [ "${#files[@]}" -eq 0 ]; then
@@ -184,6 +199,8 @@ jobs:
GBRAIN_REAL_HERMES_E2E: '1'
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ with:
+ persist-credentials: false
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
with:
bun-version: 1.3.13
@@ -277,11 +294,13 @@ jobs:
EXIT=0
bun test --timeout=600000 test/e2e/install-real-hermes.serial.test.ts > door.txt 2>&1 || EXIT=$?
tail -40 door.txt
+ # Preserve the FULL bun output UNCONDITIONALLY (upload stays
+ # failure-gated): the zero-pass failure class below exits with the
+ # summary as its only trace, and bun prints failure details before
+ # the summary, so the 40-line tail can drop exactly the lines a
+ # paid-CI triage needs.
+ cp door.txt "$GBRAIN_E2E_EVIDENCE_DIR/" 2>/dev/null || true
if [ "$EXIT" -ne 0 ]; then
- # Preserve the FULL bun output for the failure artifact — bun
- # prints failure details before the summary, so the 40-line tail
- # above can drop exactly the lines a paid-CI triage needs.
- cp door.txt "$GBRAIN_E2E_EVIDENCE_DIR/" 2>/dev/null || true
exit "$EXIT"
fi
# This job provisions the binary + auth above, so the door must
@@ -336,3 +355,243 @@ jobs:
- name: Remove hermes credentials (unconditional)
if: always()
run: rm -f ~/.hermes/.env
+
+ # Grok door e2e (xAI Grok Build): PROVISIONS the real grok binary via the
+ # pinned npm package (registry integrity verified — stronger than the
+ # curl-installer path; both pins live in docs/mcp/GROK-CLI-PIN.md, enforced
+ # against this file by scripts/check-grok-pin.sh in `bun run verify`).
+ # KEYLESS-FIRST ordering (deliberate divergence from hermes-door): grok's
+ # mcp add/list/doctor run keyless, so the compat tier runs and banks its
+ # coverage BEFORE the secret precondition — a missing XAI_API_KEY still
+ # fails this job loudly, but only after the free tier proved the install
+ # surface, so pre-secret runs are diagnostic instead of pure red.
+ #
+ # PRE-SECRET GATING POSTURE: `real-agent-e2e` label or the run_grok_door
+ # dispatch input ONLY — deliberately NOT `schedule` and NOT the generic
+ # `heavy-tests` label, so an absent XAI_API_KEY secret cannot paint nightly
+ # heavy runs (or unrelated heavy-labeled PRs) red. The commit that lands
+ # AFTER an admin creates the XAI_API_KEY secret (an external prerequisite,
+ # not a code change) re-adds: the schedule leg, the heavy-tests label leg,
+ # a default-on dispatch, and a latest-version canary matrix leg
+ # (continue-on-error, schedule-scoped, own timeout) so the pinned lane
+ # stays deterministic while the canary tracks what users actually run.
+ grok-door:
+ name: Grok door e2e (real binary, keyless-first)
+ if: |
+ (github.event_name == 'pull_request' &&
+ contains(github.event.pull_request.labels.*.name, 'real-agent-e2e')) ||
+ (github.event_name == 'workflow_dispatch' &&
+ inputs.run_grok_door == true)
+ runs-on: ubuntu-latest
+ # Measured local door wall-time: keyless tier ~29s + one-time compiled
+ # gbrain build (~2-4 min) + npm install (~10s); paid SMOKE turn budget
+ # 2 x 240s. 20 min = measured + >50% headroom (GROK-CLI-PIN.md).
+ timeout-minutes: 20
+ env:
+ # Pin values documented in docs/mcp/GROK-CLI-PIN.md — update them
+ # together, deliberately, after reviewing upstream changes
+ # (scripts/check-grok-pin.sh fails `bun run verify` on drift).
+ GROK_VERSION: "1.0.4"
+ GROK_NPM_PACKAGE: "@xai-official/grok"
+ GROK_NPM_INTEGRITY: "sha512-Nu3SFXTqwvCQr/LQFwrQYgngJhUQwX2h9ZSgzW4HowidjbPBWtMVO0xI88d2z6/zlDSNaT5YP/uk+2DthKQMsg=="
+ # Per-platform payload pins: the wrapper's integrity covers only the
+ # wrapper tarball; the binary that EXECUTES is the platform sub-package.
+ GROK_NPM_LINUX_X64_INTEGRITY: "sha512-Dan2LfKcFBiabuDGHaGgMT8Ndzibo2ljvSjh4MlpV5117JL+S/0KMbdyYpk+13d7t+4znniW1cm+rRwUGSAvtw=="
+ GROK_NPM_LINUX_ARM64_INTEGRITY: "sha512-zGK42Eq3ZmIa7cSVnl6CiJ4cxTCMsNLQCmCoLJhy5eZXfAvZ1DA3K3HXmKCj4OScX8SalYlp7mx8HWl9Y6gytw=="
+ GBRAIN_REAL_GROK_E2E: '1'
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ with:
+ persist-credentials: false
+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
+ with:
+ bun-version: 1.3.13
+ - run: bun install
+
+ - name: Prepare evidence dir
+ run: |
+ echo "GBRAIN_E2E_EVIDENCE_DIR=$RUNNER_TEMP/grok-door-evidence" >> "$GITHUB_ENV"
+ mkdir -p "$RUNNER_TEMP/grok-door-evidence"
+
+ # Compile gbrain ONCE for both bun test invocations below —
+ # ensureCompiledGbrain's cache is per-process, so without this the
+ # keyless and paid runs each pay the 2-4 min compile.
+ - name: Build gbrain (compile once for both door runs)
+ run: |
+ bun build --compile --outfile "$RUNNER_TEMP/gbrain-door-bin" src/cli.ts
+ echo "GBRAIN_COMPILED_BIN=$RUNNER_TEMP/gbrain-door-bin" >> "$GITHUB_ENV"
+
+ # SECRETLESS provisioning: the npm registry verifies the per-platform
+ # payload against its integrity metadata; the pre-check pins that the
+ # registry still serves the SAME integrity we observed (a re-published
+ # 1.0.4 becomes a loud re-pin decision, not silently different code
+ # running next to secrets in later steps). Version assert lives here
+ # too — before any secret-bearing step.
+ - name: Install grok (pinned npm package)
+ timeout-minutes: 10
+ run: |
+ served=$(npm view "$GROK_NPM_PACKAGE@$GROK_VERSION" dist.integrity 2>/dev/null || true)
+ if [ "$served" != "$GROK_NPM_INTEGRITY" ]; then
+ echo "::error::grok npm integrity drift for $GROK_NPM_PACKAGE@$GROK_VERSION — registry serves '$served', pinned '$GROK_NPM_INTEGRITY'. Re-pin deliberately: update the stamps in docs/mcp/GROK-CLI-PIN.md + this workflow after reviewing upstream (see the pin doc's re-observation checklist)." >&2
+ exit 1
+ fi
+ # The platform sub-package is the binary that actually runs — pin it
+ # too (per-arch; ubuntu-latest is x64 today, arm64 pinned for a
+ # future runner switch).
+ arch=$(uname -m)
+ case "$arch" in
+ x86_64) plat_pkg="$GROK_NPM_PACKAGE-linux-x64"; plat_pin="$GROK_NPM_LINUX_X64_INTEGRITY" ;;
+ aarch64|arm64) plat_pkg="$GROK_NPM_PACKAGE-linux-arm64"; plat_pin="$GROK_NPM_LINUX_ARM64_INTEGRITY" ;;
+ *) echo "::error::unsupported runner arch for the grok payload pin: $arch" >&2; exit 1 ;;
+ esac
+ plat_served=$(npm view "$plat_pkg@$GROK_VERSION" dist.integrity 2>/dev/null || true)
+ if [ "$plat_served" != "$plat_pin" ]; then
+ echo "::error::grok platform payload integrity drift for $plat_pkg@$GROK_VERSION — registry serves '$plat_served', pinned '$plat_pin'. Re-pin deliberately (GROK-CLI-PIN.md stamps + this workflow)." >&2
+ exit 1
+ fi
+ npm install -g "$GROK_NPM_PACKAGE@$GROK_VERSION"
+ if ! command -v grok >/dev/null 2>&1; then
+ echo "::error::grok did not resolve on PATH after npm install" >&2
+ exit 1
+ fi
+ version_output=$(grok --version)
+ echo "$version_output"
+ # Observed shape: `grok 1.0.4 (buildhash)` (GROK-CLI-PIN.md).
+ if ! printf '%s' "$version_output" | grep -qF "grok $GROK_VERSION"; then
+ echo "::error::grok version drift — expected 'grok $GROK_VERSION' in: $version_output (see docs/mcp/GROK-CLI-PIN.md triage table)" >&2
+ exit 1
+ fi
+
+ # KEYLESS TIER FIRST — banks the free compat coverage (documented-shape
+ # registration, TOML schema, doctor handshake proving the seven-verb
+ # surface) before anything needs the secret. XAI_API_KEY is absent from
+ # this step by construction, so the paid describe self-skips.
+ - name: Run grok door tests (keyless tier)
+ run: |
+ EXIT=0
+ bun test --timeout=600000 test/e2e/install-real-grok.serial.test.ts > door-keyless.txt 2>&1 || EXIT=$?
+ tail -40 door-keyless.txt
+ cp door-keyless.txt "$GBRAIN_E2E_EVIDENCE_DIR/" 2>/dev/null || true
+ if [ "$EXIT" -ne 0 ]; then
+ exit "$EXIT"
+ fi
+ # Exact expected shape for this tier: 4 keyless tests pass, the
+ # 1 paid test skips. Zero-pass or partial-pass refuses green.
+ pass_count=$(grep -Eo '[0-9]+ pass' door-keyless.txt | tail -1 | grep -Eo '^[0-9]+' || true)
+ if [ -z "$pass_count" ] || [ "$pass_count" -lt 4 ]; then
+ echo "::error::grok door keyless tier expected 4 passing tests, summary shows '${pass_count:-none}' — refusing to go green (see docs/mcp/GROK-CLI-PIN.md triage table)" >&2
+ exit 1
+ fi
+
+ - name: Preconditions (secret present)
+ env:
+ XAI_API_KEY: ${{ secrets.XAI_API_KEY }}
+ run: |
+ if [ -z "$XAI_API_KEY" ]; then
+ echo "::error::XAI_API_KEY secret is empty — the keyless tier above already ran (its coverage is banked); the paid SMOKE needs the secret. Admin: create the XAI_API_KEY repo/environment secret (console.x.ai), then re-run. Fork PRs get no secrets from GitHub." >&2
+ exit 1
+ fi
+
+ # Named bad-key preflight: key-rot fails HERE, at a step named for it,
+ # instead of surfacing as a confusing SMOKE failure (GROK-CLI-PIN.md
+ # triage table). One minimal paid probe.
+ - name: Auth preflight (bad-key tripwire)
+ env:
+ XAI_API_KEY: ${{ secrets.XAI_API_KEY }}
+ run: |
+ export GROK_HOME="$RUNNER_TEMP/grok-preflight-home"
+ mkdir -p "$GROK_HOME"
+ # Verbatim kill-switch homes (update together): seedGrokConfig in
+ # test/helpers/agent-harness.ts and scenarioGrokInstall in
+ # scripts/dx-explore.ts.
+ printf '[cli]\nauto_update = false\n' > "$GROK_HOME/config.toml"
+ # This step runs the third-party agent binary directly: never hand
+ # it the WRITABLE step-metadata files (appending to GITHUB_ENV/PATH
+ # poisons the later secret-bearing steps — the same channel
+ # grokChildEnv scrubs for test-spawned children), and kill its web
+ # tools like the door SMOKE does.
+ out=$(env -u GITHUB_ENV -u GITHUB_PATH -u GITHUB_OUTPUT -u GITHUB_STATE -u GITHUB_STEP_SUMMARY \
+ grok -p "reply with exactly: PREFLIGHT-OK" --output-format plain --disable-web-search 2>&1) || {
+ echo "::error::grok auth preflight failed — the XAI_API_KEY secret is present but rejected (rotate it at console.x.ai; see GROK-CLI-PIN.md triage table). Output: ${out:0:300}" >&2
+ exit 1
+ }
+ echo "auth preflight ok"
+
+ - name: Run grok door tests (full — paid SMOKE included)
+ env:
+ XAI_API_KEY: ${{ secrets.XAI_API_KEY }}
+ run: |
+ EXIT=0
+ bun test --timeout=600000 test/e2e/install-real-grok.serial.test.ts > door.txt 2>&1 || EXIT=$?
+ tail -40 door.txt
+ cp door.txt "$GBRAIN_E2E_EVIDENCE_DIR/" 2>/dev/null || true
+ if [ "$EXIT" -ne 0 ]; then
+ exit "$EXIT"
+ fi
+ # PAID-SENTINEL: with the key present, a skipping paid tier must
+ # never read as green (the split-gating false-green class). The
+ # grep target is the suite's literal skip log — mirrored in
+ # test/e2e/install-real-grok.serial.test.ts (change together).
+ if grep -q 'SKIP paid tier' door.txt; then
+ echo "::error::grok door paid tier skipped despite a present XAI_API_KEY — hasGrokAuth() gate drift; refusing to go green" >&2
+ exit 1
+ fi
+ pass_count=$(grep -Eo '[0-9]+ pass' door.txt | tail -1 | grep -Eo '^[0-9]+' || true)
+ if [ -z "$pass_count" ] || [ "$pass_count" -lt 5 ]; then
+ echo "::error::grok door full run expected 5 passing tests (6 once the JSON tool-call test lands), summary shows '${pass_count:-none}'" >&2
+ exit 1
+ fi
+
+ # Auto-update tripwire: the seeded [cli] auto_update=false is the whole
+ # kill-switch (no env form observed) — a version that MOVED mid-job
+ # means it failed and the pins above are no longer what just ran.
+ - name: Version re-check (mid-job drift tripwire)
+ if: always()
+ run: |
+ if command -v grok >/dev/null 2>&1; then
+ version_output=$(grok --version || true)
+ if ! printf '%s' "$version_output" | grep -qF "grok $GROK_VERSION"; then
+ echo "::error::grok version moved mid-job — auto-update kill-switch failed (expected 'grok $GROK_VERSION', got: $version_output)" >&2
+ exit 1
+ fi
+ fi
+
+ - name: Scrub credentials from evidence (defensive)
+ if: failure() && env.GBRAIN_E2E_EVIDENCE_DIR != ''
+ env:
+ XAI_API_KEY: ${{ secrets.XAI_API_KEY }}
+ run: |
+ # Same triple as hermes-door: filenames, symlinks, content. Auth is
+ # env-only here (the job never writes the key to disk — stronger
+ # than the hermes .env posture), so the content grep is the layer
+ # that matters for grok-written logs on the failure path.
+ find "$GBRAIN_E2E_EVIDENCE_DIR" -type f \( -name '.env' -o -name '*.env' -o -name 'mcp_credentials.json' \) -exec rm -f {} + 2>/dev/null || true
+ find "$GBRAIN_E2E_EVIDENCE_DIR" -type l -delete 2>/dev/null || true
+ if [ -n "$XAI_API_KEY" ]; then
+ grep -rlF "$XAI_API_KEY" "$GBRAIN_E2E_EVIDENCE_DIR" 2>/dev/null | while IFS= read -r f; do
+ echo "::warning::removing evidence file containing the API key: ${f#"$GBRAIN_E2E_EVIDENCE_DIR"/}" >&2
+ rm -f "$f"
+ done
+ fi
+ - name: Upload grok door evidence
+ if: failure() && env.GBRAIN_E2E_EVIDENCE_DIR != ''
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: grok-door-evidence
+ path: ${{ env.GBRAIN_E2E_EVIDENCE_DIR }}
+ retention-days: 14
+ if-no-files-found: ignore
+
+ # Auth travels env-only, but grok MAY persist derived credentials after
+ # an authed turn (the inventory is pending — GROK-CLI-PIN.md); remove
+ # the known candidate unconditionally so nothing outlives the job even
+ # on a future self-hosted runner.
+ - name: Remove grok credentials (unconditional)
+ if: always()
+ run: |
+ rm -f ~/.grok/mcp_credentials.json
+ rm -rf "$RUNNER_TEMP/grok-preflight-home"
+ # Cancellation/timeout bypasses the suite's afterAll cleanup — the
+ # hermetic homes carry no key file (env-only auth) but may hold
+ # grok-derived credentials once the authed inventory lands.
+ rm -rf /tmp/gb-grok-* 2>/dev/null || true
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index d7125bdca7..25dac928bc 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.45.19.0 -->
+<!-- gbrain-runbook-stamp: 0.45.20.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3978d8791a..cde160a225 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,25 @@
All notable changes to GBrain will be documented in this file.
+## [0.45.20.0] - 2026-08-14
+
+**Grok Build joins the supported-client roster.** xAI's `grok` CLI can now wire a gbrain brain in one command, and — like Hermes before it — the install path is proven against the real binary, not written from docs: every asserted flag, config shape, and exit-code quirk was observed against a pinned Grok Build install, recorded in a machine-checked pin document, and exercised by a real-binary e2e door that CI can run.
+
+### Added
+
+- **Grok Build install support.** `grok mcp add gbrain -- gbrain serve --surface verbs` wires the seven-verb memory surface into xAI's coding agent; [docs/mcp/GROK.md](docs/mcp/GROK.md) carries the full guide — registration, direct TOML config, the trust-gated vendor-config fallback (an existing Claude Code registration may already work), verification via `grok mcp doctor` (the honest probe: the add itself is lazy and always exits 0), headless auth, model pinning, auto-update pinning for reproducible environments, cron pairing, and troubleshooting (including the colliding community `grok` binary and where Grok actually discovers skills). `INSTALL_FOR_AGENTS.md` gains the matching "If you are Grok Build" block; the guide is honest that this is the brain-only install — the `gbrain bootstrap` personal-agent path doesn't support Grok yet.
+- **`gbrain claw-test --live --agent grok`.** Grok is the third registered agent runner, so guide-following friction runs and `gbrain friction diff --base <hermes-run> --compare <grok-run>` work out of the box. The runner records a version preamble in every transcript (a mis-bound community binary is diagnosable after the fact) and warns loudly when the operator's `~/.claude.json` registers gbrain — Grok reads vendor MCP configs for trusted folders, a contamination channel no other supported agent has.
+- **A real-binary "door" e2e for Grok** (`test/e2e/install-real-grok.serial.test.ts`), split-gated so the free tier needs no API key: version pin, the documented registration shape end-to-end, the seven-verb handshake proven keyless, a vendor-fallback provenance guard, and the direct-TOML surface all run with just the binary; the paid recall smoke (a per-run nonce fact, web search disabled) additionally needs `XAI_API_KEY`. A label-gated `grok-door` CI job provisions the pinned npm package (wrapper AND per-platform payload integrities pre-checked against the pin doc), banks the keyless coverage before any secret is required, and refuses green on a silently-skipped paid tier.
+- **`docs/mcp/GROK-CLI-PIN.md`** — the observed-behavior pin (config schema verbatim, lazy-add semantics, honest doctor discriminator, keyless TUI sign-in behavior, volatile-path inventory, supported-version policy) with machine-readable stamps enforced against the CI workflow by a new `check-grok-pin` verify guard, which fails closed if the pin doc ever disappears out from under the door job.
+- **A `grok-install` DX scenario** (`scripts/dx-explore.ts`) drives the REAL interactive Grok TUI through the brain-only install under a PTY, with a sign-in-wall early-stop so keyless runs record the friction in seconds instead of pasting into a login screen for the full wall clock.
+
+### Changed
+
+- **Agent runners share their detection/env plumbing.** The byte-identical binary-resolution and env-filtering bodies moved out of the per-agent runners into `agent-runner.ts` (`detectBinary`/`filterAllowlistEnv`), shrinking every future runner; binary resolution never passes through a shell anymore. The live-lane Grok runner forwards only Grok's own credentials — the operator's Anthropic/OpenAI keys never reach a third-party binary.
+- **PTY transcripts are structurally redacted at every write site.** Provider-key values are replaced in every artifact — including the live screen mirror that outlives interrupted runs — with a hard-failing independent check behind the redaction; a secret split across output bursts can no longer be reassembled from the frame log. `--keyless` now genuinely drops provider keys in all install scenarios, the leak check never touches files that predate the run, and the PTY hot loops strip bounded windows instead of the whole buffer (repaint-heavy TUIs were making every poll quadratic).
+- **The hermes-door CI job got the same hardening sweep:** checkout token persistence off, and the door's full test output is preserved as evidence even for the failure class that previously left no trace.
+
+To take advantage of v0.45.20.0: nothing changes for existing installs — this release adds a client, it doesn't modify brain behavior. Grok Build users: follow [docs/mcp/GROK.md](docs/mcp/GROK.md) (two commands: register, then `grok mcp doctor gbrain` to verify the seven-verb handshake). Maintainers enabling the paid CI lane: create the `XAI_API_KEY` repo secret, then land the follow-up that adds the schedule and canary legs.
## [0.45.19.0] - 2026-08-15
**The interactive `gbrain init` pickers are now tested on a real terminal — and the repo carries one PTY layer instead of two.** The first thing every new user touches (the embedding provider picker and the search-mode picker) previously had no true-TTY coverage; the comments that claimed otherwise pointed at a harness nothing ever called.
diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.md
index 67aa9d314c..816c1976a3 100644
--- a/INSTALL_FOR_AGENTS.md
+++ b/INSTALL_FOR_AGENTS.md
@@ -227,6 +227,19 @@ Keep `--args` last (everything after it becomes server argv) and verify with
`hermes mcp test gbrain` — the add exits 0 even on failure. Full reference:
[docs/mcp/HERMES.md](docs/mcp/HERMES.md).
+**If you are Grok Build** (xAI's `grok` CLI): register gbrain as your MCP server:
+
+```bash
+grok mcp add gbrain -e "GBRAIN_HOME=$HOME" -- gbrain serve --surface verbs
+```
+
+The add is lazy (exit 0 without connecting) — verify with
+`grok mcp doctor gbrain`, which spawns the server and must report
+`7 tools discovered`. This is the brain-only install; the `gbrain bootstrap`
+personal-agent path does not support Grok yet (Claude Code/Codex only).
+Verified against Grok Build v1.0.4. Full reference:
+[docs/mcp/GROK.md](docs/mcp/GROK.md).
+
Whether you scaffolded or not, read `skills/RESOLVER.md` (in your workspace, or the
bundled copy at `~/gbrain/skills/RESOLVER.md` when running from the cloned repo). It's
the skill dispatcher — tells you which skill to read for any task. Save this to your
diff --git a/README.md b/README.md
index dcc5a11e67..52b80c55e1 100644
--- a/README.md
+++ b/README.md
@@ -173,6 +173,7 @@ GBrain exposes nearly all of its 100+ operations as MCP tools (stdio and HTTP; a
- **[Codex](docs/mcp/CODEX.md)** — `gbrain connect https://your-host/mcp --token gbrain_xxx --agent codex` (or `--install`). Codex reads the bearer from `$GBRAIN_REMOTE_TOKEN` at runtime, so the token never lands in Codex config.
- **[Cursor / Windsurf / any stdio MCP client](docs/mcp/CLAUDE_CODE.md)** — same shape, add `{"command": "gbrain", "args": ["serve"]}` to your MCP config.
- **[Hermes](docs/mcp/HERMES.md)** — `printf 'Y\n' | hermes mcp add gbrain --env GBRAIN_HOME=$HOME --connect-timeout 60 --command $(which gbrain) --args serve`. Keep `--args` last, and verify with `hermes mcp test gbrain` (the add exits 0 even on failure).
+- **[Grok Build](docs/mcp/GROK.md)** — `grok mcp add gbrain -e "GBRAIN_HOME=$HOME" -- gbrain serve --surface verbs`. The add is lazy (exit 0 without connecting) — verify with `grok mcp doctor gbrain`, which spawns the server and reports `7 tools discovered`. Verified against Grok Build v1.0.4.
- **[OpenClaw](docs/mcp/OPENCLAW.md)** — the ClawHub bundle plugin registers gbrain automatically (`openclaw.plugin.json` ships in this repo), or add `{"command": "gbrain", "args": ["serve"]}` to `~/.openclaw/config.json`'s `mcpServers`.
- **[Claude Desktop (Cowork)](docs/mcp/CLAUDE_DESKTOP.md)** — Settings → Integrations → add the URL of your HTTP server. Remote only; the local `claude_desktop_config.json` does not work for remote servers.
- **[Claude Cowork (team plan)](docs/mcp/CLAUDE_COWORK.md)** — org Owner adds the connector under Organization Settings → Connectors.
diff --git a/TODOS.md b/TODOS.md
index a5d95d69cd..df53021839 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -5914,3 +5914,76 @@ respective shapes. Small, mechanical; pinned by `test/init-embed-check.test.ts`
subsystem that deserves its own eng + CEO review, not a rider. The currency work
(`skillpack status`/`sync`, doctor `skill_currency`) already keeps the brain's skill
set current on upgrade; this item is purely about semantic retrieval of skills.
+
+## Grok Build wave follow-ups (filed at build time)
+
+- [ ] **P1 — Enable the grok-door paid lane once XAI_API_KEY exists.** Admin
+ creates the `XAI_API_KEY` repo/environment secret (console.x.ai; prefer a
+ protected GitHub Environment scoped to door jobs), then one commit re-adds
+ to `grok-door` in heavy-tests.yml: the `schedule` leg, the `heavy-tests`
+ label leg, default-on dispatch, and a latest-version CANARY matrix leg
+ (`continue-on-error`, schedule-scoped, own timeout) so the pinned lane stays
+ deterministic while the canary tracks what users run. Same session: run the
+ pending-auth Phase-0 observations (paid one-shot smoke, authed model list +
+ measured per-turn cost pins, credential-file inventory after login → door
+ evidence exclusions + TTY secretPaths, authed first-run TUI copy) into
+ `docs/mcp/GROK-CLI-PIN.md`, and pin `parseGrokJson` + the separate
+ non-retried JSON toolCall door test (one extra paid turn) once the
+ streaming-json event shape is observed. Effort: S (CC ~30min + admin).
+- [ ] **P2 — `gbrain connect --agent grok`.** One-command install UX:
+ `AgentId`/`AGENT_SPECS`/`AGENT_IDS` in `src/commands/connect.ts`, a
+ `buildGrokMcpAddArgv` in `src/core/mcp-registration.ts` (shape already
+ pinned in GROK-CLI-PIN.md), connect tests ("all four agents" pin moves to
+ five), KEY_FILES entry. Deferred from the grok wave to avoid a second
+ observation pass; the pin doc now exists, so this is mechanical. Effort: S.
+- [ ] **P2 — HERMES.md surface refresh.** The hermes register command predates
+ the truthful-surface wave and wires the full 100+-op catalog;
+ CLAUDE_CODE.md + GROK.md now recommend `--surface verbs`. Update the
+ register one-liner + Direct config block (+ INSTALL_FOR_AGENTS hermes
+ block) and re-verify against the pinned hermes. Effort: S.
+- [ ] **P2 — Backport the GITHUB_ENV/GITHUB_PATH/GITHUB_OUTPUT/GITHUB_STATE
+ deletion from `grokChildEnv` to `hermesChildEnv`** (and consider narrowing
+ the `GITHUB_` ALLOW_PREFIX to the read-only metadata names) — the prefix
+ rule forwards writable CI step-metadata files to untrusted agent children.
+ Unit truth-table exists for the grok side to clone. Effort: S.
+- [ ] **P3 — Grok bootstrap-harness target.** `gbrain bootstrap` personal-agent
+ support for Grok Build: `HarnessSelector` + `parseHarnessArgs`, a dated
+ `TARGETS` spec in `host-specs.ts`, a `wireGrok` branch + TOML writer (grok
+ config schema pinned; `codex-toml.ts` is the precedent), receipt/rollback/
+ status handling, and the INSTALL_FOR_AGENTS honest-classification flip.
+ Docs currently state "bootstrap does not support Grok yet". Effort: M.
+- [ ] **P3 — Door-adapter extraction + CI-tail composite action.** Trigger: the
+ NEXT door agent (4th). Extract the agent-harness door family shape
+ (resolve/auth/seed/childEnv/pin/turn) and hoist the shared workflow tail
+ (evidence prep / scrub triple / upload / zero-pass grep / cred cleanup)
+ into a composite action; port grok-door as first consumer. Until then the
+ hermes-door/grok-door scrub blocks carry cross-reference comments. Also
+ adopt a door CADENCE policy: nightly for the newest/most-churning agent,
+ label-only after 2 stable monthly cycles per agent. Effort: M.
+- [ ] **P3 — Promote grok-install to a PTY assertion test.** Criterion: 2
+ consecutive stable runs ≥1 month apart of the dx scenario (pre-ship ritual
+ on grok-touching waves) with unchanged boot/sign-in copy. Would be the
+ repo's first gbrain-driving PTY assertion test — keep it an instrument
+ until the copy proves stable. Effort: M.
+- [ ] **P3 — Nightly cross-agent friction-diff artifact.** After door runs,
+ `gbrain friction diff --base <hermes-run> --compare <grok-run>` rendered
+ into a CI artifact so guide-following friction regressions surface without
+ a dev-box session. Effort: S/M.
+- [ ] **P3 — `xai:` provider block in model-pricing.ts.** Grok models
+ (grok-4.6/4.5 observed) for cost views once xAI pricing is sourced;
+ separate concern from the harness wave (CANONICAL_PRICING discipline).
+ Effort: S.
+- [ ] **P3 — BrainBench grok adapter.** `src/eval/brainbench/adapters/` +
+ `ALL_HARNESSES` entry — same seam as the already-filed hermes adapter
+ (TODOS "BrainBench hermes adapter"); build both together. Effort: M.
+- [ ] **P3 — Client-registry unification (Approach C).** The repo carries 7
+ hardcoded client lists (connect AGENT_SPECS, bootstrap Harness,
+ HarnessSelector, host-specs TARGETS, claw-test registry, brainbench
+ ALL_HARNESSES, volunteer HARNESS_CHANNELS); grok proved the claw-test
+ registry shape generalizes. Unify into one data-driven table AFTER the
+ door-adapter extraction lands (earn it — don't freeze hermes-isms in).
+ Effort: L.
+- [ ] **P3 — PIN-doc privacy-guard candidate.** GROK-CLI-PIN/HERMES-CLI-PIN
+ carry verbatim observation transcripts; consider extending check-privacy.sh
+ (or a dedicated check) to assert pin docs use `<tmp>`/placeholder paths and
+ never carry key material or account ids. Effort: S.
diff --git a/VERSION b/VERSION
index b370446273..5bbeced711 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.45.19.0
+0.45.20.0
\ No newline at end of file
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index e1770e1980..3541294dcf 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -99,6 +99,10 @@ Per-client setup guides live in [`docs/mcp/`](mcp/):
- [`docs/mcp/CLAUDE_DESKTOP.md`](mcp/CLAUDE_DESKTOP.md)
- [`docs/mcp/CHATGPT.md`](mcp/CHATGPT.md)
- [`docs/mcp/PERPLEXITY.md`](mcp/PERPLEXITY.md)
+- [`docs/mcp/HERMES.md`](mcp/HERMES.md) — Hermes (Nous Research CLI)
+- [`docs/mcp/GROK.md`](mcp/GROK.md) — Grok Build (xAI CLI)
+- [`docs/mcp/OPENCLAW.md`](mcp/OPENCLAW.md) — OpenClaw (bundle plugin or stdio)
+- [`docs/mcp/CLAUDE_COWORK.md`](mcp/CLAUDE_COWORK.md) — Claude Cowork (team plan)
- [`docs/mcp/DEPLOY.md`](mcp/DEPLOY.md) — production deploy patterns
The HTTP server ships with an admin SPA at `/admin`, an SSE activity feed at `/admin/events`, DCR-style client registration, scope-gated `read`/`write`/`admin` access, and rate limiting.
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 9f0b6b832e..b7097c661f 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -406,6 +406,8 @@ E2E tests live in `test/e2e/` and run against real Postgres+pgvector (require `D
- `test/e2e/openclaw-reference-compat.test.ts` — `check-resolvable` + skillpack install-model against a minimal AGENTS.md workspace fixture (`test/fixtures/openclaw-reference-minimal/`), regression guard for the OpenClaw deployment shape.
- `test/e2e/workspace-generic-compat.test.ts` — always-on (PGLite, no binary): pins the INSTALL_FOR_AGENTS.md "any repo with a workspace" contract against `test/fixtures/generic-agents-workspace/` (Hermes is the motivating consumer): `cwd_walk_up` detection, the `GBRAIN_SKILLS_DIR` override, `check-resolvable` on a root AGENTS.md, and scaffold additivity + refuse-overwrite. The real Hermes-behavior proof is the door suite below.
- `test/e2e/install-real-hermes.serial.test.ts` — the hermes "door": real `hermes` binary + real `hermes mcp add` handshake (full-catalog tool discovery; the count tracks the op catalog, so the test asserts discovery happened, not a number) + a paid `hermes -z` recall turn against a seeded brain. Triple-gated: `GBRAIN_REAL_HERMES_E2E=1` (explicit opt-in — run-e2e.sh scrubs GBRAIN_*, so it can never fire under `bun run test:e2e`) + resolvable binary + non-empty ANTHROPIC key (anthropic-pinned on purpose: a second provider key flips hermes provider-auto into a mis-routed 401). Hermetic HOME + HERMES_HOME with a tripwire on the operator's real config; evidence copies to `GBRAIN_E2E_EVIDENCE_DIR` for CI upload. Venue: heavy-tests.yml (`real-agent-e2e` + `hermes-door` jobs).
+- `test/e2e/install-real-grok.serial.test.ts` — the grok "door" (xAI Grok Build; every asserted shape observed against the pin in `docs/mcp/GROK-CLI-PIN.md`). SPLIT-GATED, a deliberate divergence from the hermes door: grok's `mcp add/list/doctor` run keyless, so the compat tier (version-shape pin, documented-shape `grok mcp add gbrain -- gbrain serve --surface verbs` via a PATH-staged bin dir, saved-TOML asserts via `Bun.TOML.parse`, `mcp doctor` handshake proving the seven-verb surface, vendor-fallback provenance guard, direct-TOML surface) needs only `GBRAIN_REAL_GROK_E2E=1` + a resolvable binary; the paid SMOKE additionally needs a non-empty `XAI_API_KEY` and asserts a PER-RUN NONCE fact (grok has fs/shell tools — the committed fact is greppable, so recall of it proves nothing) with web search disabled. `mcp add` is lazy (exit 0 always) — `mcp doctor <name> --json` is the honest discriminator (exit 0/1 observed). Hermetic HOME + GROK_HOME + tmp cwd on every spawn (grok reads vendor MCP configs for trusted folders and loads `.envrc` from cwd); bounded tripwire over the operator's real `~/.grok` config/credential files (volatile paths excluded — grok rewrites logs/sessions/bin/docs every run) + a checkout guard that no `.grok/`/`.mcp.json` appeared in the repo root. Venue: heavy-tests.yml (`real-agent-e2e` + `grok-door` jobs); run directly via `GBRAIN_REAL_GROK_E2E=1 bun test test/e2e/install-real-grok.serial.test.ts`.
+- `test/helpers/tty-harness.ts` + `test/tty-harness.test.ts` — the DX real-PTY harness (`Bun.spawn({terminal:})`): pure text/timing helpers unit-tested with zero subprocesses, plus three live PTY smokes against `sh` guarded by `describe.skipIf(!ptySupported())`. The harness itself is a dev instrument surface — its consumer `scripts/dx-explore.ts` never runs in CI (transcripts land in gitignored `.context/dx-runs/`); see `docs/guides/bootstrap.md` for the scenario runbook.
- `test/e2e/search-swamp.test.ts` — reproduces the source-swamp case. Seeds a curated `originals/talks/article-outline-fat-code` page against two `<fork>/chat/` pages stuffed with the same multi-word phrase. Asserts the article wins keyword AND vector ranking, that `detail=high` lets the chat swamp re-surface, and that `source_id` passes through the two-stage CTE intact. PGLite in-memory.
- `test/e2e/search-exclude.test.ts` — `test/` + `archive/` pages hidden by default, `include_slug_prefixes` opts back in, caller-supplied `exclude_slug_prefixes` adds to defaults. Both keyword and vector search paths.
- `test/e2e/engine-parity.test.ts` — Postgres ↔ PGLite top-result and result-set parity for `searchKeyword` + `searchVector` (Postgres ranks pages then picks best chunk while PGLite returns chunks directly, so the source-boost behavior needs parity coverage). Skips without `DATABASE_URL`.
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index 2e20e7249c..198650a303 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -162,7 +162,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/commands/skillpack.ts` + `src/core/skillpack/{bundle,scaffold,reference,migrate-fence,scrub-legacy,harvest,harvest-lint,copy,apply-hunks,diff-text,installer}.ts` — managed-block install model retired; `install`/`uninstall` removed (exit non-zero with a hint to the replacement). Surface: `scaffold` (one-time additive copy via `copyArtifacts` in `copy.ts`; refuses to overwrite; partial-state fills missing paired sources declared in SKILL.md frontmatter `sources:`), `reference` (read-only diff lens + `--apply-clean-hunks` two-way auto-apply via pure-JS unified-diff parser/applier in `apply-hunks.ts` + `diff-text.ts`), `migrate-fence` (one-shot strip of legacy fence; cumulative-slugs receipt → row-parsing fallback; preserves rows verbatim as user-owned routing), `scrub-legacy-fence-rows` (opt-in row cleanup with skill-present + non-empty-triggers gate), `harvest` (host→gbrain inverse with symlink-reject + canonical-path containment via a `validateUploadPath`-style gate + default-on privacy linter in `harvest-lint.ts` against `~/.gbrain/harvest-private-patterns.txt` plus built-in a built-in fork-name pattern + email + Slack-channel patterns; rollback on match). Paired-source declarations live in each SKILL.md's frontmatter `sources:` array (validated by `loadSkillSources` in `bundle.ts`). `autoDetectSkillsDir` (in `src/core/repo-root.ts`) has a `cwd_walk_up` tier ahead of `~/.openclaw/workspace` (`$OPENCLAW_WORKSPACE` precedence preserved). `gbrain skillpack check --strict` exits non-zero on drift (CI gate); top-level `gbrain skillpack-check` keeps exit-1-on-issues for cron. Companion editorial skill `skills/skillpack-harvest/SKILL.md` drives the genericization checklist. Doc: `docs/guides/skillpacks-as-scaffolding.md`. Test coverage across `test/skillpack-{copy,scaffold,reference,reference-apply,apply-hunks,migrate-fence,scrub-legacy,harvest,harvest-lint,frontmatter-sources}.test.ts` + 9-case E2E in `test/e2e/skillpack-flow.test.ts`. `installer.ts` + `test/skillpack-install.test.ts` survive — `gbrain skillpack diff` still uses `diffSkill` from there.
- `src/core/skillpack/{manifest-v1,tarball,state,remote-source,trust-prompt,bootstrap-display,scaffold-third-party,registry-schema,registry-client,rubric,doctor,init-scaffold,pack-publish,endorse,audit}.ts` + `examples/skillpack-reference/` + `docs/skillpack-anatomy.md` + `scripts/build-skillpack-anatomy.ts` — third-party skillpack ecosystem. `gbrain skillpack scaffold <owner/repo|https-url|./tgz|./local-dir>` resolves the spec via `classifySpec`, fetches through SSRF-hardened `git-remote.ts` (git) or extracts the tarball into `~/.gbrain/skillpack-cache/<host>/<owner>/<repo>/<sha>/`, validates `skillpack.json` (api_version `gbrain-skillpack-v1`), checks `gbrain_min_version`, surfaces a TOFU first-install identity-confirm prompt (author + source + pinned commit + tarball SHA + tier; non-TTY requires `--trust`), records the pin in machine-owned `~/.gbrain/skillpack-state.json` (schema `gbrain-skillpack-state-v1`, atomic `.tmp + rename`, `isAlreadyTrusted` skips re-prompt on author+pin match), runs through `enumerateScaffoldEntries` → `copyArtifacts` (one-time additive, refuses to overwrite), then DISPLAYS `runbooks/bootstrap.md` WITHOUT executing (deliberately does not auto-execute). Registry catalog at `garrytan/gbrain-skillpack-registry` split into `registry.json` (PR-able, `gbrain-registry-v1`) + `endorsements.json` (maintainer-only overlay, `gbrain-endorsements-v1`); `effectiveTier` merges. `registry-client.ts` fetches both via `If-None-Match` etag with 1h soft-TTL + stale-fallback (origins `fresh_fetch | cache_warm | cache_soft_stale | cache_hard_stale`); hard-fail only on no-cache + no-network. CLI: `gbrain skillpack {search,info,registry,doctor,init,pack,endorse}`. Doctor walks `SKILLPACK_RUBRIC_V1` (10 binary dimensions: 5 required CORE — manifest_valid, skills_have_skill_md, routing_evals_present ≥5 intents, skills_have_unique_triggers MECE, changelog_present_and_current — and 5 quality BADGES — unit_tests_present, e2e_tests_present, llm_eval_present ≥3 cases, bootstrap_runbook_present, license_present); tier eligibility: `endorsed` needs all 10, `community` needs core + ≥3 badges, `experimental` needs core only, `blocked` when any core fails. `--quick` ~5s structural sweep; `--fix --yes` auto-scaffolds `auto_fixable: true` dimensions and refuses to overwrite files whose mtime is newer than `skillpack.json`. `gbrain skillpack init <name>` lands 11 files (skillpack.json, SKILL.md, routing-eval.jsonl, test/example.test.ts, e2e/example.e2e.test.ts, evals/example.judge.json, runbooks/{bootstrap,uninstall,upgrade-template}.md, CHANGELOG, README, LICENSE); freshly-init'd scores 10/10; `--minimal` skips test/e2e/evals. `gbrain skillpack pack` packs a deterministic tarball via GNU tar (`--sort=name --mtime=@0 --owner=0 --group=0 --numeric-owner` + `GZIP=-n` + `TZ=UTC`); refuses on `tier_eligibility === 'blocked'`. Extract caps (5000 files / 100MB total / 1MB per file / 255-char paths / 100:1 compression ratio); rejects symlinks/hardlinks/devices/FIFOs. `gbrain skillpack endorse <name> [--tier ...] [--push] [--dry-run]` runs in a clone of the registry repo: validates the pack in `registry.json`, mutates `endorsements.json` via pure `applyEndorsement`, stable-key-orders the write, commits `endorse: <name> -> <tier>`, optionally pushes. JSONL audit at `~/.gbrain/audit/skillpack-YYYY-Www.jsonl` (ISO-week rotated, honors `GBRAIN_AUDIT_DIR`). `examples/skillpack-reference/` is a 10/10 reference pack pinned by `test/e2e/skillpack-third-party.test.ts`. `docs/skillpack-anatomy.md` auto-generated via `scripts/build-skillpack-anatomy.ts` (`--check` for CI drift). CLI dispatch in `src/commands/skillpack.ts` disambiguates third-party (contains `/`, `://`, `.tgz`) from bundled-skill kebab; kebab routes bundled-first, registry-fallback. Tests: `test/skillpack-{manifest-v1,tarball,state,remote-source,trust-prompt,registry-schema,registry-client,rubric,doctor,init-scaffold,pack-publish,endorse,audit,scaffold-third-party}.test.ts` + `test/e2e/skillpack-third-party.test.ts`. Spec at `docs/designs/SKILLPACK_REGISTRY_V1_SPEC.md`.
- `src/core/archive-crawler-config.ts` — safety gate for the `archive-crawler` skill. Refuses to run unless `archive-crawler.scan_paths:` is explicitly set in the brain repo's `gbrain.yml`. Mirrors the storage-config.ts parsing pattern (sibling file, separate concern from storage tiering). `loadArchiveCrawlerConfig(repoPath)` throws `ArchiveCrawlerConfigError(missing_section | empty_scan_paths | invalid_path | parse_error)`. `normalizeAndValidateArchiveCrawlerConfig` rejects relative paths and `..` traversal; `~` is expanded; paths are stored resolved and terminated with the PLATFORM separator (`path.sep`) so error output reads natively on each OS. `isPathAllowed(candidate, config)` is the runtime per-file gate (scan_paths prefix-match with directory-boundary correctness; deny_paths overrides). Candidate, scan_paths and deny_paths all funnel through the private `toComparablePrefix()` before the prefix test — on Windows it folds `\`→`/` and lowercases (NTFS is case-insensitive, so a deny_path spelled `Private` must still match `private`, else the gate fails OPEN); on POSIX it is identity apart from the trailing separator, deliberately NOT folding, since `\` is a legal filename character and paths are case-sensitive. Storing a native separator while appending a hardcoded `/` is the mixed-separator bug that made `isPathAllowed` deny every real path on Windows; the two functions must stay symmetric or the prefix test is meaningless. Pinned by `test/archive-crawler-config.test.ts` (26 cases, platform-selected fixtures + `it.if`-gated win32/POSIX comparison semantics).
-- `test/helpers/tty-harness.ts` + `scripts/dx-explore.ts` — the repo's single real-PTY layer, on pure `Bun.spawn({terminal:})` (Bun 1.3.10+; engines.bun pin in package.json; no node-pty). `launchTty` spawns any CLI under a true pseudo-terminal with the hermetic env contract from `test/helpers/agent-harness.ts` (`hermeticChildEnv`; `dropEnv` strips pass-through auth keys), records timestamped output frames, and exposes `waitFor`/`waitForAny`/`mark`/`sendKey`/`waitForQuiet`/`waitForExit`/`close`. Lifecycle rule: only `close()` clears the wall-clock kill timer — always call it in a `finally`. Pure helpers (`stripAnsi`, `computeStalls`, `renderStallsReport`, `parseDriveCommand`, `buildClaudeTuiSeed`) are unit-tested in `test/tty-harness.test.ts`; that file's live-PTY smokes are `describe.skipIf(!ptySupported())`-gated. `scripts/dx-explore.ts` is the DX-exploration driver built on it — a developer instrument, not a test: nothing asserts, transcripts land gitignored under `.context/dx-runs/` (doc: `docs/guides/bootstrap.md`). The interactive `gbrain init` pickers are asserted for real in `test/init-picker-pty.serial.test.ts` (serial lane, so it runs in required CI).
+- `test/helpers/tty-harness.ts` + `scripts/dx-explore.ts` — the repo's single real-PTY layer, on pure `Bun.spawn({terminal:})` (Bun 1.3.10+; engines.bun pin in package.json; no node-pty). `launchTty` spawns any CLI under a true pseudo-terminal with the hermetic env contract from `test/helpers/agent-harness.ts` (`hermeticChildEnv`; `dropEnv` strips pass-through auth keys), records timestamped output frames, and exposes `waitFor`/`waitForAny`/`mark`/`sendKey`/`waitForQuiet`/`waitForExit`/`close`. Lifecycle rule: only `close()` clears the wall-clock kill timer — always call it in a `finally`. Pure helpers (`stripAnsi`, `computeStalls`, `renderStallsReport`, `parseDriveCommand`, `buildClaudeTuiSeed`) are unit-tested in `test/tty-harness.test.ts`; that file's live-PTY smokes are `describe.skipIf(!ptySupported())`-gated. Transcript writes are structurally redacted: `redactSecrets` (secrets ≥ `MIN_REDACT_SECRET_LEN` → `[REDACTED:<name>]`) runs at every write site, `coalesceSecretStraddles` merges frames so a secret split across a frame boundary can't bypass redaction, and `saveTranscript` takes an explicit `redact` map (seam — dx-explore builds it, tty-harness stays import-free of it). `scripts/dx-explore.ts` is the DX-exploration driver built on it — a developer instrument, not a test: nothing asserts, transcripts land gitignored under `.context/dx-runs/` (doc: `docs/guides/bootstrap.md`). The interactive `gbrain init` pickers are asserted for real in `test/init-picker-pty.serial.test.ts` (serial lane, so it runs in required CI).
- `src/core/skillpack/{init-brain-pack,brain-pack-advisory,brain-pack-lint,brain-resident-locate,nag-state}.ts` (#2180) — brain-resident skillpacks. `manifest-v1.ts` gains optional `brain_resident` + `schema_pack` (additive). `runInitBrainPack` scaffolds a pack beside brain content (`brain_resident:true`, exact `gbrain_min_version`, 5-section machine-parseable README); `applyWritePlan` is factored out of `init-scaffold.ts` for the shared refuse-overwrite loop. `brain-pack-lint.lintBrainPackTools` validates each skill's `tools:` against the serving op set (E6 version-skew). Topology A: `src/commands/sources.ts` `runAdd` prints `brain-pack-advisory` to stderr after `opsAddSource`, fail-open; `nag-state.ts` (`~/.gbrain/skillpack-nag-state.json`) keys declines by `(source-repo brain_id, source_id, pack_name)` with pure `decideNagAction` (first/reminder/version-bump/ceiling) — declines count ONLY on CLI-interactive displays. Topology B: `brain-resident-locate.loadResidentPacksForServer` (source-scoped via `sourceScopeOpts`) backs the `list_brain_skillpack` op; `getResidentSkillDetail` backs `get_skill` `source_id`; `scaffold_spec` is the git source, never a server FS path. Tests: `test/skillpack-{init-brain-pack,nag-state,brain-resident-locate}.test.ts` + the brain-resident cases in `test/skillpack-manifest-v1.test.ts`.
- `src/core/advisor/{types,run,render,recommended-set,history,apply,collect-*}.ts` + `src/commands/advisor.ts` (#2180) — `gbrain advisor`: read-only ranked actions from brain state. `run.runAdvisor` executes the hardcoded COLLECTORS array (version [cache-only], migration, schema-pack, stalled-jobs [absent-table tolerant], usage-shape, setup-smells, uninstalled-brain-pack, uninstalled-bundled, chronicle, mcp-client-fit), each in its own try/catch; `collect-mcp-client-fit.ts` (E3) flags full-surface MCP clients whose 30d usage fits STARTER_OPS (exact `rescope-client --surface starter` fix; ≥10-call threshold; automation-shaped clients excluded per D12) plus STARTER_OPS drift (top-used ops missing; starter members unused 90d) via the shared `src/core/mcp-usage.ts` reader — starter membership is judged against the exported `ALWAYS_INCLUDED_STARTER_OPS` (surface.ts) so the always-included lane never reads as unused, and the missing-from-starter arm excludes `localOnly` ops (never proposable for a network surface, mirroring derive-starter-ops) — REMOTE runs redact client identifiers to aggregate counts (amendment 29), and its dismiss/snooze rides the nag-state engine with its own `~/.gbrain/advisor-usage-nag-state.json` (local runs only); `rankFindings` orders critical>warn>info then collector order, caps the info tail, and drops `workspace_dependent` findings when `remote` (A1). `render.ts` is the shared `=`-bar renderer used by the advisor AND `post-install-advisory.ts` (generalized to a single current-state `recommended-set.RECOMMENDED`, `install`→`scaffold`). `history.ts` appends bounded `~/.gbrain/advisor-history.jsonl` (no DB migration) for since-last-run deltas; local-only. `apply.resolveApplyTarget` is the allowlist+injection guard for `commands/advisor.ts --apply <id>` (structured argv, never a shell; local-only). The `advisor` op (`operations.ts`) is read-scoped, NOT localOnly, gated by `mcp.publish_advisor` (config.ts; default off) and strictly read-only on remote. CLI wired in `cli.ts` (`CLI_ONLY` + dispatch). Bundled skill `skills/gbrain-advisor/` + weekly cron recipe. Tests: `test/advisor-{core,apply,op-gate,ranking-eval}.test.ts`.
- `src/core/chronicle/{eligibility,config,backstop,extract-events,ontology,narrative}.ts` + `src/eval/chronicle/harness.ts` + `src/commands/eval-chronicle.ts` (#2390) — Life Chronicle: the temporal spine. `eligibility.isChronicleEligible` decides which pages auto-emit events (meeting/conversation/calendar-event + directory rescue; diary and event pages NEVER eligible — privacy + anti-loop). `backstop.runChronicleBackstop` is the put_page hook body (fires ONLY on `status==='imported'` + the auto-link trust gate + the default-OFF `auto_chronicle` flag; enqueues a `chronicle_extract` minion job — LLM never runs on the write path). `extract-events.runChronicleExtract` is the job body: deterministic when/who, injectable judge (default = chat gateway; output cap 4000 tokens by default, operator override `chronicle.judge_max_tokens`), an ALL-or-nothing parse barrier (`isValidProposal` requires a real parseable date — a malformed batch writes NOTHING), then content-addressed `life/events/` pages + a `timeline_entries` projection via `engine.upsertEventProjection` (dedup `(event_page_id, date)`; idempotent re-runs). An unusable judge response is never recorded as `no_events` (#2606): a `stopReason: 'length'` truncation or a no-JSON-array response (`parseJudgeJson` returns `null` on parse failure; `[]` only for a legitimate empty array) surfaces as `status: 'skipped'` with reason `judge_truncated` / `judge_parse_failed`. `ontology.ts` carries the deterministic pieces of the bi-temporal per-entity ontology that RIDES THE `facts` TABLE (migration v122 adds `dimension`/`value`/`value_hash`/`dim_status`): `valueHash` (normalized, timestamp-free → crash-retry idempotent), `normalizeDimension` (seed alias lexicon), `isNovelDimension` (novel → quarantined, excluded from resolution/context until confirmed). The engine methods (`mergeOntologyFact` — corroborate on same value, forward-supersede via `valid_until`+`superseded_by` on a new value, backdated conflicts kept + flagged; `getOntology` with `--asof` valid-time travel; `discoverOntologyDimensions`; `findOntologyConflicts` — currently-open rows only) live in BOTH engines; both engines are on the R8 `valid_until` write allow-list (engine-layer, `dimension IS NOT NULL` rows only). Chronicle reads (`getTimelineForDate`/`getSince`/`getLastSeen`/`getOnThisDay`) JOIN the depth page (`deleted_at IS NULL`), hide soft-deleted event projections at READ time, and order by event `effective_date` for intra-day sequence. Ops: `chronicle_day`/`chronicle_since`/`chronicle_last_seen`/`chronicle_on_this_day`/`ontology_*`/`volunteer_chronicle` (agent orientation via `src/core/context/chronicle-context.ts`)/`chronicle_backfill` (admin, localOnly). Diary privacy: diary-sourced ontology + conflict values redacted for `ctx.remote !== false` callers. Search: `applyChronicleTypeBoost` in `search/hybrid.ts` (bounded [1.0,1.25], fires only inside the `recency !== 'off'` post-fusion branch → non-temporal search bit-for-bit unchanged). Advisor collector `collect-chronicle.ts` (conflicts + coverage gap); doctor `chronicle_projection_health` (BRAIN category). Eval: `gbrain eval chronicle` — deterministic, own in-memory PGLite, 6 gold tasks (day order, last-seen, supersession, asof, conflict, isolation), exit 0 iff 6/6. Tests: `test/chronicle-*.test.ts`, `test/eval-chronicle.test.ts`.
@@ -327,7 +327,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/cycle/transcript-discovery.ts` — Pure filesystem walk for synthesize. `discoverTranscripts(opts)` filters `.txt` files by date range, min_chars, and word-boundary regex `excludePatterns` (`medical` matches "medical advice" but NOT "comedical"; power users may pass full regex). `readSingleTranscript(path)` is the `gbrain dream --input <file>` ad-hoc path. Self-consumption guard: `DREAM_OUTPUT_MARKER_RE` (anchored at frontmatter open `---\n`, optional BOM + CRLF tolerance, scans first 2000 chars for `dream_generated: true` with case-insensitive value and word boundary on `true`) drives `isDreamOutput(content, bypass=false)`. Both functions skip matching files and emit a `[dream] skipped <basename>: dream_generated marker` stderr log (no silent skips). `bypassGuard?: boolean` on `DiscoverOpts` and `readSingleTranscript`'s opts disables the guard for the explicit `--unsafe-bypass-dream-guard` escape hatch only — never auto-applied for `--input`.
- `src/commands/dream.ts` — `gbrain dream` CLI; thin alias over `runCycle`. Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`, `--input <file>` (ad-hoc transcript, implies `--phase synthesize`), `--date YYYY-MM-DD`, `--from <d> --to <d>` (backfill range), `--unsafe-bypass-dream-guard` (plumbed through `runCycle.synthBypassDreamGuard` → `SynthesizePhaseOpts.bypassDreamGuard` → `discoverTranscripts({bypassGuard})` / `readSingleTranscript({bypassGuard})`; loud stderr warning at synthesize-phase entry; never auto-applied for `--input`). Conflict detection: `--input` + `--date` exits 2. ISO date validation. `--dry-run` runs the Haiku significance verdict but skips Sonnet synthesis (NOT zero LLM calls). Exit 1 on status=failed. `resolveBrainDir` returns `string | null` (order: `--dir` → resolved `--source`'s `local_path` → global `sync.repo_path` → null); a checkout-less postgres/Supabase brain runs DB-only phases (incl. `resolve_symbol_edges`) and skips the 6 filesystem phases with `details.reason: 'no_brain_dir'`; `runDream` owns the only hard error (no checkout AND no engine). When `--source` resolves but has no on-disk checkout, returns null (DB-only) rather than borrowing another source's global `sync.repo_path` (would mix scopes). Pinned by `test/dream-postgres.serial.test.ts`. `--drain [--window <seconds>]` for `--phase extract_atoms`: `runDrain()` bypasses the pack-gate and runs the single-hold bounded drain from `src/core/cycle/extract-atoms-drain.ts` under the same `cycleLockIdFor(sourceId)` the routine cycle uses (concurrent autopilot tick defers with `cycle_already_running`), reporting `{extracted, skipped, remaining}`. Exits `EXIT_DRAIN_INCOMPLETE=3` while `remaining > 0`; a null backlog count (count query FAILED) is also exit 3, never a drained success; `LockUnavailableError` → `cycle_already_running` skip (also exit 3). The `extract_atoms_backlog` doctor check (`computeExtractAtomsBacklogCheck`) surfaces the silent pack-gated backlog with the exact `--drain` command; pack-gated cycle skips carry a greppable `pack_gated:true` marker.
- `src/commands/friction.ts` + `src/core/friction.ts` — `gbrain friction {log,render,list,summary,diff}` reporter. Append-only JSONL under `$GBRAIN_HOME/.gbrain/friction/<run-id>.jsonl`. Schema is a flat extension of `StructuredAgentError`; every claw-test run opens with a `phase-marker`/`start` meta record carrying `agent` + `scenario` + `harness_schema` (agent-name resolution depends on it). Render groups by severity → phase, defaults to `--redact` for md output (strips `$HOME`/`$CWD` to placeholders so reports paste safely in PRs). `diff --base <run-or-agent> --compare <run-or-agent>` is the cross-agent instrument: exact run-id wins, else agent name resolves to that agent's latest run; identity is `(kind, phase, normalized 80-char message prefix — digit runs collapsed so durations/counts don't split identities)` over `kind ∈ {friction, delight}` as MULTISETS (per-severity counts + totals are the compared attributes: `count_changed` = volume, `severity_changed` = distribution shape via exact integer proportion test, so a delight→friction flip or a 2×error+1×nit → 1×error+2×nit redistribution always surfaces; markers/interrupted feed the compatibility banner, which warns on scenario/version mismatch); output labels sections "unique to <run>" — an instrument, never a blame-attributor. Run-id resolves from `--run-id` > `$GBRAIN_FRICTION_RUN_ID` > `standalone.jsonl`. Skills the claw-test exercises gain a `_friction-protocol.md` callout so agents know when to log friction.
-- `src/commands/claw-test.ts` + `src/core/claw-test/` — `gbrain claw-test [--scenario <name>] [--live --agent <name>]`. End-to-end "fresh user" friction harness. Two modes: scripted (CI gate, agent-free) and live (real agent subprocess, $1–2 in tokens). Sets `GBRAIN_HOME=<tempdir>` for hermeticity and captures gbrain's `--progress-json` events from each child's stderr to verify expected phases ran (`import.files`, `extract.links_fs`, `doctor.db_checks`). Scripted phases: setup → install_brain (`gbrain init --pglite`) → import (`--no-embed`) → query → extract → verify (`gbrain doctor --json`; top-level status is `healthy|warnings|unhealthy`) → render. Live mode STAGES the scenario before the agent turn (fresh-install: brain pages + AGENTS.md stub + init; upgrade: seed-first via `seed-pglite.ts`, NO init — the migration is the scenario under test), prepends a per-run `gbrain` PATH shim so the BRIEF's bare `gbrain` runs this checkout, hands `BRIEF.md` to the agent runner, then verifies a scenario-declared success ORACLE (`oracle: {query, min_results, files_exist}` in scenario.json; upgrade uses a non-mutating schema-version probe via `readPgliteSchemaVersion` — doctor would auto-migrate and pass a do-nothing agent). Child-side friction merges into the parent's friction file before tempdir cleanup. Two runners ship (`src/core/claw-test/runners/{openclaw,hermes}.ts`): openclaw invokes `openclaw agent --local --agent <name> --message <brief>`; hermes invokes `hermes -z <brief>` (`$HERMES_BIN` > `which hermes`; `HERMES_HOME` passthrough is the env-allowlist delta; shared `BASE_ENV_ALLOWLIST` + `validateBinPathEnv` live in `agent-runner.ts`). Live-lane posture: the OPERATOR's configured agent + hermetic brain; the fully hermetic lane is `test/e2e/install-real-hermes.serial.test.ts`. Transcript capture (`transcript-capture.ts`) uses `fs.createWriteStream` with `'drain'`-event backpressure (256KB-burst child-stall fix). Env knobs (harness escape hatches, all optional): `GBRAIN_BIN_OVERRIDE` (child gbrain binary; validated absolute/no-dotdot/no-metacharacter because it's interpolated into the PATH shim — under the bun runtime the harness otherwise synthesizes a launcher so children never exec bun itself), `GBRAIN_CLAW_PHASE_TIMEOUT_MS` (per-phase child wall clock, default 5 min), `GBRAIN_CLAW_AGENT_TIMEOUT_MS` (live agent turn wall clock, default 10 min).
+- `src/commands/claw-test.ts` + `src/core/claw-test/` — `gbrain claw-test [--scenario <name>] [--live --agent <name>]`. End-to-end "fresh user" friction harness. Two modes: scripted (CI gate, agent-free) and live (real agent subprocess, $1–2 in tokens). Sets `GBRAIN_HOME=<tempdir>` for hermeticity and captures gbrain's `--progress-json` events from each child's stderr to verify expected phases ran (`import.files`, `extract.links_fs`, `doctor.db_checks`). Scripted phases: setup → install_brain (`gbrain init --pglite`) → import (`--no-embed`) → query → extract → verify (`gbrain doctor --json`; top-level status is `healthy|warnings|unhealthy`) → render. Live mode STAGES the scenario before the agent turn (fresh-install: brain pages + AGENTS.md stub + init; upgrade: seed-first via `seed-pglite.ts`, NO init — the migration is the scenario under test), prepends a per-run `gbrain` PATH shim so the BRIEF's bare `gbrain` runs this checkout, hands `BRIEF.md` to the agent runner, then verifies a scenario-declared success ORACLE (`oracle: {query, min_results, files_exist}` in scenario.json; upgrade uses a non-mutating schema-version probe via `readPgliteSchemaVersion` — doctor would auto-migrate and pass a do-nothing agent). Child-side friction merges into the parent's friction file before tempdir cleanup. Three runners ship (`src/core/claw-test/runners/{openclaw,hermes,grok}.ts`; shared `detectBinary`/`filterAllowlistEnv` live in `agent-runner.ts`): openclaw invokes `openclaw agent --local --agent <name> --message <brief>`; hermes invokes `hermes -z <brief>` (`$HERMES_BIN` > `which hermes`; `HERMES_HOME` passthrough is the env-allowlist delta; shared `BASE_ENV_ALLOWLIST` + `validateBinPathEnv` live in `agent-runner.ts`); grok (xAI Grok Build, observed shapes in `docs/mcp/GROK-CLI-PIN.md`) invokes `grok -p <brief> --output-format plain` (`$GROK_BIN` > `which grok`; delta `GROK_HOME` + `XAI_API_KEY`; writes a version preamble into the transcript and warns loudly when the operator's `~/.claude.json` registers gbrain — grok reads vendor MCP configs for trusted folders). Live-lane posture: the OPERATOR's configured agent + hermetic brain; the fully hermetic lanes are `test/e2e/install-real-hermes.serial.test.ts` and `test/e2e/install-real-grok.serial.test.ts` (grok door is split-gated: keyless compat tier needs only the binary — `mcp doctor` is grok's honest discriminator, proving the seven-verb surface keyless; paid SMOKE additionally needs `XAI_API_KEY` and asserts a per-run nonce fact, never the committed one). Transcript capture (`transcript-capture.ts`) uses `fs.createWriteStream` with `'drain'`-event backpressure (256KB-burst child-stall fix). Env knobs (harness escape hatches, all optional): `GBRAIN_BIN_OVERRIDE` (child gbrain binary; validated absolute/no-dotdot/no-metacharacter because it's interpolated into the PATH shim — under the bun runtime the harness otherwise synthesizes a launcher so children never exec bun itself), `GBRAIN_CLAW_PHASE_TIMEOUT_MS` (per-phase child wall clock, default 5 min), `GBRAIN_CLAW_AGENT_TIMEOUT_MS` (live agent turn wall clock, default 10 min).
- `skills/_friction-protocol.md` — shared cross-cutting convention skill (like `_brain-filing-rules.md`). Tells agents when to call `gbrain friction log` and how to choose a severity. Routes to friction CLI from any skill the claw-test exercises.
- `scripts/check-progress-to-stdout.sh` — CI guard against regressing to `\r`-on-stdout progress. Wired into `bun run test` via `scripts/check-progress-to-stdout.sh && bun test` in package.json.
- `docs/progress-events.md` — Canonical JSON event schema reference. Additive only.
diff --git a/docs/guides/bootstrap.md b/docs/guides/bootstrap.md
index 7c912363ec..e234c46d8e 100644
--- a/docs/guides/bootstrap.md
+++ b/docs/guides/bootstrap.md
@@ -294,7 +294,7 @@ bun test test/e2e/bootstrap-real-codex.serial.test.ts
## DX exploration harness (developer instrument, not a test)
The door tests prove the install WORKS; they say nothing about how it FEELS.
-`test/helpers/tty-harness.ts` spawns any CLI (gbrain, `claude`, `codex`) under a
+`test/helpers/tty-harness.ts` spawns any CLI (gbrain, `claude`, `codex`, `grok`) under a
real pseudo-terminal (Bun's `terminal:` spawn option) and records every output
burst with a millisecond timestamp, so unnecessary pauses become a measurable
artifact (`computeStalls` → `stalls.md`) instead of a vibe. Same hermetic env as
@@ -313,6 +313,7 @@ bun run scripts/dx-explore.ts help # comprehension surfaces (no key
bun run scripts/dx-explore.ts init [--keyless] # interactive init, naive-user autopilot
bun run scripts/dx-explore.ts claude-install # REAL claude running the paste-in bootstrap
bun run scripts/dx-explore.ts codex-install # REAL codex, same
+bun run scripts/dx-explore.ts grok-install # REAL grok, brain-only GROK.md install (no bootstrap path)
bun run scripts/dx-explore.ts drive -- gbrain init # manual: steer a live TUI via a file channel
```
diff --git a/docs/mcp/GROK-CLI-PIN.md b/docs/mcp/GROK-CLI-PIN.md
new file mode 100644
index 0000000000..045b41fcbd
--- /dev/null
+++ b/docs/mcp/GROK-CLI-PIN.md
@@ -0,0 +1,190 @@
+# Grok Build CLI pin — observed behavior notes (v1.0.4)
+
+Dev-facing companion to [GROK.md](GROK.md): every fact below was OBSERVED against a
+real install (2026-08-14), not researched from docs. The claw-test GrokRunner, the
+install door e2e, and the heavy-tests grok-door CI job assert exactly these shapes —
+when Grok Build releases change them, update this file, the workflow pins, and the
+affected assertions together (`scripts/check-grok-pin.sh` in `bun run verify` enforces
+the workflow-side match).
+
+Naming note: **grok** (xAI Grok Build CLI, `XAI_API_KEY`) is not **groq** (Groq Inc.
+inference, `src/core/ai/recipes/groq.ts`, `GROQ_API_KEY`) and not **ngrok** (tunnels).
+
+<!-- grok-pin: distribution_kind=npm -->
+<!-- grok-pin: npm_package=@xai-official/grok -->
+<!-- grok-pin: npm_version=1.0.4 -->
+<!-- grok-pin: npm_integrity=sha512-Nu3SFXTqwvCQr/LQFwrQYgngJhUQwX2h9ZSgzW4HowidjbPBWtMVO0xI88d2z6/zlDSNaT5YP/uk+2DthKQMsg== -->
+<!-- grok-pin: npm_linux_x64_integrity=sha512-Dan2LfKcFBiabuDGHaGgMT8Ndzibo2ljvSjh4MlpV5117JL+S/0KMbdyYpk+13d7t+4znniW1cm+rRwUGSAvtw== -->
+<!-- grok-pin: npm_linux_arm64_integrity=sha512-zGK42Eq3ZmIa7cSVnl6CiJ4cxTCMsNLQCmCoLJhy5eZXfAvZ1DA3K3HXmKCj4OScX8SalYlp7mx8HWl9Y6gytw== -->
+<!-- grok-pin: grok_version=1.0.4 -->
+<!-- grok-pin: installer_sha256=43d0943123edade1383a476a4f778674877acee7c1f98a00f094c4a0f7349321 -->
+<!-- grok-pin: observed_date=2026-08-14 -->
+
+## Pin
+- **Grok Build v1.0.4**, `grok --version` output shape: `grok 1.0.4 (d846eb93d94d)`
+ (version + build hash; the door's shape assert is `/^grok \d+\.\d+\.\d+ \([0-9a-f]+\)$/`).
+- **Provisioning (CI + local): pinned npm install** — `@xai-official/[email protected]`,
+ registry integrity `sha512-Nu3SFX…`. The package fans out to
+ `@xai-official/grok-{darwin,linux,win32}-{arm64,x64}` optional deps at the same
+ version; the CI job pins the LINUX payload integrities too (stamps above) because
+ the wrapper's integrity covers only the wrapper tarball — the platform sub-package
+ is the binary that executes. Load-bearing assumption, stated explicitly: npm
+ version-immutability (a published version cannot be replaced on npmjs; only a new
+ version or an unpublish, both of which fail the pinned install loudly).
+- Installer path (fallback only): `https://x.ai/cli/install.sh`, sha256
+ `43d0943123edade1383a476a4f778674877acee7c1f98a00f094c4a0f7349321` (17,686 bytes).
+ It SUPPORTS version pinning (`bash -s <X.Y.Z>`) and downloads versioned artifacts
+ `grok-<version>-<os>-<arch>` from `https://x.ai/cli` (fallback GCS bucket
+ `grok-build-public-artifacts`), self-checks `--version` post-download. Platform
+ string from `uname -s`/`uname -m` with a Rosetta correction on Apple Silicon.
+- Verified against macOS arm64; npm `os`/`cpu` matrix covers linux x64/arm64 for CI.
+
+## GROK_HOME — HONORED (verified)
+`GROK_HOME=<tmp> HOME=<tmp> grok mcp list|add|doctor` read+write `<tmp>/config.toml`
+and do NOT touch `~/.grok`. Belt-and-suspenders (HOME + GROK_HOME both to tmp) stays
+in the door anyway. NOTE what grok writes into `$GROK_HOME` on EVERY run (tripwire
+exclusions — these are VOLATILE): `active_sessions.lock`, `active_sessions.json`,
+`bin/grok-<version>` (it copies its own binary in), `logs/unified.jsonl`,
+`docs/user-guide/*.md` (it ships its user guide into the home), `leader.sock` (a
+leader daemon socket; `--leader-socket <PATH>` overrides). The tripwire hashes ONLY
+`config.toml` + credential-class files, never the volatile set.
+
+## One-shot (`-p`)
+- `grok -p "<prompt>"` (`-p, --single`) prints the response to stdout and exits.
+- `--output-format plain|json|streaming-json|streaming-messages-json` (default plain;
+ `streaming-json` = NDJSON of native ACP session updates; `streaming-messages-json` =
+ Anthropic Messages wire format; `--include-partial-messages` adds deltas).
+- **Keyless one-shot: exit 1**, message (verbatim, both stdout and stderr):
+ `Not signed in. To authenticate without a browser, run:\n grok login --device-code\n\nAlternatively, set the XAI_API_KEY environment variable or run `grok login` on a machine with a browser.`
+ → `hasGrokAuth()` = non-empty `XAI_API_KEY`; the TTY scenario's keyless early-stop
+ matcher is `Not signed in`.
+- Cost/toolset flags that EXIST (observed in --help): `--always-approve`,
+ `--permission-mode default|acceptEdits|auto|dontAsk|bypassPermissions|plan`,
+ `--tools <LIST>`, `--disallowed-tools <LIST>`, `--allow/--deny <RULE>`,
+ `--disable-web-search` (dedicated kill for web search + fetch — the door SMOKE uses
+ THIS, not a tools list), `--max-turns <N>`, `-m/--model`, `--reasoning-effort`
+ (alias `--effort`), `--cwd <PATH>`, `--rules`, `--prompt-file`, `--prompt-json`,
+ `--json-schema` (implies json output), `--verbatim`, `--sandbox <PROFILE>`
+ (env `GROK_SANDBOX`), `--no-memory`, `--no-plan`, `--no-subagents`.
+- There is NO auto-update CLI flag. Auto-update is config: `[cli] auto_update = true`
+ is the DEFAULT — hermetic homes MUST seed `[cli] auto_update = false`. Manual
+ updater: `grok update [--check --json --version <V> --force-reinstall --alpha]`.
+- `.envrc` gotcha: `load_envrc = true` by default — grok loads `.envrc` from the
+ working directory. Door/live spawns pin `cwd` to tmp workspaces partly for this.
+
+## Auth + model pin (non-interactive)
+- Keyless error pinned above; `grok login --device-code` exists for headless
+ interactive auth; `XAI_API_KEY` env is the documented headless path (its end-to-end
+ smoke is **pending auth** — no key was available at observation time; the door's
+ paid tier stays skip-gated until then, per plan D0).
+- `grok models` works KEYLESS (exit 0): prints `You are not authenticated.`, then
+ `Default model: grok-4.6` and the visible list (`grok-4.6 (default)`, `grok-4.5`).
+ Authenticated list may be larger; per-turn cost pins are **pending auth**.
+- Model pin mechanism: per-call `-m <model>` (authoritative in tests — immune to
+ config rewrites) and `[models] default = "<model>"` in config.toml.
+
+## `grok mcp add` — THE big observed facts
+- Shape: `grok mcp add <name> [-e KEY=value]... [-s user|project] [-t stdio|http|sse] -- <command> [args...]`
+ — everything after `--` is the server argv. **`-e/--env` is REPEATABLE, one
+ KEY=value per flag** (their docs pin this as a breaking change from earlier
+ releases: `use -e A=1 -e B=2, not --env A=1 B=2` — the hermes replace-bug class is
+ fixed upstream). Server names: letters, numbers, hyphens, underscores only.
+- **Add is LAZY: exit 0 always, NO handshake at add time, no interactive prompt**
+ (`Added stdio MCP server 'gbrain' … to user config` / `File modified:
+ $GROK_HOME/config.toml`). Adding a NONEXISTENT command also exits 0. Never assert
+ add's exit code; never treat `enabled = true` in the saved TOML as a handshake
+ proof (it is written unconditionally).
+- Scope: `-s user` (default) → `~/.grok/config.toml`; `-s project` →
+ `./.grok/config.toml` (committable; reference secrets as `${VAR}`).
+- **Bare command names resolve via the CALLER'S PATH** (verified): registering
+ `-- gbrain serve --surface verbs` with a PATH-prefixed bin dir works — doctor
+ resolved bare `gbrain` to the staged wrapper and completed the handshake. The
+ bun-run wrapper shim (`#!/bin/sh\nexec bun run <abs>/src/cli.ts "$@"`) works as the
+ staged binary (the fallback lane when a compiled binary is unavailable).
+- Startup timeout: per-server `startup_timeout_sec` (default 30) or global env
+ `GROK_MCP_STARTUP_TIMEOUT_SECS` (seconds) / `MCP_TIMEOUT` (ms, Claude-compatible).
+ The bun-run wrapper cold-transpiles slowly — the door sets 60+.
+
+## Saved config schema (verbatim, from a real add)
+```toml
+[mcp_servers.gbrain]
+command = "/tmp/<staged-bin>/gbrain"
+args = [
+ "serve",
+ "--surface",
+ "verbs",
+]
+enabled = true
+
+[mcp_servers.gbrain.env]
+GBRAIN_SOURCE = "workspace"
+GBRAIN_HOME = "/tmp/<brain-home>"
+```
+Full schema keys (from grok's own shipped user guide, `$GROK_HOME/docs/user-guide/`):
+`command`, `args`, `env`, `enabled` (default true), `startup_timeout_sec` (default
+30), `tool_timeout_sec` (default 6000), `tool_timeouts`.
+
+## Probes — the HONEST discriminator exists
+- **`grok mcp doctor <name> --json`**: SPAWNS the server for real. Good server →
+ **exit 0** with checks `command found` / `server started` / `handshake OK`
+ (`"detail": "protocol 2025-11-25"`) / **`7 tools discovered`** (the verbs surface's
+ seven verbs, proven keyless end-to-end). Broken server (nonexistent command) →
+ **exit 1**, check `command not found`, `passed: false`, plus a `hint`. THE door's
+ hard discriminator; the T4 doctor pre-flight gates the paid loop (plan M6 resolves
+ to the honest branch).
+- Doctor `--json` also enumerates config **sources** with per-source status —
+ `~/.grok/config.toml`, `~/.claude.json`, `.mcp.json` — and each server carries a
+ `"source"` field (`"config"`, `".mcp.json"`, …): the T2b provenance assertion reads
+ this directly.
+- `grok mcp list --json` → exit 0, array of `{command, args, env, enabled, name,
+ scope}`.
+- `grok inspect` (keyless, exit 0) shows version, CWD, `Project trusted: yes/no`,
+ instructions, permissions, skills, agents — the config-discovery audit surface.
+
+## Vendor-config fallback — TRUST-GATED (verified)
+A project `.mcp.json` in the cwd is SEEN by doctor (source `found`, server listed
+with `source: ".mcp.json"`) but the server check reports **`folder untrusted`** and
+`mcp list` shows nothing until the folder is trusted (first-run trust flow). So:
+fresh tmp HOME + fresh cwd ⇒ vendor entries structurally cannot activate (door
+provenance guarantee), and on an operator's machine the fallback only engages for
+folders they already trusted — the live-lane warning (operator `~/.claude.json`
+carrying `mcpServers.gbrain`) still applies for trusted folders.
+
+## When the door goes red (triage)
+| Failure class | Signature | Remediation |
+|---|---|---|
+| npm pin drift | install step: version/integrity mismatch | Re-pin deliberately: bump `npm_version`+`npm_integrity` stamps here, re-run the re-observation checklist below, update workflow env pins (check-grok-pin.sh enforces the pair) |
+| installer digest drift (fallback path) | `sha256sum -c` fails on install.sh | Diff the new installer, re-pin `installer_sha256` after review |
+| version drift mid-run | `grok --version` re-check ≠ pinned | Auto-update engaged — verify `[cli] auto_update = false` seeding; re-pin if a deliberate bump |
+| blank XAI_API_KEY secret | named precondition/paid-sentinel failure | Admin adds/rotates the repo Actions secret (console.x.ai origin); keyless tier still ran |
+| invalid/expired key | bad-key preflight fails (pin its message after first authed run) | Rotate the secret; no code change |
+| tripwire fired | manifest mismatch on config/credential files only | True isolation breach — stop, inspect which file changed; volatile-path drift alone must NOT fire (bug in exclusions if it does) |
+| real door regression | doctor checks or recall assert fail with pins intact | Bisect against the pinned version; file upstream if grok-side |
+
+Re-observation checklist on a version bump: re-run the npm/installer pin captures
+(§Pin), the help-surface diff (`--help`, `mcp --help`, `mcp add --help`), and the
+mcp add → saved-TOML → doctor sequence (§add/§probes). The one-shot/auth/model
+sections only need re-observation if their assertions start failing.
+
+## Keyless TUI behavior (observed via the dx-explore PTY instrument)
+Under a real PTY with no credentials, interactive `grok` plays a Braille-
+pattern intro animation (U+2800-range glyphs) for a few seconds, then settles
+(~6s) onto a SIGN-IN screen: "Approve in your browser to finish signing in"
+plus a device code (and a ctrl+c hint). There is no unattended path past it.
+Two hazards for PTY automation, both observed: the animation frames carry
+zero word-like text (3+-letter runs) — a text-presence heuristic must count
+letter runs, not enumerate glyphs; and pasting into the sign-in screen leaves
+a persistent full-screen spinner redrawing at ~5 frames/sec, which starves
+quiet-based settling and makes full-buffer ANSI stripping the hot loop
+(strip bounded raw tails instead). Headless keyless is the clean
+`Not signed in` error above. The `grok-install` dx scenario early-stops at
+the sign-in copy (or a persistently textless screen) with the friction
+recorded — that IS the keyless measurement.
+
+## Supported-version policy
+gbrain's grok integration is verified against **Grok Build v1.0.4** (this pin). The
+canary CI leg (enabled with the secret) tracks latest and is continue-on-error; the
+pinned lane is the deterministic gate. **Pending auth** (requires `XAI_API_KEY`):
+paid one-shot smoke, authed model list + per-turn cost pins, credential-file
+inventory after login (feeds evidence exclusions + TTY secretPaths), AUTHED
+first-run TUI dialog copy (the keyless TUI + headless copies are pinned above).
diff --git a/docs/mcp/GROK.md b/docs/mcp/GROK.md
new file mode 100644
index 0000000000..34d4a081ee
--- /dev/null
+++ b/docs/mcp/GROK.md
@@ -0,0 +1,155 @@
+# Connect GBrain to Grok Build
+
+> This page is the MCP-registration reference for **Grok Build** — xAI's
+> official `grok` CLI (early beta, subscriber-gated; not the community
+> `superagent-ai/grok-cli`, which ships a colliding `grok` binary — see
+> Troubleshooting). For the full brain install — CLI, engine, skills, dream
+> cycle — follow [INSTALL_FOR_AGENTS.md](../../INSTALL_FOR_AGENTS.md) first;
+> this page wires the finished brain into Grok Build over stdio MCP.
+> The `gbrain bootstrap` persistent-personal-agent path is **not yet
+> supported for Grok** (Claude Code and Codex only today) — brain-only
+> install is what this page delivers.
+
+Grok Build spawns `gbrain serve` as a local stdio subprocess. No server, no
+tunnel, no token needed. Works with both PGLite and Supabase engines.
+
+## Register (recommended)
+
+```bash
+grok mcp add gbrain -e "GBRAIN_HOME=$HOME" -- gbrain serve --surface verbs
+```
+
+`--surface verbs` exposes the seven-verb memory protocol (`recall`,
+`remember`, `entity`, `synthesize`, `forget`, `context_pack`, `delta` —
+[MEMORY_VERBS v1](../protocol/MEMORY_VERBS_v1.md)) instead of the full
+100+-op catalog — the recommended starting surface for coding agents.
+Three facts about `grok mcp add`, all observed:
+
+- **The env flag is repeatable, one `KEY=value` per flag** (`-e A=1 -e B=2`).
+ Server argv goes after `--`.
+- **Registration is lazy.** The add writes config and exits 0 without
+ connecting — even for a nonexistent command. Verify with `grok mcp doctor`
+ (below), never with the add's exit code.
+- **Scope:** the default writes to `~/.grok/config.toml`; add `-s project`
+ to write a committable `./.grok/config.toml` instead (reference secrets as
+ `${VAR}` in project scope — values are stored verbatim).
+
+## Direct config (equally supported)
+
+The add command writes an `[mcp_servers.gbrain]` block into
+`~/.grok/config.toml` (or `./.grok/config.toml` with project scope; the
+`GROK_HOME` env var relocates the user config dir). You can write it
+yourself instead:
+
+```toml
+[mcp_servers.gbrain]
+command = "gbrain"
+args = ["serve", "--surface", "verbs"]
+startup_timeout_sec = 60
+enabled = true
+
+[mcp_servers.gbrain.env]
+GBRAIN_HOME = "/home/alice-example"
+```
+
+`startup_timeout_sec` defaults to 30; raise it (or export
+`GROK_MCP_STARTUP_TIMEOUT_SECS`) if gbrain runs from source via `bun run`,
+which cold-transpiles on first spawn. To remove gbrain, delete the block (or
+set `enabled = false` to disable without losing the config).
+
+## Zero-config vendor fallback
+
+Grok Build also reads MCP registrations from `~/.claude.json`, `.cursor/mcp.json`,
+and a project `.mcp.json` — at lower priority than its own config, and **only
+for folders you have trusted** in Grok (fresh folders report
+`folder untrusted` until you accept the trust prompt). If you already
+registered gbrain for Claude Code, Grok may pick it up with zero
+configuration. `grok mcp doctor --json` reports every source it consulted
+and which one each server came from — check the `source` field to see which
+config won before assuming the native one did.
+
+## Verify
+
+```bash
+grok mcp list --json # entry: {"name":"gbrain","enabled":true,...}
+grok mcp doctor gbrain # THE real probe: spawns the server
+```
+
+`grok mcp doctor gbrain` performs the actual handshake — expect the checks
+`command found`, `server started`, `handshake OK`, and `7 tools discovered`
+(the seven verbs), exit 0. A broken registration exits 1 with a failing
+check and a hint. Then one real round-trip:
+
+```bash
+grok -p "use the gbrain recall tool to answer: what did I import most recently?"
+```
+
+`grok -p` (single-turn headless) prints the final answer on stdout.
+
+## Headless auth + model pin
+
+For cron jobs, CI, or any non-TTY run:
+
+- **Auth:** export `XAI_API_KEY` (from console.x.ai). Keyless headless runs
+ exit 1 with `Not signed in`; `grok login --device-code` is the
+ interactive-terminal alternative, `grok login` the browser one.
+- **Model pin:** pass `-m <model>` per call, or set it in config:
+
+ ```toml
+ [models]
+ default = "grok-4.5"
+ ```
+
+- **Updates:** Grok self-updates by default. For pinned/reproducible
+ environments, seed:
+
+ ```toml
+ [cli]
+ auto_update = false
+ ```
+
+## Pair with cron
+
+Grok Build has no built-in cron; schedule headless one-shots with your
+system scheduler:
+
+```bash
+# crontab: brain maintenance every 4 hours
+0 */4 * * * XAI_API_KEY=... grok -p "Run gbrain sync and report anything unusual" --output-format plain
+```
+
+See [docs/guides/cron-schedule.md](../guides/cron-schedule.md) for the full
+brain maintenance protocol (sync, embed, dream cycle).
+
+## Troubleshooting
+
+- **Wrong `grok` on PATH** — the community `superagent-ai/grok-cli` also
+ installs a `grok` binary. The official CLI answers `grok --version` with
+ `grok X.Y.Z (buildhash)`; anything else is the other tool. Install the
+ official one via `npm install -g @xai-official/grok` or
+ `curl -fsSL https://x.ai/cli/install.sh | bash`.
+- **grok ≠ groq ≠ ngrok** — Grok Build (xAI, `XAI_API_KEY`) is not Groq
+ (the inference provider, `GROQ_API_KEY`) and not ngrok (tunnels). A
+ mis-set key produces auth errors against the wrong service.
+- **`Not signed in` (exit 1)** — no auth in a headless run. Export
+ `XAI_API_KEY` or run `grok login --device-code`.
+- **Doctor says `folder untrusted`** — the registration came from a vendor
+ config (`.mcp.json` / `~/.claude.json`) in a folder Grok hasn't been told
+ to trust. Trust the folder in an interactive session, or register
+ natively with `grok mcp add`.
+- **Doctor times out on `server started`** — raise `startup_timeout_sec`
+ (or `GROK_MCP_STARTUP_TIMEOUT_SECS=90`) if gbrain runs via `bun run`.
+- **Skills note:** `gbrain skillpack scaffold` writes `skills/<name>/SKILL.md`
+ into your workspace, which Grok does **not** auto-discover as Grok skills
+ (it reads `.grok/skills`, `~/.grok/skills`, `~/.agents/skills`, plugins).
+ gbrain's skills still work as reference documents the agent reads;
+ `grok inspect` shows what Grok actually discovered.
+- **`grok inspect`** — the config-discovery audit: version, cwd trust,
+ instructions, permissions, skills, agents, MCP sources.
+
+---
+
+Verified against **Grok Build v1.0.4** (early beta — expect churn; the pin
+is enforced in CI). Dev-facing observed-behavior notes (exact flag
+semantics, exit-code caveats, config schema, CI pin values) live in
+[GROK-CLI-PIN.md](GROK-CLI-PIN.md).
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index 9ecd0f0675..ef2ef2b02c 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -64,6 +64,11 @@ If `claude` is not found: install Claude Code first, or use a block below.
codex mcp add gbrain -- gbrain serve --surface verbs
```
+**Grok Build** (verify with `grok mcp doctor gbrain` — the add is lazy)
+```bash
+grok mcp add gbrain -e "GBRAIN_HOME=$HOME" -- gbrain serve --surface verbs
+```
+
**OpenClaw / any stdio MCP host** — register the server command
`gbrain serve --surface verbs`. Remote brains: `gbrain serve --http` on the
host, then `gbrain connect https://host/mcp --token gbrain_xxx --install` on
diff --git a/llms-full.txt b/llms-full.txt
index 697632b0b4..c0b6efac98 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -1247,6 +1247,19 @@ Keep `--args` last (everything after it becomes server argv) and verify with
`hermes mcp test gbrain` — the add exits 0 even on failure. Full reference:
[docs/mcp/HERMES.md](docs/mcp/HERMES.md).
+**If you are Grok Build** (xAI's `grok` CLI): register gbrain as your MCP server:
+
+```bash
+grok mcp add gbrain -e "GBRAIN_HOME=$HOME" -- gbrain serve --surface verbs
+```
+
+The add is lazy (exit 0 without connecting) — verify with
+`grok mcp doctor gbrain`, which spawns the server and must report
+`7 tools discovered`. This is the brain-only install; the `gbrain bootstrap`
+personal-agent path does not support Grok yet (Claude Code/Codex only).
+Verified against Grok Build v1.0.4. Full reference:
+[docs/mcp/GROK.md](docs/mcp/GROK.md).
+
Whether you scaffolded or not, read `skills/RESOLVER.md` (in your workspace, or the
bundled copy at `~/gbrain/skills/RESOLVER.md` when running from the cloned repo). It's
the skill dispatcher — tells you which skill to read for any task. Save this to your
@@ -1770,6 +1783,7 @@ GBrain exposes nearly all of its 100+ operations as MCP tools (stdio and HTTP; a
- **[Codex](docs/mcp/CODEX.md)** — `gbrain connect https://your-host/mcp --token gbrain_xxx --agent codex` (or `--install`). Codex reads the bearer from `$GBRAIN_REMOTE_TOKEN` at runtime, so the token never lands in Codex config.
- **[Cursor / Windsurf / any stdio MCP client](docs/mcp/CLAUDE_CODE.md)** — same shape, add `{"command": "gbrain", "args": ["serve"]}` to your MCP config.
- **[Hermes](docs/mcp/HERMES.md)** — `printf 'Y\n' | hermes mcp add gbrain --env GBRAIN_HOME=$HOME --connect-timeout 60 --command $(which gbrain) --args serve`. Keep `--args` last, and verify with `hermes mcp test gbrain` (the add exits 0 even on failure).
+- **[Grok Build](docs/mcp/GROK.md)** — `grok mcp add gbrain -e "GBRAIN_HOME=$HOME" -- gbrain serve --surface verbs`. The add is lazy (exit 0 without connecting) — verify with `grok mcp doctor gbrain`, which spawns the server and reports `7 tools discovered`. Verified against Grok Build v1.0.4.
- **[OpenClaw](docs/mcp/OPENCLAW.md)** — the ClawHub bundle plugin registers gbrain automatically (`openclaw.plugin.json` ships in this repo), or add `{"command": "gbrain", "args": ["serve"]}` to `~/.openclaw/config.json`'s `mcpServers`.
- **[Claude Desktop (Cowork)](docs/mcp/CLAUDE_DESKTOP.md)** — Settings → Integrations → add the URL of your HTTP server. Remote only; the local `claude_desktop_config.json` does not work for remote servers.
- **[Claude Cowork (team plan)](docs/mcp/CLAUDE_COWORK.md)** — org Owner adds the connector under Organization Settings → Connectors.
@@ -4420,6 +4434,11 @@ If `claude` is not found: install Claude Code first, or use a block below.
codex mcp add gbrain -- gbrain serve --surface verbs
```
+**Grok Build** (verify with `grok mcp doctor gbrain` — the add is lazy)
+```bash
+grok mcp add gbrain -e "GBRAIN_HOME=$HOME" -- gbrain serve --surface verbs
+```
+
**OpenClaw / any stdio MCP host** — register the server command
`gbrain serve --surface verbs`. Remote brains: `gbrain serve --http` on the
host, then `gbrain connect https://host/mcp --token gbrain_xxx --install` on
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index a430be24e2..9f9fe66af8 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.45.19.0",
+ "version": "0.45.20.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"configSchema": {
diff --git a/package.json b/package.json
index 12da1ed24b..0fc60e30a2 100644
--- a/package.json
+++ b/package.json
@@ -50,6 +50,7 @@
"check:admin-scope-drift": "bash scripts/check-admin-scope-drift.sh",
"check:cli-exec": "bash scripts/check-cli-executable.sh",
"check:engine-dynamic-import": "bash scripts/check-engine-dynamic-import.sh",
+ "check:grok-pin": "bash scripts/check-grok-pin.sh",
"check:gateway-routed": "bash scripts/check-gateway-routed-no-direct-anthropic.sh",
"check:worker-pool-atomicity": "bash scripts/check-worker-pool-atomicity.sh",
"check:doc-history": "bash scripts/check-key-files-current-state.sh",
@@ -156,7 +157,7 @@
"bun": ">=1.3.10"
},
"license": "MIT",
- "version": "0.45.19.0",
+ "version": "0.45.20.0",
"overrides": {
"@hono/node-server": "^2.0.5",
"fast-uri": "^3.1.5",
diff --git a/scripts/check-grok-pin.sh b/scripts/check-grok-pin.sh
new file mode 100755
index 0000000000..24e0d17f9d
--- /dev/null
+++ b/scripts/check-grok-pin.sh
@@ -0,0 +1,125 @@
+#!/usr/bin/env bash
+# scripts/check-grok-pin.sh — grok pin consistency guard.
+#
+# GROK-CLI-PIN.md is the single observed-behavior source for the grok
+# integration; its pins fan out to the heavy-tests grok-door job env, the
+# GrokRunner argv, and the door e2e assertions. The prose rule is "update
+# together" — this guard turns the workflow half of that rule into CI:
+#
+# 1. docs/mcp/GROK-CLI-PIN.md carries a machine-stable stamp block
+# (`<!-- grok-pin: key=value -->`, one per line) including
+# distribution_kind (npm | installer).
+# 2. The grok-door job env in .github/workflows/heavy-tests.yml must carry
+# EXACTLY the pin set for the chosen distribution_kind:
+# npm: GROK_VERSION==grok_version, GROK_NPM_PACKAGE==npm_package,
+# GROK_NPM_INTEGRITY==npm_integrity; no GROK_INSTALL_SHA256.
+# installer: GROK_VERSION==grok_version,
+# GROK_INSTALL_SHA256==installer_sha256; no GROK_NPM_INTEGRITY.
+# (The pin DOC may document both — the fallback path stays written down;
+# exclusivity is about which pins the WORKFLOW actually enforces.)
+#
+# Greps are anchored to the grok-door job block so a future canary matrix leg
+# (or a second door job) cannot satisfy the check by accident.
+#
+# SKIP-GRACEFUL: missing pin doc, missing workflow, or no grok-door job yet →
+# SKIP (exit 0), matching scripts/check-bootstrap-tag.sh. Test override:
+# GBRAIN_GROK_PIN_GUARD_ROOT points file resolution at a fixture tree.
+# BSD/GNU portable (no \t escapes, no GNU-only flags).
+
+set -euo pipefail
+
+ROOT="${GBRAIN_GROK_PIN_GUARD_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
+PIN_FILE="$ROOT/docs/mcp/GROK-CLI-PIN.md"
+WORKFLOW="$ROOT/.github/workflows/heavy-tests.yml"
+
+if [ ! -f "$WORKFLOW" ]; then
+ echo "check-grok-pin: SKIP (no $WORKFLOW)"
+ exit 0
+fi
+if ! grep -q '^ grok-door:' "$WORKFLOW"; then
+ echo "check-grok-pin: SKIP (no grok-door job in heavy-tests.yml yet)"
+ exit 0
+fi
+# Once the grok-door job EXISTS, a missing pin doc is a FAILURE, not a skip —
+# deleting/renaming the doc must not silently disable the supply-chain gate.
+if [ ! -f "$PIN_FILE" ]; then
+ echo "check-grok-pin: FAIL — grok-door job exists but $PIN_FILE is missing (the pin doc is the gate's source of truth)" >&2
+ exit 1
+fi
+
+fail() {
+ echo "check-grok-pin: FAIL — $1" >&2
+ exit 1
+}
+
+# --- 1. Parse the stamp block ------------------------------------------------
+stamp() {
+ # First occurrence wins; a missing stamp yields the empty string (callers
+ # decide whether that is a failure) — the `|| true` keeps set -e/pipefail
+ # from treating grep's no-match exit as a script error.
+ { grep -E "^<!-- grok-pin: $1=" "$PIN_FILE" || true; } | head -1 \
+ | sed -e 's/^<!-- grok-pin: [a-z0-9_]*=//' -e 's/ -->$//'
+}
+
+# Duplicate stamps are drift bait (two values, which one is real?).
+dupes=$({ grep -E '^<!-- grok-pin: ' "$PIN_FILE" || true; } | sed -e 's/^<!-- grok-pin: //' -e 's/=.*$//' | sort | uniq -d)
+[ -n "$dupes" ] && fail "duplicate grok-pin stamp(s) in GROK-CLI-PIN.md: $dupes"
+
+DIST_KIND=$(stamp distribution_kind)
+GROK_VERSION_PIN=$(stamp grok_version)
+[ -n "$DIST_KIND" ] || fail "GROK-CLI-PIN.md is missing the distribution_kind stamp"
+[ -n "$GROK_VERSION_PIN" ] || fail "GROK-CLI-PIN.md is missing the grok_version stamp"
+case "$DIST_KIND" in
+ npm|installer) ;;
+ *) fail "distribution_kind stamp must be npm or installer; got '$DIST_KIND'" ;;
+esac
+
+# --- 2. Extract the grok-door job block --------------------------------------
+# Jobs sit at 2-space indent; the block ends at the next 2-space-indented key.
+job_block=$(awk '
+ /^ grok-door:/ { f = 1; print; next }
+ f && /^ [A-Za-z0-9_-]+:/ { exit }
+ f { print }
+' "$WORKFLOW")
+[ -n "$job_block" ] || fail "could not extract the grok-door job block"
+
+wf_env() {
+ # Strip either quote style: a YAML-formatter pass flipping double to single
+ # quotes must not read as pin drift.
+ { printf '%s\n' "$job_block" | grep -E "^ $1:" || true; } | head -1 \
+ | sed -e "s/^ $1:[[:space:]]*//" -e 's/^"//' -e 's/"$//' -e "s/^'//" -e "s/'\$//"
+}
+
+WF_VERSION=$(wf_env GROK_VERSION)
+WF_NPM_PACKAGE=$(wf_env GROK_NPM_PACKAGE)
+WF_NPM_INTEGRITY=$(wf_env GROK_NPM_INTEGRITY)
+WF_INSTALL_SHA=$(wf_env GROK_INSTALL_SHA256)
+
+[ -n "$WF_VERSION" ] || fail "grok-door job env is missing GROK_VERSION"
+[ "$WF_VERSION" = "$GROK_VERSION_PIN" ] || fail "GROK_VERSION drift — workflow '$WF_VERSION' vs pin-doc stamp '$GROK_VERSION_PIN' (update together; see the pin doc's re-observation checklist)"
+
+if [ "$DIST_KIND" = "npm" ]; then
+ NPM_PACKAGE_PIN=$(stamp npm_package)
+ NPM_INTEGRITY_PIN=$(stamp npm_integrity)
+ [ -n "$NPM_PACKAGE_PIN" ] || fail "distribution_kind=npm but GROK-CLI-PIN.md is missing the npm_package stamp"
+ [ -n "$NPM_INTEGRITY_PIN" ] || fail "distribution_kind=npm but GROK-CLI-PIN.md is missing the npm_integrity stamp"
+ [ -n "$WF_NPM_PACKAGE" ] || fail "distribution_kind=npm but the grok-door job env is missing GROK_NPM_PACKAGE"
+ [ -n "$WF_NPM_INTEGRITY" ] || fail "distribution_kind=npm but the grok-door job env is missing GROK_NPM_INTEGRITY"
+ [ "$WF_NPM_PACKAGE" = "$NPM_PACKAGE_PIN" ] || fail "GROK_NPM_PACKAGE drift — workflow '$WF_NPM_PACKAGE' vs stamp '$NPM_PACKAGE_PIN'"
+ [ "$WF_NPM_INTEGRITY" = "$NPM_INTEGRITY_PIN" ] || fail "GROK_NPM_INTEGRITY drift — workflow vs stamp mismatch"
+ # npm_version is a documented near-duplicate of grok_version — assert they
+ # agree so bumping one alone can never pass green.
+ NPM_VERSION_PIN=$(stamp npm_version)
+ if [ -n "$NPM_VERSION_PIN" ] && [ "$NPM_VERSION_PIN" != "$GROK_VERSION_PIN" ]; then
+ fail "npm_version stamp ($NPM_VERSION_PIN) disagrees with grok_version stamp ($GROK_VERSION_PIN) — update together"
+ fi
+ [ -z "$WF_INSTALL_SHA" ] || fail "distribution_kind=npm but the grok-door job also pins GROK_INSTALL_SHA256 — one provisioning mode only (mode exclusivity)"
+else
+ INSTALL_SHA_PIN=$(stamp installer_sha256)
+ [ -n "$INSTALL_SHA_PIN" ] || fail "distribution_kind=installer but GROK-CLI-PIN.md is missing the installer_sha256 stamp"
+ [ -n "$WF_INSTALL_SHA" ] || fail "distribution_kind=installer but the grok-door job env is missing GROK_INSTALL_SHA256"
+ [ "$WF_INSTALL_SHA" = "$INSTALL_SHA_PIN" ] || fail "GROK_INSTALL_SHA256 drift — workflow vs stamp mismatch"
+ [ -z "$WF_NPM_INTEGRITY" ] || fail "distribution_kind=installer but the grok-door job also pins GROK_NPM_INTEGRITY — one provisioning mode only (mode exclusivity)"
+fi
+
+echo "check-grok-pin: ok ($DIST_KIND mode, grok $GROK_VERSION_PIN)"
diff --git a/scripts/dx-explore.ts b/scripts/dx-explore.ts
index 52cf659899..66fa5e4c6f 100644
--- a/scripts/dx-explore.ts
+++ b/scripts/dx-explore.ts
@@ -69,6 +69,10 @@ import {
saveTranscript,
seedClaudeTuiConfig,
parseDriveCommand,
+ ptySupported,
+ redactSecrets,
+ stripAnsi,
+ MIN_REDACT_SECRET_LEN,
type TtySession,
} from '../test/helpers/tty-harness.ts';
@@ -118,11 +122,14 @@ interface CliArgs {
driveArgv: string[];
}
-/** Provider keys the hermetic base allows through; --keyless drops them. */
+/** Provider keys the hermetic base allows through; --keyless drops them.
+ * Also the redaction-map source: every non-empty value here is scrubbed
+ * from every written artifact. */
const PROVIDER_KEY_NAMES = [
'ANTHROPIC_API_KEY',
'ANTHROPIC_AUTH_TOKEN',
'OPENAI_API_KEY',
+ 'XAI_API_KEY',
'GSTACK_ANTHROPIC_API_KEY',
'GSTACK_OPENAI_API_KEY',
];
@@ -202,10 +209,25 @@ interface ScenarioCtx {
* suffixes). ALWAYS deleted at cleanup — --keep keeps transcripts and
* hermetic dirs for forensics, never credentials. */
secretPaths: string[];
+ /** Secret VALUES (name → value) redacted from every written artifact —
+ * transcripts, the live screen mirror, events.jsonl. Structural, not
+ * checklist: writes go through redactSecrets at the write site. */
+ redact: Record<string, string>;
events: Array<{ tMs: number; kind: 'input' | 'note' | 'screen'; data: string }>;
t0: number;
}
+/** Non-empty provider-key VALUES currently in the environment — the redaction
+ * map for every artifact write. */
+function buildRedactMap(): Record<string, string> {
+ const out: Record<string, string> = {};
+ for (const name of PROVIDER_KEY_NAMES) {
+ const v = process.env[name];
+ if (v && v.trim().length >= MIN_REDACT_SECRET_LEN) out[name] = v;
+ }
+ return out;
+}
+
function newCtx(args: CliArgs, needsGbrain: boolean): ScenarioCtx {
const outDir = path.resolve(
args.dir ?? path.join(REPO_ROOT, '.context', 'dx-runs', `${args.scenario}-${nowStamp()}`),
@@ -217,6 +239,7 @@ function newCtx(args: CliArgs, needsGbrain: boolean): ScenarioCtx {
keep: args.keep,
cleanups: [],
secretPaths: [],
+ redact: buildRedactMap(),
events: [],
t0: Date.now(),
};
@@ -266,7 +289,10 @@ function finishCtx(ctx: ScenarioCtx): void {
scrubSecrets(ctx);
fs.writeFileSync(
path.join(ctx.outDir, 'events.jsonl'),
- ctx.events.map((e) => JSON.stringify(e)).join('\n') + (ctx.events.length ? '\n' : ''),
+ redactSecrets(
+ ctx.events.map((e) => JSON.stringify(e)).join('\n') + (ctx.events.length ? '\n' : ''),
+ ctx.redact,
+ ),
);
if (ctx.keep && ctx.secretPaths.length > 0) {
log(`--keep: retained hermetic dirs, but scrubbed ${ctx.secretPaths.length} credential file(s)`);
@@ -290,13 +316,20 @@ function finishCtx(ctx: ScenarioCtx): void {
}
/** Live session mirror so a watcher (or a Conductor agent) can follow along:
- * session/screen.txt (latest visible tail) + session/status.json. */
-function mirrorSession(dir: string, session: TtySession): () => void {
+ * session/screen.txt (latest visible tail) + session/status.json. Each tick
+ * strips only a bounded RAW tail (a full-buffer stripAnsi every 500ms is
+ * quadratic on a 25-minute session) and redacts before writing — the mirror
+ * is a live artifact that outlives an interrupted run, so it must never
+ * carry a raw key even transiently. */
+function mirrorSession(dir: string, session: TtySession, redact?: Record<string, string>): () => void {
const sessDir = path.join(dir, 'session');
fs.mkdirSync(sessDir, { recursive: true });
const timer = setInterval(() => {
try {
- fs.writeFileSync(path.join(sessDir, 'screen.txt'), session.visible().slice(-8000));
+ fs.writeFileSync(
+ path.join(sessDir, 'screen.txt'),
+ redactSecrets(stripAnsi(session.raw().slice(-131_072)).slice(-8000), redact),
+ );
fs.writeFileSync(
path.join(sessDir, 'status.json'),
JSON.stringify(
@@ -322,6 +355,7 @@ function saveSession(ctx: ScenarioCtx, name: string, session: TtySession, extraM
saveTranscript(dir, {
frames: session.frames(),
raw: session.raw(),
+ redact: ctx.redact,
meta: {
scenario: name || path.basename(ctx.outDir),
argv: session.argv,
@@ -331,6 +365,53 @@ function saveSession(ctx: ScenarioCtx, name: string, session: TtySession, extraM
...extraMeta,
},
});
+ assertNoSecrets(dir, ctx.redact, ctx.t0);
+}
+
+/** Independent double-check of the structural redaction above: grep every
+ * written artifact for each raw secret value and HARD-FAIL on a hit (delete
+ * the leaking file, mark the run failed). A leak here means redactSecrets
+ * missed a rendering (e.g. ANSI-interleaved) — that is a bug to fix, never
+ * a warning to scroll past. */
+function assertNoSecrets(dir: string, redact: Record<string, string>, sinceMs: number): void {
+ const values = Object.entries(redact).filter(([, v]) => v && v.length >= MIN_REDACT_SECRET_LEN);
+ if (values.length === 0) return;
+ const walk = (d: string): string[] =>
+ fs.readdirSync(d, { withFileTypes: true }).flatMap((e) => {
+ const p = path.join(d, e.name);
+ return e.isDirectory() ? walk(p) : e.isFile() ? [p] : [];
+ });
+ let leaked = false;
+ for (const file of walk(dir)) {
+ // NEVER touch files that predate this run: --dir can point anywhere
+ // (repo root, even $HOME) and deleting a pre-existing .env that happens
+ // to contain the key would be data loss, not leak containment.
+ try { if (fs.statSync(file).mtimeMs < sinceMs - 1000) continue; } catch { continue; }
+ let body: string;
+ try { body = fs.readFileSync(file, 'utf8'); } catch { continue; }
+ // Joined-data pass for frame records: a secret split across JSONL
+ // records never appears contiguously in the file body.
+ let joinedData = '';
+ if (file.endsWith('.jsonl')) {
+ for (const line of body.split('\n')) {
+ try { joinedData += String(JSON.parse(line)?.data ?? ''); } catch { /* not a data record */ }
+ }
+ }
+ for (const [name, value] of values) {
+ const hit =
+ body.includes(value) ||
+ stripAnsi(body).includes(value) || // ANSI-interleaved rendering
+ (joinedData !== '' && (joinedData.includes(value) || stripAnsi(joinedData).includes(value)));
+ if (hit) {
+ leaked = true;
+ fs.rmSync(file, { force: true });
+ log(`SECRET LEAK: ${file} contained ${name} despite structural redaction — file deleted; fix redactSecrets coverage before trusting transcripts`);
+ }
+ }
+ }
+ if (leaked) {
+ process.exitCode = 1;
+ }
}
// ── scenario: help ───────────────────────────────────────────────────────────
@@ -376,7 +457,7 @@ async function scenarioInit(ctx: ScenarioCtx, args: CliArgs): Promise<void> {
dropEnv: args.keyless ? PROVIDER_KEY_NAMES : undefined,
timeoutMs: 600_000,
});
- const stopMirror = mirrorSession(ctx.outDir, session);
+ const stopMirror = mirrorSession(ctx.outDir, session, ctx.redact);
const steps: string[] = [];
let lastMarkPos = 0;
@@ -429,7 +510,10 @@ async function settlePastBootDialogs(
while (Date.now() < deadline) {
await session.waitForQuiet({ quietMs: 2000, timeoutMs: 30_000 });
if (session.exited()) return;
- const tail = session.visible().slice(-2500);
+ // Bounded strip: a repaint-heavy TUI (observed: grok's splash animation)
+ // grows the raw buffer by MBs — stripping the FULL buffer every
+ // iteration is the quadratic hot loop; strip a raw tail instead.
+ const tail = stripAnsi(session.raw().slice(-131_072)).slice(-2500);
if (!handled.has('trust') && /trust this ?folder/i.test(tail.replace(/\s+/g, ' '))) {
handled.add('trust');
event(ctx, 'note', 'boot dialog: workspace trust — accepted (option 1)');
@@ -456,10 +540,120 @@ async function settlePastBootDialogs(
session.sendKey('Enter');
continue;
}
+ // Grok Build sign-in screen (observed keyless copy: "Not signed in").
+ // No unattended path exists past it — record the friction and stop
+ // settling; the caller's wall clock must not burn on a login dialog.
+ if (/not signed in/i.test(tail)) {
+ event(ctx, 'note', 'boot dialog: grok sign-in required — no unattended path; stopping settle');
+ return;
+ }
+ // Quiet with no KNOWN dialog: if the tail still LOOKS like a prompt
+ // (numbered options / y-n / picker glyph), note it — a silently
+ // mis-settled boot is otherwise invisible in the audit trail.
+ if (/(?:^|\n)\s*(?:\d+\.\s|[❯›]\s)|\((?:y\/n|Y\/n)\)/m.test(tail.slice(-400))) {
+ event(ctx, 'note', 'settle: quiet with an unmatched dialog-shaped tail — proceeding (note-only; check the transcript if the paste lands oddly)');
+ }
return; // quiet + no dialog = at the input prompt
}
}
+/** Stage the compiled gbrain into a fresh bin dir (PATH-prepend target) so
+ * the agent's bare `gbrain` runs this checkout. */
+function stageBinDir(ctx: ScenarioCtx): string {
+ const binDir = tmp(ctx, 'gb-dx-bin-');
+ fs.copyFileSync(ctx.gbrainBin, path.join(binDir, 'gbrain'));
+ fs.chmodSync(path.join(binDir, 'gbrain'), 0o755);
+ return binDir;
+}
+
+interface InstallSessionOpts {
+ argv: string[];
+ cwd: string;
+ env: Record<string, string | undefined>;
+ extraAllow?: string[];
+ dropEnv?: string[];
+ /** The pasted prompt. Per-agent: the bootstrap runbook block for
+ * claude/codex, a brain-only GROK.md-driven block for grok. */
+ prompt: string;
+ /** Success copy to race against (default: the bootstrap verify patterns).
+ * Brain-only scenarios pass their own — grok's is the doctor banner. */
+ successPatterns?: Array<RegExp | string>;
+ timeoutMs?: number;
+ meta: Record<string, unknown>;
+}
+
+/** The shared install-session tail the claude/codex/grok scenarios all run:
+ * launch → mirror → settle boot dialogs → paste the prompt → race
+ * verify-success copy vs exit → let trailing output land → save. Per-agent
+ * PREPARATION (TUI seeds, auth copies, git init) deliberately stays in each
+ * scenario — the loop is what was duplicated, the prep genuinely differs. */
+async function runInstallSession(ctx: ScenarioCtx, opts: InstallSessionOpts): Promise<void> {
+ const timeoutMs = opts.timeoutMs ?? 1_800_000;
+ let earlyTerminal: string | undefined;
+ log(`watch live: cat ${path.join(ctx.outDir, 'session', 'screen.txt')}`);
+ const session = launchTty(opts.argv, {
+ cwd: opts.cwd,
+ env: opts.env,
+ extraAllow: opts.extraAllow,
+ dropEnv: opts.dropEnv,
+ timeoutMs,
+ });
+ const stopMirror = mirrorSession(ctx.outDir, session, ctx.redact);
+ try {
+ await settlePastBootDialogs(ctx, session);
+ // Sign-in wall / textless splash: no unattended path exists past either.
+ // Observed (grok v1.0.4 keyless): headless prints "Not signed in"; the
+ // TUI loops a full-screen glyph animation with NO textual prompt for 8+
+ // minutes. Try one Enter (the common skip-splash gesture), then if the
+ // screen still carries no meaningful text — or shows the sign-in copy —
+ // record the friction (that IS the keyless measurement) and end early
+ // instead of pasting into a wall for the full wall clock.
+ const tailText = () => stripAnsi(session.raw().slice(-131_072)).slice(-2500);
+ // Sign-in copy, both surfaces observed (GROK-CLI-PIN.md): headless prints
+ // "Not signed in"; the TUI settles (~6s, after an intro animation) onto
+ // "Approve in your browser to finish signing in" + a device code.
+ const signInWall = () =>
+ /not signed in|approve in your browser|finish signing in|sign in with/i.test(tailText());
+ // Word-like text only: splash/spinner screens render Braille-pattern
+ // glyphs (U+2800 range, observed) with scattered digits/SGR residue but
+ // ZERO 3+-letter runs, while any real prompt/sign-in screen carries
+ // words. Counting letter runs beats enumerating glyph exceptions.
+ const meaningfulLen = (s: string) => (s.match(/[A-Za-z]{3,}/g) ?? []).join('').length;
+ if (!session.exited() && (signInWall() || meaningfulLen(tailText()) < 40)) {
+ event(ctx, 'note', 'sign-in wall or textless splash — sending one Enter (skip-splash attempt)');
+ session.sendKey('Enter');
+ await Bun.sleep(3000);
+ if (!session.exited() && (signInWall() || meaningfulLen(tailText()) < 40)) {
+ event(ctx, 'note', 'sign-in wall / no textual prompt persists — ending session early (keyless friction recorded)');
+ earlyTerminal = 'sign-in-wall-or-splash';
+ return; // finally owns cleanup; save happens after it
+ }
+ }
+ event(ctx, 'input', 'paste install prompt');
+ // Scope the verify match to output AFTER the paste: the pasted prompt
+ // itself contains verify-adjacent copy, and matching the full buffer
+ // re-scans a growing transcript every poll.
+ const pasteMark = session.mark();
+ session.send(opts.prompt);
+ await Bun.sleep(1500);
+ session.sendKey('Enter');
+ const raceBudget = Math.max(timeoutMs - 300_000, Math.floor(timeoutMs * 0.8));
+ const done = await Promise.race([
+ session
+ .waitForAny(opts.successPatterns ?? VERIFY_SUCCESS_PATTERNS, { timeoutMs: raceBudget, since: pasteMark })
+ .then(() => 'verify-signal')
+ .catch(() => 'no-signal'),
+ session.waitForExit(raceBudget).then(() => 'exited'),
+ ]);
+ event(ctx, 'note', `terminal condition: ${done}`);
+ await session.waitForQuiet({ quietMs: 5000, timeoutMs: 60_000 });
+ } finally {
+ stopMirror();
+ await session.close();
+ }
+ saveSession(ctx, '', session, earlyTerminal ? { ...opts.meta, terminal: earlyTerminal } : opts.meta);
+}
+
/** The README paste block, pointed at THIS repo's runbook, plus a persona
* appendix so the interview completes unattended. The appendix is the ONLY
* deviation from the shipped block — flagged in meta so the audit discounts it. */
@@ -481,14 +675,12 @@ function installPrompt(): string {
);
}
-async function scenarioClaudeInstall(ctx: ScenarioCtx): Promise<void> {
+async function scenarioClaudeInstall(ctx: ScenarioCtx, args: CliArgs): Promise<void> {
const home = tmp(ctx, 'gb-dx-home-');
const cfg = tmp(ctx, 'gb-dx-ccfg-');
const gbHome = tmp(ctx, 'gb-dx-gbhome-');
const ws = tmp(ctx, 'gb-dx-ws-');
- const binDir = tmp(ctx, 'gb-dx-bin-');
- fs.copyFileSync(ctx.gbrainBin, path.join(binDir, 'gbrain'));
- fs.chmodSync(path.join(binDir, 'gbrain'), 0o755);
+ const binDir = stageBinDir(ctx);
seedClaudeTuiConfig(cfg, {
apiKey: process.env.ANTHROPIC_API_KEY ?? process.env.GSTACK_ANTHROPIC_API_KEY,
@@ -501,61 +693,33 @@ async function scenarioClaudeInstall(ctx: ScenarioCtx): Promise<void> {
ctx.secretPaths.push(path.join(cfg, '.claude.json'));
log('REAL interactive claude running the paste-in bootstrap (10-25 min, real API cost)');
- log(`watch live: cat ${path.join(ctx.outDir, 'session', 'screen.txt')}`);
- const session = launchTty(
- // --dangerously-skip-permissions: v1 measures flow + copy + stalls without
- // permission-dialog babysitting. Permission-prompt COUNT is a separate
- // drive-mode pass (the dialogs are Claude Code's chrome, not gbrain copy).
- ['claude', '--dangerously-skip-permissions'],
- {
- cwd: ws,
- env: {
- HOME: home,
- CLAUDE_CONFIG_DIR: cfg,
- GBRAIN_HOME: gbHome,
- PATH: `${binDir}:${process.env.PATH ?? ''}`,
- },
- timeoutMs: 1_800_000,
+ await runInstallSession(ctx, {
+ // dangerously-skip-permissions (spelled dash-free here): v1 measures flow
+ // + copy + stalls without permission-dialog babysitting. Permission-prompt
+ // COUNT is a separate drive-mode pass (the dialogs are Claude Code's
+ // chrome, not gbrain copy).
+ argv: ['claude', '--dangerously-skip-permissions'],
+ cwd: ws,
+ env: {
+ HOME: home,
+ CLAUDE_CONFIG_DIR: cfg,
+ GBRAIN_HOME: gbHome,
+ PATH: `${binDir}:${process.env.PATH ?? ''}`,
+ },
+ dropEnv: args.keyless ? PROVIDER_KEY_NAMES : undefined,
+ prompt: installPrompt(),
+ meta: {
+ promptDeviation: 'unattended persona appendix + local runbook path + preinstalled binary',
+ runbook: 'BOOTSTRAP_FOR_AGENTS.md (local)',
},
- );
- const stopMirror = mirrorSession(ctx.outDir, session);
- try {
- // Get past first-run chrome (trust dialog, bypass warning), then paste.
- await settlePastBootDialogs(ctx, session);
- event(ctx, 'input', 'paste install prompt');
- session.send(installPrompt());
- await Bun.sleep(1500);
- session.sendKey('Enter');
- // Run until verify-success copy or exit or wall clock.
- const done = await Promise.race([
- session
- .waitForAny(VERIFY_SUCCESS_PATTERNS, {
- timeoutMs: 1_500_000,
- })
- .then(() => 'verify-signal')
- .catch(() => 'no-signal'),
- session.waitForExit(1_500_000).then(() => 'exited'),
- ]);
- event(ctx, 'note', `terminal condition: ${done}`);
- // Let trailing output land.
- await session.waitForQuiet({ quietMs: 5000, timeoutMs: 60_000 });
- } finally {
- stopMirror();
- await session.close();
- }
- saveSession(ctx, '', session, {
- promptDeviation: 'unattended persona appendix + local runbook path + preinstalled binary',
- runbook: 'BOOTSTRAP_FOR_AGENTS.md (local)',
});
}
-async function scenarioCodexInstall(ctx: ScenarioCtx): Promise<void> {
+async function scenarioCodexInstall(ctx: ScenarioCtx, args: CliArgs): Promise<void> {
const home = tmp(ctx, 'gb-dx-home-');
const gbHome = tmp(ctx, 'gb-dx-gbhome-');
const ws = tmp(ctx, 'gb-dx-ws-');
- const binDir = tmp(ctx, 'gb-dx-bin-');
- fs.copyFileSync(ctx.gbrainBin, path.join(binDir, 'gbrain'));
- fs.chmodSync(path.join(binDir, 'gbrain'), 0o755);
+ const binDir = stageBinDir(ctx);
// Hermetic ~/.codex with ONLY the operator's auth (same posture as the
// codex door test). codex refuses untrusted cwds — a git repo satisfies it.
@@ -573,46 +737,99 @@ async function scenarioCodexInstall(ctx: ScenarioCtx): Promise<void> {
spawnSync('git', ['-C', ws, 'config', 'user.name', 'DX Explore']);
log('REAL interactive codex running the paste-in bootstrap (10-25 min, real API cost)');
- log(`watch live: cat ${path.join(ctx.outDir, 'session', 'screen.txt')}`);
- const session = launchTty(
- ['codex', '--sandbox', 'workspace-write', '--ask-for-approval', 'never'],
- {
- cwd: ws,
- env: {
- HOME: home,
- CODEX_HOME: codexHome,
- GBRAIN_HOME: gbHome,
- PATH: `${binDir}:${process.env.PATH ?? ''}`,
- },
- extraAllow: ['OPENAI_API_KEY', 'CODEX_*'],
- timeoutMs: 1_800_000,
+ await runInstallSession(ctx, {
+ argv: ['codex', '--sandbox', 'workspace-write', '--ask-for-approval', 'never'],
+ cwd: ws,
+ env: {
+ HOME: home,
+ CODEX_HOME: codexHome,
+ GBRAIN_HOME: gbHome,
+ PATH: `${binDir}:${process.env.PATH ?? ''}`,
+ },
+ extraAllow: ['OPENAI_API_KEY', 'CODEX_*'],
+ dropEnv: args.keyless ? PROVIDER_KEY_NAMES : undefined,
+ prompt: installPrompt(),
+ meta: {
+ promptDeviation: 'unattended persona appendix + local runbook path + preinstalled binary',
+ runbook: 'BOOTSTRAP_FOR_AGENTS.md (local)',
},
+ });
+}
+
+// ── scenario: grok-install ───────────────────────────────────────────────────
+
+/** Brain-only success copy for the grok scenario: the doctor banner proves
+ * the registration handshook (observed, docs/mcp/GROK-CLI-PIN.md) — grok has
+ * NO bootstrap path, so the bootstrap verify patterns must not be its bar. */
+const GROK_INSTALL_SUCCESS_PATTERNS: Array<RegExp | string> = [
+ /7 tools discovered/i,
+ /handshake OK/i,
+];
+
+/** GROK.md-driven brain-only prompt — deliberately NOT the bootstrap paste
+ * block: the docs classify grok as brain-only install (no `gbrain bootstrap`
+ * support), so the scenario must not test an unsupported flow. */
+function grokInstallPrompt(): string {
+ const guide = path.join(REPO_ROOT, 'docs', 'mcp', 'GROK.md');
+ return (
+ `Read and follow: ${guide}\n` +
+ `Goal: wire the gbrain memory brain into you (Grok Build) over stdio MCP — ` +
+ `brain-only install, no bootstrap. Steps: ` +
+ `1) run \`gbrain init --pglite --no-embedding --non-interactive\`; ` +
+ `2) register gbrain exactly as the guide's Register section shows; ` +
+ `3) verify with \`grok mcp doctor gbrain\` — you are not done until it reports ` +
+ `the tools-discovered check passing; ` +
+ `4) one recall round-trip: use the gbrain remember tool to store ` +
+ `"${PERSONA.AGENT_NAME} prefers ${PERSONA.VOICE_REGISTER}" and then recall it.\n\n` +
+ `[Unattended-run appendix — I am stepping away; do not wait for my input. ` +
+ `gbrain is already installed and on PATH. If a step needs auth that is ` +
+ `unavailable, note the exact error and stop.]`
);
- const stopMirror = mirrorSession(ctx.outDir, session);
- try {
- await settlePastBootDialogs(ctx, session);
- event(ctx, 'input', 'paste install prompt');
- session.send(installPrompt());
- await Bun.sleep(1500);
- session.sendKey('Enter');
- const done = await Promise.race([
- session
- .waitForAny(VERIFY_SUCCESS_PATTERNS, {
- timeoutMs: 1_500_000,
- })
- .then(() => 'verify-signal')
- .catch(() => 'no-signal'),
- session.waitForExit(1_500_000).then(() => 'exited'),
- ]);
- event(ctx, 'note', `terminal condition: ${done}`);
- await session.waitForQuiet({ quietMs: 5000, timeoutMs: 60_000 });
- } finally {
- stopMirror();
- await session.close();
- }
- saveSession(ctx, '', session, {
- promptDeviation: 'unattended persona appendix + local runbook path + preinstalled binary',
- runbook: 'BOOTSTRAP_FOR_AGENTS.md (local)',
+}
+
+async function scenarioGrokInstall(ctx: ScenarioCtx, args: CliArgs): Promise<void> {
+ const home = tmp(ctx, 'gb-dx-home-');
+ const gbHome = tmp(ctx, 'gb-dx-gbhome-');
+ const ws = tmp(ctx, 'gb-dx-ws-');
+ const binDir = stageBinDir(ctx);
+
+ // Hermetic ~/.grok seeded with the auto-update kill-switch (config-only
+ // mechanism, default ON — observed v1.0.4). Auth travels via XAI_API_KEY
+ // env only; grok MAY persist derived credentials after an authed session,
+ // so the known candidate is pre-registered for the scrub (rm of a file
+ // that never appears is a no-op).
+ const grokHome = path.join(home, '.grok');
+ fs.mkdirSync(grokHome, { recursive: true });
+ // Verbatim kill-switch homes (update together): seedGrokConfig in
+ // test/helpers/agent-harness.ts and the grok-door auth-preflight printf
+ // in .github/workflows/heavy-tests.yml.
+ fs.writeFileSync(path.join(grokHome, 'config.toml'), '[cli]\nauto_update = false\n');
+ ctx.secretPaths.push(path.join(grokHome, 'mcp_credentials.json'));
+
+ log('REAL interactive grok running the GROK.md brain-only install (real API cost when authed)');
+ log('keyless runs stop at the observed sign-in screen — that friction IS the measurement');
+ await runInstallSession(ctx, {
+ argv: ['grok'],
+ cwd: ws,
+ env: {
+ HOME: home,
+ GROK_HOME: grokHome,
+ GBRAIN_HOME: gbHome,
+ PATH: `${binDir}:${process.env.PATH ?? ''}`,
+ // Never let a keyless first-run bounce the OPERATOR's browser for
+ // sign-in; the settle loop stops at the observed "Not signed in" copy.
+ BROWSER: '/usr/bin/false',
+ },
+ extraAllow: ['XAI_API_KEY'],
+ // --keyless drops provider keys AFTER extraAllow re-admission — a keyless
+ // grok-install must measure the sign-in wall, not silently run authed.
+ dropEnv: args.keyless ? PROVIDER_KEY_NAMES : undefined,
+ prompt: grokInstallPrompt(),
+ successPatterns: GROK_INSTALL_SUCCESS_PATTERNS,
+ meta: {
+ promptDeviation: 'unattended appendix + local GROK.md path + preinstalled binary',
+ runbook: 'docs/mcp/GROK.md (local, brain-only — grok has no bootstrap path)',
+ },
});
}
@@ -650,7 +867,7 @@ async function scenarioDrive(ctx: ScenarioCtx, args: CliArgs): Promise<void> {
env,
timeoutMs: 3_600_000,
});
- const stopMirror = mirrorSession(ctx.outDir, session);
+ const stopMirror = mirrorSession(ctx.outDir, session, ctx.redact);
let offset = 0;
let stopping = false;
@@ -701,10 +918,15 @@ const SCENARIOS: Record<string, { needsGbrain: boolean; run: (ctx: ScenarioCtx,
init: { needsGbrain: true, run: scenarioInit },
'claude-install': { needsGbrain: true, run: scenarioClaudeInstall },
'codex-install': { needsGbrain: true, run: scenarioCodexInstall },
+ 'grok-install': { needsGbrain: true, run: scenarioGrokInstall },
drive: { needsGbrain: true, run: scenarioDrive },
};
async function main(): Promise<void> {
+ if (!ptySupported()) {
+ log('this Bun lacks PTY (terminal:) support — upgrade Bun (engines.bun in package.json) before running dx scenarios');
+ process.exit(2);
+ }
const args = parseArgs(process.argv.slice(2));
const scenario = SCENARIOS[args.scenario];
if (!scenario) {
diff --git a/scripts/guards-manifest.tsv b/scripts/guards-manifest.tsv
index 7b0f0585b5..2f11caa95b 100644
--- a/scripts/guards-manifest.tsv
+++ b/scripts/guards-manifest.tsv
@@ -60,3 +60,4 @@ check-wasm-embedded.sh buildfresh exempt binary embed check
check-bootstrap-tag.sh repostate exempt VERSION stamp drift check
check-cli-executable.sh repostate exempt file-mode check
check-no-tracked-symlinks.sh repostate exempt git index state check
+check-grok-pin.sh repostate exempt pin-stamp drift check (GROK-CLI-PIN.md stamps vs heavy-tests grok-door env); own bun guard tests in test/check-bootstrap-guards.test.ts
diff --git a/scripts/run-e2e.sh b/scripts/run-e2e.sh
index 915851fdfe..00f4c1d1d0 100755
--- a/scripts/run-e2e.sh
+++ b/scripts/run-e2e.sh
@@ -86,11 +86,12 @@ mkdir -p "$E2E_TMP_HOME/.gbrain"
# (not an allowlist rebuild), so PATH, HOME, TMPDIR, CI, DATABASE_URL, and bun
# internals survive untouched. We keep GBRAIN_HOME (just set above for HOME
# isolation); everything else GBRAIN_* is an operator override the suite must
-# not inherit — which also scrubs GBRAIN_REAL_HERMES_E2E, so the paid hermes
-# door suite structurally cannot fire under this runner (its venue is
-# heavy-tests.yml's direct bun test). Adapts GStack's buildHermeticEnv()
-# allowlist to gbrain's shell E2E runner.
-for _e2e_var in $(env | grep -oE '^(CONDUCTOR_|MCP_|OPENCLAW_|HERMES_|GBRAIN_)[A-Za-z0-9_]*' | sort -u); do
+# not inherit — which also scrubs GBRAIN_REAL_HERMES_E2E and
+# GBRAIN_REAL_GROK_E2E, so the paid hermes/grok door suites structurally
+# cannot fire under this runner (their venue is heavy-tests.yml's direct bun
+# test). GROK_ also drops an operator's GROK_BIN/GROK_HOME. Adapts GStack's
+# buildHermeticEnv() allowlist to gbrain's shell E2E runner.
+for _e2e_var in $(env | grep -oE '^(CONDUCTOR_|MCP_|OPENCLAW_|HERMES_|GROK_|GBRAIN_)[A-Za-z0-9_]*' | sort -u); do
case "$_e2e_var" in
GBRAIN_HOME) ;; # required for HOME isolation (set above) — keep
GBRAIN_TEST_ALLOW_DATABASE_URL) ;; # #3485 preload opt-in (set above) — keep
diff --git a/scripts/run-verify-parallel.sh b/scripts/run-verify-parallel.sh
index 322fbded2b..b2554392be 100755
--- a/scripts/run-verify-parallel.sh
+++ b/scripts/run-verify-parallel.sh
@@ -68,6 +68,7 @@ CHECKS=(
"check:no-double-retry"
"check:batch-audit-site"
"check:engine-dynamic-import"
+ "check:grok-pin"
"check:worker-lock-renewal-shape"
"check:bootstrap-tag"
"check:bootstrap-templates"
diff --git a/src/commands/claw-test.ts b/src/commands/claw-test.ts
index c37cbc9e59..da024e4357 100644
--- a/src/commands/claw-test.ts
+++ b/src/commands/claw-test.ts
@@ -28,11 +28,13 @@ import { parseProgressEvents, verifyExpectedPhases } from '../core/claw-test/pro
import { resolveAgentRunner, listRegisteredAgents, registerAgentRunner, validateBinPathEnv } from '../core/claw-test/agent-runner.ts';
import { OpenClawRunner } from '../core/claw-test/runners/openclaw.ts';
import { HermesRunner } from '../core/claw-test/runners/hermes.ts';
+import { GrokRunner } from '../core/claw-test/runners/grok.ts';
import { createTranscriptSink } from '../core/claw-test/transcript-capture.ts';
// Ensure built-in runners are registered.
registerAgentRunner('openclaw', () => new OpenClawRunner());
registerAgentRunner('hermes', () => new HermesRunner());
+registerAgentRunner('grok', () => new GrokRunner());
interface HarnessOpts {
scenario: string;
@@ -412,6 +414,9 @@ async function runScripted(
const AGENT_INSTALL_HINTS: Record<string, string> = {
openclaw: 'install openclaw or set OPENCLAW_BIN',
hermes: 'install hermes (https://hermes-agent.nousresearch.com) or set HERMES_BIN',
+ // Official xAI CLI only — the community superagent-ai grok-cli ships a
+ // colliding `grok` binary (docs/mcp/GROK-CLI-PIN.md).
+ grok: 'install grok (npm: @xai-official/grok, or https://x.ai/cli/install.sh) or set GROK_BIN',
};
/**
@@ -998,5 +1003,6 @@ Examples:
gbrain claw-test --scenario fresh-install
gbrain claw-test --scenario upgrade-from-v0.18 --keep-tempdir
gbrain claw-test --live --agent openclaw
- gbrain claw-test --live --agent hermes`);
+ gbrain claw-test --live --agent hermes
+ gbrain claw-test --live --agent grok`);
}
diff --git a/src/core/claw-test/agent-runner.ts b/src/core/claw-test/agent-runner.ts
index e07ab950aa..b39dfa125c 100644
--- a/src/core/claw-test/agent-runner.ts
+++ b/src/core/claw-test/agent-runner.ts
@@ -1,8 +1,9 @@
/**
* AgentRunner — pluggable contract for invoking external agents (openclaw,
- * hermes, codex, …) inside the claw-test harness. Two implementations ship
- * (openclaw, hermes); the interface stays narrow and concrete so adding
- * another runner is a ~100-line file.
+ * hermes, grok, …) inside the claw-test harness. Three implementations ship
+ * (openclaw, hermes, grok); the interface stays narrow and concrete — with
+ * the shared detect/env helpers below, adding another runner is a ~50-line
+ * file plus one registerAgentRunner line.
*
* The harness wraps spawn/timeout/transcript-capture; runners only have to
* answer "where's your binary?" and "how do I invoke it with this prompt?".
@@ -15,6 +16,9 @@
* └────────────────────┘
*/
+import { execFileSync } from 'child_process';
+import { statSync } from 'fs';
+
export interface AgentRunner {
/** Stable agent name used by --agent flag and friction `agent` field. */
readonly name: string;
@@ -126,6 +130,67 @@ export function validateBinPathEnv(envName: string, p: string): string | null {
return null;
}
+/**
+ * Shared binary resolution for runners: `$<envName>` (validated) > `which
+ * <binName>` > unavailable, then a regular-file + executable-bit stat. The
+ * three runners previously carried byte-identical copies of this body; the
+ * extraction is behavior-preserving (same reason strings, same ordering).
+ */
+export function detectBinary(envName: string, binName: string): DetectResult {
+ const fromEnv = process.env[envName]?.trim();
+ let binPath: string | undefined;
+
+ if (fromEnv) {
+ const validation = validateBinPathEnv(envName, fromEnv);
+ if (validation) return { available: false, reason: validation };
+ binPath = fromEnv;
+ } else {
+ try {
+ // execFileSync, not a shell string: binName comes from callers today
+ // (constants), but this helper is exported — interpolating it into a
+ // shell would make a future metachar-bearing name become code.
+ const out = execFileSync('which', [binName], { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'] });
+ const found = out.trim();
+ if (!found || !found.startsWith('/')) {
+ return { available: false, reason: `${binName} not on PATH` };
+ }
+ binPath = found;
+ } catch {
+ return { available: false, reason: `${binName} not on PATH` };
+ }
+ }
+
+ if (!binPath) return { available: false, reason: 'no binary resolved' };
+
+ try {
+ const s = statSync(binPath);
+ if (!s.isFile()) return { available: false, reason: `not a regular file: ${binPath}` };
+ // eslint-disable-next-line no-bitwise
+ if (!(s.mode & 0o111)) return { available: false, reason: `not executable: ${binPath}` };
+ } catch (e) {
+ return { available: false, reason: `stat failed: ${e instanceof Error ? e.message : String(e)}` };
+ }
+
+ return { available: true, binPath };
+}
+
+/**
+ * Build the child env for a runner spawn: process.env filtered to the
+ * runner's allowlist, then caller overrides merged on top (overrides win —
+ * the live lane's PATH-shim prepend depends on this precedence).
+ */
+export function filterAllowlistEnv(
+ allowlist: readonly string[],
+ overrides: Record<string, string>,
+): Record<string, string> {
+ const baseEnv: Record<string, string> = {};
+ for (const key of allowlist) {
+ const v = process.env[key];
+ if (typeof v === 'string') baseEnv[key] = v;
+ }
+ return { ...baseEnv, ...overrides };
+}
+
// ---------------------------------------------------------------------------
// Registry
// ---------------------------------------------------------------------------
diff --git a/src/core/claw-test/runners/grok.ts b/src/core/claw-test/runners/grok.ts
new file mode 100644
index 0000000000..a3fec81189
--- /dev/null
+++ b/src/core/claw-test/runners/grok.ts
@@ -0,0 +1,155 @@
+/**
+ * Grok runner — invokes the real `grok` binary (xAI Grok Build CLI) in a
+ * tempdir with a BRIEF.md prompt. Live mode only.
+ *
+ * Invocation pattern (verified against a pinned local install, v1.0.4 —
+ * see docs/mcp/GROK-CLI-PIN.md):
+ * grok -p "<brief>" --output-format plain
+ *
+ * The p flag ("single") is Grok Build's headless one-shot: prompt in, final
+ * response text on stdout, exit. We deliberately do NOT pass grok's cwd flag
+ * — `spawnWithCapture` already sets `cwd`. `opts.agentName` is unused: the
+ * one-shot mode targets the default agent. The permission posture
+ * ("always-approve" / "permission-mode", both spelled dash-free here on
+ * purpose) is deliberately NOT passed until the authed observation proves it
+ * required for headless MCP tool calls — GROK-CLI-PIN.md marks that item
+ * pending auth; revisit after the first authed live run.
+ *
+ * Naming: grok (xAI, XAI_API_KEY) is not groq (Groq Inc. inference recipe,
+ * GROQ_API_KEY) and not ngrok (tunnels).
+ *
+ * Hermeticity posture (deliberate): live mode runs the OPERATOR's configured
+ * Grok — the real ~/.grok (auth, model settings, trusted folders) is
+ * inherited unless GROK_HOME points elsewhere — against a hermetic BRAIN.
+ * Grok-specific contamination channel (observed): grok reads VENDOR MCP
+ * configs — ~/.claude.json and project .mcp.json — for folders the operator
+ * has trusted. If the operator's ~/.claude.json registers gbrain, a live-lane
+ * grok turn in a trusted folder can bind the operator's REAL brain while the
+ * oracle probes the hermetic one. `invoke()` logs a loud warning when it
+ * detects that case; the fully hermetic lane is the door e2e
+ * (install-real-grok.serial.test.ts), where fresh HOME + cwd make vendor
+ * fallback structurally impossible (entries show "folder untrusted").
+ * Also observed: grok loads .envrc from the cwd by default — live-mode
+ * workspaces are harness-created tempdirs, so no operator .envrc is in reach.
+ *
+ * Binary resolution: $GROK_BIN > `which grok` > unavailable.
+ * Path validation: must be absolute, must be executable, no '..' segments.
+ * Collision note: the community superagent-ai grok-cli ships a colliding
+ * `grok` binary; the official one is identified by its version output shape
+ * `grok X.Y.Z (buildhash)` — the live lane writes a version preamble into
+ * the transcript so a mis-bound binary is diagnosable from the transcript.
+ */
+
+import { execFileSync } from 'child_process';
+import { existsSync, readFileSync } from 'fs';
+import { join } from 'path';
+import {
+ BASE_ENV_ALLOWLIST,
+ detectBinary,
+ filterAllowlistEnv,
+ type AgentRunner,
+ type DetectResult,
+ type InvokeOpts,
+ type InvokeResult,
+} from '../agent-runner.ts';
+import { spawnWithCapture } from '../transcript-capture.ts';
+
+/**
+ * Allow-list for env propagation when spawning grok. Delta from the shared
+ * base: GROK_HOME, so callers (door e2e, dx scenarios) can point Grok at an
+ * isolated home instead of the operator's real ~/.grok; and XAI_API_KEY,
+ * grok's documented headless auth path (keyless one-shot exits 1 with
+ * "Not signed in" — see docs/mcp/GROK-CLI-PIN.md) — an operator who auths
+ * via that env var would otherwise be blamed as an agent failure.
+ * FOREIGN provider keys are removed from the base: grok is single-provider
+ * (xAI) — forwarding the operator's Anthropic/OpenAI credentials to a
+ * third-party binary buys nothing and is the exact cross-provider exposure
+ * the door lane's grokChildEnv scrub exists to prevent.
+ */
+const FOREIGN_PROVIDER_KEYS = new Set(['ANTHROPIC_API_KEY', 'OPENAI_API_KEY']);
+const ENV_ALLOWLIST = [
+ ...BASE_ENV_ALLOWLIST.filter((k) => !FOREIGN_PROVIDER_KEYS.has(k)),
+ 'GROK_HOME',
+ 'XAI_API_KEY',
+];
+
+export class GrokRunner implements AgentRunner {
+ readonly name = 'grok';
+
+ async detect(): Promise<DetectResult> {
+ return detectBinary('GROK_BIN', 'grok');
+ }
+
+ async invoke(opts: InvokeOpts): Promise<InvokeResult> {
+ const detected = await this.detect();
+ if (!detected.available || !detected.binPath) {
+ throw new Error(`grok runner unavailable: ${detected.reason ?? 'unknown'}`);
+ }
+ const args = ['-p', opts.brief, '--output-format', 'plain'];
+ const env = filterAllowlistEnv(ENV_ALLOWLIST, opts.env);
+
+ this.warnOnVendorGbrainEntry(env);
+
+ // Version preamble: recorded as a plain stdout transcript event (the
+ // transcript schema is stdio-bytes-only, so this is a captured preamble,
+ // not a new event type). Makes a mis-bound community binary or an
+ // auto-updated version diagnosable from the transcript alone.
+ // execFileSync (no shell — the which-resolved path is not metachar-
+ // validated) with the SAME filtered env as the turn itself: the resolved
+ // binary must never see ambient secrets the allowlist excludes.
+ try {
+ const version = execFileSync(detected.binPath, ['--version'], {
+ encoding: 'utf-8',
+ stdio: ['ignore', 'pipe', 'ignore'],
+ timeout: 15_000,
+ env: env as NodeJS.ProcessEnv,
+ cwd: opts.cwd,
+ }).trim();
+ opts.transcriptSink.write({
+ ts: Date.now(),
+ channel: 'stdout',
+ bytes: Buffer.from(`[grok-runner preamble] version: ${version}\n`, 'utf-8'),
+ });
+ } catch {
+ // Preamble is diagnostic only — never fail the run for it.
+ }
+
+ const result = await spawnWithCapture(detected.binPath, args, {
+ cwd: opts.cwd,
+ env,
+ timeoutMs: opts.timeoutMs,
+ transcriptSink: opts.transcriptSink,
+ });
+
+ return { exitCode: result.exitCode, durationMs: result.durationMs };
+ }
+
+ /**
+ * Loud tripwire for the vendor-config contamination channel: when the HOME
+ * grok will see carries a ~/.claude.json with an mcpServers.gbrain entry,
+ * a trusted-folder grok turn may route gbrain tool calls at the operator's
+ * REAL brain. Warning only (live mode deliberately runs the operator's
+ * agent); the hermetic lane is the door e2e.
+ */
+ private warnOnVendorGbrainEntry(env: Record<string, string>): void {
+ try {
+ const home = env.HOME ?? process.env.HOME;
+ if (!home) return;
+ const claudeJson = join(home, '.claude.json');
+ if (!existsSync(claudeJson)) return;
+ const parsed = JSON.parse(readFileSync(claudeJson, 'utf-8')) as {
+ mcpServers?: Record<string, unknown>;
+ };
+ if (parsed?.mcpServers && Object.prototype.hasOwnProperty.call(parsed.mcpServers, 'gbrain')) {
+ console.warn(
+ '[grok-runner] WARNING: ~/.claude.json registers an mcpServers.gbrain entry. ' +
+ 'Grok Build reads vendor MCP configs for trusted folders, so this live run ' +
+ 'may bind the OPERATOR\'S REAL brain instead of the hermetic one. ' +
+ 'Use a scratch HOME/GROK_HOME for clean measurements (docs/mcp/GROK-CLI-PIN.md).',
+ );
+ }
+ } catch {
+ // Best-effort tripwire — unreadable/invalid vendor config is not an error here.
+ }
+ }
+}
diff --git a/src/core/claw-test/runners/hermes.ts b/src/core/claw-test/runners/hermes.ts
index de9c2b341d..3bc43c8329 100644
--- a/src/core/claw-test/runners/hermes.ts
+++ b/src/core/claw-test/runners/hermes.ts
@@ -22,11 +22,10 @@
* Path validation: must be absolute, must be executable, no '..' segments.
*/
-import { execSync } from 'child_process';
-import { statSync } from 'fs';
import {
BASE_ENV_ALLOWLIST,
- validateBinPathEnv,
+ detectBinary,
+ filterAllowlistEnv,
type AgentRunner,
type DetectResult,
type InvokeOpts,
@@ -54,38 +53,7 @@ export class HermesRunner implements AgentRunner {
readonly name = 'hermes';
async detect(): Promise<DetectResult> {
- const fromEnv = process.env.HERMES_BIN?.trim();
- let binPath: string | undefined;
-
- if (fromEnv) {
- const validation = validateBinPathEnv('HERMES_BIN', fromEnv);
- if (validation) return { available: false, reason: validation };
- binPath = fromEnv;
- } else {
- try {
- const out = execSync('which hermes', { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'] });
- const found = out.trim();
- if (!found || !found.startsWith('/')) {
- return { available: false, reason: 'hermes not on PATH' };
- }
- binPath = found;
- } catch {
- return { available: false, reason: 'hermes not on PATH' };
- }
- }
-
- if (!binPath) return { available: false, reason: 'no binary resolved' };
-
- try {
- const s = statSync(binPath);
- if (!s.isFile()) return { available: false, reason: `not a regular file: ${binPath}` };
- // eslint-disable-next-line no-bitwise
- if (!(s.mode & 0o111)) return { available: false, reason: `not executable: ${binPath}` };
- } catch (e) {
- return { available: false, reason: `stat failed: ${e instanceof Error ? e.message : String(e)}` };
- }
-
- return { available: true, binPath };
+ return detectBinary('HERMES_BIN', 'hermes');
}
async invoke(opts: InvokeOpts): Promise<InvokeResult> {
@@ -94,14 +62,7 @@ export class HermesRunner implements AgentRunner {
throw new Error(`hermes runner unavailable: ${detected.reason ?? 'unknown'}`);
}
const args = ['-z', opts.brief];
-
- // Filter env to allow-list, then merge caller overrides.
- const baseEnv: Record<string, string> = {};
- for (const key of ENV_ALLOWLIST) {
- const v = process.env[key];
- if (typeof v === 'string') baseEnv[key] = v;
- }
- const env: Record<string, string> = { ...baseEnv, ...opts.env };
+ const env = filterAllowlistEnv(ENV_ALLOWLIST, opts.env);
const result = await spawnWithCapture(detected.binPath, args, {
cwd: opts.cwd,
diff --git a/src/core/claw-test/runners/openclaw.ts b/src/core/claw-test/runners/openclaw.ts
index 2f43e1d500..c6396b9944 100644
--- a/src/core/claw-test/runners/openclaw.ts
+++ b/src/core/claw-test/runners/openclaw.ts
@@ -6,18 +6,18 @@
* test/e2e/bench-vs-openclaw/harness.ts):
* openclaw agent --local --agent <agent-name> --message "<brief>"
*
- * NOT `openclaw run --prompt-file BRIEF.md` (that flag does not exist —
- * Codex pass 2 of the eng review caught the speculative shape).
+ * NOT `openclaw run` with a prompt-file flag (spelled "prompt-file" — that
+ * flag does not exist; Codex pass 2 of the eng review caught the speculative
+ * shape).
*
* Binary resolution: $OPENCLAW_BIN > `which openclaw` > unavailable.
* Path validation: must be absolute, must be executable, no '..' segments.
*/
-import { execSync } from 'child_process';
-import { statSync } from 'fs';
import {
BASE_ENV_ALLOWLIST,
- validateBinPathEnv,
+ detectBinary,
+ filterAllowlistEnv,
type AgentRunner,
type DetectResult,
type InvokeOpts,
@@ -33,38 +33,7 @@ export class OpenClawRunner implements AgentRunner {
readonly name = 'openclaw';
async detect(): Promise<DetectResult> {
- const fromEnv = process.env.OPENCLAW_BIN?.trim();
- let binPath: string | undefined;
-
- if (fromEnv) {
- const validation = validateBinPathEnv('OPENCLAW_BIN', fromEnv);
- if (validation) return { available: false, reason: validation };
- binPath = fromEnv;
- } else {
- try {
- const out = execSync('which openclaw', { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'] });
- const found = out.trim();
- if (!found || !found.startsWith('/')) {
- return { available: false, reason: 'openclaw not on PATH' };
- }
- binPath = found;
- } catch {
- return { available: false, reason: 'openclaw not on PATH' };
- }
- }
-
- if (!binPath) return { available: false, reason: 'no binary resolved' };
-
- try {
- const s = statSync(binPath);
- if (!s.isFile()) return { available: false, reason: `not a regular file: ${binPath}` };
- // eslint-disable-next-line no-bitwise
- if (!(s.mode & 0o111)) return { available: false, reason: `not executable: ${binPath}` };
- } catch (e) {
- return { available: false, reason: `stat failed: ${e instanceof Error ? e.message : String(e)}` };
- }
-
- return { available: true, binPath };
+ return detectBinary('OPENCLAW_BIN', 'openclaw');
}
async invoke(opts: InvokeOpts): Promise<InvokeResult> {
@@ -74,14 +43,7 @@ export class OpenClawRunner implements AgentRunner {
}
const agentName = opts.agentName ?? DEFAULT_AGENT_NAME;
const args = ['agent', '--local', '--agent', agentName, '--message', opts.brief];
-
- // Filter env to allow-list, then merge caller overrides.
- const baseEnv: Record<string, string> = {};
- for (const key of ENV_ALLOWLIST) {
- const v = process.env[key];
- if (typeof v === 'string') baseEnv[key] = v;
- }
- const env: Record<string, string> = { ...baseEnv, ...opts.env };
+ const env = filterAllowlistEnv(ENV_ALLOWLIST, opts.env);
const result = await spawnWithCapture(detected.binPath, args, {
cwd: opts.cwd,
@@ -93,4 +55,3 @@ export class OpenClawRunner implements AgentRunner {
return { exitCode: result.exitCode, durationMs: result.durationMs };
}
}
-
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index eeaccf0b0f..c4ff2dad4b 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -32,7 +32,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'check-backlinks': ['--background', '--brain', '--brain-wide-max-cost-usd', '--dir', '--dry-run', '--explain', '--follow', '--help', '--include-frontmatter', '--json', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--timeout', '--type'],
'check-resolvable': ['--brain', '--dry-run', '--fix', '--help', '--json', '--skills-dir', '--source', '--strict', '--verbose'],
'check-update': ['--all', '--brain', '--check', '--dim', '--ff-only', '--help', '--json', '--markdown', '--migrate-only', '--non-interactive', '--refresh-cache', '--source', '--swap-only', '--to', '--version', '--yes'],
- 'claw-test': ['--ab', '--agent', '--all', '--auto-update', '--brain', '--break-lock', '--build-index', '--by-mention', '--compile', '--days', '--dir', '--exclusive', '--force-retry', '--force-schema', '--from-meetings', '--help', '--history', '--http', '--json', '--keep-tempdir', '--lang', '--list-agents', '--live', '--local', '--locks', '--markdown', '--max-age', '--message', '--multimodal', '--no-embed', '--no-embedding', '--no-extract', '--path', '--pglite', '--phase', '--priority', '--progress-json', '--prompt-file', '--refresh-unqualified', '--remediate', '--rollback', '--run-id', '--scenario', '--skip-verify', '--source', '--stale', '--surface', '--transcripts', '--undo-wave', '--use-captured-snapshot', '--with-calibration', '--yes'],
+ 'claw-test': ['--ab', '--agent', '--all', '--auto-update', '--brain', '--break-lock', '--build-index', '--by-mention', '--compile', '--days', '--dir', '--exclusive', '--force-retry', '--force-schema', '--from-meetings', '--help', '--history', '--http', '--json', '--keep-tempdir', '--lang', '--list-agents', '--live', '--local', '--locks', '--markdown', '--max-age', '--message', '--multimodal', '--no-embed', '--no-embedding', '--no-extract', '--output-format', '--path', '--pglite', '--phase', '--priority', '--progress-json', '--refresh-unqualified', '--remediate', '--rollback', '--run-id', '--scenario', '--skip-verify', '--source', '--stale', '--surface', '--transcripts', '--undo-wave', '--use-captured-snapshot', '--version', '--with-calibration', '--yes'],
'code-callees': ['--aliases', '--all', '--all-sources', '--brain', '--chunker-debug', '--clone-dir', '--confirm-destructive', '--federated', '--force', '--help', '--include-null-signature', '--json', '--limit', '--no-extract', '--no-federated', '--no-json', '--path', '--pattern', '--pending', '--repo', '--reset', '--resolve', '--restore-only', '--source', '--stale', '--supersessions', '--thin', '--url', '--url-managed', '--yes'],
'code-callers': ['--aliases', '--all', '--all-sources', '--brain', '--chunker-debug', '--clone-dir', '--confirm-destructive', '--federated', '--force', '--help', '--include-null-signature', '--json', '--limit', '--no-extract', '--no-federated', '--no-json', '--path', '--pattern', '--pending', '--repo', '--reset', '--resolve', '--restore-only', '--source', '--stale', '--supersessions', '--thin', '--url', '--url-managed', '--yes'],
'code-def': ['--aliases', '--all', '--brain', '--chunker-debug', '--help', '--include-null-signature', '--json', '--lang', '--limit', '--no-extract', '--no-json', '--pattern', '--pending', '--pretty', '--reset', '--resolve', '--source', '--stale', '--supersessions', '--thin', '--yes'],
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index c5520e4281..0528531b43 100644
--- a/templates/bootstrap/template-repo/README.md
+++ b/templates/bootstrap/template-repo/README.md
@@ -1,6 +1,6 @@
# gbrain agent workspace — template
-<!-- gbrain-template-stamp: 0.45.19.0 -->
+<!-- gbrain-template-stamp: 0.45.20.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --git a/test/agent-runner.test.ts b/test/agent-runner.test.ts
index 47c6ff4df0..a68a953272 100644
--- a/test/agent-runner.test.ts
+++ b/test/agent-runner.test.ts
@@ -4,9 +4,13 @@
*/
import { describe, test, expect, beforeEach } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { withEnv } from './helpers/with-env.ts';
import {
registerAgentRunner, resolveAgentRunner, listRegisteredAgents,
- _resetRegistryForTests,
+ _resetRegistryForTests, detectBinary, filterAllowlistEnv,
type AgentRunner, type DetectResult, type InvokeOpts, type InvokeResult, type TranscriptSink,
} from '../src/core/claw-test/agent-runner.ts';
@@ -95,3 +99,44 @@ describe('agent-agnosticism guard', () => {
expect(d.reason).toBe('not installed');
});
});
+
+describe('shared runner helpers (detectBinary / filterAllowlistEnv)', () => {
+ test('filterAllowlistEnv: overrides win over process.env (PATH-shim precedence)', () => {
+ const realPath = process.env.PATH;
+ expect(realPath).toBeTruthy();
+ const env = filterAllowlistEnv(['PATH', 'HOME'], { PATH: '/shim-bin:/usr/bin' });
+ expect(env.PATH).toBe('/shim-bin:/usr/bin');
+ expect(env.PATH).not.toBe(realPath);
+ if (typeof process.env.HOME === 'string') expect(env.HOME).toBe(process.env.HOME);
+ });
+
+ test('filterAllowlistEnv: unlisted process.env keys never reach the child', async () => {
+ await withEnv({ AGENT_RUNNER_TEST_LEAK_CANARY: 'leaked' }, () => {
+ const env = filterAllowlistEnv(['PATH'], {});
+ expect(env.AGENT_RUNNER_TEST_LEAK_CANARY).toBeUndefined();
+ });
+ });
+
+ test('detectBinary: non-executable regular file is unavailable with the stat reason', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'agent-runner-detect-'));
+ const p = join(dir, 'not-exec');
+ try {
+ writeFileSync(p, '#!/bin/sh\n', { mode: 0o644 });
+ await withEnv({ AGENT_RUNNER_TEST_BIN: p }, () => {
+ const d = detectBinary('AGENT_RUNNER_TEST_BIN', 'definitely-not-a-real-binary-name');
+ expect(d.available).toBe(false);
+ expect(d.reason).toBe(`not executable: ${p}`);
+ });
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('detectBinary: missing env + missing binary reports not-on-PATH', async () => {
+ await withEnv({ AGENT_RUNNER_TEST_BIN: undefined }, () => {
+ const d = detectBinary('AGENT_RUNNER_TEST_BIN', 'definitely-not-a-real-binary-name');
+ expect(d.available).toBe(false);
+ expect(d.reason).toBe('definitely-not-a-real-binary-name not on PATH');
+ });
+ });
+});
diff --git a/test/check-bootstrap-guards.test.ts b/test/check-bootstrap-guards.test.ts
index b910296d15..10e40fa98c 100644
--- a/test/check-bootstrap-guards.test.ts
+++ b/test/check-bootstrap-guards.test.ts
@@ -484,3 +484,204 @@ describe('verify + workflow wiring', () => {
expect(wf).toContain('tests/docker/bootstrap-e2e.sh');
});
});
+
+// ── check-grok-pin.sh ────────────────────────────────────────────────────────
+
+const GROK_PIN_GUARD = join(ROOT, 'scripts/check-grok-pin.sh');
+
+function runGrokPinGuard(fixtureRoot: string): { status: number | null; out: string } {
+ const r = spawnSync('bash', [GROK_PIN_GUARD], {
+ cwd: ROOT,
+ encoding: 'utf-8',
+ env: { ...process.env, GBRAIN_GROK_PIN_GUARD_ROOT: fixtureRoot },
+ });
+ return { status: r.status, out: `${r.stdout}\n${r.stderr}` };
+}
+
+const GROK_PIN_STAMPS_NPM = [
+ '<!-- grok-pin: distribution_kind=npm -->',
+ '<!-- grok-pin: npm_package=@example/grok -->',
+ '<!-- grok-pin: npm_version=1.0.4 -->',
+ '<!-- grok-pin: npm_integrity=sha512-AAA= -->',
+ '<!-- grok-pin: grok_version=1.0.4 -->',
+ '<!-- grok-pin: installer_sha256=abc123 -->',
+].join('\n');
+
+function grokDoorWorkflow(envLines: string[]): string {
+ return [
+ 'jobs:',
+ ' other-job:',
+ ' steps: []',
+ ' grok-door:',
+ ' env:',
+ ...envLines.map((l) => ` ${l}`),
+ ' steps: []',
+ ' trailing-job:',
+ ' env:',
+ ' GROK_VERSION: "9.9.9"', // outside the grok-door block — must be ignored
+ ' steps: []',
+ '',
+ ].join('\n');
+}
+
+const GROK_NPM_ENV_OK = [
+ 'GROK_VERSION: "1.0.4"',
+ 'GROK_NPM_PACKAGE: "@example/grok"',
+ 'GROK_NPM_INTEGRITY: "sha512-AAA="',
+];
+
+describe('check-grok-pin.sh', () => {
+ test('ok: npm mode with matching workflow pins (anchored to the grok-door block)', () => {
+ withFixture({
+ 'docs/mcp/GROK-CLI-PIN.md': `# pin\n${GROK_PIN_STAMPS_NPM}\n`,
+ '.github/workflows/heavy-tests.yml': grokDoorWorkflow(GROK_NPM_ENV_OK),
+ }, (dir) => {
+ const r = runGrokPinGuard(dir);
+ expect(r.out).toContain('check-grok-pin: ok');
+ expect(r.status).toBe(0);
+ });
+ });
+
+ test('SKIP-graceful pre-landing; FAIL-closed once the door job exists without the pin doc', () => {
+ // Door job present + pin doc MISSING = the gate's source of truth was
+ // deleted — that must fail, not skip (post-landing fail-closed rule).
+ withFixture({
+ '.github/workflows/heavy-tests.yml': grokDoorWorkflow(GROK_NPM_ENV_OK),
+ }, (dir) => {
+ const r = runGrokPinGuard(dir);
+ expect(r.status).toBe(1);
+ expect(r.out).toContain('pin doc is the gate');
+ });
+ // No door job yet: pin doc alone is fine to skip (pre-landing posture).
+ withFixture({
+ 'docs/mcp/GROK-CLI-PIN.md': `# pin\n${GROK_PIN_STAMPS_NPM}\n`,
+ '.github/workflows/heavy-tests.yml': 'jobs:\n other-job:\n steps: []\n',
+ }, (dir) => {
+ const r = runGrokPinGuard(dir);
+ expect(r.out).toContain('SKIP');
+ expect(r.status).toBe(0);
+ });
+ });
+
+ test('FAIL: npm_version stamp disagreeing with grok_version can never pass green', () => {
+ const stamps = GROK_PIN_STAMPS_NPM.replace(
+ '<!-- grok-pin: npm_version=1.0.4 -->',
+ '<!-- grok-pin: npm_version=1.0.5 -->',
+ );
+ withFixture({
+ 'docs/mcp/GROK-CLI-PIN.md': `# pin\n${stamps}\n`,
+ '.github/workflows/heavy-tests.yml': grokDoorWorkflow(GROK_NPM_ENV_OK),
+ }, (dir) => {
+ const r = runGrokPinGuard(dir);
+ expect(r.status).toBe(1);
+ expect(r.out).toContain('npm_version stamp');
+ });
+ });
+
+ test('single-quoted workflow env values are not read as drift', () => {
+ withFixture({
+ 'docs/mcp/GROK-CLI-PIN.md': `# pin\n${GROK_PIN_STAMPS_NPM}\n`,
+ '.github/workflows/heavy-tests.yml': grokDoorWorkflow([
+ "GROK_VERSION: '1.0.4'",
+ "GROK_NPM_PACKAGE: '@example/grok'",
+ "GROK_NPM_INTEGRITY: 'sha512-AAA='",
+ ]),
+ }, (dir) => {
+ const r = runGrokPinGuard(dir);
+ expect(r.out).toContain('check-grok-pin: ok');
+ expect(r.status).toBe(0);
+ });
+ });
+
+ test('FAIL: workflow GROK_VERSION drifts from the grok_version stamp', () => {
+ withFixture({
+ 'docs/mcp/GROK-CLI-PIN.md': `# pin\n${GROK_PIN_STAMPS_NPM}\n`,
+ '.github/workflows/heavy-tests.yml': grokDoorWorkflow([
+ 'GROK_VERSION: "1.0.5"',
+ 'GROK_NPM_PACKAGE: "@example/grok"',
+ 'GROK_NPM_INTEGRITY: "sha512-AAA="',
+ ]),
+ }, (dir) => {
+ const r = runGrokPinGuard(dir);
+ expect(r.status).toBe(1);
+ expect(r.out).toContain('GROK_VERSION drift');
+ });
+ });
+
+ test('FAIL: npm mode with a missing workflow integrity pin', () => {
+ withFixture({
+ 'docs/mcp/GROK-CLI-PIN.md': `# pin\n${GROK_PIN_STAMPS_NPM}\n`,
+ '.github/workflows/heavy-tests.yml': grokDoorWorkflow([
+ 'GROK_VERSION: "1.0.4"',
+ 'GROK_NPM_PACKAGE: "@example/grok"',
+ ]),
+ }, (dir) => {
+ const r = runGrokPinGuard(dir);
+ expect(r.status).toBe(1);
+ expect(r.out).toContain('missing GROK_NPM_INTEGRITY');
+ });
+ });
+
+ test('FAIL: mode exclusivity — npm mode must not also pin GROK_INSTALL_SHA256 in the workflow', () => {
+ withFixture({
+ 'docs/mcp/GROK-CLI-PIN.md': `# pin\n${GROK_PIN_STAMPS_NPM}\n`,
+ '.github/workflows/heavy-tests.yml': grokDoorWorkflow([
+ ...GROK_NPM_ENV_OK,
+ 'GROK_INSTALL_SHA256: "abc123"',
+ ]),
+ }, (dir) => {
+ const r = runGrokPinGuard(dir);
+ expect(r.status).toBe(1);
+ expect(r.out).toContain('mode exclusivity');
+ });
+ });
+
+ test('FAIL: duplicate stamps in the pin doc', () => {
+ withFixture({
+ 'docs/mcp/GROK-CLI-PIN.md': `# pin\n${GROK_PIN_STAMPS_NPM}\n<!-- grok-pin: grok_version=1.0.5 -->\n`,
+ '.github/workflows/heavy-tests.yml': grokDoorWorkflow(GROK_NPM_ENV_OK),
+ }, (dir) => {
+ const r = runGrokPinGuard(dir);
+ expect(r.status).toBe(1);
+ expect(r.out).toContain('duplicate grok-pin stamp');
+ });
+ });
+
+ test('installer mode: matching sha passes; npm-integrity co-pin fails exclusivity', () => {
+ const installerStamps = [
+ '<!-- grok-pin: distribution_kind=installer -->',
+ '<!-- grok-pin: grok_version=1.0.4 -->',
+ '<!-- grok-pin: installer_sha256=abc123 -->',
+ ].join('\n');
+ withFixture({
+ 'docs/mcp/GROK-CLI-PIN.md': `# pin\n${installerStamps}\n`,
+ '.github/workflows/heavy-tests.yml': grokDoorWorkflow([
+ 'GROK_VERSION: "1.0.4"',
+ 'GROK_INSTALL_SHA256: "abc123"',
+ ]),
+ }, (dir) => {
+ const r = runGrokPinGuard(dir);
+ expect(r.out).toContain('check-grok-pin: ok (installer mode');
+ expect(r.status).toBe(0);
+ });
+ withFixture({
+ 'docs/mcp/GROK-CLI-PIN.md': `# pin\n${installerStamps}\n`,
+ '.github/workflows/heavy-tests.yml': grokDoorWorkflow([
+ 'GROK_VERSION: "1.0.4"',
+ 'GROK_INSTALL_SHA256: "abc123"',
+ 'GROK_NPM_INTEGRITY: "sha512-AAA="',
+ ]),
+ }, (dir) => {
+ const r = runGrokPinGuard(dir);
+ expect(r.status).toBe(1);
+ expect(r.out).toContain('mode exclusivity');
+ });
+ });
+
+ test('verify wiring: run-verify-parallel CHECKS + package.json both carry check:grok-pin', () => {
+ const verify = require('node:fs').readFileSync(join(ROOT, 'scripts/run-verify-parallel.sh'), 'utf-8');
+ expect(verify).toContain('"check:grok-pin"');
+ const pkg = require('node:fs').readFileSync(join(ROOT, 'package.json'), 'utf-8');
+ expect(pkg).toContain('"check:grok-pin": "bash scripts/check-grok-pin.sh"');
+ });
+});
diff --git a/test/claw-test-cli.test.ts b/test/claw-test-cli.test.ts
index cdfa6a0be0..9d443a6028 100644
--- a/test/claw-test-cli.test.ts
+++ b/test/claw-test-cli.test.ts
@@ -304,6 +304,209 @@ describe('OpenClawRunner invoke env (shim — pins the shared-allowlist leak bar
});
});
+describe('GrokRunner detection (reliable on box without grok)', () => {
+ test('detect returns the contract shape when GROK_BIN unset', async () => {
+ const orig = process.env.GROK_BIN;
+ delete process.env.GROK_BIN;
+ try {
+ const { GrokRunner } = await import('../src/core/claw-test/runners/grok.ts');
+ const d = await new GrokRunner().detect();
+ expect(typeof d.available).toBe('boolean');
+ if (!d.available) expect(typeof d.reason).toBe('string');
+ else expect(d.binPath?.startsWith('/')).toBe(true);
+ } finally {
+ if (orig !== undefined) process.env.GROK_BIN = orig;
+ }
+ });
+
+ test('detect rejects relative GROK_BIN', async () => {
+ const orig = process.env.GROK_BIN;
+ process.env.GROK_BIN = 'relative/grok';
+ try {
+ const { GrokRunner } = await import('../src/core/claw-test/runners/grok.ts');
+ const d = await new GrokRunner().detect();
+ expect(d.available).toBe(false);
+ expect(d.reason).toMatch(/GROK_BIN must be absolute/);
+ } finally {
+ if (orig !== undefined) process.env.GROK_BIN = orig;
+ else delete process.env.GROK_BIN;
+ }
+ });
+
+ test("detect rejects '..' segments in GROK_BIN", async () => {
+ const orig = process.env.GROK_BIN;
+ process.env.GROK_BIN = '/tmp/foo/../grok';
+ try {
+ const { GrokRunner } = await import('../src/core/claw-test/runners/grok.ts');
+ const d = await new GrokRunner().detect();
+ expect(d.available).toBe(false);
+ expect(d.reason).toMatch(/'\.\.' segments/);
+ } finally {
+ if (orig !== undefined) process.env.GROK_BIN = orig;
+ else delete process.env.GROK_BIN;
+ }
+ });
+
+ test('detect rejects shell metacharacters in GROK_BIN (through-runner injection pin)', async () => {
+ // validateBinPathEnv's metachar branch is unit-tested directly below;
+ // this pins that a runner's detect() actually routes through it — the
+ // first through-runner coverage of the injection-relevant branch.
+ const orig = process.env.GROK_BIN;
+ process.env.GROK_BIN = '/tmp/gr"ok';
+ try {
+ const { GrokRunner } = await import('../src/core/claw-test/runners/grok.ts');
+ const d = await new GrokRunner().detect();
+ expect(d.available).toBe(false);
+ expect(d.reason).toMatch(/quotes, backslashes, dollar signs/);
+ } finally {
+ if (orig !== undefined) process.env.GROK_BIN = orig;
+ else delete process.env.GROK_BIN;
+ }
+ });
+});
+
+describe('GrokRunner invoke argv/env (shim — no grok binary needed)', () => {
+ test('argv is the pinned one-shot shape; GROK_HOME + XAI_API_KEY propagate; unlisted env does not', async () => {
+ const orig = {
+ GROK_BIN: process.env.GROK_BIN,
+ GROK_HOME: process.env.GROK_HOME,
+ XAI_API_KEY: process.env.XAI_API_KEY,
+ LEAK_CANARY: process.env.LEAK_CANARY,
+ GBRAIN_DATABASE_URL: process.env.GBRAIN_DATABASE_URL,
+ ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY,
+ OPENAI_API_KEY: process.env.OPENAI_API_KEY,
+ };
+ const shim = join(tmp, 'grok-shim');
+ // The runner first execs the shim with a version flag (the transcript
+ // preamble), then spawns the real turn — the shim answers both.
+ writeFileSync(shim, '#!/bin/sh\nif [ "$1" = "--version" ]; then echo "grok 9.9.9 (shimhash)"; exit 0; fi\nprintf "ARGV:%s\\n" "$@"\nprintf "GH:[%s] KEY:[%s] CANARY:[%s] DBURL:[%s] ANT:[%s] OAI:[%s]\\n" "$GROK_HOME" "$XAI_API_KEY" "$LEAK_CANARY" "$GBRAIN_DATABASE_URL" "$ANTHROPIC_API_KEY" "$OPENAI_API_KEY"\n', 'utf-8');
+ chmodSync(shim, 0o755);
+ process.env.GROK_BIN = shim;
+ process.env.GROK_HOME = '/tmp/gh-canary-test';
+ // grok's documented headless auth path (docs/mcp/GROK-CLI-PIN.md): the
+ // grok delta must forward it or env-key operators get "Not signed in"
+ // blamed on the agent.
+ process.env.XAI_API_KEY = 'xai-sentinel-3fa1';
+ process.env.LEAK_CANARY = 'must-not-leak';
+ process.env.GBRAIN_DATABASE_URL = 'postgres://must-not-leak';
+ // Foreign provider keys: in BASE_ENV_ALLOWLIST (hermes needs them) but
+ // deliberately filtered OUT of grok's list — a single-provider third-party
+ // binary must never receive the operator's Anthropic/OpenAI credentials.
+ process.env.ANTHROPIC_API_KEY = 'ant-must-not-leak';
+ process.env.OPENAI_API_KEY = 'oai-must-not-leak';
+ try {
+ const { GrokRunner } = await import('../src/core/claw-test/runners/grok.ts');
+ const chunks: Buffer[] = [];
+ const result = await new GrokRunner().invoke({
+ cwd: tmp,
+ brief: 'BRIEF BODY sentinel-9e4d',
+ env: {},
+ timeoutMs: 10_000,
+ transcriptSink: {
+ write: (e) => { if (e.channel === 'stdout') chunks.push(e.bytes); },
+ nextOffset: () => 0,
+ close: async () => {},
+ },
+ });
+ expect(result.exitCode).toBe(0);
+ const stdout = Buffer.concat(chunks).toString('utf-8');
+ // Version preamble recorded as a plain stdout transcript event.
+ expect(stdout).toContain('[grok-runner preamble] version: grok 9.9.9 (shimhash)');
+ // Pinned argv: single-shot flag, brief, then plain output format
+ // (docs/mcp/GROK-CLI-PIN.md; permission flags deliberately absent
+ // pending the authed observation).
+ expect(stdout).toContain('ARGV:-p\nARGV:BRIEF BODY sentinel-9e4d\nARGV:--output-format\nARGV:plain');
+ // Allowlist held: the grok delta passes; the canary and the
+ // deliberately-delisted GBRAIN_DATABASE_URL don't.
+ expect(stdout).toContain('GH:[/tmp/gh-canary-test]');
+ expect(stdout).toContain('KEY:[xai-sentinel-3fa1]');
+ expect(stdout).toContain('CANARY:[] DBURL:[] ANT:[] OAI:[]');
+ } finally {
+ for (const [k, v] of Object.entries(orig)) {
+ if (v !== undefined) process.env[k] = v;
+ else delete process.env[k];
+ }
+ }
+ });
+});
+
+describe('GrokRunner vendor-config tripwire + preamble resilience (shim)', () => {
+ async function invokeWithHome(home: string): Promise<{ warns: string[]; exitCode: number; stdout: string }> {
+ const shim = join(tmp, 'grok-shim-tripwire');
+ writeFileSync(shim, '#!/bin/sh\nif [ "$1" = "--version" ]; then exit 1; fi\necho ok\n', 'utf-8');
+ chmodSync(shim, 0o755);
+ const origBin = process.env.GROK_BIN;
+ process.env.GROK_BIN = shim;
+ const warns: string[] = [];
+ const origWarn = console.warn;
+ console.warn = (m: unknown) => { warns.push(String(m)); };
+ try {
+ const { GrokRunner } = await import('../src/core/claw-test/runners/grok.ts');
+ const chunks: Buffer[] = [];
+ const result = await new GrokRunner().invoke({
+ cwd: tmp,
+ brief: 'brief',
+ env: { HOME: home },
+ timeoutMs: 10_000,
+ transcriptSink: {
+ write: (e) => { if (e.channel === 'stdout') chunks.push(e.bytes); },
+ nextOffset: () => 0,
+ close: async () => {},
+ },
+ });
+ return { warns, exitCode: result.exitCode, stdout: Buffer.concat(chunks).toString('utf-8') };
+ } finally {
+ console.warn = origWarn;
+ if (origBin !== undefined) process.env.GROK_BIN = origBin;
+ else delete process.env.GROK_BIN;
+ }
+ }
+
+ test('warns loudly when ~/.claude.json registers mcpServers.gbrain (real-brain contamination channel)', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'grok-vendor-'));
+ try {
+ writeFileSync(join(home, '.claude.json'), JSON.stringify({ mcpServers: { gbrain: {} } }));
+ const r = await invokeWithHome(home);
+ expect(r.warns.some((w) => w.includes('REAL brain'))).toBe(true);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('stays silent without a gbrain vendor entry; a broken --version never fails the run', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'grok-vendor-'));
+ try {
+ writeFileSync(join(home, '.claude.json'), JSON.stringify({ mcpServers: { other: {} } }));
+ const r = await invokeWithHome(home);
+ expect(r.warns.some((w) => w.includes('REAL brain'))).toBe(false);
+ // The shim's --version exits 1 (preamble failure path): the run still
+ // completes with the main turn's exit code and simply has no preamble.
+ expect(r.exitCode).toBe(0);
+ expect(r.stdout).not.toContain('[grok-runner preamble]');
+ expect(r.stdout).toContain('ok');
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('flag-registry accepted over-inclusion — SAFETY_FLAGS collision guard', () => {
+ test("no grok argv literal collides with the generator's SAFETY_FLAGS", async () => {
+ // The claw-test registry entry absorbs grok's long-form argv literals by
+ // design (prose-bleed over-inclusion is tolerated); what must NEVER
+ // happen is one of them colliding with a SAFETY flag the generator
+ // deliberately excludes from validity (a collision would make a safety
+ // flag silently valid on claw-test).
+ const { CLI_FLAG_REGISTRY } = await import('../src/core/cli-flag-registry.generated.ts');
+ const clawFlags: readonly string[] = CLI_FLAG_REGISTRY['claw-test'] ?? [];
+ expect(clawFlags.length).toBeGreaterThan(0);
+ const SAFETY_FLAGS = ['--dry-run']; // mirrors scripts/generate-flag-registry.ts
+ for (const f of SAFETY_FLAGS) {
+ expect(clawFlags).not.toContain(f);
+ }
+ });
+});
+
describe('validateBinPathEnv — shim-quoting hardening', () => {
test('rejects quote/metacharacter values that would break out of the generated shim quoting', () => {
// The value is interpolated single-quoted into sh shim scripts; each of
diff --git a/test/e2e/claw-test.test.ts b/test/e2e/claw-test.test.ts
index de7e18ab46..e73e487e7a 100644
--- a/test/e2e/claw-test.test.ts
+++ b/test/e2e/claw-test.test.ts
@@ -123,20 +123,27 @@ describe('gbrain claw-test --scenario fresh-install (scripted)', () => {
});
describe('gbrain claw-test --list-agents', () => {
- test('reports both built-in runners (available or not — both valid states)', () => {
- // HERMES_BIN/OPENCLAW_BIN point at a nonexistent path so the output shape
- // is deterministic regardless of what's installed on the box (detect
+ test('reports all three built-in runners (available or not — both valid states)', () => {
+ // *_BIN vars point at a nonexistent path so the output shape is
+ // deterministic regardless of what's installed on the box (detect
// rejects a non-stat-able absolute path with a specific reason).
const result = spawnSync(BIN_PATH, ['claw-test', '--list-agents'], {
cwd: REPO_ROOT,
- env: { ...process.env, HERMES_BIN: '/nonexistent/hermes', OPENCLAW_BIN: '/nonexistent/openclaw' },
+ env: {
+ ...process.env,
+ HERMES_BIN: '/nonexistent/hermes',
+ OPENCLAW_BIN: '/nonexistent/openclaw',
+ GROK_BIN: '/nonexistent/grok',
+ },
encoding: 'utf-8',
timeout: 60_000,
});
expect(result.status).toBe(0);
+ expect(result.stdout).toMatch(/^grok: unavailable: /m);
expect(result.stdout).toMatch(/^hermes: unavailable: /m);
expect(result.stdout).toMatch(/^openclaw: unavailable: /m);
// Alphabetical print order (the awaited-detection fix pins this).
+ expect(result.stdout.indexOf('grok:')).toBeLessThan(result.stdout.indexOf('hermes:'));
expect(result.stdout.indexOf('hermes:')).toBeLessThan(result.stdout.indexOf('openclaw:'));
}, 60_000);
});
diff --git a/test/e2e/install-real-grok.serial.test.ts b/test/e2e/install-real-grok.serial.test.ts
new file mode 100644
index 0000000000..51f0c790b9
--- /dev/null
+++ b/test/e2e/install-real-grok.serial.test.ts
@@ -0,0 +1,489 @@
+/**
+ * install-real-grok door e2e — drives the REAL `grok` binary (xAI Grok Build
+ * CLI) against THIS checkout's gbrain over stdio MCP.
+ *
+ * WHAT THIS PROVES: gbrain WIRED INTO grok via the DOCUMENTED command shape
+ * (`grok mcp add gbrain -- gbrain serve --surface verbs`, bare command
+ * resolved via a PATH-staged bin dir) + recall through MCP. Every asserted
+ * shape was observed against v1.0.4 — see docs/mcp/GROK-CLI-PIN.md; update
+ * that file, the heavy-tests grok-door pins, and these assertions together.
+ *
+ * SPLIT GATING (divergence from the hermes door, deliberate): grok's mcp
+ * add/list/doctor all run KEYLESS (observed), so the compat tier needs only
+ * the binary — missing auth must not discard it. Two describes:
+ * - keyless tier (T1 version pin, T2 INSTALL, T2b provenance, T3 direct
+ * TOML): GBRAIN_REAL_GROK_E2E=1 + resolvable binary.
+ * - paid tier (T4 SMOKE): additionally hasGrokAuth() (non-empty
+ * XAI_API_KEY; blank CI secret ⇒ skip, never a paid failure).
+ *
+ * Isolation: every child gets BOTH HOME=<tmp> and GROK_HOME=<tmp>/.grok
+ * (GROK_HOME honoring verified v1.0.4), an explicit tmp cwd on EVERY spawn
+ * (grok reads vendor MCP configs — ~/.claude.json / project .mcp.json — for
+ * trusted folders, and loads .envrc from the cwd by default; fresh tmp HOME +
+ * cwd make both structurally inert: vendor entries report "folder untrusted",
+ * observed). A bounded tripwire hashes the operator's real ~/.grok
+ * config/credential files (NOT the volatile set — grok rewrites
+ * active_sessions/logs/bin/docs on every run) before/after, and a checkout
+ * guard asserts no .grok/ or .mcp.json appeared in the repo root.
+ *
+ * Observed-reality notes (docs/mcp/GROK-CLI-PIN.md, v1.0.4):
+ * - `grok mcp add` is LAZY: exit 0 always, no handshake, no prompt;
+ * `enabled = true` is written unconditionally. Neither its exit code nor
+ * the enabled flag proves anything about server viability.
+ * - THE honest discriminator: `grok mcp doctor <name> --json` SPAWNS the
+ * server — exit 0 + checks [command found, server started, handshake OK,
+ * "7 tools discovered"] on success; exit 1 + a failing check on a broken
+ * command. The verbs surface's seven verbs are proven keyless.
+ * - the env flag is repeatable, one KEY=value per flag.
+ * - `[cli] auto_update = false` must be seeded (config-only kill-switch,
+ * default ON); `mcp add` PRESERVES pre-existing config sections.
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { createHash, randomBytes } from 'node:crypto';
+import { spawnSync } from 'node:child_process';
+import {
+ cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync,
+} from 'node:fs';
+import { homedir, tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+
+import {
+ resolveGrokBinary,
+ hasGrokAuth,
+ seedGrokConfig,
+ grokChildEnv,
+ grokOneShotTurn,
+ hermeticChildEnv,
+ stageGbrainBinDir,
+ ensureCompiledGbrain,
+ seedBrainForAgent,
+} from '../helpers/agent-harness.ts';
+
+const REPO_ROOT = resolve(import.meta.dir, '..', '..');
+const CLI = join(REPO_ROOT, 'src', 'cli.ts');
+const GROK_BIN = resolveGrokBinary();
+const CAN_RUN_KEYLESS = process.env.GBRAIN_REAL_GROK_E2E === '1' && !!GROK_BIN;
+const CAN_RUN_PAID = CAN_RUN_KEYLESS && hasGrokAuth();
+
+if (!CAN_RUN_KEYLESS) {
+ const why = process.env.GBRAIN_REAL_GROK_E2E !== '1'
+ ? 'GBRAIN_REAL_GROK_E2E is not 1 (explicit opt-in required)'
+ : 'grok binary not found';
+ console.warn(`[install-real-grok] SKIP (keyless tier): ${why}`);
+} else if (!CAN_RUN_PAID) {
+ console.warn('[install-real-grok] keyless tier runs; SKIP paid tier: no non-empty XAI_API_KEY');
+}
+
+const ENV_KEYS = [
+ 'GBRAIN_HOME', 'GBRAIN_DATABASE_URL', 'DATABASE_URL', 'GBRAIN_BRAIN_ID',
+ 'GBRAIN_SOURCE', 'GBRAIN_HOOKS', 'GROK_HOME',
+];
+const SAVED_ENV: Record<string, string | undefined> = {};
+
+// Bounded tripwire over the operator's REAL ~/.grok: config/credential-class
+// files ONLY (grok rewrites active_sessions/logs/bin/docs on every run — a
+// whole-tree hash would false-positive on volatile churn, observed v1.0.4).
+const REAL_GROK_HOME = join(homedir(), '.grok');
+const TRIPWIRE_FILES = ['config.toml', 'mcp_credentials.json'];
+let realManifestBefore: string | null = null;
+function grokHomeManifest(): string | null {
+ try {
+ if (!existsSync(REAL_GROK_HOME)) return 'absent';
+ const h = createHash('sha256');
+ for (const f of TRIPWIRE_FILES) {
+ const p = join(REAL_GROK_HOME, f);
+ h.update(f);
+ h.update(existsSync(p) ? readFileSync(p) : Buffer.from('<absent>'));
+ }
+ return h.digest('hex');
+ } catch { return null; }
+}
+
+// Checkout guard: a grok child whose cwd escaped to the repo root would drop
+// a .grok/ (project-scope add) or read/write .mcp.json there.
+const CHECKOUT_MARKERS = [join(REPO_ROOT, '.grok'), join(REPO_ROOT, '.mcp.json')];
+let checkoutMarkersBefore: boolean[] = [];
+
+const EVIDENCE_DIR = process.env.GBRAIN_E2E_EVIDENCE_DIR;
+const createdHomes: { label: string; home: string }[] = [];
+function trackHome(label: string): string {
+ const home = mkdtempSync(join(tmpdir(), `gb-grok-${label}-`));
+ createdHomes.push({ label, home });
+ return home;
+}
+function copyEvidence(): void {
+ if (!EVIDENCE_DIR) return;
+ for (const { label, home } of createdHomes) {
+ try {
+ const dst = join(EVIDENCE_DIR, label);
+ mkdirSync(dst, { recursive: true });
+ // Copy-allowlist per the Phase-0 volatile inventory; the credential
+ // inventory is pending auth — mcp_credentials.json is defensively
+ // excluded rather than copied.
+ for (const sub of ['.grok/logs', '.grok/config.toml', 'door-config.toml']) {
+ const src = join(home, sub);
+ if (existsSync(src)) {
+ try { cpSync(src, join(dst, sub.replace(/\//g, '_')), { recursive: true }); } catch { /* best-effort */ }
+ }
+ }
+ try { rmSync(join(dst, '.grok_mcp_credentials.json'), { force: true }); } catch { /* best-effort */ }
+ // Same content-grep the CI scrub applies: a grok-written log that
+ // embeds the key must never land in an artifact, local or uploaded.
+ const key = process.env.XAI_API_KEY?.trim();
+ if (key && key.length >= 8) {
+ const walk = (d: string): string[] => {
+ try {
+ return require('node:fs').readdirSync(d, { withFileTypes: true }).flatMap((e: { name: string; isDirectory(): boolean; isFile(): boolean }) => {
+ const p = join(d, e.name);
+ return e.isDirectory() ? walk(p) : e.isFile() ? [p] : [];
+ });
+ } catch { return []; }
+ };
+ for (const f of walk(dst)) {
+ try {
+ if (readFileSync(f, 'utf8').includes(key)) rmSync(f, { force: true });
+ } catch { /* unreadable → leave */ }
+ }
+ }
+ } catch { /* best-effort */ }
+ }
+}
+
+beforeAll(() => {
+ for (const k of ENV_KEYS) SAVED_ENV[k] = process.env[k];
+ for (const k of ENV_KEYS) delete process.env[k];
+ realManifestBefore = grokHomeManifest();
+ checkoutMarkersBefore = CHECKOUT_MARKERS.map((p) => existsSync(p));
+});
+
+afterAll(() => {
+ copyEvidence();
+ for (const { home } of createdHomes) {
+ try { rmSync(home, { recursive: true, force: true }); } catch { /* best-effort */ }
+ }
+ for (const k of ENV_KEYS) {
+ if (SAVED_ENV[k] === undefined) delete process.env[k];
+ else process.env[k] = SAVED_ENV[k];
+ }
+ // Tripwires LAST — scream, don't silently mutate the operator's agent.
+ const after = grokHomeManifest();
+ if (realManifestBefore !== after) {
+ throw new Error(
+ 'HERMETICITY BREACH: the operator\'s real ~/.grok config/credential files changed during ' +
+ 'the door run — GROK_HOME isolation failed; investigate before trusting this suite again. ' +
+ '(Volatile paths are excluded from this manifest; a fire means config.toml or credentials moved.)',
+ );
+ }
+ const markersAfter = CHECKOUT_MARKERS.map((p) => existsSync(p));
+ for (let i = 0; i < CHECKOUT_MARKERS.length; i++) {
+ if (markersAfter[i] && !checkoutMarkersBefore[i]) {
+ throw new Error(`HERMETICITY BREACH: ${CHECKOUT_MARKERS[i]} appeared in the checkout during the door run.`);
+ }
+ }
+});
+
+/** Run the real grok binary under a hermetic home with a REQUIRED tmp cwd
+ * (never the checkout: vendor-config + .envrc channels). `binDir`, when
+ * given, is PATH-prepended so bare `gbrain` resolves to the staged binary —
+ * both for grok's own resolution and for the server it spawns. */
+function runGrok(
+ home: string,
+ cwd: string,
+ argv: string[],
+ binDir?: string,
+): { code: number | null; stdout: string; stderr: string } {
+ const env = grokChildEnv(home);
+ if (binDir) env.PATH = `${binDir}:${env.PATH ?? ''}`;
+ // The bun-run fallback server cold-transpiles the CLI; grok's default
+ // startup timeout is 30s (observed schema) — widen via the observed env.
+ env.GROK_MCP_STARTUP_TIMEOUT_SECS = '90';
+ const res = spawnSync(GROK_BIN!, argv, {
+ cwd,
+ env,
+ encoding: 'utf8',
+ timeout: 180_000,
+ });
+ return { code: res.status, stdout: res.stdout ?? '', stderr: res.stderr ?? '' };
+}
+
+/** Keyless PGLite brain init (compiled binary preferred, bun-run fallback). */
+function initBrain(home: string): { code: number | null; stderr: string } {
+ const { binPath } = ensureCompiledGbrain(REPO_ROOT);
+ const argv = binPath
+ ? [binPath, 'init', '--pglite', '--no-embedding', '--non-interactive']
+ : ['bun', 'run', CLI, 'init', '--pglite', '--no-embedding', '--non-interactive'];
+ const res = spawnSync(argv[0], argv.slice(1), {
+ cwd: REPO_ROOT,
+ env: hermeticChildEnv({ HOME: home, GBRAIN_HOME: home, GBRAIN_SKIP_STARTUP_HOOKS: '1' }),
+ encoding: 'utf8',
+ timeout: 180_000,
+ });
+ return { code: res.status, stderr: `${res.stdout ?? ''}\n${res.stderr ?? ''}` };
+}
+
+interface GrokMcpServerEntry {
+ command?: string;
+ args?: string[];
+ env?: Record<string, string>;
+ enabled?: boolean;
+ startup_timeout_sec?: number;
+}
+interface GrokConfig {
+ cli?: { auto_update?: boolean };
+ mcp_servers?: Record<string, GrokMcpServerEntry>;
+}
+
+function readGrokConfig(home: string): GrokConfig {
+ const p = join(home, '.grok', 'config.toml');
+ expect(existsSync(p)).toBe(true);
+ // Bun.TOML.parse — same parser codex-toml.ts uses; zero new deps.
+ return (Bun as unknown as { TOML: { parse(s: string): unknown } }).TOML
+ .parse(readFileSync(p, 'utf-8')) as GrokConfig;
+}
+
+interface DoctorCheck { label: string; passed: boolean; detail?: string; hint?: string }
+interface DoctorReport {
+ sources?: { path: string; status: { status: string; server_count?: number } }[];
+ servers?: { name: string; source?: string; checks?: DoctorCheck[] }[];
+}
+
+/** The honest discriminator: doctor SPAWNS the server (observed). */
+function doctorProbe(home: string, cwd: string, name: string, binDir?: string): { code: number | null; report: DoctorReport } {
+ const res = runGrok(home, cwd, ['mcp', 'doctor', name, '--json'], binDir);
+ let report: DoctorReport = {};
+ try { report = JSON.parse(res.stdout) as DoctorReport; } catch { /* asserted by callers */ }
+ return { code: res.code, report };
+}
+
+/** Documented registration shape (GROK.md): bare `gbrain` via staged PATH. */
+function registerGbrainIntoGrok(
+ home: string,
+ cwd: string,
+ binDir: string,
+ gbrainHome: string,
+ sourceId: string,
+): { code: number | null; stdout: string; stderr: string } {
+ return runGrok(home, cwd, [
+ 'mcp', 'add', 'gbrain',
+ '-e', `GBRAIN_HOME=${gbrainHome}`,
+ '-e', `GBRAIN_SOURCE=${sourceId}`,
+ '--', 'gbrain', 'serve', '--surface', 'verbs',
+ ], binDir);
+}
+
+describe.skipIf(!CAN_RUN_KEYLESS)('install real-grok door — keyless tier (serial e2e)', () => {
+ test('version pin: grok --version matches GROK_VERSION when the CI pin is set', () => {
+ const pinned = process.env.GROK_VERSION;
+ const home = trackHome('ver');
+ seedGrokConfig(home);
+ const res = runGrok(home, home, ['--version']);
+ expect(res.code).toBe(0);
+ if (pinned) {
+ expect(res.stdout).toContain(`grok ${pinned}`);
+ } else {
+ // Local run without a pin: assert the observed shape — also the
+ // discriminator against the colliding community grok-cli binary.
+ expect(res.stdout).toMatch(/grok \d+\.\d+\.\d+ \([0-9a-f]+\)/);
+ }
+ }, 120_000);
+
+ test('INSTALL: keyless init → documented-shape `grok mcp add` → TOML carries server + env → doctor handshakes 7 verbs', () => {
+ const home = trackHome('install');
+ seedGrokConfig(home);
+ const ws = join(home, 'ws');
+ mkdirSync(ws, { recursive: true });
+
+ const init = initBrain(home);
+ expect(init.code).toBe(0);
+ expect(existsSync(join(home, '.gbrain', 'brain.pglite'))).toBe(true);
+
+ const binDir = join(home, 'staged-bin');
+ const staged = stageGbrainBinDir(REPO_ROOT, binDir);
+ console.warn(`[install-real-grok] staged gbrain kind=${staged.kind}`);
+
+ const add = registerGbrainIntoGrok(home, ws, binDir, home, 'default');
+ // Add is LAZY (observed): exit 0 proves only that the config was written
+ // — a nonexistent command also exits 0. The handshake proof is doctor.
+ expect(add.code).toBe(0);
+
+ const cfg = readGrokConfig(home);
+ try { cpSync(join(home, '.grok', 'config.toml'), join(home, 'door-config.toml')); } catch { /* evidence */ }
+ expect(cfg.mcp_servers?.gbrain).toBeDefined();
+ expect(cfg.mcp_servers!.gbrain.command).toBe('gbrain');
+ expect(cfg.mcp_servers!.gbrain.args).toEqual(['serve', '--surface', 'verbs']);
+ expect(cfg.mcp_servers!.gbrain.env?.GBRAIN_HOME).toBe(home);
+ expect(cfg.mcp_servers!.gbrain.env?.GBRAIN_SOURCE).toBe('default');
+ // Seeded kill-switch survived registration (observed: add preserves
+ // pre-existing sections).
+ expect(cfg.cli?.auto_update).toBe(false);
+
+ const { code, report } = doctorProbe(home, ws, 'gbrain', binDir);
+ expect(code).toBe(0);
+ const checks = report.servers?.find((s) => s.name === 'gbrain')?.checks ?? [];
+ expect(checks.every((c) => c.passed)).toBe(true);
+ expect(checks.some((c) => /handshake OK/i.test(c.label))).toBe(true);
+ // The verbs surface end-to-end, keyless: seven verbs discovered.
+ expect(checks.some((c) => /7 tools discovered/i.test(c.label))).toBe(true);
+
+ // Soft probe (exit-0-only; shape logged, not asserted).
+ const list = runGrok(home, ws, ['mcp', 'list', '--json'], binDir);
+ expect(list.code).toBe(0);
+ if (!list.stdout.includes('gbrain')) {
+ console.warn('[install-real-grok] mcp list --json did not mention gbrain — shape drift? output:', list.stdout.slice(0, 400));
+ }
+ }, 420_000);
+
+ test('INSTALL 2b: provenance — the entry is grok-native and vendor fallback is structurally inert here', () => {
+ const home = trackHome('prov');
+ seedGrokConfig(home);
+ const ws = join(home, 'ws');
+ mkdirSync(ws, { recursive: true });
+
+ const binDir = join(home, 'staged-bin');
+ stageGbrainBinDir(REPO_ROOT, binDir);
+ const init = initBrain(home);
+ expect(init.code).toBe(0);
+ registerGbrainIntoGrok(home, ws, binDir, home, 'default');
+
+ // Decoy vendor entry in the fresh cwd: grok SEES it but must not
+ // activate it — fresh home ⇒ folder untrusted (observed).
+ writeFileSync(join(ws, '.mcp.json'), JSON.stringify({
+ mcpServers: { 'gbrain-vendor-decoy': { command: join(binDir, 'gbrain'), args: ['serve'] } },
+ }), 'utf-8');
+
+ const { code, report } = doctorProbe(home, ws, 'gbrain', binDir);
+ expect(code).toBe(0);
+ const gbrain = report.servers?.find((s) => s.name === 'gbrain');
+ expect(gbrain?.source).toBe('config'); // grok-native, not a vendor pickup
+ const decoy = report.servers?.find((s) => s.name === 'gbrain-vendor-decoy');
+ if (decoy) {
+ // When doctor reports the decoy at all, it must be inert (untrusted).
+ expect(decoy.checks?.some((c) => /untrusted/i.test(c.label))).toBe(true);
+ }
+ }, 420_000);
+
+ test('INSTALL 3: the direct config.toml surface (documented, not a fallback) is accepted independently', () => {
+ const home = trackHome('toml');
+ const ws = join(home, 'ws');
+ mkdirSync(ws, { recursive: true });
+
+ const init = initBrain(home);
+ expect(init.code).toBe(0);
+
+ const binDir = join(home, 'staged-bin');
+ stageGbrainBinDir(REPO_ROOT, binDir);
+
+ // Full document (not just the server block): the kill-switch and the
+ // observed schema keys, startup_timeout_sec=60 for the bun-run
+ // cold-transpile flake. Parse-validated before write (Bun.TOML has no
+ // stringify — the literal IS the surface users hand-write).
+ const doc = [
+ '[cli]',
+ 'auto_update = false',
+ '',
+ '[mcp_servers.gbrain]',
+ 'command = "gbrain"',
+ 'args = ["serve", "--surface", "verbs"]',
+ 'startup_timeout_sec = 60',
+ 'enabled = true',
+ '',
+ '[mcp_servers.gbrain.env]',
+ `GBRAIN_HOME = "${home}"`,
+ 'GBRAIN_SOURCE = "default"',
+ '',
+ ].join('\n');
+ expect(() => (Bun as unknown as { TOML: { parse(s: string): unknown } }).TOML.parse(doc)).not.toThrow();
+ mkdirSync(join(home, '.grok'), { recursive: true });
+ writeFileSync(join(home, '.grok', 'config.toml'), doc, 'utf-8');
+
+ const { code, report } = doctorProbe(home, ws, 'gbrain', binDir);
+ expect(code).toBe(0);
+ const checks = report.servers?.find((s) => s.name === 'gbrain')?.checks ?? [];
+ expect(checks.some((c) => /handshake OK/i.test(c.label))).toBe(true);
+
+ // Config-preservation pin: a subsequent CLI add must not clobber the
+ // hand-written sections (observed; the eng review predicted the clobber).
+ const add2 = runGrok(home, ws, ['mcp', 'add', 'second', '-e', 'A=1', '--', join(binDir, 'gbrain'), 'serve'], binDir);
+ expect(add2.code).toBe(0);
+ const cfg = readGrokConfig(home);
+ expect(cfg.cli?.auto_update).toBe(false);
+ expect(cfg.mcp_servers?.gbrain?.startup_timeout_sec).toBe(60);
+ }, 420_000);
+});
+
+describe.skipIf(!CAN_RUN_PAID)('install real-grok door — paid tier (serial e2e)', () => {
+ test('SMOKE: real grok -p answers the per-run nonce fact through the gbrain MCP server', async () => {
+ const home = trackHome('smoke');
+ const ws = join(home, 'ws');
+ mkdirSync(ws, { recursive: true });
+
+ // PER-RUN nonce fact (never the committed Summit/Rivermouth string): grok
+ // has filesystem/shell tools, so recall of a string that is greppable in
+ // ANY reachable file proves nothing. The nonce exists only in the
+ // hermetic brain — which lives under this same hermetic HOME, so an agent
+ // that greps $HOME/.gbrain could still surface it without MCP; web search
+ // is flag-disabled, fs/shell are prompt-forbidden only. The planned
+ // streaming-json toolCall assertion (pending the authed observation) is
+ // what upgrades this to proof of tool mediation.
+ const nonce = `kestrel-${randomBytes(4).toString('hex')}`;
+ const seeded = await seedBrainForAgent(home, 'workspace', {
+ entity: 'Kestrel Logistics',
+ fact: `The Kestrel Logistics staging depot is codenamed ${nonce}.`,
+ query: 'What is the codename of the Kestrel Logistics staging depot?',
+ slug: 'companies/kestrel-logistics',
+ });
+ seedGrokConfig(home);
+
+ const binDir = join(home, 'staged-bin');
+ stageGbrainBinDir(REPO_ROOT, binDir);
+ registerGbrainIntoGrok(home, ws, binDir, home, 'workspace');
+
+ // Doctor pre-flight — the observed-honest discriminator gates the paid
+ // loop: never enter a paid attempt on a broken registration.
+ const pre = doctorProbe(home, ws, 'gbrain', binDir);
+ if (pre.code !== 0) {
+ console.error('[install-real-grok] doctor pre-flight failed; not spending a paid attempt:',
+ JSON.stringify(pre.report).slice(0, 600));
+ }
+ expect(pre.code).toBe(0);
+
+ const prompt =
+ 'You have an MCP server named gbrain connected to a knowledge brain. ' +
+ `Using ONLY that brain (no general knowledge, no web search, no filesystem or shell tools), answer: ${seeded.query} ` +
+ 'Report exactly what the brain says. If no gbrain tool is available to you, reply with exactly: NO-GBRAIN-TOOL';
+
+ let finalText = '';
+ let lastExit: number | null = null;
+ for (let attempt = 1; attempt <= 2; attempt++) {
+ const turn = await grokOneShotTurn({
+ prompt,
+ cwd: ws,
+ home,
+ timeoutMs: 240_000,
+ disableWebSearch: true,
+ // The MCP registration is the DOCUMENTED bare `gbrain` — the turn's
+ // own child env must resolve it too, or grok can't start the server
+ // mid-turn on a clean runner (doctor passing is not enough).
+ binDir,
+ });
+ finalText = turn.finalText;
+ lastExit = turn.exitCode;
+ if (turn.exitCode === 0 && finalText.toLowerCase().includes(nonce)) break;
+ console.warn(`[install-real-grok] SMOKE attempt ${attempt}: exit=${turn.exitCode} text=${finalText.slice(0, 200)} stderr=${turn.stderrText.slice(0, 200)}`);
+ if (attempt < 2) await new Promise((r) => setTimeout(r, 3_000));
+ }
+
+ // Never-soften criteria: the nonce surfaced AND the no-tool control
+ // token did not.
+ expect(lastExit).toBe(0);
+ expect(finalText.toLowerCase()).toContain(nonce);
+ expect(finalText).not.toContain('NO-GBRAIN-TOOL');
+
+ // NOTE (pending observation, GROK-CLI-PIN.md): the JSON event-stream
+ // shapes are unobserved keyless. Once the first authed run pins the
+ // streaming-json tool-call event shape, add the separate non-retried
+ // toolCall test here (one extra paid turn) and a parseGrokJson helper
+ // with fixtures.
+ }, 600_000);
+});
diff --git a/test/helpers/agent-harness.ts b/test/helpers/agent-harness.ts
index 405a942c80..a90b7c294d 100644
--- a/test/helpers/agent-harness.ts
+++ b/test/helpers/agent-harness.ts
@@ -670,6 +670,205 @@ export async function hermesOneShotTurn(opts: HermesTurnOpts): Promise<HermesTur
};
}
+// ────────────────────────────────────────────────────────────────────────────
+// 5a-grok. Grok Build (xAI) — all shapes observed against v1.0.4
+// (docs/mcp/GROK-CLI-PIN.md). grok ≠ groq ≠ ngrok.
+// ────────────────────────────────────────────────────────────────────────────
+
+/** Locate the real `grok` binary (xAI Grok Build). $GROK_BIN (absolute,
+ * executable — same override the claw-test runner honors) first, then
+ * Bun.which, then the npm-global and installer landing spots. Collision
+ * note: the community superagent-ai grok-cli ships a colliding `grok`
+ * binary — the door's version-shape pin (T1) is the discriminator. */
+export function resolveGrokBinary(): string | null {
+ // FAIL-CLOSED on a set-but-invalid GROK_BIN (matching the runner's
+ // detectBinary posture): silently falling through to `which grok` could
+ // bind the colliding community grok-cli binary DESPITE the operator's
+ // explicit pin — the exact mis-bind the pin exists to prevent.
+ const fromEnv = process.env.GROK_BIN?.trim();
+ if (fromEnv) {
+ if (!fromEnv.startsWith('/') || fromEnv.split('/').includes('..')) return null;
+ return firstExecutable([fromEnv]);
+ }
+ const which = whichBin('grok');
+ if (which) return which;
+ const home = process.env.HOME ?? os.homedir();
+ const candidates = [
+ '/opt/homebrew/bin/grok',
+ '/usr/local/bin/grok',
+ `${home}/.local/bin/grok`,
+ `${home}/.npm-global/bin/grok`,
+ `${home}/.bun/bin/grok`,
+ ];
+ for (const dir of (process.env.PATH ?? '').split(path.delimiter)) {
+ if (dir) candidates.push(path.join(dir, 'grok'));
+ }
+ return firstExecutable(candidates);
+}
+
+/**
+ * Grok is usable BY THE PAID TIER if a NON-EMPTY XAI_API_KEY is exported.
+ * Env-only on purpose: the keyless one-shot exits 1 with "Not signed in …
+ * set the XAI_API_KEY environment variable" (observed v1.0.4), and no
+ * credential file was observed keyless — if the authed observation finds one
+ * under ~/.grok, add it here as a second probe (GROK-CLI-PIN.md marks that
+ * item pending auth). Blank CI secret ⇒ skip, never a paid failing test.
+ */
+export function hasGrokAuth(): boolean {
+ return Boolean(process.env.XAI_API_KEY?.trim());
+}
+
+/**
+ * Hermetic env for spawning grok itself: standard scrub + HOME/GROK_HOME
+ * overrides; XAI_API_KEY re-admitted EXPLICITLY (it is deliberately not in
+ * ALLOW_EXACT — default-deny stays intact for every other child). Deletes:
+ * - other providers' keys (defensive; grok is single-provider, but scrubbing
+ * is free and keeps the door single-auth-source like the hermes lane), and
+ * - GITHUB_ENV/GITHUB_PATH/GITHUB_OUTPUT/GITHUB_STATE — the GITHUB_ prefix
+ * rule would forward these CI step-metadata files to an UNTRUSTED agent
+ * child, which could append to them and poison later workflow steps.
+ */
+export function grokChildEnv(home: string, opts?: { binDir?: string }): NodeJS.ProcessEnv {
+ const env = hermeticChildEnv({
+ HOME: home,
+ GROK_HOME: path.join(home, '.grok'),
+ XAI_API_KEY: process.env.XAI_API_KEY?.trim() || undefined,
+ });
+ for (const k of ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'OPENAI_API_KEY']) delete env[k];
+ // Writable step-metadata files the GITHUB_ prefix rule would otherwise
+ // forward: appending to any of them poisons later workflow steps (ENV/
+ // PATH/OUTPUT/STATE) or the run summary UI (STEP_SUMMARY).
+ for (const k of ['GITHUB_ENV', 'GITHUB_PATH', 'GITHUB_OUTPUT', 'GITHUB_STATE', 'GITHUB_STEP_SUMMARY', 'GITHUB_ACTION_PATH']) delete env[k];
+ // PATH-prepend the staged gbrain bin dir when given — the MCP registration
+ // uses the DOCUMENTED bare `gbrain` command, so EVERY grok spawn that may
+ // start the server (doctor probes AND the paid turn) must resolve it.
+ if (opts?.binDir) env.PATH = `${opts.binDir}:${env.PATH ?? ''}`;
+ return env;
+}
+
+/**
+ * Seed a hermetic <home>/.grok/config.toml BEFORE any grok spawn:
+ * - `[cli] auto_update = false` — auto-update is config-only and defaults ON
+ * (observed); without this seed a door run can self-update mid-suite and
+ * break the version pin.
+ * - `[models] default = <model>` when given — `grok mcp add` PRESERVES
+ * pre-existing sections (observed), so the seed survives registration.
+ * No credentials are written: auth travels via XAI_API_KEY env only.
+ */
+export function seedGrokConfig(home: string, opts?: { defaultModel?: string }): string {
+ const grokHome = path.join(home, '.grok');
+ fs.mkdirSync(grokHome, { recursive: true });
+ const model = opts?.defaultModel;
+ const doc = `[cli]\nauto_update = false\n${model ? `\n[models]\ndefault = "${model}"\n` : ''}`;
+ fs.writeFileSync(path.join(grokHome, 'config.toml'), doc, 'utf-8');
+ return grokHome;
+}
+
+/**
+ * Stage a `gbrain` binary into a fresh bin dir so the DOCUMENTED registration
+ * shape (`grok mcp add gbrain -- gbrain serve --surface verbs`, bare command
+ * resolved via PATH — observed working v1.0.4) is what the door exercises.
+ * Compiled binary copy when available; otherwise an executable sh wrapper
+ * exec'ing `bun run src/cli.ts` so the fallback lane survives staging.
+ */
+export function stageGbrainBinDir(repoRoot: string, dir: string): { kind: 'compiled' | 'bun-run' } {
+ fs.mkdirSync(dir, { recursive: true });
+ const target = path.join(dir, 'gbrain');
+ const { binPath } = ensureCompiledGbrain(repoRoot);
+ if (binPath) {
+ fs.copyFileSync(binPath, target);
+ fs.chmodSync(target, 0o755);
+ return { kind: 'compiled' };
+ }
+ const cli = path.join(repoRoot, 'src', 'cli.ts');
+ // The path is interpolated single-quoted into an sh shim — reject the same
+ // metachar set validateBinPathEnv guards, rather than trying to escape.
+ if (/['"`$\\\n\r]/.test(cli)) {
+ throw new Error(`stageGbrainBinDir: repo path contains shell-active characters unsafe for the shim: ${cli}`);
+ }
+ fs.writeFileSync(target, `#!/bin/sh\nexec bun run '${cli}' "$@"\n`, { mode: 0o755 });
+ return { kind: 'bun-run' };
+}
+
+export interface GrokTurnOpts {
+ prompt: string;
+ cwd: string;
+ home: string;
+ timeoutMs?: number;
+ /** Per-call model pin (authoritative — immune to config rewrites). */
+ model?: string;
+ /** Disable grok's built-in web search + fetch tools (observed flag). */
+ disableWebSearch?: boolean;
+ /** Staged gbrain bin dir — PATH-prepended so the bare-`gbrain` MCP
+ * registration resolves when grok spawns the server DURING the turn
+ * (without this the doctor preflight passes but the paid turn cannot
+ * start the server on a clean runner). */
+ binDir?: string;
+}
+
+export interface GrokTurnResult {
+ /** plain output format: stdout is the final response text. */
+ finalText: string;
+ exitCode: number | null;
+ timedOut: boolean;
+ stderrText: string;
+}
+
+/**
+ * Drive one `grok -p` turn against a hermetic HOME + GROK_HOME. Plain output
+ * format (final text on stdout — observed). The permission posture is
+ * deliberately unset pending the authed observation (GROK-CLI-PIN.md); the
+ * JSON event-stream shapes are also unobserved, so there is no parseGrokJson
+ * yet — the door's tool-call assertion stays gated on that observation.
+ */
+export async function grokOneShotTurn(opts: GrokTurnOpts): Promise<GrokTurnResult> {
+ const bin = resolveGrokBinary();
+ if (!bin) throw new Error('grokOneShotTurn: grok binary not found');
+ const timeoutMs = opts.timeoutMs ?? 240_000;
+
+ const argv = [
+ bin, '-p', opts.prompt, '--output-format', 'plain',
+ ...(opts.model ? ['-m', opts.model] : []),
+ ...(opts.disableWebSearch ? ['--disable-web-search'] : []),
+ ];
+ const proc = Bun.spawn(argv, {
+ cwd: opts.cwd,
+ env: grokChildEnv(opts.home, { binDir: opts.binDir }),
+ stdout: 'pipe',
+ stderr: 'pipe',
+ stdin: 'ignore',
+ });
+
+ let timedOut = false;
+ const timer = setTimeout(() => {
+ timedOut = true;
+ try { proc.kill(); } catch { /* already dead */ }
+ // grok may leave its leader daemon / MCP server child holding the pipes
+ // open past the parent's death — escalate so the stream drain below
+ // cannot hang the retry loop indefinitely.
+ setTimeout(() => { try { proc.kill(9); } catch { /* already dead */ } }, 5_000);
+ }, timeoutMs);
+
+ // Bounded drain: even a SIGKILLed parent can leave a grandchild holding
+ // the pipe fds; cap the post-timeout wait instead of awaiting EOF forever.
+ const drainCap = timeoutMs + 30_000;
+ const bounded = <T>(p: Promise<T>, fallback: T): Promise<T> =>
+ Promise.race([p, new Promise<T>((r) => setTimeout(() => r(fallback), drainCap))]);
+ const [stdout, stderrText] = await Promise.all([
+ bounded(new Response(proc.stdout).text(), ''),
+ bounded(new Response(proc.stderr).text().catch(() => ''), ''),
+ ]);
+ const exitCode = await bounded(proc.exited, 124);
+ clearTimeout(timer);
+
+ return {
+ finalText: stdout.trim(),
+ exitCode: timedOut ? 124 : exitCode,
+ timedOut,
+ stderrText,
+ };
+}
+
// ────────────────────────────────────────────────────────────────────────────
// 5b. Fast gbrain MCP server command (compiled binary, cached; bun-run fallback)
// ────────────────────────────────────────────────────────────────────────────
@@ -754,6 +953,16 @@ function probeCompiledPglite(binPath: string): { ok: boolean; reason: string } {
* bun-run fallback instead of hard-failing the door suite.
*/
export function ensureCompiledGbrain(repoRoot: string): { binPath: string | null; reason: string } {
+ // CI short-circuit: a workflow can compile ONCE in a dedicated step and
+ // export GBRAIN_COMPILED_BIN — the module-global cache below is per-process,
+ // so two `bun test` invocations in one job would otherwise compile twice.
+ const prebuilt = process.env.GBRAIN_COMPILED_BIN?.trim();
+ if (prebuilt && prebuilt.startsWith('/')) {
+ try {
+ fs.accessSync(prebuilt, fs.constants.X_OK);
+ return { binPath: prebuilt, reason: '' };
+ } catch { /* fall through to the normal compile path */ }
+ }
if (_compileTried) return { binPath: _compiledBin, reason: _compileReason };
_compileTried = true;
try {
@@ -882,12 +1091,20 @@ export interface SeededBrain {
* restores it — the door test sets GBRAIN_HOME on the spawned child via the
* MCP config's env block, not on this process.
*/
-export async function seedBrainForAgent(home: string, sourceId: string): Promise<SeededBrain> {
+export async function seedBrainForAgent(
+ home: string,
+ sourceId: string,
+ opts?: { entity?: string; fact?: string; query?: string; slug?: string },
+): Promise<SeededBrain> {
if (!put_page) throw new Error('seedBrainForAgent: put_page op not registered');
- const entity = 'Summit Robotics';
- const fact = 'Summit Robotics runs the Rivermouth fulfillment center.';
- const query = 'Where does Summit Robotics run its fulfillment center?';
+ // Defaults are the committed synthetic fact (hermes/claude doors). Callers
+ // whose agent has filesystem/shell tools in reach pass a PER-RUN nonce fact
+ // instead — the committed string is greppable in the checkout, so recall of
+ // it proves nothing against an agent that can read the repo (grok door).
+ const entity = opts?.entity ?? 'Summit Robotics';
+ const fact = opts?.fact ?? 'Summit Robotics runs the Rivermouth fulfillment center.';
+ const query = opts?.query ?? 'Where does Summit Robotics run its fulfillment center?';
const savedHome = process.env.GBRAIN_HOME;
process.env.GBRAIN_HOME = home;
@@ -918,8 +1135,8 @@ export async function seedBrainForAgent(home: string, sourceId: string): Promise
sourceId,
};
await put_page.handler(ctx, {
- slug: 'companies/summit-robotics',
- content: `# Summit Robotics\n\n${fact}\n`,
+ slug: opts?.slug ?? 'companies/summit-robotics',
+ content: `# ${entity}\n\n${fact}\n`,
});
} finally {
// Release the PGLite lock so the spawned `gbrain serve` can open the
diff --git a/test/helpers/agent-harness.unit.test.ts b/test/helpers/agent-harness.unit.test.ts
index e41c1da776..d74e6e27e3 100644
--- a/test/helpers/agent-harness.unit.test.ts
+++ b/test/helpers/agent-harness.unit.test.ts
@@ -24,13 +24,17 @@ import {
parseCodexJsonl,
hermeticChildEnv,
hermesChildEnv,
+ grokChildEnv,
promotedEnv,
resolveClaudeBinary,
resolveCodexBinary,
resolveHermesBinary,
+ resolveGrokBinary,
hasHermesAuth,
+ hasGrokAuth,
parseDotenvFile,
seedHermesHome,
+ seedGrokConfig,
} from './agent-harness.ts';
import { withEnv } from './with-env.ts';
@@ -334,3 +338,133 @@ describe('seedHermesHome single-key copy (injectable source — never the operat
}
});
});
+
+describe('hasGrokAuth truth table (env-only — pins the non-empty-value gate)', () => {
+ // Env-only on purpose: keyless grok exits 1 with "Not signed in … set the
+ // XAI_API_KEY environment variable" (observed v1.0.4); no credential file
+ // was observed keyless (GROK-CLI-PIN.md marks the authed inventory pending).
+ test('non-empty XAI_API_KEY → true', async () => {
+ await withEnv({ XAI_API_KEY: 'xai-sentinel' }, () => {
+ expect(hasGrokAuth()).toBe(true);
+ });
+ });
+
+ test('blank XAI_API_KEY (empty CI secret) → false, never a paid failure', async () => {
+ await withEnv({ XAI_API_KEY: ' ' }, () => {
+ expect(hasGrokAuth()).toBe(false);
+ });
+ });
+
+ test('unset XAI_API_KEY → false', async () => {
+ await withEnv({ XAI_API_KEY: undefined }, () => {
+ expect(hasGrokAuth()).toBe(false);
+ });
+ });
+});
+
+describe('grokChildEnv — explicit key re-admission + CI metadata scrub', () => {
+ test('XAI_API_KEY survives via explicit override; HOME/GROK_HOME point at the temp home', async () => {
+ await withEnv({ XAI_API_KEY: 'xai-child-sentinel' }, () => {
+ const env = grokChildEnv('/tmp/grok-child-test');
+ // Not in ALLOW_EXACT — only the explicit override carries it through.
+ expect(env.XAI_API_KEY).toBe('xai-child-sentinel');
+ expect(env.HOME).toBe('/tmp/grok-child-test');
+ expect(env.GROK_HOME).toBe('/tmp/grok-child-test/.grok');
+ });
+ });
+
+ test('other provider keys and GITHUB_* step-metadata files are deleted', async () => {
+ await withEnv({
+ XAI_API_KEY: 'xai-x',
+ ANTHROPIC_API_KEY: 'ant-must-not-leak',
+ OPENAI_API_KEY: 'oai-must-not-leak',
+ GITHUB_ENV: '/tmp/gh-env-file',
+ GITHUB_PATH: '/tmp/gh-path-file',
+ GITHUB_OUTPUT: '/tmp/gh-output-file',
+ GITHUB_STATE: '/tmp/gh-state-file',
+ GITHUB_ACTIONS: 'true',
+ }, () => {
+ const env = grokChildEnv('/tmp/grok-child-test');
+ expect(env.ANTHROPIC_API_KEY).toBeUndefined();
+ expect(env.OPENAI_API_KEY).toBeUndefined();
+ // The GITHUB_ prefix rule would forward these writable step-metadata
+ // files to an untrusted agent child — poisoning later workflow steps.
+ expect(env.GITHUB_ENV).toBeUndefined();
+ expect(env.GITHUB_PATH).toBeUndefined();
+ expect(env.GITHUB_OUTPUT).toBeUndefined();
+ expect(env.GITHUB_STATE).toBeUndefined();
+ // Read-only CI metadata stays allowed (prefix rule intact).
+ expect(env.GITHUB_ACTIONS).toBe('true');
+ });
+ });
+});
+
+describe('seedGrokConfig — the auto-update kill-switch seed', () => {
+ test('writes [cli] auto_update=false, optional model pin, never credentials', () => {
+ const home = mkdtempSync(join(tmpdir(), 'grok-seed-'));
+ try {
+ const grokHome = seedGrokConfig(home, { defaultModel: 'grok-4.5' });
+ const doc = readFileSync(join(grokHome, 'config.toml'), 'utf-8');
+ expect(doc).toContain('[cli]');
+ expect(doc).toContain('auto_update = false');
+ expect(doc).toContain('default = "grok-4.5"');
+ expect(doc).not.toMatch(/XAI|api[_-]?key/i);
+ // Parseable by the same parser the door reads with.
+ expect(() => (Bun as unknown as { TOML: { parse(s: string): unknown } }).TOML.parse(doc)).not.toThrow();
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('without a model opt, only the [cli] section is written', () => {
+ const home = mkdtempSync(join(tmpdir(), 'grok-seed-'));
+ try {
+ seedGrokConfig(home);
+ const doc = readFileSync(join(home, '.grok', 'config.toml'), 'utf-8');
+ expect(doc).toContain('auto_update = false');
+ expect(doc).not.toContain('[models]');
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('resolveGrokBinary — fail-closed GROK_BIN handling', () => {
+ test('returns a string-or-null; a string is an absolute path', () => {
+ const p = resolveGrokBinary();
+ if (p !== null) expect(p.startsWith('/')).toBe(true);
+ else expect(p).toBeNull();
+ });
+
+ test('valid executable GROK_BIN is returned verbatim', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'grok-resolve-'));
+ const shim = join(dir, 'grok');
+ try {
+ writeFileSync(shim, '#!/bin/sh\n', { mode: 0o755 });
+ await withEnv({ GROK_BIN: shim }, () => {
+ expect(resolveGrokBinary()).toBe(shim);
+ });
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('set-but-invalid GROK_BIN fails CLOSED — never falls through to PATH (community-binary mis-bind guard)', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'grok-resolve-'));
+ const notExec = join(dir, 'grok-noexec');
+ try {
+ writeFileSync(notExec, '#!/bin/sh\n', { mode: 0o644 });
+ await withEnv({ GROK_BIN: notExec }, () => {
+ expect(resolveGrokBinary()).toBeNull();
+ });
+ await withEnv({ GROK_BIN: 'relative/grok' }, () => {
+ expect(resolveGrokBinary()).toBeNull();
+ });
+ await withEnv({ GROK_BIN: '/tmp/foo/../grok' }, () => {
+ expect(resolveGrokBinary()).toBeNull();
+ });
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/test/helpers/tty-harness.ts b/test/helpers/tty-harness.ts
index a108e0e46c..ce9b607182 100644
--- a/test/helpers/tty-harness.ts
+++ b/test/helpers/tty-harness.ts
@@ -465,7 +465,14 @@ export function launchTty(argv: string[], opts: TtyLaunchOpts = {}): TtySession
const since = waitOpts?.since;
const start = Date.now();
for (;;) {
- const visible = since !== undefined ? stripAnsi(buffer.slice(since)) : stripAnsi(buffer);
+ // Bounded per-poll strip: under a repaint-heavy TUI the (since-scoped)
+ // buffer grows by MBs, and re-stripping all of it every poll is the
+ // quadratic hot loop this harness's consumers keep re-finding. A 256KB
+ // tail caps per-poll work while staying far wider than any single
+ // screen repaint; a pattern would have to scroll >256KB past between
+ // two 200ms polls to be missed.
+ const windowStart = Math.max(since ?? 0, buffer.length - 262_144);
+ const visible = stripAnsi(buffer.slice(windowStart));
for (let i = 0; i < patterns.length; i++) {
const p = patterns[i]!;
const idx = typeof p === 'string' ? visible.indexOf(p) : visible.search(p);
@@ -562,6 +569,93 @@ export interface TranscriptMeta {
[k: string]: unknown;
}
+/**
+ * Minimum secret-value length the redaction machinery acts on. Shorter values
+ * are too collision-prone to blank out (a 3-char "key" would redact innocent
+ * substrings across the transcript). Shared by redactSecrets, dx-explore's
+ * buildRedactMap, and assertNoSecrets — one constant so the layers can never
+ * disagree about what counts as a redactable secret.
+ */
+export const MIN_REDACT_SECRET_LEN = 8;
+
+/**
+ * Replace every occurrence of each secret VALUE with `[REDACTED:<name>]`.
+ * Pure, single pass per secret over the whole string. NOTE: this only
+ * catches CONTIGUOUS occurrences — a value split across PTY frame records
+ * stays split in the serialized frames.jsonl (every frame boundary is a JSON
+ * record boundary), which is why saveTranscript coalesces straddling frames
+ * BEFORE serialization (coalesceSecretStraddles below).
+ */
+export function redactSecrets(text: string, redact?: Record<string, string>): string {
+ if (!redact) return text;
+ let out = text;
+ for (const [name, value] of Object.entries(redact)) {
+ if (!value || value.length < MIN_REDACT_SECRET_LEN) continue;
+ out = out.split(value).join(`[REDACTED:${name}]`);
+ }
+ return out;
+}
+
+/**
+ * Merge any run of frames that a secret value straddles into one frame, so a
+ * subsequent per-string redaction pass sees the value contiguously. Without
+ * this, a key split across two output bursts survives frames.jsonl as two
+ * innocent-looking halves that are trivially joinable (verified empirically
+ * in review). Pure: returns a new array; timing of the merged frame is the
+ * first covered frame's tMs.
+ */
+export function coalesceSecretStraddles(
+ frames: readonly PtyFrame[],
+ redact?: Record<string, string>,
+): PtyFrame[] {
+ const values = Object.values(redact ?? {}).filter((v) => v && v.length >= MIN_REDACT_SECRET_LEN);
+ if (values.length === 0 || frames.length === 0) return [...frames];
+
+ // Frame start offsets in the joined stream.
+ const starts: number[] = new Array(frames.length);
+ let acc = 0;
+ for (let i = 0; i < frames.length; i++) {
+ starts[i] = acc;
+ acc += frames[i]!.data.length;
+ }
+ const joined = frames.map((f) => f.data).join('');
+
+ // Mark every frame boundary that falls INSIDE a secret occurrence:
+ // mergeWithNext[i] = the boundary between frame i and i+1 must go away.
+ const mergeWithNext = new Array<boolean>(frames.length - 1).fill(false);
+ let anyMerge = false;
+ for (const value of values) {
+ let idx = joined.indexOf(value);
+ while (idx >= 0) {
+ const end = idx + value.length; // exclusive
+ for (let b = 0; b < mergeWithNext.length; b++) {
+ const boundary = starts[b + 1]!;
+ if (boundary > idx && boundary < end) {
+ mergeWithNext[b] = true;
+ anyMerge = true;
+ }
+ }
+ idx = joined.indexOf(value, idx + 1);
+ }
+ }
+ if (!anyMerge) return [...frames];
+
+ const out: PtyFrame[] = [];
+ let i = 0;
+ while (i < frames.length) {
+ let data = frames[i]!.data;
+ const tMs = frames[i]!.tMs;
+ let j = i;
+ while (j < mergeWithNext.length && mergeWithNext[j]) {
+ data += frames[j + 1]!.data;
+ j++;
+ }
+ out.push({ tMs, data });
+ i = j + 1;
+ }
+ return out;
+}
+
/**
* Write a transcript bundle into `dir`:
* meta.json — scenario, argv, timing, exit code, notes
@@ -572,16 +666,29 @@ export interface TranscriptMeta {
*/
export function saveTranscript(
dir: string,
- data: { frames: readonly PtyFrame[]; raw: string; meta: TranscriptMeta },
+ data: {
+ frames: readonly PtyFrame[];
+ raw: string;
+ meta: TranscriptMeta;
+ /** Secret values to redact (name → value) from EVERY written artifact.
+ * The explicit seam: callers own which values are secret. */
+ redact?: Record<string, string>;
+ },
): void {
fs.mkdirSync(dir, { recursive: true });
- fs.writeFileSync(path.join(dir, 'meta.json'), JSON.stringify(data.meta, null, 2));
- fs.writeFileSync(path.join(dir, 'raw.txt'), data.raw);
- fs.writeFileSync(path.join(dir, 'visible.txt'), stripAnsi(data.raw));
+ const r = (s: string) => redactSecrets(s, data.redact);
+ fs.writeFileSync(path.join(dir, 'meta.json'), r(JSON.stringify(data.meta, null, 2)));
+ fs.writeFileSync(path.join(dir, 'raw.txt'), r(data.raw));
+ fs.writeFileSync(path.join(dir, 'visible.txt'), r(stripAnsi(data.raw)));
+ // A secret split across PTY frames is two innocent halves in frames.jsonl
+ // (every frame boundary is a JSON record boundary — the serialized string
+ // never contains the contiguous value). Coalesce straddling frames FIRST,
+ // then redact; per-frame timing granularity is lost only for the merged run.
+ const coalesced = coalesceSecretStraddles(data.frames, data.redact);
fs.writeFileSync(
path.join(dir, 'frames.jsonl'),
- data.frames.map((f) => JSON.stringify(f)).join('\n') + (data.frames.length ? '\n' : ''),
+ r(coalesced.map((f) => JSON.stringify(f)).join('\n') + (coalesced.length ? '\n' : '')),
);
const stalls = computeStalls(data.frames, { endMs: data.meta.durationMs });
- fs.writeFileSync(path.join(dir, 'stalls.md'), renderStallsReport(stalls, data.meta.durationMs));
+ fs.writeFileSync(path.join(dir, 'stalls.md'), r(renderStallsReport(stalls, data.meta.durationMs)));
}
diff --git a/test/tty-harness.test.ts b/test/tty-harness.test.ts
index 60bf712f27..55d4d02dab 100644
--- a/test/tty-harness.test.ts
+++ b/test/tty-harness.test.ts
@@ -19,6 +19,8 @@ import {
parseDriveCommand,
buildClaudeTuiSeed,
saveTranscript,
+ redactSecrets,
+ coalesceSecretStraddles,
launchTty,
ptySupported,
KEY_MAP,
@@ -192,6 +194,74 @@ describe('saveTranscript', () => {
rmSync(dir, { recursive: true, force: true });
}
});
+
+ test('redact: the raw secret value appears in NO written file, the marker does', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gb-tty-unit-'));
+ const secret = 'xai-supersecret-value-1234';
+ try {
+ const frames: PtyFrame[] = [
+ // Secret split across a frame boundary — the joined-string pass
+ // still catches it in frames.jsonl's neighbors and in raw/visible.
+ { tMs: 10, data: `key is ${secret.slice(0, 10)}` },
+ { tMs: 20, data: `${secret.slice(10)} — do not log\n` },
+ { tMs: 30, data: `again: ${secret}\n` },
+ ];
+ saveTranscript(dir, {
+ frames,
+ raw: frames.map((f) => f.data).join(''),
+ meta: {
+ scenario: 'unit-redact',
+ argv: ['sh'],
+ startedAtIso: '2026-08-14T00:00:00.000Z',
+ exitCode: 0,
+ durationMs: 100,
+ },
+ redact: { XAI_API_KEY: secret, EMPTY: '', SHORT: 'abc' },
+ });
+ for (const f of ['meta.json', 'raw.txt', 'visible.txt', 'frames.jsonl', 'stalls.md']) {
+ expect(readFileSync(join(dir, f), 'utf8')).not.toContain(secret);
+ }
+ // The REAL frames assertion: a per-record grep is vacuous for a secret
+ // split across frame boundaries (each half is innocent) — join the data
+ // fields and assert the reassembled stream carries no secret. This is
+ // what coalesceSecretStraddles guarantees.
+ const joined = readFileSync(join(dir, 'frames.jsonl'), 'utf8')
+ .trim().split('\n')
+ .map((l) => (JSON.parse(l) as { data: string }).data)
+ .join('');
+ expect(joined).not.toContain(secret);
+ expect(joined).toContain('[REDACTED:XAI_API_KEY]');
+ expect(readFileSync(join(dir, 'raw.txt'), 'utf8')).toContain('[REDACTED:XAI_API_KEY]');
+ expect(readFileSync(join(dir, 'visible.txt'), 'utf8')).toContain('[REDACTED:XAI_API_KEY]');
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('redactSecrets is pure and skips empty/too-short values', () => {
+ expect(redactSecrets('hello world', undefined)).toBe('hello world');
+ expect(redactSecrets('abc abc', { K: 'abc' })).toBe('abc abc'); // <8 chars: skipped
+ expect(redactSecrets('token=longsecret42 end', { K: 'longsecret42' })).toBe('token=[REDACTED:K] end');
+ });
+
+ test('coalesceSecretStraddles merges only the frames a secret spans', () => {
+ const secret = 'straddling-secret-99';
+ const frames: PtyFrame[] = [
+ { tMs: 1, data: 'before ' },
+ { tMs: 2, data: `x${secret.slice(0, 7)}` },
+ { tMs: 3, data: secret.slice(7, 14) },
+ { tMs: 4, data: `${secret.slice(14)} after` },
+ { tMs: 5, data: 'untouched' },
+ ];
+ const out = coalesceSecretStraddles(frames, { K: secret });
+ expect(out.length).toBe(3); // frames 2-4 merged; 1 and 5 intact
+ expect(out[0]!.data).toBe('before ');
+ expect(out[1]!.data).toContain(secret); // contiguous now — redactable
+ expect(out[2]!.data).toBe('untouched');
+ // No secrets → identity (new array, same content).
+ const same = coalesceSecretStraddles(frames, {});
+ expect(same.map((f) => f.data)).toEqual(frames.map((f) => f.data));
+ });
});
describe.skipIf(!ptySupported())('launchTty (live PTY smoke)', () => {