The complete guide to Grok Build

By

Updated

Tagged: AI

Learn Grok Build across the desktop app (formerly Cursor) and the grok CLI: Agents Window, IDE, Plan and Debug Mode, MCP, Cloud Agents, and automation.

Grok Build is SpaceXSI’s coding agent platform, and it brings two interfaces under one roof.

On November 30, 2026, SpaceXSI renamed Cursor to Grok Build.

Cursor became the Grok Build desktop app, with a rewritten Agents Window and the classic VS Code-based editor still beside it.

The original terminal coding agent from xAI became the Grok Build TUI (grok), and it now runs the same Cursor agent harness underneath, and it also supports third-party models.

The Grok Build product page showing both the desktop download and the terminal CLI

You can use Grok Build visually in the desktop app, in your browser, on mobile, or straight from your terminal. You describe a change, and the agent reads your files, edits them, runs tests or opens the app, and shows you the diff to review.

In this guide we’ll cover both sides of Grok Build.

First we’ll walk through the desktop app (Agents Window, IDE, Plan Mode, Debug Mode, Design Mode, Agent Review, Bugbot, Cloud Agents, Projects, Computer Use, Voice Chat).

Then we’ll dive into the terminal CLI (grok), including a real debugging walkthrough, sessions, the Agent Dashboard, goals, workflows, headless scripting, ACP.

At the end we’ll cover the shared customization layer (rules, skills, subagents, MCP, hooks, permissions) that works across both.

What Grok Build does

A language model on its own can generate code from a prompt. Grok Build pairs the model with tools that work on your actual repository, reading files, editing code, running shell commands, and driving a browser or desktop app to check its own work.

Ask it to fix a broken calculation or a button that’s not working, and it will search your project, read the files, propose edits, and run your tests or dev server, over several rounds, before coming back to you.

You still verify the result yourself at the end. An agent’s summary can sound completely confident while a subtle edge case is still broken.

How Grok Build fits in the Grok ecosystem

SpaceXSI unified all its products under the Grok brand, so many names look similar.

Here’s how they divide the work:

ProductWhat you use it for
GrokGeneral chat assistant on web, mobile, and X
Grok BuildCoding agent across the desktop app, web, mobile, and terminal CLI
Grok BotPersistent AI teammates with their own cloud computer
Grok APICalling Grok models, voice, and image APIs from your own software
Grok OriginAgent-first code repository hosting

I cover Grok Bot separately (also available as the free Grok Bot Handbook). Here we’ll stick to Grok Build.

Desktop app vs Terminal UI

Both interfaces share the same agent harness, model catalog and project config, so you can move between them on the same repo.

Here’s how they compare:

AreaGrok Build desktop appGrok Build TUI (grok)
Primary interfaceRewritten Agents Window + classic VS Code-based IDEFullscreen terminal UI + headless CLI
Best forVisual web work, parallel chats, diffs, Design Mode, Tab editsTerminal-first workflows, SSH servers, scripts, CI, ACP clients
Command namegrok-build (opens the desktop app)grok (and legacy agent / cursor-agent keep working)
Cloud & remoteLocal, Cloud Agents, Projects, Live Apps, remote SSHLocal, worktrees, mobile remote control, headless automation
Built-in extrasBuilt-in browser, Annotate, Debug Mode, Voice Chat, Computer UseAgent Dashboard, /goal, .rhai workflows, /loop, /btw, ACP

One small migration date to remember if your team uses integrations: starting December 7, 2026, tagging @Build will replace @Cursor in Slack, GitHub, Linear and Jira. Existing CLI and API automations calling agent will continue to work as-is.

If you’re still deciding if an IDE, a terminal agent or a web builder is your thing, I compared the tradeoffs in IDE, CLI, vibe coding tool, …how to decide?.

Plans, usage pools, and models

Grok Build is sold as part of The X Subscription, which bundles Grok Build, Grok chat, and X.

Every paid plan gives you a weekly pool of included usage shared across the desktop app, the grok CLI, Cloud Agents, Grok Bot, and the Grok apps.

PlanListed monthly priceIncluded weekly pool (Grok & Composer)Third-party models
Free$0LimitedNot available
Plus$8BaseNot available
Premium$304x PlusNot included (API list price from prepaid credit)
Super$10015x PlusNot included (API list price from prepaid credit)
Ultra$20050x PlusNot included (API list price from prepaid credit)

Check the models and pricing guide before you subscribe, as prices exclude tax and plans change.

Non-Grok models are not included in new Grok Build subscriptions. Your weekly usage pool only covers SpaceXSI’s own models (Grok 4.7, Grok 4.6, Grok 4.5, and Composer 2.5, plus their Fast variants).

On December 2, 2026, Grok Build added OpenAI’s GPT-6 family (GPT-6.2 Astra, GPT-6.2 Sol, and the rest of the GPT-6 lineup) alongside Anthropic (Claude), Google (Gemini), and Meta (Muse Wonder) across both the desktop app and the terminal CLI.

The catch is billing. Even on Premium ($30), Super ($100), or Ultra ($200), none of those third-party models draw from your weekly pool.

Pick GPT-6.2 Sol, Claude, or Gemini and Grok Build tells you the model isn’t included in your weekly usage and asks you to buy prepaid credits, billed at API list price from the first request. On Teams and Enterprise, eligible third-party models also add a $0.25 per million token Grok Build Token Rate on top of API pricing.

That changes the math if you mainly want to code with OpenAI, Claude, or Gemini. As Theo pointed out, paying for a Grok Build subscription and then buying prepaid credits at API rates for non-Grok models is hard to recommend when first-party plans like ChatGPT / Codex, Claude, or Google AI give you far more usage on those models directly (I compared them in What’s the best value AI subscription?).

Grok Build vs first-party plans for GPT-6, Claude, and Gemini

Here’s what the same monthly budget buys if your main goal is coding with OpenAI, Anthropic, or Google models:

BudgetGrok Build (The X Subscription)First-party alternativeNon-Grok models included?
$20 to $30/moPremium ($30): 4x Plus Grok/Composer pool + Grok BotChatGPT Plus ($20), Claude Pro ($20, or $17/yr), or Google AI Pro ($19.99)No in Grok Build (prepaid API credits), yes in each first-party plan
$100/moSuper ($100): 15x Plus Grok/Composer pool + Grok BotChatGPT Pro 100 ($100), Claude Max ($100), or Google AI Ultra 5x ($99.99)No in Grok Build (prepaid API credits), yes in each first-party plan
$200/moUltra ($200): 50x Plus Grok/Composer pool + Grok BotChatGPT Pro 200 ($200), Claude Ultra ($200), Google AI Ultra 20x ($199.99), or Pro 100 + Claude Max ($200)No in Grok Build (prepaid API credits), yes (even both OpenAI and Claude at once for $200)

Running GPT-6.2 Sol ($2 input / $10 output per million tokens) or Claude Opus 5.5 ($4 / $20) inside Grok Build comes straight out of prepaid credit on top of your $30 to $200 plan. On a $200 budget, splitting $100 into ChatGPT Pro 100 and $100 into Claude Max gives you heavy weekly Codex and Claude Code pools directly, plus bundled platform API credits for your own apps, without paying per token for your editor runs.

Grok Build’s subscription pool makes sense when you actually want Grok 4.7, Composer 2.5, Grok Bot, and the X bundle as your daily driver, or when you’re still on a legacy Cursor plan.

If you’re still on a legacy Cursor plan (Pro, Pro+, Ultra, or legacy Teams), it keeps working with two monthly pools: one for first-party models and an Other Models pool that still covers third-party models. Switching to The X Subscription is permanent and drops that included third-party allowance, so check the legacy plans comparison before migrating.

API keys bill separately too. If we authenticate the CLI using XAI_API_KEY instead of signing in through the browser, those calls bill at API token rates and never pull from our subscription pool. I always run /usage inside the CLI or check the dashboard to see which bucket I’m spending from.

Let’s check our installed versions and available models right from the terminal:

grok --version
grok-build --version
grok models

Terminal showing grok CLI version 1.0.92, grok-build desktop version 3.32.23, and the available Grok models

Notice that grok-build-0.1 reached end of life on November 19, 2026. If you have older scripts or configs pinning that ID, switch them to an active model like grok-4.7 or grok-4.7-build-fast.

In the desktop app, you can pick the model from the dropdown next to the composer.

A fast and cheaper model like Composer 2.5 or grok-4.7-build-fast is more than enough for small styling edits.

I recommend saving the stronger reasoning models and higher effort levels for difficult bugs, where you already have a clean reproduction.

I explain how automatic model routing compares to choosing a fixed model in model routing.

Part 1: The Grok Build desktop app

The desktop app is where Cursor users will feel right at home, only much faster.

Install and open the Agents Window

You can download the desktop installer for macOS, Windows, and Linux from grok.com/product/build (or cursor.com/downloads). On Debian/Ubuntu you can install via apt, and on RHEL/Fedora via dnf (the quickstart docs have the exact repository commands).

Open Grok Build and sign in through your browser.

You land straight in the Agents Window, which SpaceXSI rewrote from scratch off the VS Code renderer internals, moving heavy work onto worker threads.

It boots faster, uses less memory, and switches between long agent chats instantly.

The rewritten Grok Build Agents Window on macOS showing the sidebar, prompt composer, model picker, voice button, and IDE switch

Look at what sits right in front of you in the new Agents Window:

  • Left sidebar: New Chat, Automations, Customize, pinned threads, Projects, and your recent history.
  • Top right: the IDE button (IDE ↗) to jump into the classic VS Code-based editor anytime, and the side-panel toggle.
  • Composer: pick the repo (~/www/flaviocopes.com), branch (master), execution target (This Mac or Run in Cloud), model (Grok 4.7 High Fast), dictation mic, or the real-time Voice Chat waveform button.
  • Quick actions: Plan New Idea (Shift+Tab), Multitask, and Run in Cloud.
  • Migration helper: at the bottom, you can import existing Claude Code conversations straight into Grok Build.

You can also switch between the Agents Window and the editor from the Command Palette (Cmd+Shift+P on macOS, Ctrl+Shift+P on Windows and Linux) with Open Agents Window and Open IDE.

Read the Agents Window guide for the full layout.

A quick note on the screenshots in the walkthrough sections below: some feature shots come from earlier Cursor versions before the rename, so some icons or labels might look slightly different in Grok Build 3.32+, but the workflow is the same.

Start a project and use the side panel

Let’s try the desktop workflow on something concrete.

Create an empty folder named tic-tac-toe (assuming you have Node.js LTS, npm and Git installed) and open it from the workspace picker in the Agents Window.

Give the agent a prompt with a clear finish line, instead of a vague one-liner:

Build a local two-player tic-tac-toe game with Vite and React.
Use JavaScript and npm. Keep everything in this project folder.
Show whose turn it is, prevent playing in occupied squares,
detect wins and draws, and add a New game button.
Keep the layout usable on a phone.
Use accessible buttons for the squares and a text status message.
Do not add accounts, a backend, or online multiplayer.
Run the production build and report the command and result.

