# Google Antigravity Quota-Saving & Optimization Guide (One-Click Setup)

> **How to use**: Drag and drop this Markdown file directly into your **Google Antigravity** chat window, then send:
>
> **"Follow this guide step by step: first audit my local Antigravity setup for quota leaks, Orchestrator waste, and hidden background safety reviews; then deploy the zero-token native hooks, slim GEMINI.md rules, and detached backup/audit script, and run the final audit check."**

---

## 1. What This Fix Solves

1. **Stop the Broken Orchestrator & Custom-Agent Multiplier Leaks**:
   - Turn off **Orchestrator** in the model selector — Google recently acknowledged that Orchestrator causes repeated token waste while passing context back and forth, and advised users to stick to a single model tier for now.
   - Remove any `.agents/agents/*.md` custom main agents and keep all instructions in `GEMINI.md` / `AGENTS.md` / on-demand `SKILL.md` so you stay on the standard 1x billing rate.
2. **Cut Off Hidden Background Safety Review Burns**:
   - Antigravity runs a 3-stage background safety pipeline (`agy_tool_safety` → `sir_flash_lite` → `gemini-4-hydrogen-sonar`).
   - Complex chained shell commands (`|`, `&&`, `;`, `>`, `<`, multiline `python3 -c`), unnecessary MCP calls, or legacy manual hook rules in `GEMINI.md` repeatedly escalate to Stage 3, shipping up to ~300K chars (~80K uncached tokens) per review directly against your 5-hour and weekly quota — invisible in `/usage`.
   - This setup tightens command discipline and migrates third-party status hooks to native async `hooks.json` (<10ms, 0 tokens).
3. **Protect 95%+ Prompt Cache Hit Rates & Stop 400K-Token Monster Threads**:
   - Installs a lightweight (~25ms) native `PreInvocation` guard (`context_guard.py`) that reads only the tail 128KB of `transcript.jsonl`.
   - **Green (<120K tokens)**: silent, zero overhead.
   - **Yellow (120K–180K) & Red (180K–240K)**: displays a user-only notice via `metadata.user_markdown` with `systemMessage: ""` — **zero extra model tokens, 100% KV-cache safe**.
   - **Critical (>=240K)**: injects a one-time handoff reminder so you can cleanly run `/compact` or start a fresh chat.
   - **Mid-Session Model Switch & Cache Drop Alerts**: warns immediately if you switch models mid-thread or cache hit rate falls below 35%.
4. **Detached Backup & Post-Upgrade Audit**:
   - All files live in `~/.gemini/` (separate from the Antigravity app binary). Includes `agy_harness_manager.py` to back up, restore, and benchmark hook latency and real cache hit rates after every Google update.

---

## 2. Step-by-Step Instructions for Antigravity

### Step 1: Read-Only Local Audit (Do Not Delete User Data)

1. Check `~/.gemini/config/config.json` to see if an Orchestrator model is active; if so, remind the user to switch to a fixed single model tier in the UI.
2. Check `~/.agents/agents/` and `~/.gemini/agents/` for any custom main agents.
3. Check `~/.gemini/GEMINI.md` for legacy rules asking the model to manually run external hook scripts every turn.
4. Check `~/.agents/skills/` count; if there are dozens of unused global skills, offer to archive them safely into `~/.agents/skills_disabled/`.
5. If `~/.gemini/antigravity-cli/log/cli-*.log` exists, summarize Stage 1 / Stage 2 / Stage 3 background safety review counts for the user.

---

### Step 2: Deploy Native Context & Cache Guard (`~/.gemini/config/hooks/`)

#### 2.1 Create `~/.gemini/config/hooks/harness_config.json`

```json
{
  "soft_warn_tokens": 120000,
  "hard_warn_tokens": 180000,
  "handoff_inject_tokens": 240000,
  "cache_miss_min_tokens": 50000,
  "cache_miss_warn_ratio": 0.35,
  "warn_repeat_every_turns": 10
}
```

#### 2.2 Create `~/.gemini/config/hooks/context_guard.py`

