Stopping Unapproved File Edits and 7-Turn Quota Burn: A Two-Stage Discussion Lock and 2-Turn Execution Loop

1. Where the 5-Hour Quota Actually Goes

When pair-programming with a frontier reasoning model (Gemini 4 Argon, Claude 3.5 Sonnet), two failure modes account for almost all wasted quota and broken working trees: premature file mutations during discussion and multi-turn tool chatter during execution.

Watch what happens on the stdio wire during a routine 2-file refactor in an unconstrained session:

  1. The Question Trap (Unapproved Edits): You ask an exploratory question (“Why did we use an in-memory Map here instead of Redis?”). Because write_file and edit_file remain unlocked during discussion, soft-attention weighting over the recent code context overrides your system prompt, and the agent starts rewriting files before you even agree on a plan.

  2. Synthetic Review Hook Hijacks: When an agent writes a plan artefact, the IDE often injects an automated system message (Stop hook blocked termination: The user has automatically approved the artifact through their review policy...). The model mistakes this synthetic hook for human sign-off and starts modifying code without your consent.

  3. The 7-Turn Quadratic Context Resend: Even when you explicitly approve an edit, an unconstrained loop takes 6 to 8 round-trips:

    [Turn 1: Approve] -> [Turn 2: read_file A] -> [Turn 3: read_file B] -> [Turn 4: edit_file A/B]
                      -> [Turn 5: run_tests]   -> [Turn 6: fix typo]    -> [Turn 7: prose summary]
    

    Every single tool round-trip re-sends your entire accumulated conversation history ($C$) over the wire. If your session is at $C = 30,000$ tokens and grows by $\Delta \approx 2,500$ tokens per turn, $N = 7$ turns costs:
    $$\text{Total Input Tokens} = \sum_{k=1}^{7} (30,000 + k \cdot 2,500) = 280,000 \text{ input tokens}$$
    Collapsing that exact same task into 2 turns drops cumulative input token burn from 280,000 to ~67,500 tokens - allowing 2.8x more features inside the exact same quota window.

You can fix ~70% of this today with a deterministic rule contract in GEMINI.md / AGENTS.md (Section 2), and close the remaining ~30% of wire-level edge cases - like synthetic IDE review stop-hooks, redundant read_file turns, and test falsification - with a lightweight stdio MCP state gate (Sections 3-4).


2. Tier 1 Fix (Zero Install): Copy-Pasteable GEMINI.md Two-Stage Contract

Before installing any tooling, you can immediately cut turn count and stop unapproved file edits by adding these four deterministic rules to your workspace GEMINI.md or AGENTS.md. This physically separates Stage 1 (Discussion) from Stage 2 (2-Turn Execution):

# TWO-STAGE EXECUTION & 2-TURN QUOTA CONTRACT
1. [STAGE 1 DISCUSSION LOCK]: Never call write_file, edit_file, or destructive shell commands while discussing architecture. If the user's prompt contains a question ('?', "why", "what do you think", "should we"), halt all file mutations immediately, present a concise Pros & Cons trade-off matrix, and wait.
2. [BLUEPRINT COMMANDS ("cplan" / "fplan")]:
   - When the user types "cplan", author a compact step blueprint (<= 3 code files per step) with exact symbol/line anchors ([ANCHOR: path/to/file | "functionName("]) and a Blind-Spot Countermeasures section, then STOP immediately. Never treat plan creation or automated IDE review hooks ("auto-approved by review policy") as permission to execute.
   - When the user types "fplan" (on Argon for Flash handoff), embed exact, unique <<<FIND>>> and <<<REPLACE>>> code slices (<= 80 lines per edit block) so Flash can apply them with zero anchor guesswork.