Once the agent scaffolds the project and installs the dependencies, ask it to start the dev server and open the built-in browser:

Run the app and open it in the built-in browser.

The generated tic-tac-toe game running in the built-in browser panel

The side panel next to the conversation gives you 4 views of what the agent is doing:

PanelUse it to answer
FilesWhere did the agent put the code?
BrowserWhat does the running app actually do?
TerminalWhat happened when a command ran?
GitWhat changed since my last commit?

The file panel showing the generated project structure beside the conversation

Before asking for more features, play the game yourself. Win once, draw once, click an occupied square, try clicking an empty square after someone wins.

If you spot a bug, describe the exact steps rather than guessing which state variable broke:

X wins across the top row. After the winning move,
I can still click an empty square and add another mark.
Stop accepting moves after a win or draw.
Keep New game working and check both cases.

Once it works, run git init and commit the clean baseline, so every future edit starts from a known state.

If you want a refresher on React components or Git commits, grab the free React handbook or Git cheat sheet handbook.

Ask, Plan, Agent, and Debug Mode

The mode selector beside the prompt controls how the agent will handle your request:

ModeWhen to use it
AskUnderstand existing code without editing files
Plan (Shift+Tab)Research the repo, answer clarifying questions, and approve a plan first
AgentImplement a clear change directly
DebugInvestigate a reproducible runtime or build bug with temporary logging

I use Plan whenever a change touches multiple files, like adding a scoreboard with a reset action. Read the plan carefully for scope creep (like an unwanted dependency or localStorage persistence you didn’t ask for) before approving it.

See the desktop Plan Mode docs to see how to save plans in the workspace.

Debug Mode is my favorite tool for bugs you can reproduce, but you can’t immediately explain. Instead of guessing at a fix, it forms hypotheses, adds logging if needed, and asks you to reproduce the issue.

I used Debug Mode on a real build warning on this site, about an invalid path pattern in _headers. I picked Debug and pasted the build output:

Selecting Debug mode and pasting the site build warnings into the prompt

It pointed out the invalid pattern, fixed it, and listed the steps to rebuild and verify the warnings were gone:

Debug mode showing the fix, reproduction steps, and the Mark Fixed button

Once you confirm the bug is gone, click Mark Fixed so the app can remove the temporary logging and leave just the fix.

Visual edits with Design Mode and image generation

Sometimes describing a CSS tweak in words might point the agent at the wrong element.

Design Mode (also labeled Annotate in the browser toolbar, see the Design Mode docs) lets you click any element right in the built-in browser and attach a note:

The Design Mode icon above the running game in the built-in browser

Turn it on, click an element, and write what should change.

The agent will receive the DOM selection and a screenshot, along with your note:

A visual note asking the agent to change the selected mark color to yellow

The agent edits the source code and the preview updates right away:

The running game after the visual edit changed the marks to yellow

How a visual edit in Design Mode updates source codeSelect an element in the built-in browser, attach a note, let the agent edit the source files, and check the updated preview.Select element inpreviewAttach your noteSelection +screenshot sent toagentAgent edits sourcefilesDev server updatespreviewCheck desktop andmobile widths

Always check both desktop and mobile widths after a visual edit, because changing a shared class can affect other buttons or headings on the page.

