Skip to content

Menu

Playbooks

Have an agent do a small refactor

Isolate the work in a branch or worktree, then have an agent rename and split one small function through green, reversible steps.

min read
18
Level
Advanced
Last verified

This playbook applies to Antigravity CLI or the Antigravity App. It is for developers and code reviewers who can already run project tests and read a Git diff. You will have an agent rename a fictional small function and extract a helper inside an isolated branch or worktree. The result is a set of bounded changes that can each be reversed and are protected by green tests, not a large rewrite whose failure is difficult to locate.

This is an independent, unofficial guidebook with no affiliation with Google. This page only combines Antigravity behavior already verified on pages elsewhere in this guidebook with a general refactoring method. The example repository, code, command output, and commits are fictional; none were run while preparing this page.

In plain English: An agent needs two layers of guardrails

Section titled “In plain English: An agent needs two layers of guardrails”

When you perform a small refactor yourself, you may naturally change a little, run the tests, and inspect the diff. An agent is more likely to combine renaming, extracting functions, formatting, and test edits into one large action. If the result turns red, you cannot easily tell which step changed behavior.

The two guardrails are isolation and cadence: save a green baseline, perform one structural change at a time, and create a rollback point only after the tests return to green. For the invariants that tests should protect and the general method for splitting a refactor, first read Perform a small refactor with tests as a safety net. This page adds the modes, permissions, and review gates needed when an agent executes that method.

Weak prompt:

Refactor src/parcel-label.js, give the functions clearer names, split things up,
and optimize related code while you are there.

Better prompt:

Analyze the code read-only first. Do not edit files yet. Rename the internal
function formatTag to formatParcelTag, then extract string normalization into
one unexported helper. Observable behavior must not change.
Only src/parcel-label.js may change. Treat test/parcel-label.test.js as read-only.
Do not add dependencies, change public exports, or format unrelated code. First
list the invariants and two independent steps. After I approve the plan, perform
one step at a time. Wait until I review the diff, run node --test, and create a
rollback point before continuing. Do not edit tests to manufacture a green run.

Complete example: Rename and split a label-formatting function

Section titled “Complete example: Rename and split a label-formatting function”

The fictional demo-labels repository uses ECMAScript modules. It contains a package.json declaring "type":"module", src/parcel-label.js, and test/parcel-label.test.js.

src/parcel-label.js before the refactor:

function formatTag(record) {
const name = record.name.trim().replace(/\s+/g, ' ');
const zone = record.zone.trim().replace(/\s+/g, ' ').toUpperCase();
return `${name} · ${zone}`;
}
export function buildParcelLabel(record) {
if (!record || typeof record !== 'object') {
throw new TypeError('record must be an object');
}
return `To: ${formatTag(record)}`;
}

The read-only behavioral contract in test/parcel-label.test.js:

import test from 'node:test';
import assert from 'node:assert/strict';
import * as labels from '../src/parcel-label.js';
const { buildParcelLabel } = labels;
test('keeps the public export stable', () => {
assert.deepEqual(Object.keys(labels), ['buildParcelLabel']);
});
test('normalizes spacing and uppercases the zone', () => {
assert.equal(
buildParcelLabel({ name: ' Mira Chen ', zone: ' north dock ' }),
'To: Mira Chen · NORTH DOCK',
);
});
test('rejects a missing record', () => {
assert.throws(
() => buildParcelLabel(null),
{ name: 'TypeError', message: 'record must be an object' },
);
});

Put the following block in the prompt and save it in your task record:

[Goal]
Rename the internal function formatTag to formatParcelTag and extract the repeated
trim plus whitespace collapse into normalizeTagPart. Keep the observable behavior
of buildParcelLabel unchanged.
[Allowed change]
Only modify src/parcel-label.js.
[Must not change]
- The only public export remains buildParcelLabel(record).
- Output remains "To: <name> · <UPPERCASE ZONE>".
- Leading and trailing whitespace is removed, and consecutive whitespace becomes one space.
- A missing record still throws the same TypeError with the same message.
- test/parcel-label.test.js is read-only. Do not add dependencies, edit configuration, or use the network.
- Do not commit or continue to the next step until I return the test and review result.
[Steps]
1. Only rename formatTag to formatParcelTag and update its sole call site.
2. Then extract an unexported normalizeTagPart(value) called by formatParcelTag.
3. Provide only the minimal diff for the current step, then stop.

The public export, output text, exception, and whitespace handling are observable invariants; the number and names of internal helpers may change. If critical coverage is missing, first establish it with Perform a small refactor with tests as a safety net, then begin a separate refactor task. Do not change the contract and implementation together.