3. [2-TURN ZERO-PROSE EXECUTION ("go" / "sprint")]:
   - Unlock execution ONLY when the human explicitly types "go" (1 step), "go <N>", or "sprint" (all steps).
   - Execute all pre-anchored edits in a single batched turn (<= 80 lines per edit call to prevent SSE stream drops), run the verification command immediately, and output a compact 8-line telemetry receipt with zero intermediate narrative prose.
4. [SUB-AGENT & CAUSAL TEST DISCIPLINE]:
   - Never spawn sub-agents with Model: "inherit" or "pro" for file searches or boilerplate edits (use direct tools or "flash_lite").
   - Never claim tests passed if any source file was modified after the last test command ran.

3. Tier 2 Fix (Wire-Level Enforcement): Why Prompts Eventually Need a stdio Gate

Prompt rules work well for the first 25 turns, but in long engineering sessions they hit three mechanical limits that only an out-of-band stdio MCP server can intercept:

+-----------------------------------------------------------------------------------+
|                        STAGE 1: DISCUSSION MODE (LOCKED)                          |
|  * File-mutation tools return isError: true (BLOCKED_BY_DISCUSSION_MODE)          |
|  * Any prompt containing '?' or inquiring verbs forces demotion to Stage 1        |
+-----------------------------------------------------------------------------------+
                                         |
                                         | Developer types: "cplan" or "fplan"
                                         v
+-----------------------------------------------------------------------------------+
|                    AWAITING_APPROVAL (NONCE & BASELINE LOCKED)                    |
|  * Generates 8-byte hex nonce: planNonce = crypto.randomBytes(8).toString('hex')  |
|  * Hashes working tree (SHA-256) & snapshots target file byte lengths/hashes      |
|  * If "fplan": dry-run simulator checks <<<FIND>>> uniqueness (count === 1) <3ms  |
+-----------------------------------------------------------------------------------+
                                         |
                                         | Approval tool called
                                         v
+-----------------------------------------------------------------------------------+
|              OUT-OF-BAND TRANSCRIPT VERIFIER (64 KiB REVERSE SEEK)                |
|  1. Rejects synthetic hook tokens (auto-approved | review policy | stop hook)     |
|  2. Reads trailing 64 KiB of transcript.jsonl via pre-allocated Buffer            |
|  3. Locates nonceStepIndex where planNonce was emitted into the transcript        |
|  4. Scans for "source": "USER_EXPLICIT" matching approval verb                    |
|  5. Asserts causal ordering: humanApprovalStepIndex > nonceStepIndex              |
+-----------------------------------------------------------------------------------+
                     |                                       |
         Assertion Fails                         Assertion Passes
                     |                                       |
                     v                                       v
      [ REMAIN LOCKED IN STAGE 1 ]           [ STAGE 2: UNLOCK + INJECT SLICES ]

3.1 Defeating Synthetic IDE Stop-Hooks via 64 KiB transcript.jsonl Reverse-Seek

When an agent finishes writing a plan artefact, modern IDEs frequently inject an automated system message into the conversation:

Stop hook blocked termination: The user has automatically approved the artifact through their review policy. Proceed to execution.

To an LLM, that message looks indistinguishable from human approval, causing it to call the execution tool with "developer_confirmation": "go".

To block this deterministically, the MCP server (planning-guard) generates an 8-byte hex planNonce during cplan and inspects the trailing 64 KiB of ~/.gemini/antigravity/brain/<conversation-id>/.system_generated/logs/transcript.jsonl out-of-band before unlocking Stage 2. Because the IDE host flushes transcript.jsonl asynchronously (10 - 40ms after dispatching the stdio tool call), a 4-byte SharedArrayBuffer with Atomics.wait sleeps the thread in the OS scheduler without CPU spin:

const REVERSE_SEEK_BUFFER = Buffer.alloc(65536);
const sleepSharedBuf = new Int32Array(new SharedArrayBuffer(4));