You can also ask the agent to generate images directly in chat (for example, Generate a hero image for the home page, matching the site's colors). It reads your project for context and writes the image file directly into your workspace.

Work in the classic IDE

Whenever you want to edit code by hand, click IDE ↗ in the top right of the Agents Window (or run Open IDE from the Command Palette). You’ll get the full VS Code-compatible editor, with your extensions, split panes and Explorer.

Two features stand out inside the IDE:

  • Tab autocomplete: start typing a function like export function turnLabel(player) in src/turn-label.js, and Tab predicts the rest in gray text. Press Tab to accept all of it, Escape to reject it, or Cmd+Right Arrow (Ctrl+Right Arrow on Windows/Linux) to accept word by word.
  • Send selected code to Agent: highlight a function and press Cmd+L (Ctrl+L on Windows/Linux) or Cmd+K to attach those exact lines to Agent.

For example, select turnLabel and ask Agent to reject invalid players:

Change only the selected turnLabel function.
Keep the existing labels for X and O.
For every other value, return 'Choose X or O'.
Use no dependencies and leave the rest of the project alone.

You get back a focused edit like this:

export function turnLabel(player) {
  if (player !== 'X' && player !== 'O') {
    return 'Choose X or O'
  }

  return `Next player: ${player}`
}

I sometimes have small helpers that I want to test directly with Node, before I wire them to the UI:

node --input-type=module -e "
import assert from 'node:assert/strict'
import { turnLabel } from './src/turn-label.js'
assert.equal(turnLabel('X'), 'Next player: X')
assert.equal(turnLabel('O'), 'Next player: O')
assert.equal(turnLabel(null), 'Choose X or O')
assert.equal(turnLabel('Z'), 'Choose X or O')
console.log('Turn labels passed')
"

Agent Review, Bugbot, and Checkpoints

Before committing a big change, check it with the built-in review tools.

In the Agents Window, the diff view has a Find Issues button that runs a targeted review on your uncommitted changes:

The Find Issues button in the Agents Window review view

It will look at the diff and tell you if there are real bugs, or if nothing stood out:

Agent Review reporting that it found no issues in the diff

For pull requests on GitHub or GitLab, Bugbot runs the same kind of review automatically whenever a PR opens or updates.

Included starting on the Premium plan.

Bugbot commenting on a pull request to flag a CORS bug

Each comment has a button to open the desktop app with a ready-to-run fix prompt (or hand it off to a Cloud Agent in the browser):

Desktop app opened from a Bugbot comment with the fix prompt ready

If an agent edit goes wrong locally, you don’t have to worry. Grok Build creates checkpoints automatically during a session, independent of Git.

You can hover over an earlier prompt and choose Restore Checkpoint to preview and roll back files to that point.

SituationBest recovery tool
Reject one bad hunk during reviewDiff view reject control
Undo a whole agent turnRestore Checkpoint
Save a clean milestone permanentlyGit commit
Undo part of a file that also has good editsAsk Agent for a targeted correction
Recovering from an unwanted edit in Grok BuildStop the active agent, preserve useful edits, choose either a targeted correction or a checkpoint restore, and verify with git diff.YesNoStop active agentCheck uncommittedmanual editsKeep part of thechange?Ask for a targetedcorrectionPreview and restorecheckpointCheck app and gitdiff

Checkpoints only revert local files. Anything the agent pushed to Git, or sent to an external MCP tool, will stay sent.

Cloud Agents, Live Apps, Projects, Computer Use, and Voice Chat

Grok Build is not just a local laptop session.

When I want work to keep going after I close my laptop, I use Cloud Agents, which run tasks on a remote VM instead of my computer.

Click Run in Cloud (or switch the location menu from local to Cloud) in the Agents Window, or open grok.com/build, which now runs on the same rewritten frontend as the desktop Agents Window.

Switching an agent run between Local and Cloud in the Agents Window

Cloud Agents can clone your repo, edit files, run tests, control a browser, and push a branch for review.

We can hand an agent back and forth between local and cloud, or spin up a cloud subagent from a local chat with /in-cloud.

Remote SSH agents also keep running even when we close our laptop.

See the Cloud Agents docs to set it up and give GitHub permissions.

We can also take a web app past localhost with Apps (Live Apps).

Ask a Cloud Agent to build and publish a hosted app, and it will take care of hosting, provision a managed PostgreSQL database when needed, put private or team apps behind SSO, and run automated security checks for leaked secrets before anything goes live.

For multi-PR features or big migrations, Projects gives us a long-lived coordinator agent instead of a pile of separate chats.

Projects now support multiplayer workspaces, so a team can share tasks, docs, context and memory, while each person still has their own coordinator chat.

Read the Projects docs or my walkthrough in How to use Cursor Projects.

Computer Use lets an agent see the screen, click controls, and type inside desktop apps and the iOS Simulator, both locally and on cloud VMs, if you’re building native macOS apps or iOS apps instead of web pages.

I explained how to set it up and the permissions needed in How to use Cursor Computer Use.

Voice Chat turns the empty composer waveform button into a live 2-way voice call, powered by Grok Voice, across desktop, web and iOS (Android app coming in closed beta).

You can ask what an agent changed, or steer a task out loud while the coding agent is working in the background.

It’s separate from the speech-to-text dictation (Cmd+Shift+Space).

When Privacy Mode is on, there’s zero data retention.

Agent SDK exposes the harness that powers Grok Build, to let you embed this same agent loop inside your own software, to build and deploy your own agents.

Part 2: The Grok Build CLI (grok TUI)

If you live in the terminal, work over SSH or want to script coding agents in CI, the Grok Build TUI is the companion terminal product.

It keeps xAI’s fast native terminal interface, and now runs Cursor’s agent harness underneath, bringing third-party models, dynamic memory, agent-to-agent messaging and remote mobile control to your shell.

Install and sign in to the CLI

On macOS, Linux, and WSL, install the grok binary with:

curl -fsSL https://x.ai/cli/install.sh | bash

Grok Build CLI installer completing on macOS and linking the grok command

Want to inspect the script before running it? Download it first:

curl -fsSL https://x.ai/cli/install.sh -o /tmp/grok-install.sh
less /tmp/grok-install.sh
bash /tmp/grok-install.sh

On Windows PowerShell, run:

irm https://x.ai/cli/install.ps1 | iex

Verify the install and inspect the available flags:

grok version
grok --help

Terminal showing grok version and command-line options from grok --help

You can check for updates any time with grok update --check and upgrade with grok update.

See the Terminal UI overview if the instructions for your platform change.

The first time you run grok the browser will open to authenticate, or you can explicitly do so:

grok login

Grok login showing a browser authorization URL and successful sign-in

On a headless server or SSH box with no browser, use device-code auth instead:

grok login --device-auth

For CI pipelines, export XAI_API_KEY from your secret store.

You can sign out and wipe the cached tokens with grok logout.

Never commit ~/.grok/ to a repository, as it contains your local config, sessions, and MCP OAuth tokens.

Hands-on CLI walkthrough: debug a broken project

Let’s do a real terminal session on a small buggy JavaScript project, so you can see the full CLI loop.

(If you want a quick JavaScript or Node refresher, see the free JavaScript handbook and Node.js handbook)

Create a scratch directory and initialize Git:

mkdir grok-build-demo
cd grok-build-demo
git init

Add package.json using Node’s built-in test runner:

{
  "name": "grok-build-demo",
  "private": true,
  "type": "module",
  "scripts": {
    "test": "node --test"
  }
}

Create median.js with a deliberately broken median function:

export function median(values) {
  values.sort()
  return values[values.length / 2]
}

Put six tests in median.test.js:

import test from 'node:test'
import assert from 'node:assert/strict'
import { median } from './median.js'

test('finds the middle value with numeric sorting', () => {
  assert.equal(median([10, 2, 3]), 3)
})

test('averages the two middle values', () => {
  assert.equal(median([1, 2, 10, 20]), 6)
})

test('keeps the input array unchanged', () => {
  const values = [3, 1, 2]
  median(values)
  assert.deepEqual(values, [3, 1, 2])
})

test('rejects an empty array', () => {
  assert.throws(() => median([]), RangeError)
})

test('supports one value', () => {
  assert.equal(median([7]), 7)
})

test('supports negative and duplicate values', () => {
  assert.equal(median([-5, -1, -1, 8]), -1)
})

Run npm test to confirm all six fail:

npm test

Node.js test runner reporting all six median tests failing before the fix

Commit this broken baseline so we can diff everything Grok touches:

git add package.json median.js median.test.js
git commit -m 'Add median exercise with failing tests'

Now launch Grok with the workspace sandbox profile, which restricts writes to your project folder, Grok’s home directory, and temp paths:

grok --sandbox workspace

First launch in a new directory asks whether you trust its contents:

Grok Build asking whether to trust the grok-build-demo directory

Confirm trust and you land on the TUI welcome screen:

Grok Build TUI welcome screen in the demo project with Grok 4.7 selected

Start with a read-only diagnosis prompt, so you can watch how it inspects the repo:

Explain this project and why npm test fails.
Inspect median.js and median.test.js.
Don't edit files or run commands that change project state.

Grok Build processing the diagnosis prompt without editing files

In this run, Grok caught every single bug (lexicographical sort, fractional index, missing even-length average, input mutation, missing empty-array check) without editing a file:

Grok explaining all median bugs and reporting six failed tests with no files modified

You can also point Grok straight at a file with @median.js.

Now ask for the fix with clear constraints (a good habit from spec-driven development):

Fix median.js so all existing tests pass.
Keep the input array unchanged and throw RangeError for an empty array.
Don't change the tests or add dependencies.
Run npm test, then explain the diff and any remaining limitations.
Don't commit or push.

A clean fix looks like this:

export function median(values) {
  if (values.length === 0) {
    throw new RangeError('Cannot calculate the median of an empty array')
  }

  const sorted = [...values].sort((a, b) => a - b)
  const middle = Math.floor(sorted.length / 2)

  if (sorted.length % 2 === 1) {
    return sorted[middle]
  }

  return (sorted[middle - 1] + sorted[middle]) / 2
}

Quit with /quit (or open a second terminal) and check the diff and tests yourself:

git status --short
git diff -- median.js median.test.js package.json
npm test

Once everything passes and only median.js changed, commit it:

git add median.js
git commit -m 'Fix median calculation'

Plan mode, Agent Dashboard, sessions, and background tasks

The TUI packs a lot of workflow controls into slash commands and shortcuts.

Plan mode in the CLI works like the desktop app. Start with /plan (or press Shift+Tab) and reopen the preview anytime with /view-plan:

KeyAction in CLI plan preview
aApprove and start building
sRequest changes
cComment on a line or range
qQuit plan preview and leave Plan mode
TabSwitch focus between preview and prompt

One catch from the CLI Plan mode docs: before approval, Grok’s file-edit tools can only touch the plan file, but shell commands and subagents still follow your active permission mode. Pair Plan mode with a sandbox when inspecting a sensitive repo.

Agent Dashboard gives you a live overview of every running TUI session, grouped by state (Needs input, Working, Idle, Completed, Failed).

Open it from the shell with grok dashboard, inside a session with /dashboard, or with Ctrl+\.

You can peek at any agent, answer permission prompts inline with number keys, dispatch new prompts, and toggle Git worktrees with Ctrl+W (see the Agent Dashboard docs).

Sessions and migrating from other CLIs live under ~/.grok/sessions/ (see sessions for how this compares with Claude Code and Codex):

grok -c                  # continue most recent session in this folder
grok sessions list       # list saved sessions
grok --resume <id>       # resume a specific session

Don’t confuse --resume with --session-id, which sets a UUID on a brand-new session.

Inside a session you can also:

  • Branch a conversation with /fork or Ctrl+F (opening a session already active in another window also offers to fork).
  • Check context usage with /context and trim old turns with /compact <what to keep>.
  • Roll files and chat back with /rewind (reverted uncommitted edits are gone for good, so commit first).
  • Import your Claude Code setup (permissions, env vars, MCP servers, hooks) with /import-claude, or pick up past sessions from other CLIs with /resume-claude and /resume-codex.
  • Use dynamic memory (/remember, grok memory) so insights carry across sessions, or pass --no-memory for a clean run.
  • Steer a running laptop session from the Grok Build mobile app with remote control, while commands and file edits still execute locally on your machine.

Worktrees isolate parallel terminal sessions on separate Git branches:

grok -w

By default -w copies uncommitted changes from your current HEAD. Pass --ref to start with a clean branch.

You can list active worktrees with grok worktree list and remove finished ones with the worktree management commands (see the worktree docs).

Background tasks, queueing, /btw and /loop

Long running commands can be moved out of the way.

Press Ctrl+B to send a running foreground command to the background.

Ctrl+G (or /tasks) lets you see what tasks are currently running.

You can type while Grok is busy to queue follow-up prompts (/queue).

Press Ctrl+C to abort a turn (Esc does not cancel a running turn).

Need a quick side question without interrupting the current run? Use /btw (see side chats):

/btw Why does Array.sort() need a comparison function for numbers?

If you need to perform a recurring check inside your session, you can use /loop (minimum 60 seconds, expires after 7 days):

/loop 5m Run npm test and report only new failures. Don't edit files.

Goals and repeatable workflows

When a job takes multiple fix-and-verify rounds, /goal keeps iterating until a concrete target is met (see goal mode):

/goal Add finite-number input validation to median(), keep existing valid-input behavior, and finish when regression tests and new invalid-input tests pass. Don't change unrelated files or publish anything.

When Grok thinks it’s done, reviewer subagents will check the work and push it back if there are gaps.

You can control an active goal using /goal status, /goal pause, /goal resume, /goal clear and pass --budget <tokens> so a wide goal does not burn through your usage without you noticing.

Workflows are a way to save a repeatable multi-agent routine.

A workflow is a fixed pipeline that is saved as an executable .rhai script under .grok/workflows/ or ~/.grok/workflows/:

/create-workflow Review the current branch for correctness bugs, verify each finding with code or a reproducing test, and return only actionable findings. Don't edit project source.

Always read the .rhai file generated before running it.

You can launch a saved workflow using /workflow <name>, see which workflows are running with /workflows, and start a background research with /deep-research <query>.

Headless scripting, CI, and ACP

Headless mode runs a prompt without opening the fullscreen TUI (compare with claude -p and codex exec in headless mode):

grok --no-auto-update --sandbox read-only --no-subagents \
  -p 'Explain median.js and identify gaps in its tests. Do not edit files.'

A bare -p reads from stdin (grok -p < prompt.txt), and in non-TTY environments like CI or cron a positional prompt runs headlessly automatically.

Pick the output format your caller expects:

FormatOutput
plainHuman-readable text
jsonOne JSON object at the end
streaming-jsonNewline-delimited JSON events as work progresses

To drive Grok safely from Node.js, without shell interpolation, you can use spawn() with an argument array (review.mjs):

import { spawn } from 'node:child_process'

const child = spawn('grok', [
  '--no-auto-update',
  '--sandbox', 'read-only',
  '--no-subagents',
  '--max-turns', '8',
  '-p', 'Review median.js for correctness bugs. Do not edit files.',
  '--output-format', 'json'
], {
  cwd: process.cwd(),
  stdio: ['ignore', 'pipe', 'inherit']
})

let output = ''

child.stdout.setEncoding('utf8')
child.stdout.on('data', chunk => {
  output += chunk
})

child.on('error', error => {
  console.error(error.message)
  process.exitCode = 1
})

child.on('close', code => {
  if (code !== 0) {
    console.error(`Grok exited with code ${code}`)
    process.exitCode = 1
    return
  }

  try {
    console.log(JSON.parse(output))
  } catch {
    console.error('Grok did not return a valid JSON report')
    process.exitCode = 1
  }
})

Run it with node review.mjs.

In CI jobs I always pass --no-auto-update and --max-turns, and instead of --always-approve I pair them with a job-level timeout and narrow permissions.

Headless runs also have a 5-minute inactivity timeout and automatic error resumption. See headless scripting and Enterprise Deployments.

To connect another editor or custom client to Grok Build over ACP (Agent Client Protocol, see agent client protocol), you launch the stdio JSON-RPC entry point:

grok agent stdio

ACP is the protocol used to connect the editor to the agent.

MCP is the protocol used to connect the agent to external tools.

Assistant text is streamed using session/update notifications, while session/prompt returns the completion metadata.

Daily workflows across Desktop and CLI

Once you know the buttons and commands, the real productivity jump comes from building a steady rhythm. Most people struggle with coding agents because they open a huge prompt, let the model roam across ten files, and then spend an hour untangling a messy diff.

A repeatable daily loop keeps every change small, verifiable, and easy to roll back.

Picking between Agents Window, classic IDE, and grok CLI

Because Grok Build gives you the Agents Window, the classic VS Code-based IDE, and the grok terminal CLI, you will often pause and ask which one fits the job in front of you.

Picking the right surface saves minutes on every task. Here is the quick decision table I use:

TaskBest surfaceWhy it fits
New UI feature or layout tweakAgents WindowBuilt-in browser preview and Design Mode show results immediately
Multi-file feature with visual checksAgents WindowSide panel shows Files, Browser, Terminal, and Git together
5-line logic edit or renameClassic IDE (IDE ↗)Tab autocomplete and Cmd+L are faster than writing a prompt
Reading unfamiliar code line by lineClassic IDE (IDE ↗)Go-to-definition, split panes, and Explorer beat chat summaries
Quick bug fix while already in shellgrok CLI TUIZero window switching, fast launch, clean git diff right below
Work on a remote Linux box over SSHgrok CLI TUIRuns directly on the remote host with grok login --device-auth
Parallel tasks on separate branchesgrok -w or Cloud AgentsIsolates each agent in its own Git worktree or cloud VM
Automated PR checks or cron scriptsgrok -p headless CLIPredictable JSON output with --max-turns and --sandbox read-only

You do not need to stay locked into one surface for the whole day. I often start a feature in the Agents Window, jump into IDE ↗ to tweak one stubborn helper with Tab autocomplete, and run a final headless review from my terminal.

A good rule of thumb is task size and feedback loop. When you need to see pixels in a browser, stay in the Agents Window. For tasks you can verify with one terminal command, grok is faster, and when you already know the exact three lines to type, open the classic IDE and type them yourself.

Choosing the right mode across surfaces

Picking between the Agents Window, the classic IDE, and the grok CLI is only the first choice. The second choice is picking the right mode for the task, because running every prompt in plain Agent mode slows you down and creates messy diffs.

I match the surface to how I will verify the result, then I pick the narrowest mode that fits. Here is the decision matrix I use across everyday coding tasks:

Daily taskBest surfaceMode or runnerWhy this pairing works
Map an unfamiliar repoAgents Window or grok CLIAsk or --sandbox read-onlyReads files and traces callers with zero edits on disk
Plan a multi-file changeAgents Window or grok CLIPlan (Shift+Tab or /plan)Locks file boundaries and catches scope creep early
Fix a layout or CSS bugAgents WindowDesign Mode (Annotate)Sends the exact DOM node and preview screenshot together
Track a runtime bugAgents WindowDebug modeForms hypotheses, logs real values, cleans up on Mark Fixed
Edit one small helperClassic IDE (IDE ↗)Tab or Cmd+L promptFaster than describing a three-line change in chat
Fix tests over roundsgrok CLI (grok -w)/goal --budget <tokens>Loops until tests pass in an isolated Git worktree
Clear a backlog ticketAgents Window or grok.com/buildRun in Cloud (/in-cloud)Runs on a remote VM and pushes a branch while you work elsewhere
Coordinate linked PRsAgents WindowProjectsKeeps shared tasks, docs, and context across branches

You rarely stay in one mode from start to finish on a real task. I often open a thread in Ask or Plan mode, switch to Agent or Debug mode for the edit, and finish with Find Issues in the diff view.

Let’s walk through four everyday tasks so you can see how these surface and mode switches work in practice.

Worked example 1: Fixing a clipped mobile header

Suppose your site header looks fine on a laptop, yet the right-side button clips off screen at 375px width. Explaining which flex wrapper broke in plain text is slow, and the model often edits the wrong container.

I open the repo in the Agents Window, start the dev server in the Terminal panel, and narrow the Browser panel to mobile width. Next I enable Design Mode (Annotate), click the clipped header bar, and attach a short note:

At 375px width, the right button clips outside the header.
Keep logo and button on one row with no horizontal scroll.
Edit only the header CSS and leave desktop layout alone.

Because Design Mode sends the DOM selection and screenshot together, the agent jumps straight to the right CSS rule. After checking both mobile and desktop widths, I click IDE ↗ only if a shared spacing variable needs a two-line manual tweak with Tab.

Worked example 2: Tracing an off-by-one date bug in Node

Imagine an invoice summary route returns yesterday’s date in western time zones while UTC tests pass. Dropping that symptom straight into Agent mode often pushes the model to guess or rewrite working formatting helpers.

I start in Ask mode (or grok --sandbox read-only) to map every file that parses invoice dates. Once I know the two files involved, I switch to Debug mode and send a clean reproduction:

Bug reproduction:
1. Run TZ=America/New_York npm test -- tests/invoice.test.js
2. Pass "2026-11-01" to formatInvoiceDay()

Expected: "2026-11-01"
Actual: "2026-10-31"
Trace the parsed Date value before editing the formatter.

Debug Mode adds temporary logging if needed and asks me to run the reproduction command so it can inspect the real value. After it fixes the parser and both TZ=UTC and TZ=America/New_York pass, I click Mark Fixed so the temporary logs are removed cleanly.

Worked example 3: Renaming a config field across six files

Renaming a field across routes, types, and tests is tedious by hand and risky when an agent improvises mid-edit. I start from a clean commit in Plan mode (Shift+Tab in desktop or /plan in the CLI):

/plan Rename timeoutMs to requestTimeoutMs in src/ and tests/.
Keep backward compatibility for configs passing timeoutMs
and log one deprecation warning.
List every file to edit and the tests before changing code.
Do not edit unrelated docs or scripts.

In the CLI, I open /view-plan to inspect the proposed file list, pressing c to comment on any unwanted file and s to tighten the plan. Once the scope looks right, I press a to approve, let the agent apply the edits, and run Find Issues in the Agents Window before committing.

Worked example 4: Offloading test coverage while you switch tasks

For a self-contained job like adding unit tests to an older validation module, you have two clean ways to keep your main working directory untouched.

When local tools or fixtures matter, I open a second terminal in a clean Git worktree and start a budgeted /goal:

grok -w --ref main

Inside that worktree, I launch the goal and watch progress from grok dashboard (Ctrl+\):

/goal --budget 120000 Add unit tests for src/validators/slug.js
covering empty input, uppercase letters, and double hyphens.
Finish when npm test passes with zero production code edits.

When I am closing my laptop, I switch the Agents Window target to Run in Cloud (or invoke /in-cloud) so a Cloud Agent runs on a remote VM and pushes a branch for review. If the work expands into three linked PRs across teammates, I move it into Projects instead.

Common surface and mode mismatches to avoid

Most frustrating sessions come from using a mode that works against the task. Here are five mismatches I try to catch early:

Common mismatchWhat goes wrongBetter choice
Agent Mode on a murky runtime bugModel guesses and edits unrelated filesDebug mode with exact repro steps
Cloud Agent for a 4-line renameVM startup and PR review take longer than typingClassic IDE (IDE ↗) with Tab or Cmd+L
Plan Mode for a one-line typoExtra planning turns waste time and tokensQuick edit in IDE ↗ or short Agent prompt
/goal without --budget on a fuzzy taskAgent loops and drains your weekly poolClear pass target plus --budget <tokens>
Hand edits in IDE during a local agent runManual saves collide with active agent writesIsolate the agent via grok -w or Run in Cloud

Taking a real feature from Plan Mode to PR

Let’s walk through a realistic end-to-end cycle for a small React and Node task manager app: adding a status filter (All, Open, Done) and an Export CSV button.

Every stage has one clear job before you move to the next.

Step 1: Start from a clean Git commit and enter Plan Mode

Before you type a prompt, run git status --short in the Terminal panel or your shell. Commit or discard leftover edits so the agent’s diff contains only this feature.

Switch the composer to Plan (Shift+Tab in either the Agents Window or the grok CLI) and describe the contract without dictating every line of code:

Plan a CSV export button and status filter for the tasks list.
Filter options: All, Open, Done.
Export only the currently visible filtered tasks.
Escape commas and quotes in task titles so spreadsheets open
cleanly without broken columns.
Do not add new npm packages or change the API response shape.
List the files to edit, edge cases, and test cases before coding.

Read the generated plan like a code review. If the agent proposes adding a third-party CSV library or rewriting your table styling, ask it to trim the plan right there. In the CLI you can press c in /view-plan to comment on a specific line, or s to request revisions.

Step 2: Implement in small, verified batches

Once the plan looks tight, approve it (a in the CLI or the approve button in desktop) and ask the agent to work in two short checkpoints instead of one giant sweep:

Implement the approved plan in two small steps.
First add the filter helper and CSV formatter with unit tests,
and run npm test.
Then wire the filter controls and Export CSV button in the UI,
run the production build, and report the changed files.

Splitting logic from UI gives you an early green test signal. If the CSV escaping helper has a subtle bug, you catch it in seconds before any React components change.

Open the Browser panel in the Agents Window and actually click the controls yourself. Filter by Open, switch to Done, and export a CSV with tricky characters in the titles.

Step 3: Switch to Debug Mode when something breaks

Suppose you test a task titled Ship "v2", check logs, export the CSV, and notice the title splits across two columns when you open the file.

Do not paste a vague complaint like “CSV export is broken” into Agent mode. Switch to Debug mode and give a minimal reproduction:

Bug reproduction:
1. Create a task titled: Ship "v2", check logs
2. Click Export CSV in the built-in browser
3. Open the downloaded file in a text editor

Expected: one row with escaped double quotes around the title.
Actual: the title splits across two columns at the comma.
Investigate why the quotes were not escaped before fixing it.

Debug Mode inspects the serializer, adds temporary logging if needed, and asks you to reproduce the click so it can see the real values flowing through the formatter. Once it patches the escaping rule and you confirm the downloaded CSV opens cleanly, click Mark Fixed so Grok Build strips out the temporary logs.

Ask the agent to add a regression test for Ship "v2", check logs right away so that bug can never come back.

Step 4: Run Agent Review and inspect the diff yourself

Now open the Git panel in the Agents Window and read every changed hunk from top to bottom. Click Find Issues to run Agent Review on your uncommitted changes.

Look specifically for leftover debug logs, accidental edits outside the planned files, and missing keyboard accessibility on the new filter buttons. If one hunk looks wrong, reject that single hunk in the diff view instead of discarding the whole session.

Run your local checks one last time from the terminal so you see the raw exit codes with your own eyes:

git status --short
git diff --stat
npm test
npm run build

Step 5: Commit, open the PR, and triage Bugbot

Commit with a clear message describing what changed and why, push your branch, and open your pull request.

If you have Bugbot enabled on the repository, wait a minute for its review comments on GitHub or GitLab. Treat each Bugbot comment as a hypothesis to verify, not an order to blindly accept. When a finding is real, click the comment button to open the desktop app with the prefilled fix prompt, apply the patch, re-run npm test, and push the follow-up commit.

Cloud Agents, parallel runs, and usage discipline

Running one local agent at a time feels natural at first. Soon you will have three small bugs, a documentation update, and a test refactor sitting in your backlog, and you will want to run several agents at once or offload long jobs to Cloud Agents.

Parallelism only saves time when you keep each agent isolated and keep an eye on your weekly usage pool.

Splitting work into clean non-overlapping slices

Two agents editing the same file at the same time will overwrite each other’s changes or create painful merge conflicts. Before launching parallel runs, carve the backlog into slices with disjoint file boundaries.

Here is how I decide whether two tasks can run in parallel:

Slice ASlice BSafe to run in parallel?
Add unit tests in tests/csv.test.jsFix CSS spacing in src/styles/header.cssYes, zero overlapping files
Update src/api/tasks.tsUpdate src/components/TaskRow.tsxOnly if the API response shape stays fixed
Refactor shared src/types.tsAdd a feature that imports src/types.tsNo, finish the type refactor first
Upgrade packages in package.jsonAdd a new dependency in package.jsonNo, lockfile conflicts are guaranteed

Write the file boundary straight into each agent’s prompt so the model knows where to stop:

Scope: edit only src/utils/csv.js and tests/csv.test.js.
Add support for multiline task notes in CSV export.
Keep existing single-line tests passing and add 3 new tests
for newlines, quotes, and empty notes.
Run npm test and open a draft pull request when green.
Do not modify UI components or package.json.

That short scope boundary prevents a Cloud Agent from “helpfully” reformatting unrelated files and colliding with another branch you have open locally.

Avoiding Git conflicts across parallel agents

Grok Build gives you two clean isolation mechanisms for parallel coding: local Git worktrees in the CLI, and Cloud Agents on remote VMs.

In the terminal, never open two grok sessions in the same working folder if both will write files. Launch each writing agent in its own worktree with -w, and pass --ref when you want it to start from a clean base branch instead of copying your uncommitted edits:

# Terminal 1: backend validation on a clean branch from main
grok -w --ref main

# Terminal 2: UI state cleanup on a second isolated worktree
grok -w --ref main

# Inspect all active worktrees from your main shell
grok worktree list

Open grok dashboard (or press Ctrl+\) to monitor both worktrees from one screen. You can answer permission prompts inline, see which session finished, and toggle worktree visibility with Ctrl+W.

In the desktop Agents Window, click Run in Cloud (or use /in-cloud from a local chat) to send self-contained tasks to remote VMs. Each Cloud Agent clones the repo onto its own VM, works on a dedicated branch, runs tests, and pushes for review. Your local working tree stays untouched while you focus on your primary task.

When two parallel branches finish, merge the smaller or more foundational PR first, rebase or merge main into the second branch, and run tests again before merging the second one. For larger multi-PR efforts where several slices share a single roadmap, put them inside a Project so the coordinator keeps shared context across tasks without forcing you to copy-paste status between chats.

Reviewing Cloud Agent pull requests systematically

Because you did not watch a Cloud Agent type every edit live, treat its pull request with the same discipline you would use for an external contributor.

I run through a short five-point check before merging any Cloud Agent PR:

  1. Check the file list first. Confirm the PR only touched files inside the slice you assigned. Unexpected edits to lockfiles, configs, or unrelated modules are an immediate red flag.
  2. Verify the test evidence. Look at the CI run and the test cases the agent added. Make sure it did not weaken an existing assertion or skip a failing test to get a green run.
  3. Read security and data boundaries carefully. Check authentication checks, error messages, environment variables, and external network calls line by line.
  4. Pull and run locally for UI or stateful changes. For anything user-facing, check out the branch or inspect the Live App preview and click through the happy path plus one failure case.
  5. Request narrow follow-up fixes. If something needs cleanup, leave a concrete comment or hand the branch back to the Cloud Agent with the exact failing input rather than rewriting half the PR by hand.

If Bugbot also commented on the Cloud Agent’s PR, resolve its findings before merging so you do not ship an obvious edge case.

Managing your weekly usage pool

Every paid plan on The X Subscription shares one weekly usage pool across the desktop app, the grok CLI, Cloud Agents, Grok Bot, and the Grok apps. Heavy parallel runs or the wrong model choice can drain a week’s allowance in a single afternoon.

Four habits keep your pool lasting all week:

  • Match the model to the task. Use Composer 2.5 or grok-4.7-build-fast for CSS tweaks, test scaffolding, copy edits, and simple refactors. Save Grok 4.7 and high reasoning effort for tricky architecture plans and hard bugs.
  • Keep third-party models intentional. Remember that GPT-6, Claude, and Gemini do not draw from your X Subscription weekly pool. They draw from prepaid API credits from the very first turn, so verify the model picker before starting a long session.
  • Set hard caps on autonomous loops. Always pass --budget <tokens> on /goal runs and --max-turns on headless grok -p scripts so a stuck test loop stops early instead of retrying for twenty rounds.
  • Check /usage before kicking off parallel work. If your weekly pool is already low, finish one high-priority task locally instead of spawning four Cloud Agents at once.
# Check current pool usage inside an interactive TUI session
/usage

# Cap a multi-round goal so it stops before burning your pool
/goal --budget 150000 Fix failing parser tests in src/parser.js

# Cap scripted CI runs with turn limits and no subagents
grok --no-auto-update --no-subagents --max-turns 6 \
  --sandbox read-only -p "Check diff for null dereferences."

Checking your pool takes two seconds and prevents unpleasant surprises right before a deadline.

Model routing across weekly pools and prepaid credits

One habit that drains budgets quickly is leaving a heavy reasoning model selected for every small edit, or switching to a third-party model for one question and forgetting to switch back. Those choices pull from different billing buckets.

Before starting a long session, verify which bucket you are spending from:

How you run Grok BuildBilling bucketWhat to check
The X Subscription + Grok or Composer modelsShared weekly usage poolRun /usage in CLI or inspect your dashboard
The X Subscription + GPT-6, Claude, Gemini, or Muse WonderPrepaid credits at API list priceConfirm you want per-token billing on this run
Teams or Enterprise + eligible third-party modelsAPI list price + $0.25/M Token RateKeep third-party runs short and intentional
Legacy Cursor plan (Pro, Pro+, Ultra, legacy Teams)Separate first-party + Other Models poolsSwitching to The X Subscription is permanent
CLI with XAI_API_KEY exported in your shellDirect API token billingUnset XAI_API_KEY to use your plan pool

That last row surprises many terminal users. If your shell exports XAI_API_KEY for another project, grok bills API token rates instead of drawing from your X Subscription weekly pool.

I also audit older scripts and custom subagents for retired model IDs. Since grok-build-0.1 reached end of life on November 19, 2026, update any config pinning that ID to grok-4.7, grok-4.7-build-fast, or Composer 2.5.

For daily routing inside your weekly pool, I divide work into three tiers:

  • Fast tier (Composer 2.5 or grok-4.7-build-fast): CSS adjustments, copy edits, boilerplate tests, simple refactors, and read-only explorer subagents.
  • Core tier (Grok 4.7 or Grok 4.7 High Fast): Multi-file features, Plan mode blueprints, Debug Mode sessions, and pre-PR reviews.
  • Prepaid second opinion (GPT-6.2 Sol or Claude Opus 5.5): Targeted audits on a clean minimal reproduction when paying per token from prepaid credits makes sense.

Inside custom subagents under .cursor/agents/, set model: fast in the frontmatter instead of model: inherit whenever the child agent only reads files or scans logs. That keeps heavy reasoning models reserved for the parent thread.

Keeping rules, skills, and MCP lean for sharp context

Every always-loaded instruction file, auto-invocable skill description, and connected MCP tool schema rides along on every single turn. When you stack a long AGENTS.md, a dozen alwaysApply: true rules, and six idle MCP servers, you pay for those tokens on every message, every subagent call, and every /goal retry.

Noisy background instructions also dilute the rules you care about most. Every couple of weeks, I run a quick context audit from the repo root:

grok inspect
grok mcp list
grok memory

Inside an interactive CLI session, I also check /context before deciding whether to compact or open a fresh thread.

Four habits keep your customization stack sharp without hurting usefulness:

  1. Keep root AGENTS.md under roughly 30 lines. Put only repo-wide stack facts, verification commands, and hard boundaries there, and move folder-specific rules into .cursor/rules/*.mdc with alwaysApply: false and narrow globs:.
  2. Gate manual checklists with disable-model-invocation: true. For pre-PR or release SKILL.md files that you trigger yourself, keep user-invocable: true and disable-model-invocation: true so they never fire during unrelated chats.
  3. Disconnect unused MCP servers. Every active server advertises its tool schemas on every turn even when unused, so keep write-capable trackers or database servers disabled until a specific task needs them.
  4. Prune stale dynamic memory entries. Use /remember only for durable conventions, clean out outdated notes from grok memory, and pass grok --no-memory whenever you want a clean run.

For scripted CI checks with grok -p, combine --no-subagents, --sandbox read-only, and --system-prompt-file so headless runs stay cheap and focused.

Recovering drifted sessions with Checkpoints and /rewind

Every coding agent eventually hits a turn where it misreads a requirement, breaks working code, and piles workarounds onto a bad edit. The most expensive reaction is arguing with the agent for eight more turns in that same thread.

Debating a drifted session drains your weekly pool twice, because you resend the failed history on every turn while the model keeps anchoring on broken diffs right above your prompt.

I stop immediately when I spot any of these three drift signals:

  • The agent re-introduces a bug it already fixed two turns earlier.
  • The diff touches files outside the scope we agreed on in Plan mode.
  • The agent weakens a test assertion or skips a failing check instead of fixing the cause.

Press Ctrl+C in the CLI (remember Esc does not cancel a running turn) or click Stop in the Agents Window. Check git status --short and git diff --stat to see if any manual edits are sitting in your working tree, then pick the cleanest rollback tool:

SituationClean recovery moveFollow-up step
Desktop session went off trackHover over the earlier prompt and click Restore CheckpointRe-prompt with tighter file boundaries
CLI session drifted after a clean commitRun /rewind to roll back files and chatConfirm with git diff before prompting again
Half the diff is good and one hunk brokeReject that single hunk in the Agents Window diff viewAsk for a narrow fix on the remaining helper
You want to try a risky refactor safelyRun /fork (Ctrl+F) in the CLI firstDrop the branch if the experiment fails
Context is cluttered after 30+ turnsAsk for a 6-line handoff note and open New ChatAttach active files directly with @file

Keep two rollback limits in mind. Both desktop Checkpoints and CLI /rewind only revert local files on disk, so anything pushed to Git, executed on a Cloud Agent, or sent through an external MCP tool stays sent.

Also remember that /rewind permanently drops reverted uncommitted edits, so commit clean milestones to Git before asking an agent to run a wide refactor. Once your tree is clean again, send a shorter prompt with the exact file paths and verification command you expect.

Part 3: Shared configuration across Desktop and CLI

One of the nicest parts of the unified platform is that your project instructions, skills, subagents, MCP servers, and rules carry across the desktop app and the terminal CLI.

Project rules (AGENTS.md), ignore files, and Privacy Mode

Put a short AGENTS.md file in your repo root so you stop repeating stack choices and test commands in every chat:

# Project instructions

This is a dependency-free JavaScript package using ES modules.

- Run tests with `npm test`.
- Keep public functions free of input mutations.
- Use two spaces, single quotes, and no semicolons.
- Keep existing regression tests when fixing bugs.
- Do not add dependencies without explaining why.
- Do not commit, push, or publish unless asked.

Both the desktop app and the CLI read AGENTS.md (and compatible CLAUDE.md files). In the desktop app you can also add scoped .mdc rule files under .cursor/rules/ that apply always, by file glob, or on demand (see the rules docs and my full AGENTS.md guide).

In the terminal, run grok inspect inside any folder to see every instruction file, rule, hook, plugin, and MCP server that Grok picked up, including imported configs from Cursor or Claude Code.

For one-off scripted system prompts, pass --system-prompt-file ./prompts/review-system.txt.

To keep local notes or sensitive files out of AI file context in the desktop app, add a .cursorignore file in the project root:

private-notes/
.env*
*.pem

Keep .gitignore too, because .cursorignore only affects AI context features, and it won’t stop a shell command from reading a file.

Turn on Privacy Mode in Settings (or check /privacy in the CLI) to avoid your code being used to train the AI.

Writing rules that agents actually follow

Most AGENTS.md files fail for one simple reason: they read like a five-page employee handbook. When you stuff vague prose like “write clean, scalable code” into a 300-line file, the model ignores half of it and wastes context tokens on every turn.

Good project rules are short, concrete, and paired with commands the agent can run to verify its own work.

Here is a practical AGENTS.md for a TypeScript and React web app that fits in twenty lines and prevents the most common mistakes:

# AGENTS.md

## Stack
- Node.js 22, TypeScript, Vite, and React 19
- Plain CSS modules under src/styles/, no Tailwind

## Verification commands
- Unit tests: `npm test`
- Type check: `npm run typecheck`
- Lint: `npm run lint`
- Production build: `npm run build`

## Hard rules
- Run `npm run typecheck` and `npm test` after every code edit.
- Report the exact command and exit status in your final reply.
- Keep functions pure when possible and avoid mutating inputs.
- Never edit `.env`, `.env.local`, or files in `config/prod/`.
- Do not install new packages unless I approve the package name.
- Do not commit, push, or open a PR unless I ask you to.

Notice the pairing between rules and verification commands. Instead of only asking the agent to “avoid type errors”, we give it npm run typecheck and require it to report the exact command and exit status. That turns a soft preference into a concrete self-check loop.

When a rule only applies to one part of the codebase, keep it out of the root AGENTS.md and put it in a scoped .mdc rule file under .cursor/rules/. That way the desktop app only loads API rules when the agent works on API files:

---
description: Rules for HTTP route handlers and API responses
globs: src/api/**/*.ts
alwaysApply: false
---

- Validate every request body and query parameter at the edge.
- Return JSON errors as `{ error: string, code: string }`.
- Never log authorization headers, cookies, or session tokens.
- Add one integration test per new route in `tests/api/`.

Keep one simple rule for maintaining these files: whenever an agent makes the same mistake twice across different chats, add one short bullet to AGENTS.md or a scoped .mdc file. Whenever a rule becomes outdated because you migrated a tool or renamed a script, delete it immediately. Run grok inspect after editing rules to confirm Grok Build actually picks up every file you expect.

Context hygiene: fresh threads vs long sessions

Even with great rules, long coding threads gradually degrade. After forty turns of failed attempts, huge stack traces, and half-reverted edits, the model spends more attention reading stale mistakes than reading your actual source code.

Good context hygiene means keeping each thread tied to one coherent task and trimming or resetting before the conversation gets noisy.

Use this table to decide whether to continue, compact, fork, or start fresh:

SituationBest actionWhy
Next step is part of the same featureContinue in current threadKeeps recent file reads and decisions warm
Context is getting large mid-featureRun /compact <what to keep>Drops noisy tool output while keeping key facts
You want to test an alternate approachRun /fork (Ctrl+F)Branches the session without polluting the main path
Previous task is merged or committedStart a New ChatClean slate with zero stale diffs or old errors
Agent is stuck repeating a wrong fixStart fresh with clean promptRemoves the broken reasoning chain from context
You have a quick unrelated questionUse /btw <question>Answers on the side without cluttering main history

In the grok CLI, check your context usage before it gets cramped, compact with explicit instructions on what to preserve, or fork before trying a risky refactor:

/context
/compact Keep the CSV rules, edited files, and test status
/fork

When you decide to open a fresh thread halfway through a larger piece of work, ask the current agent for a short handoff note before closing it:

Before I open a fresh thread, write a 6-line handoff note:
- What we finished and which files changed
- Which test commands passed
- The next small task and any open edge cases
Do not edit files.

Paste those six lines into a new chat, attach the relevant files with @, and you keep the useful decisions while dropping thousands of tokens of old terminal logs.

Use dynamic memory (/remember and grok memory) only for durable facts that apply across weeks, like your preferred test conventions or deployment workflow. If you ever want a strict, reproducible run with zero carried-over memory, start the CLI with grok --no-memory.

Skills, plugins, and marketplaces

A skill is a folder with a SKILL.md file that packages a repeatable procedure.

Project skills are stored in .agents/skills/, .grok/skills/ or .cursor/skills/. Personal skills are stored in the corresponding folder in your home directory.

Here’s a focused review skill, saved in .grok/skills/review-numeric-function/SKILL.md:

---
name: review-numeric-function
description: Review a numeric utility for input mutation and edge cases.
user-invocable: true
disable-model-invocation: true
---

Read the requested function and its callers.
Identify the input contract before proposing a change.
Check empty input, one item, duplicates, negative values, and invalid values.
Look for input mutations and implicit string sorting.

Report concrete findings with file locations and a reproducing input.
Do not edit files unless the user asks for a fix.

You can invoke it in either interface with /review-numeric-function Review median.js.

If you remove disable-model-invocation: true the agent will invoke the skill when a task matches the description.

In the CLI, the allowed-tools field does not grant or block access to tools. Real tool boundaries are in the permission rules.

Plugins are a way to bundle skills, subagents, hooks, and MCP servers into a package that can be installed. See Plugins.

You can find plugins in Customize in the desktop app, /plugins or /marketplace in the TUI, or from the shell with grok plugin list.

Always inspect a plugin before enabling it, as hooks and local MCP servers run code on your machine.

See the desktop skills docs and CLI plugins docs.

Subagents

Subagents run delegated work in their own clean context window and send a summary back to the parent thread, keeping noisy searches and test logs out of your main conversation.

The desktop app ships with built-in Explore, Bash, and Browser subagents (backed by codebase indexing), while the CLI ships with general-purpose, explore, and plan.

You can also define custom subagents as Markdown files in .cursor/agents/ or ~/.cursor/agents/ (and manage CLI agents with /config-agents or behavioral overlays with /personas).

Here’s a read-only security reviewer saved as security-auditor.md:

---
name: security-auditor
description: Security review for auth, payments, and sensitive data.
model: inherit
readonly: true
---

Audit the code for security vulnerabilities:

- SQL injection and XSS
- Authentication bypass
- Hardcoded secrets
- Missing input validation
- Insecure data handling

Report findings with severity and file locations.

A custom security-auditor subagent definition open in the desktop app

Frontmatter fieldDefaultWhat it does
namefilenameIdentifier and slash-command name
descriptionnoneTells the parent agent when to delegate
modelinheritinherit, fast, or a specific model ID
readonlyfalseRestricts the subagent to reading files
is_backgroundfalseRuns without blocking the main conversation

Call it with /security-auditor or ask by name:

Starting the security-auditor subagent from a prompt

In the latest Grok Build TUI, subagents can also message each other, to coordinate work, and you can step in to steer any child agent.

Keep parallel writing subagents on disjoint files, so they don’t overwrite each other’s assumptions.

MCP servers and hooks

MCP (Model Context Protocol, read more in What is MCP) allows Grok Build to be connected to external apps, docs, issue trackers, databases, and more.

In the desktop app, you can install integrations from Customize, or add them to .cursor/mcp.json (project) or ~/.cursor/mcp.json (user):

The Customize page listing available integrations and MCP servers

For a quick public test with no API key, add OpenAI’s public docs server to .cursor/mcp.json:

{
  "mcpServers": {
    "openaiDeveloperDocs": {
      "url": "https://developers.openai.com/mcp"
    }
  }
}

Once connected, MCP settings show the server and its active tools:

MCP settings showing configured servers and their connection status

In the CLI you can manage servers directly from your shell, and diagnose startup issues with grok mcp doctor:

grok mcp add --transport http linear https://mcp.linear.app/mcp
grok mcp list
grok mcp doctor linear

Passing --scope project will write the shared connection settings into .grok/config.toml, and keep your OAuth credentials out of Git.

See the desktop MCP docs and CLI MCP docs.

Hooks are the deterministic layer. They are shell commands or HTTP calls that fire automatically on lifecycle events, like PreToolUse or Stop, whether the model remembers or not.

You can save a personal hook under ~/.grok/hooks/ or a project hook under .grok/hooks/.

For example, this is a turn logger in .grok/hooks/turn-log.json:

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "date -u >> /tmp/grok-build-turns.log",
            "timeout": 5
          }
        ]
      }
    ]
  }
}