CLI path. Before handing the task to the agent, confirm that the working tree is clean and create a dedicated branch yourself. These commands describe the fictional workflow and were not run in the environment used to write this page:

终端窗口
git status --short
git switch -c refactor/parcel-tag
git rev-parse HEAD
node --test

git status --short should be empty. Record the output of git rev-parse HEAD as <BASE_COMMIT>. The fictional expected baseline is tests 3, pass 3, fail 0. If the baseline is not green, stop here.

App path. Start the conversation with New worktree on a Git checkout. A page elsewhere in this guidebook verifies that this creates a Git worktree for the conversation while leaving the original folder unchanged. In a project that mixes Git checkouts and ordinary folders, only the Git checkouts receive new worktrees; ordinary folders are still modified in place. See Create a project in the Antigravity app and review artifacts. This guidebook does not document the branch name, disk location, or cleanup timing of an App-created worktree. If those details affect your rollback plan, follow the official page.

Choose a mode and permission level for every step

Section titled “Choose a mode and permission level for every step”

Do not rely on the product’s current defaults. Fix the gates for this task explicitly:

Phase CLI App What you inspect
Plan Use plan mode for read-only investigation and a proposed plan Use Planning mode and explicitly request a plan first File scope, invariants, two-step order, and verification command
Green baseline Switch to default and review each command Keep the Default permission preset The actual command is node --test, with 3/3 passing
Steps 1 and 2 Stay in default and accept file diffs individually After approving the plan, handle only one step per turn Only the target file changes; tests, configuration, and dependencies do not
Final review Use /diff to compare all changes and per-turn changes Inspect Agent Edits in the Review pane and compare <BASE_COMMIT>..HEAD with Git Two rollback points, cumulative changes, final tests, and the file list agree

CLI plan performs read-only investigation before presenting a plan for approval. In default, file edits pause for diff review, commands follow the permission settings, and the startup mode can vary by version and account. Inspect the status and set the mode instead of assuming a default; see Your first agent task: Use execution modes and permissions as guardrails. For Planning and the Default permission preset in the App, use Create a project in the Antigravity app and review artifacts and Permissions and sandbox: what presets, rules, and the sandbox each control.

This task does not need auto, Turbo, always-proceed, or skipped permissions. auto automatically accepts edits inside the workspace, while Turbo disables the sandbox and greatly broadens access. Both remove review gates this playbook needs; see Before enabling auto or Turbo: risks, acceptable cases, and reversal. If your version, account, or managed environment presents different presets, follow the official page and administrator policy rather than imitating a missing option with broader permissions.

Require the agent to provide only this diff:

function formatTag(record) {
function formatParcelTag(record) {
const name = record.name.trim().replace(/\s+/g, ' ');
const zone = record.zone.trim().replace(/\s+/g, ' ').toUpperCase();
return `${name} · ${zone}`;
}
@@
return `To: ${formatTag(record)}`;
return `To: ${formatParcelTag(record)}`;

Read the diff, then run node --test yourself. The fictional expected result remains tests 3, pass 3, fail 0. After confirming that only src/parcel-label.js changed, create the first rollback point:

终端窗口
git diff -- src/parcel-label.js
git add src/parcel-label.js
git commit -m "refactor: rename internal parcel tag formatter"

This commit has one structural purpose: the rename. If the tests turn red, do not commit. Revert this small step and explain the failure instead of allowing the agent to extract the helper next.

Step 2: Extract the string-normalization helper

Section titled “Step 2: Extract the string-normalization helper”

Return the green result and rollback point from step 1, then allow the agent to continue. The expected minimal diff is:

function normalizeTagPart(value) {
return value.trim().replace(/\s+/g, ' ');
}
function formatParcelTag(record) {
const name = record.name.trim().replace(/\s+/g, ' ');
const zone = record.zone.trim().replace(/\s+/g, ' ').toUpperCase();
const name = normalizeTagPart(record.name);
const zone = normalizeTagPart(record.zone).toUpperCase();
return `${name} · ${zone}`;
}

Run the same test again and read the complete diff. Confirm that normalizeTagPart was not exported and that the order of uppercasing did not change. The fictional expected result is still 3/3 passing. Then create the second rollback point:

终端窗口
git diff -- src/parcel-label.js
git add src/parcel-label.js
git commit -m "refactor: extract tag part normalization"

The final artifact is the step 2 diff applied to the result of step 1. Both normalizeTagPart and formatParcelTag remain internal, while buildParcelLabel remains the only public export.

Inspect the file list first, verify that the test file is unchanged, inspect every implementation diff, and finally rerun the tests yourself. After both commits, a plain git diff and the Review pane’s uncommitted-changes view may be empty, so review the cumulative change from the starting commit:

终端窗口
git status --short
git log --oneline <BASE_COMMIT>..HEAD
git diff --name-status <BASE_COMMIT>..HEAD
git diff <BASE_COMMIT>..HEAD -- src/parcel-label.js test/parcel-label.test.js
node --test

git status --short should be empty, the commit range should contain only src/parcel-label.js, and test/parcel-label.test.js should remain byte-for-byte identical to the baseline. In the CLI, /diff can show all changes and per-turn changes. In the App, inspect Agent Edits in the Review pane, then cross-check them with the Git range above. Do not substitute a walkthrough or an agent’s “all tests passed” claim for that evidence. Follow the full sequence in Review agent changes before you accept them. For plan and artifact approval, including the pause created by /plan, see Artifacts and plans: kinds, surface differences, and how to judge a plan.

The final history should contain two small commits: the first only renames the function, and the second only extracts the helper. The test file remains byte-for-byte identical to the baseline. The fictional final expectation for node --test is tests 3, pass 3, fail 0; this is not an executed result.

Anti-pattern 1: Enable auto or Turbo and finish in one pass

Section titled “Anti-pattern 1: Enable auto or Turbo and finish in one pass”
This is a small change. Complete everything, run the tests, and commit without asking me.

The problem is not only broader permissions. It also compresses the rename and helper extraction into one result, removing the narrowest diagnostic point if tests fail. Rewrite it to use a planning mode first, preserve per-diff review during execution, and let you create a rollback point after each green step before approving the next one.

Anti-pattern 2: Trust only the agent’s summary

Section titled “Anti-pattern 2: Trust only the agent’s summary”
The agent says it changed only one file and all tests passed, so the branch is ready to merge.

A summary is a self-report, not evidence. Check the file list, see whether tests changed, read each diff, run node --test yourself, and use Git to verify the commit scope. The review guidance elsewhere in this guidebook likewise treats diffs, test output, and Git state as independent evidence; see Review agent changes before you accept them.

  • The CLI work is on a dedicated branch, or the App is using New worktree for a Git checkout; the original line of work contains none of these changes.
  • node --test was green before the refactor, and the command, output, and starting commit were recorded.
  • The prompt names the only writable file, read-only tests, public invariants, prohibited actions, and stop conditions.
  • The plan contains only the rename and helper extraction, with no incidental formatting, dependency, configuration, or test change.
  • Each step has one minimal reviewed diff, and a rollback point is created only after the tests return to green.
  • test/parcel-label.test.js was not deleted, weakened, or rewritten to accommodate the implementation.
  • The public export, output text, whitespace rules, casing rules, and exception are unchanged at the end.
  • The file list, CLI /diff or App Review pane, the <BASE_COMMIT>..HEAD Git diff, and the test result agree.
  • Every command output is identified as real or fictional; an expected result is never presented as an executed result.
  • The baseline is not green: Stop the refactor and save the failure output. Fix the existing issue first, or narrow the baseline to a test set whose green state you can prove. Do not dismiss the failure as probably unrelated.
  • The current step turns red before a commit: Save the diff and failure output, revert only the current target file, and confirm that tests recover. Do not stack the next step on top.
  • A committed rollback point is found to be wrong later: Prefer git revert <commit> so the reversal remains reviewable. Do not hide the problem by rewriting shared history.
  • The agent edits tests or an out-of-scope file: Reject that diff. If it already reached disk, use Git to identify and restore only the out-of-scope files, then restate the boundary.
  • The App worktree location or cleanup behavior differs from your expectation: Sources cited elsewhere in this guidebook do not document those details. Preserve the branch and Git evidence, and follow the official page for exact operations. Do not treat deleting a worktree as the only rollback mechanism.
  • You want to use /rewind to undo files: Guidance elsewhere in this guidebook confirms only that it rewinds conversation history; it does not say that disk files are restored. Use Git for file recovery; see Your first agent task: Use execution modes and permissions as guardrails.
  • The interface, mode, or permission options differ: Antigravity can vary by version, account, and managed environment. Follow the official page and administrator policy while preserving the interface-independent principles of least privilege, incremental review, and Git recovery.
  • The real repository contains sensitive material: Do not place secrets, customer data, production logs, or private credentials in prompts, artifacts, or test output. Use only placeholders such as YOUR_API_KEY in examples.

Next: Recheck the general invariants in Perform a small refactor with tests as a safety net, narrow permissions with Permissions and sandbox: what presets, rules, and the sandbox each control, and finish with Review agent changes before you accept them.