```python
#!/usr/bin/env python3
"""Antigravity Context & Cache Guard Hook (<30ms, zero model tokens for warnings)."""
import json
import os
import sys

CONFIG_PATH = os.path.expanduser("~/.gemini/config/hooks/harness_config.json")
DEFAULT_CONFIG = {
    "soft_warn_tokens": 120000,
    "hard_warn_tokens": 180000,
    "handoff_inject_tokens": 240000,
    "cache_miss_min_tokens": 50000,
    "cache_miss_warn_ratio": 0.35,
    "warn_repeat_every_turns": 10,
}


def load_config() -> dict:
    cfg = dict(DEFAULT_CONFIG)
    try:
        with open(CONFIG_PATH, "r", encoding="utf-8") as f:
            cfg.update(json.load(f))
    except Exception:
        pass
    return cfg


def read_last_usage(transcript_path: str):
    if not transcript_path or not os.path.isfile(transcript_path):
        return None
    try:
        size = os.path.getsize(transcript_path)
        read_bytes = min(size, 131072)
        with open(transcript_path, "rb") as f:
            if size > read_bytes:
                f.seek(size - read_bytes)
            chunk = f.read().decode("utf-8", errors="ignore")
        for line in reversed(chunk.splitlines()):
            if '"input_tokens"' not in line:
                continue
            try:
                obj = json.loads(line)
            except Exception:
                continue
            if "input_tokens" in obj:
                inp = int(obj.get("input_tokens") or 0)
                cr = int(obj.get("cache_read_tokens") or 0)
                total = inp + cr
                return {
                    "input_tokens": inp,
                    "cache_read_tokens": cr,
                    "total_tokens": total,
                    "cache_ratio": (cr / total) if total > 0 else 1.0,
                    "model": str(obj.get("model") or ""),
                    "step_index": int(obj.get("step_index") or 0),
                }
    except Exception:
        return None
    return None


def load_state(cid: str) -> dict:
    path = f"/tmp/agy_harness_state_{cid}.json"
    try:
        with open(path, "r", encoding="utf-8") as f:
            return json.load(f)
    except Exception:
        return {}


def save_state(cid: str, state: dict) -> None:
    path = f"/tmp/agy_harness_state_{cid}.json"
    try:
        with open(path, "w", encoding="utf-8") as f:
            json.dump(state, f)
    except Exception:
        pass


def main() -> None:
    try:
        raw = sys.stdin.read()
        data = json.loads(raw) if raw.strip() else {}
    except Exception:
        sys.stdout.write("{}\n")
        return

    if data.get("hookEventName") != "PreInvocation" or int(data.get("invocationNum") or 1) != 1:
        sys.stdout.write("{}\n")
        return

    cid = str(data.get("conversationId") or "unknown")
    usage = read_last_usage(str(data.get("transcriptPath") or ""))
    if not usage or usage["total_tokens"] <= 0:
        sys.stdout.write("{}\n")
        return

    cfg = load_config()
    state = load_state(cid)
    total = usage["total_tokens"]
    ratio = usage["cache_ratio"]
    step_idx = usage["step_index"]
    last_step = int(state.get("last_warn_step") or 0)
    last_level = str(state.get("last_level") or "green")
    handoff_sent = bool(state.get("handoff_sent") or False)
    repeat_gap = max(3, int(cfg.get("warn_repeat_every_turns") or 10)) * 2

    inject_steps = []
    notices = []

    cur_model = usage.get("model", "")
    prev_model = str(state.get("last_model") or "")
    if cur_model and prev_model and cur_model != prev_model and total >= cfg["cache_miss_min_tokens"]:
        notices.append(
            f"🔄 **Mid-Session Model Switch Detected** (`{prev_model}` → `{cur_model}`, `{total/1000:.0f}K` tokens): "
            "switching models invalidates the server KV cache and forces full uncached recomputation. Stick to one model per thread."
        )
    if cur_model:
        state["last_model"] = cur_model

    if (
        total >= cfg["cache_miss_min_tokens"]
        and ratio < cfg["cache_miss_warn_ratio"]
        and step_idx > int(state.get("last_cache_warn_step") or 0)
    ):
        notices.append(
            f"⚡ **Low Prompt Cache Hit Rate** (`{ratio*100:.1f}%` at `{total/1000:.0f}K` tokens): "
            "usually caused by switching models mid-thread or a disconnect exceeding cache TTL."
        )
        state["last_cache_warn_step"] = step_idx

    level = "green"
    if total >= cfg["handoff_inject_tokens"]:
        level = "critical"
    elif total >= cfg["hard_warn_tokens"]:
        level = "red"
    elif total >= cfg["soft_warn_tokens"]:
        level = "yellow"

    if level != "green" and (level != last_level or (step_idx - last_step) >= repeat_gap):
        state["last_level"] = level
        state["last_warn_step"] = step_idx
        if level == "yellow":
            notices.append(
                f"🟡 **Context Watermark Notice**: `{total/1000:.0f}K` tokens (cache `{ratio*100:.1f}%`). "
                "Consider running `/compact` at the next milestone to keep quota burn low."
            )
        elif level == "red":
            notices.append(
                f"🟠 **Compact Recommended**: `{total/1000:.0f}K` tokens (over 180K threshold, cache `{ratio*100:.1f}%`). "
                "Run `/compact` or open a fresh chat thread now."
            )
        elif level == "critical":
            notices.append(
                f"🔴 **Critical Context Limit (`{total/1000:.0f}K` tokens)**: continuing will slow down and risk huge uncached recomputation. "
                "Please run `/compact` or start a new chat after this turn."
            )

    if notices:
        inject_steps.append(
            {
                "systemMessage": {
                    "systemMessage": "",
                    "metadata": {"user_markdown": "\n\n".join(notices)},
                }
            }
        )

    if level == "critical" and not handoff_sent:
        state["handoff_sent"] = True
        inject_steps.append(
            {
                "systemMessage": {
                    "systemMessage": (
                        f"[Harness Context Guard] Current context has reached {total:,} tokens. "
                        "Keep tool outputs concise. At the end of this turn, briefly summarize "
                        "key progress and next steps so the user can cleanly run /compact or start a fresh session."
                    )
                }
            }
        )

    save_state(cid, state)
    sys.stdout.write((json.dumps({"injectSteps": inject_steps}, ensure_ascii=False) if inject_steps else "{}") + "\n")
    sys.stdout.flush()


if __name__ == "__main__":
    main()
```

