griz
Code edits as composable primitives, for agents and the programs they write.
griz splits an edit into small steps whose outputs feed the next step: find text, plan a change without writing it, diff or select part of the plan, apply it all-or-nothing, and undo it later. Served over MCP, every step is its own tool, so a Code Mode program composes griz with anything else it can call: run checks through apoc, judge matches with jev, record work in devsql.
// One apoc Code Mode program: rename across files, check, roll back on failure.
const root = "/path/to/repo";
const expectedMatches = 12;
const found = await griz.;
if
return ;
const ops = found..;
const plan = await griz.;
if return ;
const applied = await griz.;
if return ;
const check = await apoc.;
const result = ;
if return result;
const undone = await griz.;
return ;
Only what the program returns reaches the model. A failed preflight stops before the next step. For a pending check, keep its execution id and the operation id, then wait for the check to finish before deciding whether to undo. A terminal check failure returns the undo verdict too; undo can refuse later file changes.
Guarantees
- Nothing is written before apply.
planbuilds every file's new text in memory and records it;diffshows it. - Search failures are explicit. Missing search paths, traversal errors, and file read failures return an error instead of an empty or partial result. Non-UTF-8 files are skipped; empty readable directories still return no matches.
- Stale files are refused. Every match and every planned file carries the
fingerprint of the text it was computed against.
applywrites nothing unless every file still has that fingerprint, or, withon_stale: "merge", unless a three-way merge is clean. - All or nothing. Every file is staged before the first rename, and the operation is journaled first. A process killed mid-apply is finished by the next griz invocation. Recovery skips operations that another writer already completed.
- Tolerant matches are labeled. An anchor is matched exactly first, then
ignoring trailing whitespace, then by relative indentation, then trimmed.
Only exact matches and find ranges are
machineconfidence;applyrefusesmaybeedits unless asked, andselectcan keep only the exact ones. - Ambiguity is an error. An anchor matching twice reports every candidate
line instead of taking the first. Selecting
occurrence: "all"also refuses overlapping tolerant matches and lists their lines; select one occurrence or narrow the anchor. - Misses show the real text. A missed anchor records the nearest real window
of the file, readable with
get. - Undo never clobbers. Undo restores only files still exactly as the
operation left them, or, with
on_stale: "merge", merges cleanly around later edits. An undo is itself an operation that can be undone. - Restores follow history.
undo --sincerewinds a span of operations only where every file's writes hand off the same fingerprint; a change made outside griz in between refuses the restore. The starting operation must exist; an unknown ID is rejected before any restoration. History follows journal order under file locks, so a delayed concurrent edit appears after the writes it builds on, regardless of when its ID was created. - Parse facts. A plan reports whether each file still parses. Request
expect_syntax: "clean"to fail a plan that introduces syntax errors. - Parent paths follow the filesystem. Before traversing
.., griz resolves the preceding directory, including directory symlinks. Missing or non-directory prefixes are rejected instead of silently choosing a different file. Mutation retries consult their original receipt before resolving target paths again. - Directory aliases compose. New plans resolve existing parent directories, so a directory symlink and its target share one planned file and one lock. Retargeting the link later does not redirect a new saved plan. Missing directory suffixes stay creatable; dangling directory links are rejected. Older saved paths and their original filters remain usable, but a write containing multiple paths to the same destination is refused before staging. This identifies parent directories.
- Native edit fields are checked. Operations, anchors, byte ranges, and structural-pattern locators reject unknown fields. Plan errors name the operation index and unexpected field, so a misspelled guard cannot be ignored.
- Existing filename aliases compose. When the filesystem resolves differently cased names to one existing file, reads, plans, and filters use its actual entry name. Case-sensitive filesystems keep distinct names separate, as do distinct hard-link entries. This does not add case-only renames or infer equivalence between new filenames that do not yet exist.
- File aliases address their targets. New reads, plans, and path filters resolve file symlinks without replacing the links. Edits through an alias and its target compose in one file. A saved plan keeps that target even if the alias is later retargeted or removed. Creating through a dangling file link creates its target; link cycles are errors. Moving or deleting through a file link operates on its target and leaves the link entry unchanged. An older saved path, or a recorded target newly replaced by a link, is refused before staging: plan again to record the intended target.
- Replacement permissions stay intact. Replacing an existing file retains its Unix access and executable bits, including during undo and crash recovery. A later permission change is retained when undo replaces that file. Newly created files, including restores of deleted files, use creation defaults.
- Batch work has bounded concurrency. Snapshot reads use at most four workers. Staging uses at most four workers, each with one open stage file, plus one retained flush descriptor per device. All stages are synchronized before journaling. Journal entries retain plan order; independent source renames use at most 16 workers. Workers finish and attempt temporary cleanup before errors return.
- Formatters do not break undo. Run a formatter after
apply, thenabsorbthe operation; undo restores the text from before the apply. Concurrent absorbs retain one another's selected-file updates. Undo and span restore refresh selected records after waiting for file locks, including absorbs that completed during the wait. A span keeps its original operation IDs. - Selection uses saved inputs. Selecting part of a plan uses its original file snapshots, including files whose operations cancelled out. An older plan missing a required snapshot is refused; plan again to use current files. Selection loads only snapshots needed by the operations it keeps, including both ends of a move; missing discarded snapshots do not block selection.
- Retries are safe. Mutations take an
idempotency_key; the same key and input replay the original result, and different input with the same key is refused.
Commands
| Command | Kind | Does |
|---|---|---|
read PATH |
read | Numbered lines and fingerprint; --grep, --lines. |
find |
read | Literal, regex, or structural (--pattern 'foo($A, $$$REST)') matches with byte ranges, captures, fingerprints; --within comment; honors .gitignore; --expect-matches; --files-only returns paged file counts and fingerprints. |
plan |
records | Operations (--ops), Codex patch text (--patch, @file), or an LSP --workspace-edit into a plan id, with parse facts. |
select PLAN |
records | A new plan from part of another, by path, edit id, or confidence. |
diff ID |
read | Unified diff of a plan or operation, with the named items it changes; --grep or --lines. |
apply PLAN |
writes | All-or-nothing write; --min-confidence, --on-stale merge, --expect-files. |
undo OP |
writes | Restore an operation's files; --paths, --on-stale merge, or --since OP for a span. |
absorb OP |
records | Fold a later formatter run into an operation so undo still works. |
log / get ID |
read | Operation history, narrowed with --paths; the complete record of a plan, operation, or blob_<hash>. |
diff items keep kind, name, and change. Nested definitions also include
scope, an outer-to-inner list such as ["left", "impl A"]. File-level items
omit it. Same-named definitions in different scopes remain distinct; overloads
can produce multiple items with the same kind, name, and scope. Rust callers
constructing DiffItem values must initialize scope; use Vec::new() at file
scope.
Mutations answer {id, outcome} with outcome one of passed, failed
(a declared expectation did not hold), or error (nothing was done). Add
--verbosity warn|info|debug|trace for more. Each level retains the fields and
values below it; trace also includes the full record without dropping the
reason, summary, or detail.
A verdict other than passed exits nonzero.
Absorb retries retain the original call's counts, skipped-file reason, and
operation snapshot, even after another absorb updates the operation. Use get
for the operation's current state. Older absorb receipts saved only the ID and
verdict: they still replay at off or error verbosity, but requesting details
returns IDEMPOTENCY_DETAIL_UNAVAILABLE instead of reconstructing missing facts.
WorkspaceEdit plan retries compare the parsed edit JSON and position encoding
(default utf-16) before reading target files. Keep any @file input available
and unchanged for a retry. Older versions identified these requests by converted
operations: their WorkspaceEdit keys now return IDEMPOTENCY_CONFLICT, while
saved plan IDs remain usable. New planning requests need new keys.
Parent-traversal paths retain .. in mutation request identities. Older keys
whose recorded inputs removed those components can return IDEMPOTENCY_CONFLICT;
their saved plan and operation IDs remain available. Use a new key for a new request.
Operations, applied in order:
{op:"replace", path, find:"text" | {text, after?, whole_lines?} | range:{start,end} | pattern:{pattern, language?}, target?, replace, occurrence?, expect_hash?}
{op:"insert", path, anchor:{text}, after?, text, expect_hash?}
{op:"create", path, text, overwrite?}
{op:"delete", path, expect_hash?}
{op:"move", path, to, expect_hash?}
A range replacement requires expect_hash from the read/find used to compute
it, or find containing the exact old text at that range. The hash protects the
whole observed file; expected text protects the addressed span. An unchecked
range produces an invalid plan, which cannot be applied.
CLI programs
The CLI uses positional identifiers and repeated flags; MCP uses named JSON fields.
| Task | CLI | MCP |
|---|---|---|
| Apply a passed plan | griz apply PLAN ... |
griz.apply({ plan, ... }) |
| Undo an operation | griz undo OP --root ROOT ... |
griz.undo({ root, operation, ... }) |
| Select two paths | --paths 'src one.rs' --paths 'src two.rs' |
paths: ["src one.rs", "src two.rs"] |
| Inspect a record | griz get ID --format json |
griz.get({ id }) |
The ellipses above stand for the mutation's required purpose and idempotency key.
get returns the complete record; it does not take --purpose or --verbosity.
--paths '["src one.rs"]' is one literal path on the CLI, not an array.
Programs must pass --format json, check process exit status and
outcome == "passed", and only then extract the identifier. Parsing a particular
output line or extracting id alone can hide a failure. A failed plan can retain
an ID for inspection; its count and syntax expectations are not carried into
apply. Stop before apply when planning fails. Preserve stdout and stderr when
the process fails or its response is malformed, including errors without an ID.
The guarded CLI example uses Python's
standard library and exact argument arrays to find, plan, apply, check, and
report a guarded undo after a failed check. A complete literal search becomes
one occurrence: "all" operation per file, retaining its fingerprint and the
total expected edit count. Conflicting or missing fingerprints are refused.
It never starts the check after a refused apply. Run it under apoc to supervise the whole attempt:
The same helper accepts --regex or --pattern instead of --literal.
Use --replace for constant text, or --transform transform.py for caller-owned
Python defining replace(match) -> str. --transform - reads the program from
stdin. For example, with --pattern 'legacy($ARG)', the caller can supply:
return + +
Structural matching leaves member calls, comments, and strings alone. For JSON,
use --regex '(?s)\A.*\z' to match whole files, parse match["text"], change
the selected values, and return the serialized text. Regex captures are in
match["captures"], with group 1 at index 0. The helper retains each original
byte range and fingerprint even if the function modifies its match dictionary.
All replacements are computed before planning. A transform error stops before
apply; a failed check uses the same guarded undo as a literal edit. The function
runs as caller code: return text instead of writing source files. Diagnostic
prints go to stderr so stdout remains the receipt.
For caller-written Codex patches, use --patch edits.patch (or --patch -
for UTF-8 stdin) with --expected-files N --expected-edits N, instead of
match and replacement options. Paths in the patch resolve under --root.
The patch file itself resolves from the caller's working directory. griz parses
the patch and checks the declared counts and syntax; apply guards the
fingerprints captured during planning. The helper uses the same check and undo
path as match-based edits and stages large inputs in a temporary file.
Run this recipe directly for these edits. It checks declared counts, fingerprints,
and planned syntax, then runs the supplied check once. Use --help for arguments.
A passed receipt already includes the check result; do not read the helper source
or repeat its checks on the successful path. Inspect the implementation when
diagnosing a reported failure.
Put --check last: everything after it is the check's executable and arguments.
Use a stable key for an attempt; a different edit needs a new key. The example
does not resume an interrupted workflow automatically. Retain apoc's execution
ID and inspect its terminal result before starting another attempt. Its report
retains the applied operation ID if the check cannot start, and includes the
original check output and undo verdict when a check fails. A successful undo
does not turn a failed check into success. Successful checks report exit status
and output byte counts without repeating the check command or printing its logs.
Put --show-check-output before --check to include the command and logs on
success too; failed checks always include the command and both streams. Text is decoded as UTF-8, with undecodable bytes shown as
\xNN; byte counts use the captured bytes. Operation JSON travels through a temporary --ops @file,
so large plans do not exceed command-line argument limits. The input file is
removed after planning, including when planning fails.
Compose with apoc
Register the installed griz executable as a provider to make its primitives available immediately in apoc Code Mode:
Then apoc capability search griz.find should include griz.find. Pass
root explicitly on path-resolving griz calls. A configured server appearing
in apoc mcp check is not proof that the running Code Mode actor exposes its
namespace; verify a direct call before building a workflow around it.
Measure workflow text
The workflow-text benchmark
executes the same literal edits through search plus a patch, a short Python
script invoked from the shell, and the guarded griz example. It verifies every
result against independently rendered expected file contents, then counts
request and response text with cl100k_base and o200k_base:
The report retains transcripts and the tested binary's hash. Counts exclude model reasoning, schemas, transport envelopes, caching, billing, and common fixture/check setup. The shell baseline has no snapshot guard or journal; these measurements compare successful edits, not equivalent recovery guarantees. Absolute command paths and generated IDs affect the counts.
Search implementation
Literal queries use a reusable byte substring finder. Match positions count newlines with memchr, then count characters only after the last newline. These byte-oriented scans are inspired by fsearch's content search. Returned ranges, scopes, pagination, and fingerprints still come from freshly read text.
Measure sparse literal and capturing-regex searches locally:
The measurement checks 64 matches and the final line and character column in a 7.34 MB file, then prints the median of nine runs for each query.
SHA-256 fingerprints use CPU acceleration when available. Repeated large inputs reuse a digest only after comparing every freshly read byte. The cache retains at most 32 MiB of input bytes; this is not a limit on total memory. Small literal and regex pages can also reuse match positions after fresh fingerprint verification. At most eight pages are retained, each with a JSON representation of at most 64 KiB.
On Unix, ordinary CLI reads use a private worker that expires after two idle minutes. Each request still walks the requested paths and reads current files. MCP serves directly from its own engine process. Cold requests, changed files, and working sets larger than the cache still need hashing and scanning.
Compare complete MCP calls against a prior build:
This creates an isolated 7.34 MB fixture through griz, alternates both binaries,
and checks every range, position, capture, and SHA-256 fingerprint. Add
--blocks 128 --limit 64 --samples 51 to measure a paged search over 14.68 MB.
It reports first-request latency separately from repeated-call medians; a warm
speedup does not describe cold searches. Measure uncached
SHA and cache churn with the ignored search_stage_measurement and
cache_churn_measurement tests in release mode.
Batch write implementation
On Apple platforms, staging synchronizes each file, then requests a full device flush after all staging workers finish. Only then can the operation be journaled as applying and source files renamed. Independent destinations can commit concurrently; every worker finishes before the operation is marked applied. Conflicting ancestor/child destinations are refused before journaling. Other platforms retain a full file synchronization for each stage.
Planning uses the same staging primitive for new content blobs. Text is borrowed. Staging groups contain at most 64 MiB of content; in builds supporting binary payloads, decoding can temporarily add one incoming file. This does not bound total plan or process memory. Each group is synchronized before its blob names become visible, and all groups finish before the plan is stored.
Before:
+-----------------------+
| Stage + full sync/file|
+-----------+-----------+
|
v
+-----------------------+
| Journal, then rename |
+-----------------------+
After:
+-----------------------+
| Stage, then fsync |
+-----------+-----------+
| all workers finish
v
+-----------------------+
| Full sync per device |
+-----------+-----------+
|
v
+-----------------------+
| Journal + commit pool |
+-----------------------+
Compare complete calls against a prior installed build:
The benchmark alternates both binaries, writes fresh revisions, and verifies all file bytes and the exact unique journal path inventory with independent SHA-256 values. It records both executable hashes. The reported pipeline sums find, plan, and apply call latency; caller preparation, verification, and undo are excluded. Undo is measured separately. Batch size, transport, platform, and filesystem affect the speedup; a large-batch result does not describe single files.
On macOS, observe the actual synchronization and rename calls:
The observer requires one successful full flush per source device after all file synchronizations and before any source rename. A 96 MiB plan must publish blobs in observed groups no larger than 64 MiB. The observer rejects unknown fcntl signatures; the proof fails if a covered run reaches one. These checks establish requested synchronization ordering, not recovery from a physical power cut.
Use
Installation places griz and its companion griz-engine together. Keep both
binaries in the same directory.
State lives in $GRIZ_HOME, or the user data directory. The journal uses schema 2.
Opening a schema-1 store saves a consistent *.pre-v2-from-v1-*.sqlite3 backup
beside the database and preserves its insertion order during the upgrade.
Older binaries refuse the upgraded store; keep the newer binary for continued
use of that history.
Workspace
griz-core: the pure engine. It reads files it is handed and never writes;cargo xtask checkenforces that.griz-store: journal, content store, locks, idempotency receipts, recovery.griz: the command graph, CLI, and MCP server.xtask: quality policy. Files at most 300 lines, functions at most 60 code lines, narrow test-only lint suppressions, dependency directiongriz → griz-store → griz-core.