How-to: task-oriented recipes#

Recover a failed builtin edit#

A harness’s builtin Edit(path, old_string, new_string) just failed with a no-match error.

uv run tact heal PATH --old "OLD_STRING" --new "NEW_STRING"

Use the exact same old/new triple the failed builtin call used. heal is read-only. It returns either a corrected match (rung reached, actual current lines, a ready-to-apply preview) or a structured refusal (ambiguous with candidates, or genuinely no match). On success, either apply the corrected edit yourself or call tact edit/apply_edits with the same arguments directly. Those direct calls heal internally and write in one step.

Apply an LLM-emitted patch#

A model emitted patch-shaped text rather than a builtin Edit call:

uv run tact apply-patch change.patch          # write
uv run tact apply-patch change.patch --check  # dry run: parse + resolve, write nothing

Or pipe it in: cat change.patch | uv run tact apply-patch - (patch and apply are aliases of the verb). Tact reads one dialect per patch, picked by the first structural marker in the text. The dialects are:

  1. *** Begin Patch, the OpenAI/Codex apply_patch grammar. A Codex agent can pipe the exact text its own apply_patch tool would have taken. *** Update File chunks become edits, and *** Add File creates a file. *** Delete File and *** Move to are refused, because tact never deletes or renames; the refusal says what to do in the shell instead.

  2. Unified diff (diff -u, git diff). Strict parsing by the hunk header’s counts comes first. When a hunk’s counts are wrong, a blank context line lost its leading space, or a stray *** End Patch follows, the hunk body is read up to the next hunk or file header instead. Extra context or removed lines after the counted body are read too, and the file must match them. Extra + lines are read only when they continue an insertion run; after a context line they are refused as ambiguous, so fix the header counts. A --- /dev/null hunk creates its file, and a +++ /dev/null deletion is refused.

  3. SEARCH/REPLACE blocks (<<<<<<< SEARCH, =======, >>>>>>> REPLACE), with the path on the line above. A block with two ======= lines, such as a merge-conflict resolution, is refused because either one could be the separator; send that edit as a unified diff, Begin-Patch, or tact edit --old-file/--new-file.

  4. Fenced blocks: a File: path line followed by ```old/```new pairs, for a model asked to show before/after.

A creation never overwrites. If the file already holds exactly the requested content it is a no-op, and any other existing file is refused. Creations commit before edits, so a refused creation still leaves the transaction all-or-nothing.

A parse error in any file blocks the whole patch: nothing is written, and the error names the file. A marker of a patch dialect outside the part that was read (a unified diff after a *** End Patch, say) blocks it too, and the error names the line. A patch example inside a SEARCH/REPLACE or fenced block is content, not a second patch. Text that matches no dialect at all is a refusal (exit 1, ok: false), never a success over zero files. Over MCP, every path a write tool takes must be absolute, because the server’s working directory may not be yours (a worktree, say); the CLI resolves relative paths against your own directory.

Parsing never applies. The resulting edits still go through the same reconciliation ladder every other verb uses.

Pass multi-line text without fighting the shell#

Shell quoting is the most common way a CLI edit goes wrong: a newline typed as \n inside single quotes arrives as a backslash and an n, and an unquoted space splits one argument into two. Avoid quoting altogether:

# Blocks from files (`-` reads one of them from stdin); the file's final newline is dropped.
uv run tact edit PATH --old-file old.txt --new-file new.txt

# A JSON batch on stdin, in the same shapes the MCP tool accepts.
echo '[{"old_block": "x = 1", "new_block": "x = 2"}]' | uv run tact edit PATH

# Fenced blocks on stdin: no File: line needed, they apply to PATH.
uv run tact edit PATH < blocks.md

--old/--new, their aliases (--old-string/--new-string, --search/--replace), and the -file forms pair up in the order written.

If literal escapes reach tact anyway, it tries the text as written first. Only when that text is absent from the file, or matches only approximately, does it decode \n, \t, \r, \\, and escaped quotes and try again, and only when the decoding yields a line break. The decoded text is used only if it then matches at a stronger rung than FUZZY, and the result reports escapes decoded. Text found in the file as written, even at two places, is edited as written or refused as ambiguous, never decoded. In a Python file, a decoded edit that would not parse is refused. In other code, a decoded line break inside a quoted string (printf("hi\n")) is refused, because that one may be meant as source text; send real newlines.

An --old block that ends in a newline, paired with an empty --new, deletes the whole line rather than leaving it blank. A block’s final line break is otherwise read as its last line’s terminator, so an edit whose only change is a trailing line break is refused rather than reported as applied. To add a blank line after a, send --old $'a\n' --new $'a\n\n', or include the next line in both blocks.