Trust the project hook with /hooks-trust and inspect loaded hooks with /hooks. Remember one rule from the hooks docs: PreToolUse hooks can block a tool call by exiting with code 2, but timeouts, crashes, and malformed output fail open. Always pair blocking hooks with a sandbox when you need hard boundaries.

Permissions and sandboxing

Permissions decide if a tool call can run, and the sandbox limits which files and network endpoints child processes can touch (see permission modes).

In the desktop app, you can choose a Run Mode under Settings → Agents → Approvals & Execution: Auto-review (runs allowlisted calls, sandboxes shell commands where possible, uses a classifier for the rest), Allowlist, or Run Everything (skips the sandbox and classifier).

In the CLI, you can switch modes using Shift+Tab, /auto, or /always-approve (Ask is the default), and you must pick a sandbox profile explicitly as the CLI sandbox is off by default (see the CLI sandbox docs):

CLI sandbox profileReadsWritesChild-process network
offUnrestrictedUnrestrictedAllowed
workspaceEverywhereWorking directory, Grok home, tempAllowed
read-onlyEverywhereGrok home and tempBlocked on Linux
strictWorking directory and system pathsWorking directory, Grok home, tempBlocked on Linux
devboxEverywhereTop-level directories except /dataAllowed

On macOS, child-network blocks in read-only and strict are a no-op, and credential folders like ~/.ssh are always readable in built-in profiles unless you add custom deny rules.