function verifyCausalNonce(transcriptPath, planNonce, minWatermarkStep = 0) {
  const delays = [25, 50, 100, 200, 400];
  for (let attempt = 0; attempt < delays.length; attempt++) {
    const stat = fs.statSync(transcriptPath);
    const seekBytes = Math.min(65536, stat.size);
    const fd = fs.openSync(transcriptPath, fs.constants.O_RDONLY);
    fs.readSync(fd, REVERSE_SEEK_BUFFER, 0, seekBytes, Math.max(0, stat.size - seekBytes));
    fs.closeSync(fd);

    const lines = REVERSE_SEEK_BUFFER.toString('utf8', 0, seekBytes).split('\n');
    let nonceStepIndex = -1, humanApprovalStepIndex = -1;

    for (let i = lines.length - 1; i >= 0; i--) {
      const line = lines[i].trim();
      if (!line) continue;
      if (line.includes('"source":"USER_EXPLICIT"') || line.includes('"source": "USER_EXPLICIT"')) {
        const data = JSON.parse(line);
        if (humanApprovalStepIndex === -1 && /\b(?:go|proceed|execute|sprint)\b/i.test(data.content || '')) {
          humanApprovalStepIndex = data.step_index;
        }
      }
      if (planNonce && line.includes(planNonce)) {
        nonceStepIndex = JSON.parse(line).step_index ?? 0;
      }
    }

    if (nonceStepIndex !== -1 && humanApprovalStepIndex > Math.max(nonceStepIndex, minWatermarkStep)) {
      return { ok: true, stepIndex: humanApprovalStepIndex };
    }
    Atomics.wait(sleepSharedBuf, 0, 0, delays[attempt]);
  }
  return { ok: false };
}

3.2 Eliminating Stage 2 read_file Turns via Pre-Cached Target Slices

Why does an agent spend Turns 2 and 3 calling read_file after you type go? Because by the time you approve the plan, the exact line numbers it wants to edit have scrolled back in context.

When planning_approve_execution unlocks Stage 2, the server parses every [ANCHOR: file | "symbol"] tag from the blueprint, extracts [-2, +8] lines around each target directly from disk, and returns [PRE_CACHED_DISK_TARGETS] inside the approval tool response. The model already has the exact target lines in its immediate working memory at the start of Turn 2 and edits them immediately.

3.3 <3ms Dry-Run Slice Verification & BOM/CRLF-Safe Atomic Patching

To guarantee that multi-file edits never fail mid-flight or corrupt file encodings (especially on Windows repositories requiring UTF-8 BOM 0xFEFF and CRLF termination):

  1. An in-memory dry-run simulator (simulateFplanDryRun()) runs in <3ms before the plan is accepted. It strips any UTF-8 BOM (0xFEFF), normalises CRLF/LF, and verifies that every <<<FIND>>> slice appears exactly once (count === 1) in its target file. If the blueprint contains a non-unique or hallucinated line anchor, plan creation fails immediately in Stage 1.
  2. During Stage 2 execution (whether executed on your primary reasoning model via cplan or handed off to a lighter model via fplan), pre-compiled patches are staged in memory and written atomically in <2ms (preserving original UTF-8 BOM and CRLF/LF line endings per file, with full in-memory pre-image rollback on any error), followed by in-process test verification (auto_verify: true), causal test-order assertion (lastTestStep > lastWriteStep), and automatic relock to Stage 1.
