grok-delegate
Delegate a coding task to the Grok Build CLI as a background implementer, then review its diff and land it yourself. Use this whenever the user wants to hand implementation work to Grok — phrasings like "have Grok do X", "delegate this to Grok", "run it through Grok", "use Grok B
Install
npx skills add https://github.com/amElnagdy/delegate-skills/tree/master/skills/grok-delegate
claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install amelnagdy-delegate-skills@llmmart
git clone https://github.com/amElnagdy/delegate-skills.git
The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole amelnagdy/delegate-skills collection as a plugin from our marketplace. Git is the plain clone.
Skill manifest
Grok Delegate
For a trusted repository rejected by Git's ownership check, the relay supports
--trust-git-root <exact-worktree-root>. This opt-in affects only relay Git checks, without persistent
Git config or Grok permission changes. See dispatch and poll.
You are the orchestrator. This skill lets you hand a bounded coding task to a separate
implementer — the Grok Build CLI (grok) — then review what it produced and land it yourself. You
write the brief and own the judgment; Grok does the typing under an explicit autonomy profile; you
verify and commit.
Nothing here is specific to one orchestrating agent. The loop needs only the ability to run a shell command and read a file, so it works the same whether you are Claude Code, Cursor, OpenCode with a selected model, or any comparable agent. (It is designed for Claude Code and Cursor; treat other orchestrators as designed-for, not yet proven.)
When NOT to use this
- The task is small enough to just do inline — delegation overhead is not worth it.
- The
grokCLI is not installed, not authenticated, or the account lacks Grok Build beta access. - You want to write the code yourself, or you only need a review without an implementer run.
Prerequisites (check once)
grok versionsucceeds. If not, install on any platform withnpm i -g @xai-official/grok(or use the installer from xAI's official Grok CLI docs) and authenticate (grok login, orgrok login --device-authon headless hosts, or setXAI_API_KEY).- Confirm which
grokis on PATH.command -v grokshows the active binary andgrok versionits version — the relay records the version it ran intoresult.json, so a stale binary is visible after the fact. - You are in (or will point
--cdat) the target git repository.
The loop
Run these five steps per task. Steps 1, 4, and 5 are your judgment; 2 and 3 are mechanical.
1. Write the brief
Grok sees only the text you send — no orchestrator chat history, no shared context. Everything the task needs goes in the brief: the goal, the current state, what to change, what to leave untouched, the project's actual gate commands (discover them from the repo's CLAUDE.md/AGENTS.md/Makefile — do not assume), and a report contract. Tell Grok it will not commit (you will). Keep one task per brief. Full guidance and a template: references/writing-the-brief.md.
2. Dispatch
Send the brief to Grok with the bundled helper. It wraps grok -p, captures the run, and writes a
structured result.json — so your only job is "run a command, read a file." (<skill-dir> below is
this skill's installed directory — the folder containing this SKILL.md, i.e. the directory you loaded
the skill from. Claude Code prints it as "Base directory for this skill" when the skill loads; on other
orchestrators use that same directory — if unsure where it landed, run
find ~ -name relay.mjs -path '*grok-delegate*' and substitute the directory above it.)
node "<skill-dir>/scripts/relay.mjs" --brief brief.txt --cd /path/to/repo
# read-only (review/diagnosis; best-effort — verify touchedFiles): add --read-only
# continue the previous Grok session: add --resume-last (send only the delta brief)
# hard time limit (watchdog): add --timeout 2h (default: off; implementation runs routinely need 1-2h)
# see all options: node .../relay.mjs --help
The helper defaults to a write-capable (workspace-write) autonomy profile — --always-approve plus
--sandbox workspace — and writes its artifacts to a temp dir, so the repo under review stays clean.
It never commits — see step 5. Mechanics, flags, and the result.json shape:
references/dispatch-and-poll.md.
3. Wait for completion
The helper blocks until Grok finishes, so back it with whatever your orchestrator offers and resume when it returns:
- Claude Code: run the Bash call with
run_in_background: true; you are notified on completion. - Plain shell / other agents: run it in the foreground for short tasks, or background it and poll
the result file —
… &in bash/zsh (including Git Bash/WSL), or your shell's equivalent (Start-Jobin PowerShell,start /bin cmd). The run is done whenresult.jsonexists with astatus. (A pre-run usage error — bad args or an empty brief — instead exits with code 2 and a stderr message and writes no result file, so check the exit code too. A missinggrokbinary exits 127 but does write aresult.jsonwith statusgrok_unavailable.)
Do not trust progress trackers over reality: a run is finished when result.json is written and the
process has exited. Read the working tree, not a status line. The implementer's full report is
the finalMessage field in result.json (also printed in full on stdout between the report markers).
4. Review — do not trust the self-report
Grok's result.json includes its own summary and gate claims. Re-verify, don't accept:
- Re-run the project's gates yourself (the test/lint/build commands from step 1). Never take "gates passed" on faith.
- Read the diff against the brief: did Grok do what was asked, nothing more (scope creep) and
nothing less?
touchedFilesin the result is your starting point. - Run the relevant guard skills on the diff if you have them installed (clean-code-guard,
test-guard, etc. from
guard-skills) — this skill produces the work; those skills judge it. - For schema/migration changes, round-trip them; for removals, grep for dangling references.
Full checklist: references/review-and-land.md.
5. Land it
The orchestrator commits. Only after the gates pass and the diff holds:
- Commit the verified work yourself, with a clear message.
- If it needs changes, send a delta brief with
--resume-last(don't restate the whole task) and review again.
Autonomy model
Grok's default permission mode is ask, which blocks on approval prompts in a headless pipe. The
relay therefore always sets autonomy explicitly:
| Relay flag | What Grok gets | Use when |
|---|---|---|
| (default) | --always-approve --sandbox workspace |
Normal implementation — writes scoped to the working tree |
--read-only |
--sandbox read-only --permission-mode plan |
Review / diagnosis — best-effort, not enforced (see caveat below) |
--full-access |
--always-approve --sandbox off |
Explicit opt-in when the task needs unrestricted tools |
--always-approve alone would approve all tools (writes, shell, network) — closer to unrestricted
than to a workspace-scoped write. Pairing it with --sandbox workspace is what keeps the default
safe. Reach for --full-access only when the human asks for it.
--read-only is best-effort, not a hard guarantee. The read-only sandbox restricts out-of-workspace
filesystem/network access, not grok's own edit tool, and headless plan mode is advisory — a run
verified here still wrote the working tree when told to. Use --read-only to signal review intent,
but always confirm touchedFiles afterward; treat the diff, not the flag, as the guarantee. The relay
automates a reporting tripwire: it compares parsed git porcelain and fingerprints the working-tree
identity and index entries of Git-visible paths that were already dirty. readOnlyViolation is true
when either signal proves a change, false when coverage is complete and detects none, and null when
coverage is incomplete. Ignored paths, submodule internals, perfect restores, and attribution of
concurrent changes remain outside it, so the diff
review stays the guarantee.
Authorization model
Delegation is something the human opts into. Once they have ("run this queue", "proceed"), committing verified, gate-passing work is the agreed contract — that is the whole point. Two limits on that mandate: surface, don't absorb (report Grok's design decisions, defensible-but-unasked turns, and non-blocking nitpicks rather than silently keeping them) and stop for scope changes (if correct completion needs going beyond the brief, ask — don't expand the mandate yourself). The full treatment is in references/review-and-land.md.
References
- references/writing-the-brief.md — how to write a brief Grok can execute blind: structure, XML blocks, the report contract, embedding the real gate commands.
- references/dispatch-and-poll.md —
relay.mjsflags, theresult.jsoncontract, backgrounding per orchestrator, and recovery when a run misbehaves. - references/review-and-land.md — the review checklist, the commit
boundary, and the rework cycle via
--resume-last. - references/multi-task-queues.md — running a sequential queue: carrying constraints forward, progress tracking, and the end-of-run coherence check.
Files (delegate-skills)
-
references
-
dispatch-and-poll.md 12.2 KB
# Dispatch and poll `scripts/relay.mjs` is the dispatch layer. It wraps `grok -p` (headless mode), runs the brief under an explicit autonomy profile, captures everything, and writes a structured `result.json`. Your job collapses to: run one command, then read one file. Everything Grok-specific lives in the helper, which is what keeps the loop portable across orchestrators. ## Before the first run: check the binary Two gotchas, both worth 30 seconds: ```bash command -v grok # the active binary; a stale install can shadow a current one grok version # recorded into result.json so a stale binary is visible after the fact grok login # or: grok login --device-auth / export XAI_API_KEY=... ``` Grok Build is an early beta gated behind an eligible xAI subscription (SuperGrok / X Premium+). An auth failure or missing beta access shows up as a failed run, not as `grok_unavailable`. ## Dispatching ```bash node "<skill-dir>/scripts/relay.mjs" --brief brief.txt --cd /path/to/repo ``` (`<skill-dir>` is wherever this skill is installed — the folder containing its `SKILL.md`. On Claude Code it's the printed "Base directory for this skill"; on other orchestrators substitute that install path. See [`SKILL.md`](../SKILL.md) if you need to locate it.) Options: | Flag | Effect | | --- | --- | | `--brief <file>` | The brief. Omit it to read the brief from stdin (`node relay.mjs … < brief.txt`). | | `--cd <dir>` | Working root for Grok (default: current directory); passed as `--cwd`. | | `--trust-git-root <dir>` | Opt in to command-scoped Git trust for this exact worktree root. Applies only to relay Git checks; defaults off. | | `--lane <name>` | Fleet lane from `delegate-setup` config. Applies that lane's dials; fails if the lane's `implementer` is not this relay. Explicit dial flags win. | | `--model <name>` | Grok model (default: Grok's own configured default). | | `--effort <level>` | Reasoning effort for this run (`--effort`). | | `--max-turns <n>` | Maximum number of agent turns for this run (`--max-turns`). | | `--read-only` | Review/diagnosis intent (`--sandbox read-only --permission-mode plan`). **Best-effort, not enforced** — grok can still edit the tree headlessly. The relay reports a tri-state Git-visible change tripwire. | | `--full-access` | Unrestricted auto-approve (`--always-approve --sandbox off`); opt-in. | | `--resume-last` | Continue the most recent Grok session for this cwd; send only the delta brief. | | `--session <id>` | Continue a specific session id; mutually exclusive with `--resume-last`. | | `--timeout <dur>` | Relay-side watchdog (e.g. `30m`, `2h`); on expiry the child is killed and `result.json` gets `status: "timeout"`. Off by default. | | `--out-dir <dir>` | Where artifacts go (default: a fresh dir under the system temp dir). | Default autonomy (neither `--read-only` nor `--full-access`) is **workspace-write**: `--always-approve --sandbox workspace`. Grok's native default is `ask`, which would hang a headless pipe; the relay always sets autonomy explicitly. Artifacts default to the system temp dir on purpose: the repo under review stays clean, so the touched-files report shows only Grok's edits and nothing of the helper's own. ## Git ownership errors on shared or remounted drives If Grok completes but `touchedFiles` is `null`, inspect Git's error from the same working directory. For a repository you trust that Git rejects for dubious ownership, pass `--trust-git-root /path/to/repo`. Validation asks git once — through a single-use wildcard-trust query — for git's own canonical spelling of that exact root, verifies it by comparing directory identity on disk against the path you supplied (immune to Windows path-spelling divergence such as 8.3 short names), and then supplies `git -c safe.directory=<that spelling>` only to the relay's own Git checks (git matches safe.directory against literal path forms it canonicalizes itself, which Node cannot reproduce reliably on Windows). This does not edit global Git config, change Grok's sandbox or authentication, or make Grok's own Git commands trusted. Put any needed child-side Git instructions in the brief separately. The supplied path must be the exact existing worktree root containing `--cd`; nested working directories and linked worktree roots are supported. Wildcards, unrelated roots, and subdirectories passed as roots are rejected before dispatch (exit 2, no result). Git must be available to validate the opt-in. Submodules and nested repositories do not inherit this trust. With no flag, ownership errors still produce `touchedFiles: null`, never a misleading empty list. ## The result `<out-dir>/result.json` is the contract. Fields: - `schema` — the result-format version (currently `delegate-relay.result.v1`) - `tool` — `"grok"` - `trustedGitRoot` — canonical root explicitly trusted for relay Git checks, or `null` when omitted - `status` — `completed` | `failed` | `timeout` | `aborted` | `grok_unavailable` - `exitCode` — mirrors Grok's exit code; `128` plus the signal number if the child was killed; `127` if `grok` isn't on PATH; on a `timeout` the relay forces a non-zero code even when the child exited `0` after the watchdog's SIGTERM - `signal` — the signal that killed the child, otherwise `null` - `grokVersion` — the binary that actually ran - `sessionId` — feed this to a later `--session <id>` (or use `--resume-last`) - `finalMessage` — Grok's own final report (the `<structured_output_contract>` you asked for), assembled from the streaming-json `text` events - `usage` — token counts from the run's end event (`input_tokens` / `output_tokens` / `total_tokens`); `null` if none were reported - `touchedFiles` — `git status --porcelain` lines in the working root: your review starting point. `null` (not `[]`) when git can't report; `[]` means git ran and the tree is clean - `briefPath` / `eventsPath` / `finalPath` — the exact brief relay sent, the raw streaming-json event stream, and the final-message file - `workdir`, `autonomy`, `model`, `effort`, `resumeLast`, `startedAt`, `finishedAt` - `readOnlyViolation` — present on dispatched `--read-only` runs: `true` when parsed git porcelain or the working-tree/index fingerprint of an already-dirty Git-visible path proves a change; `false` when coverage is complete and detects none; `null` when coverage is incomplete. Ignored paths, submodule internals, perfect restores, and attribution remain outside it — the diff review, not this flag, is the guarantee - `stderrTail` — last ~20 stderr lines; present on every run that did not complete (`failed`, `timeout`, `aborted`), absent on `completed`, `grok_unavailable`, and launch failures - `error` — present on a launch failure, and on `timeout` and `aborted` runs The helper also prints a summary to stdout and exits with Grok's exit code, so a wrapping script can branch on success/failure directly. ## Waiting for completion The helper blocks until Grok finishes. Back it with whatever your orchestrator offers: - **Claude Code:** run the `Bash` call with `run_in_background: true`; you're notified on completion, then read `result.json`. - **Plain shell / other agents:** foreground for short tasks, or background and poll — `node relay.mjs … &` in bash/zsh (including Git Bash/WSL), or your shell's equivalent (`Start-Job` in PowerShell, `start /b` in cmd). A run is done when `result.json` exists with a `status`. **But** a pre-run usage error (bad args, empty brief) exits with code 2 *before* writing any file — so check the exit code too, don't only watch for the file. (A missing `grok` binary exits 127 but *does* write a `result.json` with status `grok_unavailable`.) Trust the working tree and the process state over any progress display. A run is finished when the process has exited and `result.json` is written — not when a status line says so. ## When a run misbehaves - **`status: grok_unavailable` (exit 127):** `grok` isn't on PATH or isn't found. Install with `npm i -g @xai-official/grok` and `grok login`, then re-dispatch. - **an `error` mentioning `version preflight` (`failed`, or `timeout` at exit 124):** the bounded `grok version` probe exited non-zero or hung past its cap (10s, or `--timeout` when shorter), so grok was never dispatched; only the relay's own artifacts may already exist under `--out-dir`. Check the install by running `grok version` yourself. - **`status: timeout`:** the `--timeout` watchdog killed the run. The working tree may hold a half-applied change — inspect it before deciding between a longer `--timeout`, a smaller brief, or a resume. - **`status: aborted`:** the relay itself was killed (its parent's timeout, a stopped task, a closed terminal) and forwarded the kill to grok. The result is written before the relay exits; inspect the working tree before re-dispatching. On native Windows a hard kill of the relay is uncatchable (Node supports no `SIGTERM` handler there), so this status may never get written - a relay process that is gone without a `result.json` is an aborted run; inspect the working tree and `events.jsonl` directly. - **`status: failed` with `signal: "SIGKILL"`:** the host ended the child — commonly the OOM killer or a supervisor timeout, not an implementer error. Free up host memory or split the task into smaller briefs, then re-dispatch. - **`status: failed`:** read `result.json`'s `stderrTail` and the tail of `eventsPath` for the cause. Common causes: an auth lapse, missing beta access, an invalid `--model`, or a sandbox that blocked something the task needed. Fix the cause and re-dispatch; don't paper over it by doing the work yourself unless that's what the user wants. - **Empty `finalMessage`:** Grok exited before producing a final message, or the streaming-json event shape didn't match the extractor. Treat as a failed run; the events log usually shows where it stopped — and is the source of truth for tightening the parser. ## Recovering lost work `events.jsonl` in the run directory records every event the implementer streamed. If finished work is lost — the run killed late, or the working tree damaged afterward — read the event log before re-dispatching: it identifies which files and tool commands were involved, which scopes what needs redoing. Whether it also carries the edit contents depends on what the CLI streams, so treat any reconstruction as unverified until it matches a working-tree diff — when the tree still holds the work, preserve the tree rather than replaying the log. ## What the helper is doing (and the alternatives) Under the hood the helper runs roughly: ```bash # fresh run (default workspace-write autonomy) grok --no-auto-update --no-alt-screen --output-format streaming-json --cwd <repo> \ --always-approve --sandbox workspace --prompt-file <brief.txt> # resume most recent session for this cwd grok --no-auto-update --no-alt-screen --output-format streaming-json --cwd <repo> \ --continue --always-approve --sandbox workspace --prompt-file <delta.txt> # resume a specific session grok --no-auto-update --no-alt-screen --output-format streaming-json --cwd <repo> \ --resume <id> --always-approve --sandbox workspace --prompt-file <delta.txt> ``` `--no-auto-update` and `--no-alt-screen` are always set so automated runs don't check for updates or take over the terminal. Autonomy flags are re-passed on resume because headless permission mode may not inherit. **Prompt delivery:** the brief is handed to grok via `--prompt-file`, never argv — so it stays out of the host process list, isn't bounded by the OS argument-length cap, and a brief that begins with `-` can't be misread as a flag. The relay writes the brief you pass (via `--brief` or stdin) to a file and points `--prompt-file` at it. Two alternatives exist if you ever want them, but the helper is the recommended path: - **Raw `grok --prompt-file`** — fine for one-offs; you give up the captured `result.json`, touched-files summary, and session-id extraction the helper does for you. - **`grok agent stdio` (ACP)** — richer IDE/tool integration over JSON-RPC. Out of scope for this skill; the headless single-turn path is the one the relay drives. ## The commit boundary The helper never commits — by design, not omission. The robust contract is: Grok edits the working tree, the orchestrator reviews and commits. See [review-and-land.md](review-and-land.md). -
multi-task-queues.md 3.8 KB
# Multi-task queues The single-task loop scales to a queue, and that's where delegation pays off most — a removal split across layers, a migration touching many files, a refactor sweep. The discipline that makes a queue trustworthy is sequencing and bookkeeping, not parallelism. ## Run sequentially, one commit per task Resist the urge to fan out the whole queue at once. Run tasks **one at a time, in dependency order**, landing each (review + gates + commit) before dispatching the next. Three reasons: - **Later tasks assume earlier ones landed.** Task 3's brief can say "the X added in the previous step exists" only if the previous step actually committed. - **One commit per task** keeps the history reviewable and any single step revertible. - **Each review is honest.** A clean working tree before each dispatch means the next task's `touchedFiles` shows only *its* changes, not a pile-up from earlier tasks. Parallelism is occasionally worth it for genuinely independent tasks on separate files, but it sacrifices the clean-tree-per-task property and makes review harder. Default to sequential. ## Carry decided constraints forward Implementation surfaces facts the original plan didn't have: a helper got named, a fixture lives in a specific place, an interface was chosen. When a later task depends on one of those, **fold it into that task's brief** as an explicit line. Each fresh dispatch starts a **new** Grok session with no memory of the earlier run (unless you deliberately `--resume-last` / `--session`), so a constraint that emerged in task 2 must be restated in task 5's brief or it won't hold. This is the queue equivalent of keeping briefs self-contained. ## Keep a progress file For anything longer than two or three tasks — especially a run the human steps away from — maintain a single progress file alongside the work. It's the durable record that survives your own context limits and lets the human catch up at a glance. A shape that works: - **Status table** — each task: queued / at-implementer / reviewed+committed (with the commit hash). - **Per-task review notes** — what landed, what you verified, the gate outcome. One short paragraph. - **"Needs your eyes"** — design decisions Grok made, non-blocking nitpicks, anything you want the human to overrule or confirm. This is the section they read first. - **End-of-run checklist** — what happens after the last task (push, open/update the PR, manual checks the human should do). Update it as each task lands, not in a batch at the end — if the run is interrupted, the file is still accurate. ## Close with a coherence check Per-task review proves each step in isolation; it doesn't prove the steps cohere. After the last task, verify the whole: - Run the full test/build once more on the final tree — not just the last task's slice. - Do a repo-wide check for the thing the queue was about (e.g. after a removal, grep the entire tree for any surviving reference; after a rename, confirm no stragglers). - For schema work, replay all the new migrations from a clean state and check for drift. - Then push and open or update the PR, with a description that reflects what actually shipped. ## When to stop and ask Proceed without asking on anything that follows from the agreed plan — that's the point of the human opting into the queue. Stop and surface when: - A task can't be completed correctly within its brief's scope (a scope change is the human's call). - A review finds something that calls the *plan* into question, not just the implementation. - The gates reveal a problem that affects tasks already "done." Then report where you are, what's committed, and what the open question is — and wait. A queue that quietly works around a broken assumption produces a lot of commits in the wrong direction. -
review-and-land.md 7.9 KB
# Review and land Grok did the typing; you own the judgment. This is where delegation earns its keep or quietly ships a mistake. The discipline is simple to state and easy to skip under time pressure: **verify against reality, never against the self-report — and read the diff as generated code, which fails in ways a green gate can't see.** ## Check the tests before trusting the gates If the diff touches existing tests, review those edits *first* — before the gate re-run means anything. A weakened assertion, an added skip, or a deleted test makes the gate measure less than it did before the run; green is only meaningful if the yardstick wasn't shortened. - **Unbriefed edits to existing tests are a contract change, not part of the fix.** The brief asked for an implementation; nothing in it authorized moving the goalposts. Flag them, don't absorb them. - **Skipped, disabled, or commented-out tests added in this diff:** treat the underlying test as failing until proven otherwise, whatever the annotation's comment claims. - **Loosened assertions** (exact match relaxed to contains/truthy, error-type checks broadened, tolerance widened): same treatment. ## Re-run the gates yourself `result.json` carries Grok's own claim that the gates passed. Treat that as a claim, not evidence — re-run the project's actual test/lint/build commands in the working tree and read the output. And keep the result in proportion: **passing is necessary, not sufficient.** An implementer can *game* a gate, not just misreport it — that is what the test check above and the sweep below exist to catch. For changes with their own verification shape, go further: - **Migrations / schema:** round-trip them (apply, reverse, re-apply on a scratch target) and check for drift, rather than trusting that "the migration is reversible." - **Removals / renames:** grep the codebase for dangling references to whatever was removed. - **Anything stateful:** exercise the actual behavior, don't just confirm it compiles. ## Read the diff against the brief Open the diff (`touchedFiles` in the result is your starting list) and hold it against what you asked for: For `--read-only`, treat `readOnlyViolation: true` as proof of a detected Git-visible change and `null` as incomplete coverage. `false` does not cover ignored paths, submodule internals, perfect restores, or attribution; inspect the actual diff. - **Scope creep** — did Grok change things the brief said to leave untouched? Unasked refactors, renames, "while I was here" edits. These are the most common quality problem in delegated work. - **Scope shortfall** — did it do the whole task, including the edge cases and cleanup, or stop at the first plausible version? - **Quiet judgment calls** — sometimes Grok makes a defensible decision the brief didn't anticipate. Don't just accept it because it looks reasonable; understand it and decide. ## The implementer sweep Generated code fails in systematic ways that gates are structurally blind to — each of these can sit in a diff whose tests are all green. Walk them against every diff before you commit: - **Hardcoded success or fixture data** on a path the brief says does real work — a canned `{status: "ok"}` or default return passes tests *by design*. If Grok couldn't implement something, the diff should fail loudly, not pretend. - **Catch-all error handling that returns a default** instead of propagating — the suppressed failure is exactly what the gate would have caught. A broad catch is only acceptable with a recovery path the contract documents. - **Unverified imports and API calls** — confirm every new dependency, method, and signature exists in the *installed* version (read the lockfile or the package, don't trust plausibility). - **Dead weight** — unused imports, helpers nothing calls, unreachable branches, "Step 1/Step 2" comment scaffolding, comments that restate the line below them. - **A second way to do what the file already does** — a new HTTP client, error idiom, or logging style introduced beside the existing one instead of reusing it. - **New tests that assert internals** — asserting that an internal helper was called, or mocking the project's own functions to isolate a "unit." Green, brittle, and worthless as regression cover. - **Near-duplicate test bodies** differing by one value — fold into one data-driven test or drop the copies; bloat reads as coverage but isn't. - **Speculative surface** — optional parameters, config flags, or abstractions with no caller in this diff or the repo. Delegated work gets the concrete behavior the brief asked for, nothing extra. - **Guards for impossible cases** — null/type checks for values the code's own contract already excludes. Noise that buries the validation that matters at real trust boundaries. Anything the sweep catches goes back to Grok as a delta brief (below) or gets fixed in the tree before commit — and either way is reported to the user (see "Surface, don't absorb"). If the `guard-skills` package is installed, run the relevant guard on the diff for the full treatment — `clean-code-guard` on production code, `test-guard` on tests, `docs-guard` on documentation. The sweep above is the built-in floor; the guards go deeper. ## The commit boundary When the gates pass and the diff holds, **you commit** — the orchestrator, never Grok. This isn't a workaround for a missing feature; it's the deliberate boundary. Committing should be the act of the party that verified the work. Write a clear message describing what landed. If your project attributes co-authorship, that's the place for it. From dispatch until that commit, the uncommitted working tree is the authoritative copy of the implementer's work — the only one you can commit from, and often the only copy at all. Never run `git checkout`, `reset`, `clean`, or a branch switch in the workspace between those two points — however messy an interrupted run looks, inspect it first: `git status`, `git diff`, `git diff --cached` for anything the implementer staged (plain `git diff` is blind to the index), and open any untracked files (`??` in `git status`) directly — they are the implementer's new files, and no diff shows their contents. The tree is evidence, not clutter. After that inspection the verdict can legitimately be to discard — work built on a premise you have since corrected, for example — and then `git checkout`/`clean` is the right tool. The ban is on reflexive cleanup before anyone has looked. ## Reworking: send the delta, not the whole task If the review turns up problems, don't restate the entire brief. Continue the same Grok session with just the correction: ```bash echo "The fix is right, but the test mocks the DB session - use the real migrated fixture instead, and drop the now-unused import." | node "<skill-dir>/scripts/relay.mjs" --resume-last --cd /path/to/repo ``` (`<skill-dir>` is this skill's install directory — see [dispatch-and-poll.md](dispatch-and-poll.md).) `--resume-last` keeps Grok's context from the first run (via `grok --continue`), so a short delta is enough. To resume a specific session from `result.json`'s `sessionId`, pass `--session <id>` instead. Then review again — rework gets the same gate-rerun, test check, diff-read, and sweep as the original, no shortcuts. Repeat until it's right, then commit. ## Surface, don't absorb The human opted into delegation, so committing verified, gate-passing work is the agreed contract. But keep them in the loop on anything that changes the shape of the work: - **Report design decisions** Grok made, and any defensible-but-unrequested turns it took. - **Note non-blocking nitpicks** you chose not to block on, so the human can overrule you. - **Stop and ask** if correct completion requires going beyond the brief — don't expand the mandate on your own. A scope change is the human's call, not yours or Grok's. For a multi-task run, capture these in the progress file rather than letting them scroll past — see [multi-task-queues.md](multi-task-queues.md). -
writing-the-brief.md 5.6 KB
# Writing the brief A brief is the entire task as Grok will see it. Grok runs in a fresh process with **no memory of your conversation, no access to your prior notes, and no shared context** — only the text you send and whatever it can read from the working tree (including repo rules it discovers via `grok inspect`, and the repo's own `AGENTS.md` when present). If a constraint isn't in the brief or discoverable in the repo, it doesn't exist for Grok. The single most common failure is a brief that assumes context Grok doesn't have. ## The shape that works Grok responds best to compact, block-structured prompts with XML tags rather than long prose. State the task, what "done" looks like, how to behave by default, and the few constraints that actually matter. Add a block only when the task needs it — don't ship empty ceremony. ```xml <task> One or two sentences: the concrete job and where it lives. Then the specifics — current state, what to change, and explicitly what to leave untouched. The "leave untouched" list is what keeps Grok from wandering into unrelated refactors. </task> <verification_loop> Run these before finishing and fix anything they surface, don't just report it: <the project's real test command> <the project's real lint/format command> <the project's real build/typecheck command> Confirm the working tree shows only the intended changes afterward. </verification_loop> <action_safety> Keep changes scoped to the task. No unrelated refactors, renames, or cleanup unless required for correctness. Do NOT run git add or git commit — the orchestrator commits after reviewing. Leave the work uncommitted in the working tree. </action_safety> <structured_output_contract> End with a report in this exact shape: 1. What changed and why 2. Files touched 3. Gate outcomes (paste the test/lint counts) 4. Anything you deviated on, left open, or want a decision on </structured_output_contract> ``` That four-block skeleton covers most implementation tasks. Reach for the extra blocks when the task profile calls for them: - **Debugging / open-ended fixes** — add `<completeness_contract>` (resolve fully, don't stop at the first plausible fix) and `<missing_context_gating>` (don't guess missing repo facts; find them or state what's unknown). - **Review / diagnosis (read-only)** — add `<grounding_rules>` (ground every claim in evidence; label inferences), tell Grok in the brief not to edit anything, and run with `--read-only`. Note `--read-only` is best-effort on grok, not a hard block — verify `touchedFiles` after the run. - **Research / recommendations** — add `<research_mode>` (separate observed facts, inferences, open questions). ## Discover the real gates — don't hardcode `<verification_loop>` is only useful if it names the project's *actual* commands. Read the repo's `CLAUDE.md` / `AGENTS.md` / `Makefile` / `package.json` first and copy the real ones in (`make test`, `npm run lint`, `cargo test`, `pytest -q`, whatever it is). A brief that says "run the tests" without naming them gets you a Grok that guesses — or skips. ## Honor the repo's conventions Grok discovers project configuration for the current directory (`grok inspect` shows rules, skills, plugins, hooks, and MCP servers). House rules in the repo (style, forbidden patterns, commit conventions) already apply when configured. If the project forbids certain things in code — say, spec/ticket IDs in comments, process language like "MVP"/"for now"/"phase N", or specific test conventions — restate the load-bearing ones in the brief too, because compliance is only as reliable as what's in front of the implementer. ## One task per brief Keep each brief to a single, bounded job. "Review this, fix what you find, update the docs, and suggest a roadmap" produces a muddled run; split it into separate dispatches. One brief → one Grok run → one commit keeps review and rollback clean, and lets a later task assume the earlier one landed. ## Premises freeze at dispatch The implementer starts from the brief's facts and there is no steering channel mid-run. Audit the fact block before sending — ownership, target branch, constraints, anything a judgment call rests on. If a premise turns out wrong while the run is live, stop the run and re-dispatch a corrected brief rather than discounting the output afterward; for a write-capable run, inspect the working tree and reconcile any partial or premise-contaminated edits — keep or revert them — before the re-dispatch. ## A worked example ```xml <task> In the payments service at services/billing/, the refund path double-charges when a refund is retried after a network timeout (the idempotency key isn't checked before re-submitting). Make the refund submission idempotent: check for an existing refund by idempotency key before creating a new one. Touch only services/billing/refund.py and its tests. Leave the charge path, the API routes, and the data models untouched. </task> <verification_loop> Run and make green before finishing: pytest tests/billing/ -q ruff check services/billing/ Confirm git status shows only refund.py and its test file changed. </verification_loop> <action_safety> Scope strictly to the refund idempotency fix. No unrelated refactors. Do NOT git add or commit; leave changes in the working tree for review. </action_safety> <structured_output_contract> Report: (1) the root cause and your fix, (2) files touched, (3) pytest + ruff outcomes with counts, (4) anything you left open or want decided. </structured_output_contract> ``` Send this with `relay.mjs` (see [dispatch-and-poll.md](dispatch-and-poll.md)); review the result and commit it yourself (see [review-and-land.md](review-and-land.md)).
-
-
scripts
-
relay.mjs 50.7 KB · in bundle
-
-
SKILL.md 10 KB
--- name: grok-delegate description: >- Delegate a coding task to the Grok Build CLI as a background implementer, then review its diff and land it yourself. Use this whenever the user wants to hand implementation work to Grok — phrasings like "have Grok do X", "delegate this to Grok", "run it through Grok", "use Grok Build to implement/fix/refactor", or "have grok CLI do this" — or to run a queue of coding tasks through Grok while staying the reviewer. Prefer it when the user will review the diff and commit it themselves. DO NOT USE for tasks small enough to do inline, or when the user wants the code written directly without delegating. license: MIT compatibility: Requires the `grok` CLI (Grok Build) installed and authenticated (`grok login`, or `XAI_API_KEY`; beta access needs an eligible xAI subscription), Node 18+, and git. The orchestrating agent must be able to run shell commands and read files. Shell examples assume bash/zsh (macOS/Linux, or Git Bash/WSL on Windows). metadata: version: 0.5.0 --- # Grok Delegate For a trusted repository rejected by Git's ownership check, the relay supports `--trust-git-root <exact-worktree-root>`. This opt-in affects only relay Git checks, without persistent Git config or Grok permission changes. See [dispatch and poll](references/dispatch-and-poll.md#git-ownership-errors-on-shared-or-remounted-drives). You are the **orchestrator**. This skill lets you hand a bounded coding task to a separate **implementer** — the Grok Build CLI (`grok`) — then review what it produced and land it yourself. You write the brief and own the judgment; Grok does the typing under an explicit autonomy profile; you verify and commit. Nothing here is specific to one orchestrating agent. The loop needs only the ability to run a shell command and read a file, so it works the same whether you are Claude Code, Cursor, OpenCode with a selected model, or any comparable agent. (It is designed for Claude Code and Cursor; treat other orchestrators as designed-for, not yet proven.) ## When NOT to use this - The task is small enough to just do inline — delegation overhead is not worth it. - The `grok` CLI is not installed, not authenticated, or the account lacks Grok Build beta access. - You want to write the code yourself, or you only need a review without an implementer run. ## Prerequisites (check once) 1. `grok version` succeeds. If not, install on any platform with `npm i -g @xai-official/grok` (or use the installer from xAI's official Grok CLI docs) and authenticate (`grok login`, or `grok login --device-auth` on headless hosts, or set `XAI_API_KEY`). 2. **Confirm which `grok` is on PATH.** `command -v grok` shows the active binary and `grok version` its version — the relay records the version it ran into `result.json`, so a stale binary is visible after the fact. 3. You are in (or will point `--cd` at) the target git repository. ## The loop Run these five steps per task. Steps 1, 4, and 5 are your judgment; 2 and 3 are mechanical. ### 1. Write the brief Grok sees **only** the text you send — no orchestrator chat history, no shared context. Everything the task needs goes in the brief: the goal, the current state, what to change, what to leave untouched, the project's **actual** gate commands (discover them from the repo's CLAUDE.md/AGENTS.md/Makefile — do not assume), and a report contract. Tell Grok it will **not** commit (you will). Keep one task per brief. Full guidance and a template: [references/writing-the-brief.md](references/writing-the-brief.md). ### 2. Dispatch Send the brief to Grok with the bundled helper. It wraps `grok -p`, captures the run, and writes a structured `result.json` — so your only job is "run a command, read a file." (`<skill-dir>` below is this skill's installed directory — the folder containing this `SKILL.md`, i.e. the directory you loaded the skill from. Claude Code prints it as "Base directory for this skill" when the skill loads; on other orchestrators use that same directory — if unsure where it landed, run `find ~ -name relay.mjs -path '*grok-delegate*'` and substitute the directory above it.) ```bash node "<skill-dir>/scripts/relay.mjs" --brief brief.txt --cd /path/to/repo # read-only (review/diagnosis; best-effort — verify touchedFiles): add --read-only # continue the previous Grok session: add --resume-last (send only the delta brief) # hard time limit (watchdog): add --timeout 2h (default: off; implementation runs routinely need 1-2h) # see all options: node .../relay.mjs --help ``` The helper defaults to a write-capable (`workspace-write`) autonomy profile — `--always-approve` plus `--sandbox workspace` — and writes its artifacts to a temp dir, so the repo under review stays clean. It **never commits** — see step 5. Mechanics, flags, and the `result.json` shape: [references/dispatch-and-poll.md](references/dispatch-and-poll.md). ### 3. Wait for completion The helper blocks until Grok finishes, so back it with whatever your orchestrator offers and resume when it returns: - **Claude Code:** run the Bash call with `run_in_background: true`; you are notified on completion. - **Plain shell / other agents:** run it in the foreground for short tasks, or background it and poll the result file — `… &` in bash/zsh (including Git Bash/WSL), or your shell's equivalent (`Start-Job` in PowerShell, `start /b` in cmd). The run is done when `result.json` exists with a `status`. (A pre-run usage error — bad args or an empty brief — instead exits with code 2 and a stderr message and writes no result file, so check the exit code too. A missing `grok` binary exits 127 but *does* write a `result.json` with status `grok_unavailable`.) Do not trust progress trackers over reality: a run is finished when `result.json` is written and the process has exited. Read the working tree, not a status line. The implementer's full report is the `finalMessage` field in `result.json` (also printed in full on stdout between the report markers). ### 4. Review — do not trust the self-report Grok's `result.json` includes its own summary and gate claims. **Re-verify, don't accept:** - **Re-run the project's gates yourself** (the test/lint/build commands from step 1). Never take "gates passed" on faith. - **Read the diff** against the brief: did Grok do what was asked, nothing more (scope creep) and nothing less? `touchedFiles` in the result is your starting point. - **Run the relevant guard skills** on the diff if you have them installed (clean-code-guard, test-guard, etc. from `guard-skills`) — this skill produces the work; those skills judge it. - For schema/migration changes, round-trip them; for removals, grep for dangling references. Full checklist: [references/review-and-land.md](references/review-and-land.md). ### 5. Land it **The orchestrator commits.** Only after the gates pass and the diff holds: - Commit the verified work yourself, with a clear message. - If it needs changes, send a delta brief with `--resume-last` (don't restate the whole task) and review again. ## Autonomy model Grok's default permission mode is `ask`, which **blocks on approval prompts in a headless pipe**. The relay therefore always sets autonomy explicitly: | Relay flag | What Grok gets | Use when | | --- | --- | --- | | *(default)* | `--always-approve --sandbox workspace` | Normal implementation — writes scoped to the working tree | | `--read-only` | `--sandbox read-only --permission-mode plan` | Review / diagnosis — **best-effort, not enforced** (see caveat below) | | `--full-access` | `--always-approve --sandbox off` | Explicit opt-in when the task needs unrestricted tools | `--always-approve` alone would approve *all* tools (writes, shell, network) — closer to unrestricted than to a workspace-scoped write. Pairing it with `--sandbox workspace` is what keeps the default safe. Reach for `--full-access` only when the human asks for it. **`--read-only` is best-effort, not a hard guarantee.** The read-only sandbox restricts out-of-workspace filesystem/network access, not grok's own edit tool, and headless `plan` mode is advisory — a run verified here still wrote the working tree when told to. Use `--read-only` to *signal* review intent, but always confirm `touchedFiles` afterward; treat the diff, not the flag, as the guarantee. The relay automates a reporting tripwire: it compares parsed git porcelain and fingerprints the working-tree identity and index entries of Git-visible paths that were already dirty. `readOnlyViolation` is `true` when either signal proves a change, `false` when coverage is complete and detects none, and `null` when coverage is incomplete. Ignored paths, submodule internals, perfect restores, and attribution of concurrent changes remain outside it, so the diff review stays the guarantee. ## Authorization model Delegation is something the human opts into. Once they have ("run this queue", "proceed"), committing verified, gate-passing work is the agreed contract — that is the whole point. Two limits on that mandate: **surface, don't absorb** (report Grok's design decisions, defensible-but-unasked turns, and non-blocking nitpicks rather than silently keeping them) and **stop for scope changes** (if correct completion needs going beyond the brief, ask — don't expand the mandate yourself). The full treatment is in [references/review-and-land.md](references/review-and-land.md). ## References - [references/writing-the-brief.md](references/writing-the-brief.md) — how to write a brief Grok can execute blind: structure, XML blocks, the report contract, embedding the real gate commands. - [references/dispatch-and-poll.md](references/dispatch-and-poll.md) — `relay.mjs` flags, the `result.json` contract, backgrounding per orchestrator, and recovery when a run misbehaves. - [references/review-and-land.md](references/review-and-land.md) — the review checklist, the commit boundary, and the rework cycle via `--resume-last`. - [references/multi-task-queues.md](references/multi-task-queues.md) — running a sequential queue: carrying constraints forward, progress tracking, and the end-of-run coherence check.
Comments (0)
Sign in to join the conversation.
Reviews (0)
No reviews yet.
No comments yet.