#### 2.3 Register in `~/.gemini/config/hooks.json` (Merge Only — Preserve Existing Hooks)

```json
{
  "context-guard": {
    "enabled": true,
    "PreInvocation": [
      {
        "type": "command",
        "command": "python3 ~/.gemini/config/hooks/context_guard.py",
        "timeout": 3
      }
    ]
  }
}
```

Run `chmod +x ~/.gemini/config/hooks/context_guard.py`.

---

### Step 3: Add Slim Quota-Shield Rules to `~/.gemini/GEMINI.md` (Back Up First)

```markdown
# Harness Discipline (Token, Cache, Speed & Quota Shield)
- **Keep outputs small**: Read large files in chunks via `read_file` (<=150 lines); prefer `rg -n -m 30` over unbounded dumps.
- **Avoid hidden safety-review storms**: Send single clean shell commands in `run_command`; avoid unnecessary `|`, `&&`, `;`, `>`, `<` chains or multiline `python3 -c` scripts; prefer built-in `read_file` over shell or MCP whenever possible.
- **Protect cache & billing rate**: Do not use `.agents/agents/` custom main agents; stay on one fixed single model tier (avoid Orchestrator until fixed); isolate high-sensitivity operations (`git push`, out-of-workspace scripts) into short sessions; suggest `/compact` or a fresh chat around 180K tokens.
```

---

### Step 4: Deploy Detached Backup & Upgrade Audit Script (`~/.gemini/config/hooks/agy_harness_manager.py`)

Create the same `agy_harness_manager.py` utility supporting `backup`, `restore`, and `audit` (checks config integrity, hook latency < 150ms, custom agent count, and average prompt cache hit rate across recent large-context turns), then run:

1. `python3 ~/.gemini/config/hooks/agy_harness_manager.py backup`
2. `python3 ~/.gemini/config/hooks/agy_harness_manager.py audit`

Verify the final report prints `PASS` and summarize findings to the user.