Multi-file rename via LSP#

Renaming a symbol requires knowing which occurrences are the same binding. It is not a textual find-replace. A textual find-replace risks renaming an unrelated local or a string that happens to match:

uv run tact rename PATH TARGET NEW_NAME

TARGET is a bare symbol name (resolved name-first) or a LINE:CHARACTER position. This is the one verb in the package that is not LSP-optional. It needs a live pyrefly server for the file’s project root, found by walking up for pyproject.toml/.git. If no server is available, it structurally refuses and never falls back to text search-and-replace. The computed WorkspaceEdit is converted into one apply_many transaction, so a rename across several files either lands everywhere or nowhere.

Anchor a block across sessions, then delta re-read#

Anchor a block of interest before a context compaction or session boundary:

uv run tact anchor PATH --block "def target_function():" --name my-anchor

Later, in a new session after compaction, re-locate it:

uv run tact resolve-anchor my-anchor

resolve_anchor short-circuits to the remembered position if the file’s sha256 hasn’t moved at all, else re-runs the reconciliation ladder biased toward the anchor’s own remembered line. To find out cheaply what changed in a file since a hash you already have (without re-sending the whole file):

uv run tact delta PATH KNOWN_SHA256

delta composes with the undo journal. If the journal still has the content behind KNOWN_SHA256, the result carries a real unified diff. If the baseline aged out of the journal’s ring or was never a tact-managed write, the result degrades honestly. The result includes the full current content plus a note that the baseline wasn’t recoverable. It never returns a silent empty diff.

Fleet-native routing#

tact hook is a JSON-over-stdin adapter for the five hook-bearing agent CLIs (Claude Code, Codex, Factory Droid, Gemini, Kimi). It reads only the tool name, working directory, and target path. It neither needs nor retains content.

The default posture is butler, not bouncer. In warn mode, the native edit proceeds and records the route without repeating standing advice in the agent context. The agent keeps a harness’s native rendering for the common case. It reaches for tact when an edit actually drifts, or via tact_heal after a builtin Edit fails. Switch to deny only when you want every eligible edit rerouted through tact unconditionally.

# default: native edit proceeds; the route is recorded without added context
cat native-hook-input.json | tact hook --harness claude            # --mode warn is the default
cat native-hook-input.json | tact hook --harness codex --mode warn
# stricter: refuse the builtin edit and point at tact
cat native-hook-input.json | tact hook --harness droid --mode deny
cat native-hook-input.json | tact hook --harness gemini --mode deny
# observe only, no context added (rollout dry-run)
cat native-hook-input.json | tact hook --harness claude --mode shadow

The eligibility boundary is deliberately narrow:

  • existing ordinary files route to tact;

  • new files and notebooks stay with harness-native tools;

  • unrecognized tools and malformed payloads fail open, as does any path tact cannot normalize;

  • the hook never reads file content.

For Claude Code, Codex, and Factory Droid, add this command to the native PreToolUse group for their edit tools. For Gemini, use BeforeTool and write_file|replace:

{
  "hooksConfig": {"enabled": true},
  "hooks": {
    "BeforeTool": [
      {
        "matcher": "write_file|replace",
        "hooks": [
          {"type": "command", "command": "tact hook --harness gemini --mode warn"}
        ]
      }
    ]
  }
}

A warn/shadow fleet rolls back to the bare native editor trivially. Drop the hook, and nothing changes about how edits land. A deny fleet depends on the agent actually following the redirect, so prefer warn unless you have a reason to force the issue.

Native-style rendering for tact tools#

A harness renders its own builtin Read/Edit with bespoke UI that no MCP mechanism can opt into. That rendering lives in the client, not the protocol. What the protocol does offer is the MCP Apps extension (io.modelcontextprotocol/ui), which tact-mcp wires up so tact tools render “something akin to native” in the hosts that support it.

Codex: ordinary tool output by default#

In auto mode, Codex connections receive ordinary MCP text instead of an embedded widget. Tool discovery omits the UI template for that connection, so Codex does not open the “Opened Tact” widget card. Other clients retain their existing rendering.

Tools have readable titles such as “Read file” and “Edit file”. Reads return file text with its full hash; edits name the file and outcome; checks include the diff and say “nothing written”. Complete results remain in structuredContent. Healed matches, refusals, drift, diagnostics, and explicit detail="full" also retain their complete JSON text evidence.

Set the server environment to choose a presentation, then restart the MCP server:

[mcp_servers.tact.env]
TACT_MCP_PRESENTATION = "text"
  • auto (default): text for the observed Codex client identities, existing extension negotiation for other clients.

  • text: ordinary MCP text for every connected client, with no UI template advertised.

  • widget: retain the widget when the client advertises MCP Apps support; otherwise use the existing terminal output.

Codex controls its tool-call row, argument disclosure, and result layout. Disabling the widget removes tact’s embedded app card; it cannot select the built-in Write/Edit renderer or hide Codex’s own tool-call controls. The OpenAI tool reference documents UI template opt-in, readable titles, and status metadata. Those are presentation hints, not a native-editor rendering API. A running server caches this setting at startup, and clients can cache tool discovery, so restart or reconnect after an update.

GUI hosts (Claude.ai, Claude Desktop, Cursor)#

tact-mcp registers one inline widget (ui://tact/view.html) and points every tool at it. A GUI host that advertises the UI extension fetches the widget and renders it in a sandboxed iframe. The host pushes each tool result’s structuredContent into it.

The widget shows a lightly-syntax-highlighted file view for tact_read, a coloured unified-diff view for tact_check/tact_heal/tact_delta, and a key/value outcome/outline table. The model-facing text stays compact. The host owns whether and how it retains structuredContent. MCP does not guarantee that widget data costs zero context tokens. Terminal hosts (Claude Code, Codex CLI, Gemini CLI, Droid) do not fetch the widget.

Routine all-EXACT tact_edit, tact_check, and tact_apply_patch successes return a compact text receipt by default. Request detail="full" when a consumer needs the former JSON/data shape. Healed or ambiguity-resolved matches, refusals, drift, and new diagnostics always retain full evidence.

With auto, non-Codex hosts negotiate the extension automatically at connect time. Use widget to restore this behavior for Codex, or text to disable widgets for every host.

Terminal cosmetic (optional, opt-in)#

Claude Code renders ANSI inside MCP tool output, but some other terminals strip it. On a compatible terminal, set TACT_MCP_ANSI=1 to prefix non-compact results with a single jade-coloured status word. This is a cosmetic touch, not a re-render:

TACT_MCP_ANSI=1 uv run --extra mcp --project /path/to/tact tact-mcp

It is off by default so it can never pollute a model’s context with literal escape codes in a host that strips ANSI. The honest ceiling in any terminal is that the result can get a coloured status word. The client renders the call (the grey parameter block), which has no server-side override. The butler-mode warn routing above is the practical mitigation. That routing leaves the harness’s native editor as the common path and invokes tact when an edit drifts or fails. The text presentation above is the option for agents that use tact directly for every edit.

Gemini CLI versions before 0.26.0 do not execute runtime hooks. tact doctor reports the installed surfaces. The opt-in live suite makes the compatibility floor observable rather than silently treating a projected-but-dormant hook as healthy.

# ordinary suite: every live canary is skipped
uv run pytest

# all installed harnesses; real model calls, so explicit and billable
uv run pytest --run-live-harness -m live_harness -vv

# one harness, or an ephemeral known hook-capable Gemini build
TACT_LIVE_HARNESS=codex uv run pytest --run-live-harness -m live_harness -x -vv
TACT_LIVE_HARNESS=gemini \
TACT_GEMINI_COMMAND='bunx --bun @google/gemini-cli@0.26.0' \
uv run pytest --run-live-harness -m live_harness -x -vv

Diagnose a fleet install#

tact doctor
tact --json doctor

The doctor checks the Python and CLI surfaces, the optional MCP extra, the state directory, and telemetry readability. JSON output is stable enough for a fleet preflight. Human output keeps the authoritative path and failure detail visible.

Wire the MCP server into an agent harness#

The server is one stdio process: uv run --extra mcp --project /path/to/tact tact-mcp. --extra mcp is required. The server imports fastmcp, an optional dependency.

Claude Code#

Add a tact entry to your MCP config (e.g. .mcp.json):

{
  "mcpServers": {
    "tact": {
      "type": "stdio",
      "command": "uv",
      "args": ["run", "--extra", "mcp", "--project", "/path/to/tact", "tact-mcp"]
    }
  }
}

Factory Droid#

Merge the same server block into ~/.factory/mcp.json’s mcpServers object.

Codex CLI#

Add to ~/.codex/config.toml:

[mcp_servers."tact"]
command = "uv"
args = ["run", "--extra", "mcp", "--project", "/path/to/tact", "tact-mcp"]

Cursor#

Add to ~/.cursor/mcp.json’s mcpServers object (same shape as the Claude Code block above).

No env block is needed for any harness. tact-mcp reads no environment secrets.