We can set narrow project-level allow and deny rules in .grok/config.toml. Deny rules always win (see CLI permissions):

[permission]
rules = [
  { action = "allow", tool = "bash", pattern = "git status*" },
  { action = "allow", tool = "bash", pattern = "git diff*" },
  { action = "allow", tool = "bash", pattern = "npm test" },
  { action = "deny", tool = "bash", pattern = "git push*" },
  { action = "deny", tool = "bash", pattern = "git reset --hard*" },
]

Personal TUI defaults like your default sandbox profile, theme (/theme), transcript density (/density), and custom OpenAI- or Anthropic-compatible model endpoints live in ~/.grok/config.toml (documented in the settings reference):

[sandbox]
profile = "workspace"

[ui]
permission_mode = "ask"
theme = "auto"

[cli]
auto_update = true

Practical MCP, hooks, and sandboxing recipes

Reading about hooks, sandboxes, and MCP in the abstract is one thing. Seeing a few small, working configs you can copy into a real repository is where they start paying off.

Here are five practical recipes built with the exact config formats Grok Build uses across projects.

Recipe 1: Block edits to .env and production configs with PreToolUse

Putting “never touch .env” inside AGENTS.md helps, yet a model can still slip up during a long session. A PreToolUse hook adds a deterministic check before a tool call runs.