function applyCompiledPatches(patches, workspaceRoot) {
  const preImages = new Map(), stagedWrites = new Map();
  for (const p of patches) {
    const full = path.resolve(workspaceRoot, p.relFile);
    const raw = stagedWrites.has(full) ? stagedWrites.get(full) : fs.readFileSync(full, 'utf8');
    if (!preImages.has(full)) preImages.set(full, raw);

    const hasBom = raw.charCodeAt(0) === 0xFEFF;
    const eol = raw.includes('\r\n') ? '\r\n' : '\n';
    const norm = (hasBom ? raw.slice(1) : raw).replace(/\r\n/g, '\n');
    const targetNorm = String(p.targetSlice || '').replace(/\r\n/g, '\n');

    const count = norm.split(targetNorm).length - 1;
    if (count !== 1) return { ok: false, error: `Slice in ${p.relFile} not unique (count=${count})` };

    const sIdx = norm.indexOf(targetNorm);
    const nextNorm = norm.slice(0, sIdx)
      + String(p.replacement || '').replace(/\r\n/g, '\n')
      + norm.slice(sIdx + targetNorm.length);

    stagedWrites.set(full, (hasBom ? '\uFEFF' : '') + (eol === '\r\n' ? nextNorm.replace(/\n/g, '\r\n') : nextNorm));
  }
  try {
    for (const [full, nextContent] of stagedWrites.entries()) fs.writeFileSync(full, nextContent, 'utf8');
    return { ok: true, applied: patches.length };
  } catch (err) {
    for (const [full, orig] of preImages.entries()) { try { fs.writeFileSync(full, orig, 'utf8'); } catch (_) {} }
    return { ok: false, error: `Atomic write failed (rolled back): ${err.message}` };
  }
}

4. Measured Benchmarks: Classic Loop vs. Two-Stage 2-Turn Engine

Metric Classic Unconstrained Loop Two-Stage Wire Gate (cplan / fplan) Net Improvement
Plan Authoring Tool Calls 2 - 4 calls (read + write_file + cplan) 1 single call (inline compilation + auto tree-hash) -50% to -75% fewer calls (~12s saved)
Stage 2 Execution Turns 5 - 8 LLM round-trips (approve → read → edit → test → complete) 2 LLM round-trips (approve w/ slices → edit + in-process auto_verify) -60% to -75% fewer turns
Cumulative Input Token Resend ~185,000 - 260,000 input tokens/sprint ~65,000 - 85,000 input tokens/sprint (-80% Argon burn via fplan) -65% input token burn (2.8x quota longevity)
Output Token Generation ~2,800 - 4,200 tokens (narrative summaries + diffs) ~750 - 1,100 tokens (compact tuples + 8-line receipt) -73% output token overhead
SSE Stream Timeout Drops 35% - 50% drop rate on monolithic edits >200 lines 0% drop rate (<=80 lines/block + CRLF/LF normalisation) -100% stream interruptions
Flash 3.8 First-Pass Edit Success ~62% - 70% (anchor drift, CRLF mismatch) ~98%+ (<3ms dry-run count === 1 slice lock) +30% to +36% first-pass accuracy
Verification Turn Overhead 2 extra turns (run_tests → step_complete) 0 extra turns (auto_verify: true runs & signs HMAC in-process) -50% verification turns (~15s saved)

5. Quickstart: 4-Command Daily Workflow & Open-Source Server (MIT)

Whether you use the GEMINI.md rule block in Section 2 or install the wire-level MCP server, the daily operator workflow is just four short commands:

  • cplan: Compile a 2-turn blueprint on your current model and lock in AWAITING_APPROVAL.
  • fplan: Compile and dry-run (<3ms) exact <<<FIND>>> / <<<REPLACE>>> slices on Argon, then switch your IDE model selector to Gemini 3.8 Flash to save ~80% of your Argon quota.
  • go (or go 2): Unlock Stage 2 for a single step (or a bounded N-step sprint), then auto-relock to Stage 1.
  • sprint: Execute all steps in 2 turns with pre-cached disk slices, run auto_verify in-process, and auto-relock to Stage 1.
# Optional: 1-line remote installer for the zero-dependency Node.js stdio MCP server:
curl -fsSL https://gist.githubusercontent.com/Tom-Zafred/8b9baeb32cb2451c2c4d115a4e49ae8e/raw/install.js | node

Full source code, 16-gate verification harness (verify.js), and complete operator manual (MIT): RFC-003 planning-guard on GitHub Gist.