Create a small Node script at scripts/block-sensitive-paths.mjs that inspects the incoming hook payload on stdin and exits with code 2 if it sees a protected path:

import fs from 'node:fs'

const payload = fs.readFileSync(0, 'utf8')
const blocked = [
  /\.env(\.[a-z0-9_-]+)?/i,
  /config\/production\//i,
  /\.pem\b/i
]

for (const pattern of blocked) {
  if (pattern.test(payload)) {
    console.error('Blocked sensitive path by PreToolUse hook.')
    process.exit(2)
  }
}

Now wire it in .grok/hooks/protect-secrets.json:

{
  "hooks": {
    "PreToolUse": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "node scripts/block-sensitive-paths.mjs",
            "timeout": 5
          }
        ]
      }
    ]
  }
}

Approve the project hook with /hooks-trust and confirm it appears under /hooks. Remember that a PreToolUse hook fails open if the script crashes or hits its timeout, so keep it paired with .cursorignore, deny rules, and a sandbox.

Recipe 2: Auto-format changed files on Stop

Formatting drift is annoying when an agent touches four files and leaves inconsistent spacing behind. Instead of asking the model to format code in every prompt, let a Stop hook run your formatter automatically at the end of each turn.

First create scripts/format-changed.sh and make it executable (chmod +x scripts/format-changed.sh):

#!/usr/bin/env bash
set -euo pipefail

files=$(git diff --name-only --diff-filter=ACM \
  -- '*.js' '*.ts' '*.tsx' '*.css' '*.json')

if [ -n "$files" ]; then
  printf '%s\n' "$files" | xargs npx prettier --write
fi

Then register it in .grok/hooks/format-changed.json:

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "bash scripts/format-changed.sh",
            "timeout": 15
          }
        ]
      }
    ]
  }
}

Because the script reads git diff --name-only, it only formats files touched during your work and leaves the rest of the repository alone.

Recipe 3: Run fast unit tests after an agent turn

If your test suite finishes in a few seconds, you can also run it from a Stop hook and save the output to a log file you can inspect anytime:

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "npm test > /tmp/grok-tests.log 2>&1",
            "timeout": 20
          }
        ]
      }
    ]
  }
}

Keep Stop hooks fast. If a full end-to-end suite takes three minutes, do not put it in a Stop hook or every short conversation turn will feel sluggish. Run only fast unit tests automatically and trigger heavy integration suites manually before opening a PR.

Recipe 4: Safe sandbox and permission policies for a team repo

Think of permissions and sandboxing as two layers that cover each other’s blind spots. Permission rules decide which commands can run without prompting and which commands are never allowed. The sandbox limits where child processes can write on disk.

In your repository’s .grok/config.toml, allow safe read and verification commands while explicitly blocking destructive Git commands and raw network fetches:

[permission]
rules = [
  { action = "allow", tool = "bash", pattern = "git status*" },
  { action = "allow", tool = "bash", pattern = "git diff*" },
  { action = "allow", tool = "bash", pattern = "npm test*" },
  { action = "allow", tool = "bash", pattern = "npm run lint" },
  { action = "allow", tool = "bash", pattern = "npm run build" },
  { action = "deny", tool = "bash", pattern = "git push*" },
  { action = "deny", tool = "bash", pattern = "git reset*" },
  { action = "deny", tool = "bash", pattern = "rm -rf*" },
  { action = "deny", tool = "bash", pattern = "curl*" },
]

Because deny rules always win, even an accidental broader allow rule cannot override git push* or rm -rf*.

Pair that project config with a safe personal default in ~/.grok/config.toml (profile = "workspace" and permission_mode = "ask"), because the CLI sandbox starts off if you never set it. Keep the macOS caveat in mind too: read-only and strict do not block child-process networking on macOS, and folders like ~/.ssh remain readable in built-in profiles unless you add custom deny rules.

Recipe 5: Auditing MCP servers and tool permissions

Every MCP server you connect adds more tools to the agent’s context and expands what a mistaken tool call could touch. Before adding a new server or working on a sensitive repository, run a quick four-step audit from the terminal:

grok inspect
grok mcp list
grok mcp doctor openaiDeveloperDocs
ls -la ~/.grok/logs/mcp/

Walk through these checks on every active server:

  1. Separate read-only servers from write-capable servers. Documentation and search servers are safe to leave enabled. Keep servers that can modify issues, databases, or cloud resources disabled until a concrete task needs them.
  2. Check where credentials live. When adding a shared team server via the CLI, pass --scope project so connection details go into .grok/config.toml while your OAuth tokens stay local in ~/.grok/. Never hardcode API tokens inside .cursor/mcp.json.
  3. Remove unused servers. Extra MCP tool schemas eat context tokens on every turn even when you never call them. If you have not used a server in two weeks, remove it.
  4. Verify health before debugging prompts. If the agent claims it cannot reach Linear or your docs server, run grok mcp doctor <name> first instead of rephrasing your prompt five times.

Troubleshoot common problems

ProblemWhat to check first
Agent is in the wrong repo or folderCheck the workspace picker in desktop or pass --cwd in CLI, then run grok inspect
Rules or skills aren’t loadingConfirm the path isn’t gitignored, check user-invocable: true in SKILL.md, and run grok inspect
Built-in preview stays blankCheck that the dev server is still running, match its printed port, and inspect browser console errors
Usage burns faster than expectedRun /usage or check your dashboard for third-party model credit, high reasoning effort, or parallel subagents
Command fails inside CLI sandboxPackage caches often write outside the repo; add those paths in a custom sandbox profile
MCP server won’t startRun grok mcp doctor, check ~/.grok/logs/mcp/, and raise startup_timeout_sec for npx servers
Terminal shortcuts behave oddlyRun /terminal-setup or check the keyboard shortcuts reference
Agent says it’s done, but behavior is wrongAsk for the exact verification command and output, add a reproducing test, and request the smallest fix

Diagnosing rules, skills, hooks, and MCP that fail to load

When a rule, custom skill, hook, or MCP server seems invisible, avoid rewriting your prompt three times. Almost every loading issue comes from a wrong working directory, a gitignored path, an untrusted project hook, or a failing server startup command.

I start every diagnosis from the repository root with four commands:

pwd
git status --short
grok inspect
grok mcp list

Read grok inspect line by line first. It shows every instruction file (AGENTS.md, CLAUDE.md), rule, skill, hook, plugin, and MCP server that Grok Build picked up for that folder, including imported Cursor and Claude Code configs.

When a specific layer is still missing, check its most common failure point:

  • Wrong workspace root: Confirm the composer repo picker in desktop points to the folder containing AGENTS.md, or pass --cwd in the CLI when launching from outside the project.
  • Rule or skill missing: Verify the path is not gitignored, uses a supported directory (.cursor/rules/*.mdc for scoped desktop rules, and .agents/skills/, .grok/skills/, or .cursor/skills/ for skills), and sets user-invocable: true in SKILL.md for manual /name calls.
  • Skill never auto-triggers: Check whether disable-model-invocation: true is set in SKILL.md, which restricts it to explicit slash invocations.
  • Project hook never fires: Run /hooks in the CLI to inspect status and /hooks-trust to approve project hooks under .grok/hooks/.
  • PreToolUse hook fails to block: Remember PreToolUse only blocks on exit code 2, while crashes, timeouts, or bad output fail open.
  • MCP server stays offline: Run grok mcp doctor <name>, inspect ~/.grok/logs/mcp/, and increase startup_timeout_sec for slow npx servers.

Test any blocking hook script directly in your shell before trusting it in a live session:

printf '{"path":".env.production"}' | \
  node scripts/block-sensitive-paths.mjs
echo "Exit code: $?"

If that prints anything other than Exit code: 2, fix the script before relying on it.

Fixing CLI sandbox and permission surprises

Most CLI permission surprises come from expecting the terminal client to match desktop defaults. In the desktop app you pick Auto-review, Allowlist, or Run Everything under Settings -> Agents -> Approvals & Execution, while the CLI sandbox starts off until you turn it on.

If you run grok with no sandbox flag and no [sandbox] block in ~/.grok/config.toml, child commands can write anywhere your user account can write. I set profile = "workspace" and permission_mode = "ask" in ~/.grok/config.toml so every terminal session starts inside predictable boundaries.

Four sandbox and permission behaviors catch teams off guard most often:

  • Package caches blocked inside workspace or strict: Tools like npm or compilers often write to cache folders outside the repo, so inspect the failing path and allow that cache directory in a custom sandbox profile or point the cache env variable to temp storage.
  • macOS sandbox limits: On macOS, child-process network blocks in read-only and strict are a no-op and ~/.ssh stays readable in built-in profiles, so add explicit deny rules in .grok/config.toml on sensitive repos.
  • allowed-tools inside skills: In the CLI, allowed-tools in SKILL.md does not grant or block tools, so real boundaries belong in .grok/config.toml where deny rules always win.
  • Shell commands during CLI Plan mode: Before approval, file-edit tools can only touch the plan file, yet shell commands and subagents still follow your active permission mode, so pair /plan with --sandbox read-only or --sandbox workspace on unfamiliar repos.

When a safe check like npm run typecheck prompts too often, add one narrow allow rule in .grok/config.toml instead of switching to /always-approve or Run Everything.

Triaging Agent Review and Bugbot findings carefully

Automated reviews save hours when they catch real defects before merge, yet they add regressions when you accept every comment blindly. Treat both local Agent Review (Find Issues in the Agents Window diff view) and PR-level Bugbot (included on GitHub and GitLab starting on Premium) as hypotheses to verify.

I follow four quick steps before applying any automated review comment:

  1. Read the surrounding file, not just the diff hunk. Open the full function in the Files panel or IDE ↗ to confirm an earlier guard does not already handle the flagged case.
  2. Prove real bugs with a test first. When Bugbot flags a CORS bug or missing null check, add a small failing test before patching so you verify the failure path and lock in the fix.
  3. Narrow the desktop handoff prompt. Clicking a Bugbot fix button opens the desktop app with a prefilled prompt (or hands it to a Cloud Agent), so add one line limiting edits to the affected function before running it.
  4. Inspect git diff and re-run local checks. After applying a patch, check the diff yourself and reject any stray hunk in the Agents Window diff view.

Here is how I sort review findings in practice:

Finding typeHow to verifyNext step
Real bug or security flawReproduce with a test or local requestApply focused fix, add test, re-run checks
Unreachable edge caseTrace every caller in the repoDismiss or add a small guard if fragile
Style nit outside PR scopeCompare against your planned filesSkip in this PR to keep the diff clean
Broad rewrite suggestionCheck diff size against the defectReject the rewrite and fix only the bug

Spending two minutes on triage keeps automated reviews sharp without turning pull requests into noisy churn.

Sharing Grok Build configs safely across a team

Because the desktop app and the grok CLI read the same project configs, teams can version shared instructions, skills, subagents, hooks, workflows, and permissions right in Git. The rule is separating shared repo configs from personal tokens and local state.

Use this checklist before committing .grok/ or .cursor/ files:

File or folderCommit to Git?Why
AGENTS.mdYesShared stack, test commands, and hard repo rules
.cursorignore and .gitignoreYesKeeps local notes and secrets out of context and Git
.cursor/rules/*.mdcYesScoped rules matched to specific file globs
.grok/skills/, .agents/skills/, .cursor/skills/YesRepeatable slash-command checklists for the team
.cursor/agents/*.mdYesShared read-only auditors and helper subagents
.grok/config.tomlYesShared [permission] rules and --scope project MCP URLs
.grok/hooks/*.json and .grok/workflows/*.rhaiYes, after reviewExecutable scripts that run on developer machines
~/.grok/ (sessions, memory, OAuth tokens)NeverPersonal defaults, history, and MCP OAuth credentials
~/.cursor/mcp.json, .env*, XAI_API_KEYNeverLocal tokens, secrets, and direct API keys

When adding a shared HTTP MCP server from the CLI, pass --scope project so only the URL enters .grok/config.toml while OAuth tokens stay local in ~/.grok/:

grok mcp add --transport http --scope project \
  linear https://mcp.linear.app/mcp
git diff .grok/config.toml

Check git diff .grok/config.toml right away to confirm zero tokens or personal headers entered the repository.

Four team habits prevent onboarding friction once several developers share the config:

  • Review hooks, workflows, and plugins like source code. Because .grok/hooks/, .grok/workflows/*.rhai, and plugins execute locally, require PR review before merging and read new hooks before running /hooks-trust.
  • Standardize Privacy Mode. Have every developer turn on Privacy Mode in desktop Settings and confirm /privacy in the CLI so proprietary code stays out of model training.
  • Update integration mentions. Remember @Build replaces @Cursor in Slack, GitHub, Linear, and Jira starting December 7, 2026, while existing agent CLI and API automations continue working.
  • Share the Teams and Enterprise billing rule. Make sure teammates know Grok 4.7 and Composer 2.5 draw from the shared pool while eligible third-party models bill API list price plus the $0.25/M Grok Build Token Rate.

Add one line to your team onboarding doc asking new developers to run grok inspect on day one so they can confirm every shared rule, skill, hook, and MCP server loaded cleanly.

Hands-on exercises

The fastest way to make Grok Build feel second nature is to run through short, bounded tasks on a real project. These ten exercises start with safe read-only inspection and build up to custom skills, hooks, MCP auditing, and isolated parallel workflows.

You can run them on the grok-build-demo repo from Part 2, the tic-tac-toe app from Part 1, or any small Git repository on your machine. Make sure git status --short is clean before you begin each exercise.

Exercise 1: Read-only repository diagnosis

Launch grok in read-only sandbox mode (or switch the desktop Agents Window to Ask mode) and map out a repository without modifying a single file. Your goal is to confirm you can inspect architecture, entry points, and test commands with zero risk of unwanted edits.

Here is one clean solution:

Start the CLI with the read-only sandbox and subagents turned off:

grok --sandbox read-only --no-subagents

Send this bounded diagnosis prompt:

Read package.json and the main entry file in this repository.
Explain how the app starts, how tests run, and which files hold
core business logic.
Do not edit files or run commands that write to disk.

Quit with /quit and confirm nothing changed on disk with git status --short. You should get an empty status output and a concise map of the repo.

Exercise 2: Targeted single-function edit in the classic IDE

Open the classic IDE (IDE ↗ from the Agents Window), create a small utility file src/format-price.js, select the function with Cmd+L (Ctrl+L on Windows and Linux), and ask Agent to add strict input validation without touching any other file.

Here is one clean solution:

Start with a naive function in src/format-price.js (export function formatPrice(cents) { return '$' + (cents / 100).toFixed(2) }), select it, press Cmd+L, and run this prompt:

Change only the selected formatPrice function.
Throw RangeError if cents is not a non-negative integer.
Keep the dollar formatting with two decimals for valid values.
Do not add dependencies or edit any other file.

You should get a tight helper like this:

export function formatPrice(cents) {
  if (!Number.isInteger(cents) || cents < 0) {
    throw new RangeError('cents must be a non-negative integer')
  }
  return `$${(cents / 100).toFixed(2)}`
}

Verify the behavior directly with Node before wiring it into any UI:

node --input-type=module -e "
import assert from 'node:assert/strict'
import { formatPrice } from './src/format-price.js'
assert.equal(formatPrice(0), '\$0.00')
assert.equal(formatPrice(1999), '\$19.99')
assert.throws(() => formatPrice(-5), RangeError)
assert.throws(() => formatPrice(1.5), RangeError)
console.log('formatPrice checks passed')
"

Exercise 3: Plan a multi-file feature before writing code

Practice using Plan mode (Shift+Tab in desktop or /plan in the CLI) on a feature that touches both logic and UI: adding a case-insensitive search box to a list view with a clean empty state. Inspect the plan for scope creep before approving it.

Here is one clean solution:

Enter Plan mode and send a prompt with explicit non-goals:

/plan Add a case-insensitive title search input above the list.
Filter tasks in memory without adding new dependencies.
Show a clear "No matching tasks" message when nothing matches.
List the files to edit, edge cases, and unit tests first.
Do not modify existing CSS tokens or add localStorage saving.

Open the plan preview with /view-plan in the CLI (or read the plan card in the Agents Window). If the plan mentions extra files or packages you did not ask for, press c to comment on that line or s to request a revision. Only press a to approve once every listed file belongs to the feature.

Exercise 4: Reproduce and fix a bug in Debug Mode

Introduce or pick a small reproducible bug in a search or filter function, such as forgetting to .trim() leading and trailing spaces from user input. Use Debug mode in the desktop app to investigate before editing, verify the fix, and clean up temporary instrumentation.

Here is one clean solution:

Switch the composer mode selector to Debug and paste exact reproduction steps with expected and actual behavior:

Bug reproduction:
1. Enter "   milk  " in the search box
2. Press Enter

Expected: matches the task titled "Buy milk"
Actual: shows "No matching tasks" because whitespace is kept.
Trace the search filter value before proposing a fix.

Follow the reproduction step in the built-in browser when Debug Mode asks you to trigger the bug. Once it fixes the filter and you confirm " milk " matches "Buy milk", click Mark Fixed so temporary logs are removed, then check git diff and add a unit test for padded whitespace.

Exercise 5: Write a tight AGENTS.md and verify it with grok inspect

Create a concise AGENTS.md and .cursorignore at the root of your project so both the desktop app and the grok CLI know your stack, verification command, and boundaries automatically.

Here is one clean solution:

Save this focused AGENTS.md in the repository root:

# Project rules

- Runtime: Node.js LTS with ES modules.
- Run `npm test` after every code change and report the output.
- Keep functions free of input mutation.
- Never add dependencies without asking first.
- Never commit or push automatically.

Add a matching .cursorignore beside it so private notes and local secrets stay out of AI context:

.env*
*.pem
private-notes/

Run grok inspect from your terminal and verify that AGENTS.md appears in the loaded instructions list.

Exercise 6: Package a repeatable checklist as a project skill

Create a manual, user-invocable pre-PR review skill under .grok/skills/pre-pr-check/SKILL.md so you can run the same review routine across both desktop and CLI with one slash command.

Here is one clean solution:

Create .grok/skills/pre-pr-check/SKILL.md:

---
name: pre-pr-check
description: Check uncommitted changes for bugs and test gaps.
user-invocable: true
disable-model-invocation: true
---

Inspect `git status --short` and `git diff`.
Check for leftover console logs, missing edge-case tests,
and accidental edits to config files or lockfiles.
Run `npm test` and report exact pass/fail counts.
Do not edit files unless I ask for a fix.

Run grok inspect to verify the skill is registered, then invoke it inside a session:

/pre-pr-check Review my current branch changes before I push

Because disable-model-invocation: true is set, the skill only runs when you call it explicitly.

Exercise 7: Block edits to .env and production files with a PreToolUse hook

Build a deterministic PreToolUse guard script that blocks any tool call referencing .env or config/prod/, test its exit code directly from your shell, and trust it inside Grok Build.

Here is one clean solution:

Save scripts/guard-env.mjs:

import fs from 'node:fs'

const input = fs.readFileSync(0, 'utf8')
if (/\.env\b|config\/prod\//i.test(input)) {
  console.error('Blocked edit touching .env or config/prod/.')
  process.exit(2)
}

Register the hook in .grok/hooks/guard-env.json:

{
  "hooks": {
    "PreToolUse": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "node scripts/guard-env.mjs",
            "timeout": 5
          }
        ]
      }
    ]
  }
}

Test the script from your terminal first and confirm it returns exit code 2:

printf '{"path":".env.local"}' | node scripts/guard-env.mjs
echo "Exit code: $?"

Then open grok, run /hooks-trust to approve the project hook, and run /hooks to confirm it is active.

Exercise 8: Configure a .grok/config.toml permission policy and Stop hook

Set up a project permission policy that auto-allows read-only Git checks and npm test, explicitly denies git push* and git reset*, and logs a UTC timestamp to /tmp/grok-session-audit.log whenever an agent turn ends.

Here is one clean solution:

Add .grok/config.toml to your project:

[permission]
rules = [
  { action = "allow", tool = "bash", pattern = "git status*" },
  { action = "allow", tool = "bash", pattern = "git diff*" },
  { action = "allow", tool = "bash", pattern = "npm test" },
  { action = "deny", tool = "bash", pattern = "git push*" },
  { action = "deny", tool = "bash", pattern = "git reset*" },
]

Add .grok/hooks/session-audit.json:

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "date -u >> /tmp/grok-session-audit.log",
            "timeout": 5
          }
        ]
      }
    ]
  }
}

Launch Grok inside the workspace sandbox and trust the hook:

grok --sandbox workspace

Run /hooks-trust, ask Grok to run npm test, and verify that /tmp/grok-session-audit.log gained a fresh timestamp while git push remains blocked by your deny rule.

Exercise 9: Connect and audit a read-only MCP documentation server

Add OpenAI’s public read-only documentation MCP server at the project scope, verify its connection with grok mcp doctor, and check git status --short to confirm no personal credentials entered your repository.

Here is one clean solution:

Run the CLI setup and diagnostic commands:

grok mcp add --transport http --scope project \
  openaiDocs https://developers.openai.com/mcp
grok mcp list
grok mcp doctor openaiDocs
git status --short

Confirm that grok mcp doctor openaiDocs reports a healthy connection and that only .grok/config.toml (with the server URL, not personal tokens) appears in git status --short. If you also use the desktop app, check Customize to see the connected server and its read-only tools.

Exercise 10: Run an isolated worktree fix, headless JSON review, and PR check

Put isolation, automation, and human verification together in one end-to-end drill. Start an isolated worktree from a clean main branch, make a small bounded fix with unit tests, run a capped read-only headless JSON review, and walk through your final PR checklist.

Here is one clean solution:

Launch an isolated worktree session and run your bounded fix inside it, then trigger a read-only headless review before pushing:

# 1. Work in an isolated worktree from main
grok -w --ref main

# 2. Run a capped read-only JSON review before opening the PR
grok --no-auto-update --sandbox read-only --no-subagents \
  --max-turns 6 --output-format json \
  -p "Review git diff against main for bugs. Do not edit."

Before pushing your worktree branch and opening a pull request, run through this five-item checklist yourself:

  1. Run git status --short and git diff --stat to confirm only intended files changed.
  2. Run npm test and your build command locally and check the exit code directly.
  3. Read the JSON review findings (and click Find Issues in the Agents Window if you open the branch in desktop).
  4. Check /usage to see how much of your weekly pool the task consumed.
  5. Remove the finished worktree after the PR merges so your repo stays tidy.

How I use Grok Build

I do most of my day-to-day visual and multi-file work in the desktop Agents Window. Having the running app right next to the conversation makes it easy to test every change immediately, use Design Mode to fix a specific layout issue, or jump into the classic IDE (IDE ↗) when writing a few lines by hand is faster than describing them.

I use the grok CLI when I’m already in a terminal, when I’m working on a remote machine over SSH, when I’m inspecting a repository with grok inspect, or when I want to run a read-only review in headless mode.

For bigger changes, in either interface, I start in Plan mode and keep the project stack, commands and hard constraints in AGENTS.md. I wait until I repeat a checklist a few times before turning it into a skill, and I only connect MCP servers when a concrete task requires it.

One thing I try to stick to: I finish and review one task before starting 5 more in parallel. Every additional agent run is another diff I need to read and test myself.

If you’re coming from Codex or Codex CLI, try the same bounded bug fix from a clean commit in Grok Build and compare the diff, test run and usage.

And I skip coding agents altogether for deterministic jobs that a 15-line script already does reliably.

Want me to talk about your product? You can sponsor this site.

Related posts about ai: