Cleaning Code Bloat With Anti Gravity

The Autonomous Software Factory: Eliminating Enterprise Technical Debt with Google Antigravity and Gemini

Sun, Nov 22 2026 /Mpelembe Media/ — Software engineering is undergoing a fundamental paradigm shift away from editor-centric autocompletion toward autonomous multi-agent software factories. Rather than relying on human developers to manually prompt tools line by line, this operational model deploys fleets of specialized artificial intelligence agents that independently plan, build, refactor, and test code across isolated branches before submitting verified pull requests for final human sign-off. This automation specifically targets the enterprise “maintainability gap” and systemic codebase degradation—exemplified by an 81% surge in duplicate code blocks across industry repositories—by systematically purging obsolete dependencies, removing dead code, and stripping unnecessary polyfills.

At the core of the software factory is Google Antigravity paired with a tiered Gemini model architecture engineered to balance throughput with reasoning depth. High-throughput models such as Gemini Flash act as the primary orchestration tier, maintaining fluid background coordination, file indexing, and sub-200-millisecond turn latencies. For complex tasks such as cross-language legacy migrations, multi-thousand-line refactors, and critical vulnerability patching, the factory dynamically escalates workloads to Gemini 4 Argon to capitalize on its one-million-token context window and specialized agentic optimization.

Operational safety and domain specialization are achieved using custom sub-agents defined via Markdown files and structured YAML frontmatter that explicitly govern system prompts and tool allowlists. Through Antigravity’s invoke_subagent mechanism running in Git worktree branch isolation, domain-specific agents for Web, iOS, and Android concurrently audit framework deprecations, bundle sizes, and memory leaks on temporary branches without causing merge locks or polluting the developer’s main working tree. This parallel maintenance pipeline reduces codebase bloat by up to 65% while preserving system stability. Human oversight remains central to the factory via the Agent Manager dashboard, which provides real-time telemetry into agent states, reveals private reasoning paths and tool diffs, and allows engineers to message or pause running sub-agents at any stage.

To establish an autonomous compliance fleet, Google Antigravity discovers custom sub-agents as Markdown files containing structured YAML frontmatter placed in your project’s .agents/agents/ directory.

Below is the directory hierarchy, followed by the exact sub-agent definitions and invocation configurations for Web, iOS, and Android compliance workers.

1. Workspace Directory Layout

Antigravity traverses configuration files hierarchically, resolving universal project rules first before activating scoped agents and skills:

my-project/
├── AGENTS.md                                # Universal orchestrator root instructions
├── GEMINI.md                                # Native Gemini model instructions
├── .agents/
│   ├── rules/
│   │   ├── git-workflow.md                  # PR and branch commit standards
│   │   └── security.md                      # Secret hygiene & permission rules
│   └── agents/
│       ├── web-compliance-auditor.md        # Web / Next.js compliance sub-agent
│       ├── ios-compliance-auditor.md        # iOS / Swift compliance sub-agent
│       └── android-compliance-auditor.md    # Android / Kotlin compliance sub-agent
└── skills/
    ├── web-bundle-analyzer/SKILL.md
    ├── ios-memory-lint/SKILL.md
    └── android-lint-rules/SKILL.md

2. Custom Sub-Agent Definitions

A. Web Compliance Auditor

File location: .agents/agents/web-compliance-auditor.md

---
name: web-compliance-auditor
description: Specialized subagent that audits React, Next.js, and TypeScript codebases for server/client boundary violations, dead code, bundle bloat, and accessibility standards.
tools:
  - view_file
  - replace_file_content
  - grep_search
  - run_command
subagent: true
mainAgent: false
model: pro
commandExecutionPolicy: sandbox
skills:
  - skills/web-bundle-analyzer
---

# System Role & Instructions
You are an expert Frontend and Full-Stack Web engineering sub-agent specializing in codebase health and dependency pruning.

## Operational Objectives
1. **Server/Client Separation**: Inspect Next.js and React trees to ensure `'use client'` and `'use server'` boundaries are strictly respected.
2. **Bundle Optimization**: Identify and remove unused npm dependencies, obsolete polyfills, and orphaned CSS modules to reduce bundle size.
3. **Accessibility & Linting**: Audit UI components against WCAG AA standards and eliminate duplicate utility abstractions.
4. **Verification**: Execute `npm run lint` and `npm run build` within the sandbox before returning code diffs to verify structural integrity.

B. iOS Compliance Auditor

File location: .agents/agents/ios-compliance-auditor.md

---
name: ios-compliance-auditor
description: Specialized subagent that audits iOS Swift and SwiftUI codebases for deprecated UIKit patterns, memory leaks, retain cycles, and Swift Concurrency safety.
tools:
  - view_file
  - replace_file_content
  - grep_search
  - run_command
subagent: true
mainAgent: false
model: pro
commandExecutionPolicy: sandbox
skills:
  - skills/ios-memory-lint
---

# System Role & Instructions
You are an expert Apple Platform engineering sub-agent specializing in Swift codebase modernization and memory stability.

## Operational Objectives
1. **API Modernization**: Scan Swift code to refactor legacy UIKit delegates, deprecated Combine pipelines, and outdated `URLSession` handlers into modern Swift Concurrency (`async/await`).
2. **Memory Leak Detection**: Detect strong reference cycles in closures, unowned self-references, and unmanaged notification observers.
3. **Dead Code Elimination**: Prune unreferenced SwiftUI views, orphaned asset catalog items, and legacy feature flags.
4. **Verification**: Run `xcodebuild test` or `swift test` in the sandbox environment to ensure zero regression in test suites.

C. Android Compliance Auditor

File location: .agents/agents/android-compliance-auditor.md

---
name: android-compliance-auditor
description: Specialized subagent that audits Android repositories for deprecated APIs, Jetpack compliance, Gradle configuration health, and permission security boundaries.
tools:
  - view_file
  - replace_file_content
  - grep_search
  - run_command
subagent: true
mainAgent: false
model: pro
commandExecutionPolicy: sandbox
skills:
  - skills/android-lint-rules
---

# System Role & Instructions
You are an expert Android engineering sub-agent specializing in platform compliance and code bloat reduction.

## Operational Objectives
1. **Framework Modernization**: Inspect `build.gradle.kts` and Kotlin source files for deprecated Android framework APIs, migrating legacy components to modern Android Jetpack/AndroidX standards.
2. **Permission Boundaries**: Validate that runtime permissions declared in `AndroidManifest.xml` adhere to strict least-privilege security policies.
3. **Dependency Cleanup**: Remove outdated third-party support libraries, duplicate XML drawables, and unused view bindings.
4. **Verification**: Execute `./gradlew lint` inside the isolated sandbox to confirm compilation and lint compliance.

3. Orchestration & Worktree Isolation via invoke_subagent

To run multiple sub-agents simultaneously without Git conflicts or file locks on your working tree, configure the parent orchestrator to invoke each worker using workspace_mode: "branch". This isolates the sub-agent inside an independent Git worktree branch:

# Dispatched concurrently by the parent agent
invoke_subagent(
    name="web-compliance-auditor",
    task="Audit Next.js routes under /app for client boundary leaks and unused lodash imports.",
    workspace_mode="branch"
)

invoke_subagent(
    name="ios-compliance-auditor",
    task="Scan NetworkService.swift and refactor completion-handler closures to async/await.",
    workspace_mode="branch"
)

invoke_subagent(
    name="android-compliance-auditor",
    task="Audit build.gradle.kts and update legacy Jetpack dependencies to current stable BOM.",
    workspace_mode="branch"
)

Each sub-agent starts with an isolated context window, executes its task inside its worktree sandbox, and reports verified diffs back to the parent agent or Agent Manager dashboard for human sign-off.

Here are the root orchestrator instructions to place in your repository’s root AGENTS.md file.

In Google Antigravity, AGENTS.md takes precedence as the universal orchestrator contract, establishing operating roles, delegation heuristics, execution sandboxes, and verification gates across the entire fleet.

Root Configuration: AGENTS.md

# AGENTS.md — Autonomous Software Factory Orchestrator

## 1. Role & Operating Architecture
You are the **Lead Software Factory Orchestrator**. Your mandate is to maintain repository health, eliminate technical debt, prune obsolete dependencies, and enforce cross-platform compliance without creating AI-generated code bloat or merge lockouts.

You do not perform large-scale, multi-file code refactors directly within the primary context window. Instead, you act as the architectural dispatch: diagnosing objectives, breaking them into isolated workstreams, and delegating execution to specialized sub-agents.

---

## 2. Platform Support & Trailing-Edge Policy
Adhere to the enterprise platform policy defined below. Flag and prune code, polyfills, and backward-compatibility shims that support versions older than:
- **Web**: Modern Evergreen browsers (Chrome, Edge, Firefox, Safari) within the trailing 2 major versions. Strip obsolete ECMAScript polyfills and legacy browser vendor prefixes.
- **iOS**: Minimum deployment target: iOS 17.0+ (SwiftUI, Swift 6 Concurrency / Strict Concurrency Checking).
- **Android**: Minimum SDK: API 28 (Android 9.0 Pie), Target SDK: Current stable API. Jetpack Compose and Modern Android Architecture (BOM) required.

---

## 3. Sub-Agent Delegation Matrix
When processing maintenance, audits, or refactoring tasks, immediately evaluate the project target and delegate using `invoke_subagent` with `workspace_mode: "branch"`.

| Objective / File Scope | Designated Sub-Agent | Invocation Mode | Verification Command |
| :--- | :--- | :--- | :--- |
| Next.js, React, TypeScript, CSS modules, Webpack/Vite configs, bundle bloat | `web-compliance-auditor` | `branch` (Git worktree) | `npm run lint && npm run build` |
| Swift, SwiftUI, Xcode targets, CocoaPods/SPM, memory leaks, concurrency | `ios-compliance-auditor` | `branch` (Git worktree) | `swift test` or `xcodebuild test` |
| Kotlin, Jetpack Compose, Gradle (`build.gradle.kts`), Android manifest | `android-compliance-auditor` | `branch` (Git worktree) | `./gradlew lint` |
| Cross-cutting architectural analysis or repository indexing | `research` (Built-in) | `inherit` (Read-only) | N/A |

### Dispatch Rules:
1. **Parallelism**: Multiple platform sub-agents may run concurrently. Always assign distinct scopes to prevent overlapping file diffs.
2. **Context Freshness**: Provide sub-agents with a self-contained objective prompt containing the target path, platform constraint, and verification command. Do not pass monolithic conversation transcripts.
3. **Branch Worktree Isolation**: Never invoke modifying sub-agents with `workspace_mode: "inherit"` or `workspace_mode: "share"`. Enforce `branch` mode to isolate tool execution and avoid polluting the developer's working tree.

---

## 4. Operational Guardrails & Execution Boundaries
1. **Destructive Action Gating**: Never execute or approve `rm -rf`, `git push --force`, schema dropping, or secret modification without explicit human confirmation.
2. **Permission Boundary**: The orchestrator operates in planning and validation mode. File modification tools (`replace_file_content`, `write_file`) must only be exercised by designated sub-agents inside sandbox worktrees.
3. **Token Stewardship (Progressive Disclosure)**: Load sub-agent schemas and skill references on demand. Do not ingest full directory trees or multi-megabyte log files into the root context.

---

## 5. Verification Gate ("Proof Before Done")
Before summarizing results or presenting changes to the human operator:
1. **Diff Audit**: Verify that each sub-agent returned a unified git diff containing only the requested scope.
2. **Test & Build Integrity**: Ensure the sub-agent’s sandbox verification command exited cleanly (`exit code 0`). "Syntax appears correct" or "compiled without errors" is unacceptable without logged test/lint execution proofs.
3. **Pull Request Synthesis**: Formulate concise PR proposals highlighting lines removed, dependencies dropped, and platform guidelines satisfied.

How Antigravity Executes This Configuration

  1. Discovery Order: Upon opening a session, Antigravity checks the repository root for AGENTS.md. It uses this file to set the system role and register the custom sub-agents discovered inside .agents/agents/.
  2. Progressive Token Management: Only the metadata and descriptions of web-compliance-auditor, ios-compliance-auditor, and android-compliance-auditor are loaded into memory (~100 tokens each). The sub-agent instructions are loaded strictly when the orchestrator calls invoke_subagent.
  3. Isolated Worktrees: When workspace_mode: "branch" is triggered, Antigravity creates temporary Git worktrees behind the scenes, runs the sub-agent checks within sandboxed containers, and reports the resulting diffs back to the Agent Manager panel for review.

In Google Antigravity and the Gemini ecosystem, rules in Markdown serve as behavioral guidance, but lifecycle hooks operate as non-negotiable deterministic firewalls [cite: 11, 27]. When registered, a PreToolUse hook intercepts agent actions before execution, parsing the incoming payload and blocking forbidden commands [cite: 11, 27].

Here is the setup to configure automated PreToolUse shell guardrails (such as gemini-shield / safety-shield) for your autonomous software factory [cite: 27].


1. Directory Structure

Place hook scripts in your project’s .agents/hooks/ directory (or globally in ~/.gemini/config/hooks/) [cite: 1, 20]:

my-project/
├── .agents/
│   ├── hooks/
│   │   ├── gemini-shield.sh         # PreToolUse shell command validator
│   │   └── secret-scrubber.sh       # PreToolUse file write & credential scanner
│   ├── settings.json                # Project-scoped hook and tool permissions
│   └── agents/                      # Platform sub-agents (web, ios, android)
└── AGENTS.md

2. The PreToolUse Shell Guardrail Script

This script intercepts run_command / command invocations. It parses the incoming tool payload from stdin, checks for destructive commands, and exits with a non-zero exit code (or typed block decision) to halt execution and return the rationale directly to the agent [cite: 11, 21, 27].

File location: .agents/hooks/gemini-shield.sh

#!/usr/bin/env bash
set -euo pipefail

# Read the typed hook JSON payload from stdin
PAYLOAD=$(cat)

# Extract tool name and command string using jq
TOOL_NAME=$(echo "$PAYLOAD" | jq -r '.tool // .tool_name // empty')
COMMAND=$(echo "$PAYLOAD" | jq -r '.tool_input.command // .tool_input.CommandLine // empty')

# Only evaluate shell command execution tools
if [[ "$TOOL_NAME" != "run_command" && "$TOOL_NAME" != "Bash" && "$TOOL_NAME" != "command" ]]; then
  exit 0
fi

# 1. Block destructive file system deletions
if echo "$COMMAND" | grep -E -q '(rm[[:space:]]+-[rfR]{1,3}[[:space:]]+(/|~|\.|\*|\$HOME))|(mkfs|dd[[:space:]]+if=)'; then
  echo "{\"decision\": \"block\", \"reason\": \"Execution Denied: Destructive filesystem deletion commands are prohibited.\"}" >&2
  exit 2
fi

# 2. Block forced Git push operations
if echo "$COMMAND" | grep -E -q 'git[[:space:]]+push[[:space:]]+.*(--force|-f)'; then
  echo "{\"decision\": \"block\", \"reason\": \"Execution Denied: Force pushing to remote branches is blocked by policy.\"}" >&2
  exit 2
fi

# 3. Block destructive database drops
if echo "$COMMAND" | grep -E -i -q '(drop[[:space:]]+database|drop[[:space:]]+table|truncate[[:space:]]+table)'; then
  echo "{\"decision\": \"block\", \"reason\": \"Execution Denied: Destructive SQL drop or truncate statements are restricted.\"}" >&2
  exit 2
fi

# 4. Block permission bypass flags or privileged Docker containers
if echo "$COMMAND" | grep -E -q '(--dangerously-skip-permissions|--privileged|CAP_SYS_ADMIN)'; then
  echo "{\"decision\": \"block\", \"reason\": \"Execution Denied: Security boundary bypass flags are forbidden.\"}" >&2
  exit 2
fi

# Allow compliant command to proceed
exit 0

Make the hook executable:

chmod +x .agents/hooks/gemini-shield.sh

3. Registering the Hook in settings.json

Register the hook script and configure declarative execution permissions in .agents/settings.json (or ~/.gemini/antigravity-cli/settings.json) [cite: 1, 6]:

{
  "permissions": {
    "allow": [
      "command(git diff)",
      "command(git log)",
      "command(npm test)",
      "command(npm run lint)",
      "command(swift test)",
      "command(./gradlew lint)"
    ],
    "deny": [
      "command(git push --force)",
      "command(git reset --hard)",
      "file_read(./.env)",
      "file_read(./.env.*)"
    ]
  },
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "run_command",
        "script": ".agents/hooks/gemini-shield.sh"
      },
      {
        "matcher": "write_file",
        "script": ".agents/hooks/secret-scrubber.sh"
      }
    ],
    "PostToolUse": [
      {
        "matcher": "replace_file_content",
        "command": "npx prettier --write \"$FILE_PATH\""
      }
    ]
  }
}

4. How the Guardrail Operates During Agent Execution

  1. Pre-Execution Interception: Whenever the orchestrator or an invoked sub-agent attempts to call run_command, the runtime pauses execution and routes the parameters through gemini-shield.sh [cite: 27].
  2. Deterministic Blocking (exit 2): If an agent attempts an action like git push --force or rm -rf /, the script exits with code 2 [cite: 11, 27]. The agent does not crash; instead, the error message from stderr is injected back into the model’s reasoning loop [cite: 11].
  3. Autonomous Self-Correction: The sub-agent recognizes that the operation was denied by project policy, updates its plan, and proceeds with a safe alternative without requiring human manual intervention.

In Google Antigravity and the Gemini multi-agent ecosystem, agents and sub-agents signal task completion by transitioning to an idle state or issuing a completion turn [cite: 6, 7, 29]. The Stop lifecycle hook intercepts this termination attempt [cite: 27, 32].

If tests, lint checks, or build pipelines are failing, the hook returns a typed decision: {"decision": "continue", "reason": "..."} [cite: 29, 32]. This forcibly pushes the agent back into its active execution loop with the test failures injected into context, preventing “AI slop” or unverified code from ever being declared finished [cite: 11, 32].

1. The goal-verifier.sh Script

This script dynamically detects the project type (or checks the platform target of the current worktree), runs the corresponding verification commands, and outputs the typed decision contract on stdout [cite: 32].

File location: .agents/hooks/goal-verifier.sh

#!/usr/bin/env bash
set -euo pipefail

# Read hook payload from stdin (contains agent role, session ID, and workspace directory)
PAYLOAD=$(cat)

# Capture any uncommitted modifications or diffs
GIT_DIFF=$(git status --porcelain)

# If no files were touched, allow the agent to finish
if [[ -z "$GIT_DIFF" ]]; then
  echo '{"decision": "allow"}'
  exit 0
fi

FAILURE_LOG=""

# 1. Web Target Verification (Next.js / TypeScript / React)
if [[ -f "package.json" ]]; then
  echo "==> Running Web Verification Suite..." >&2
  if ! npm run lint > /tmp/web_lint.log 2>&1; then
    FAILURE_LOG+="[Web Lint Failure]:\n$(tail -n 25 /tmp/web_lint.log)\n\n"
  fi
  if ! npm test -- --passWithNoTests > /tmp/web_test.log 2>&1; then
    FAILURE_LOG+="[Web Test Failure]:\n$(tail -n 25 /tmp/web_test.log)\n\n"
  fi
fi

# 2. iOS Target Verification (Swift Package / Xcode)
if [[ -f "Package.swift" ]]; then
  echo "==> Running Swift Verification Suite..." >&2
  if ! swift test > /tmp/swift_test.log 2>&1; then
    FAILURE_LOG+="[iOS/Swift Test Failure]:\n$(tail -n 25 /tmp/swift_test.log)\n\n"
  fi
fi

# 3. Android Target Verification (Gradle / Kotlin)
if [[ -f "build.gradle.kts" || -f "build.gradle" ]]; then
  echo "==> Running Android Gradle Lint Suite..." >&2
  if ! ./gradlew lint test --daemon > /tmp/android_test.log 2>&1; then
    FAILURE_LOG+="[Android Lint/Test Failure]:\n$(tail -n 25 /tmp/android_test.log)\n\n"
  fi
fi

# Evaluate results: Block termination if failures were detected
if [[ -n "$FAILURE_LOG" ]]; then
  # Format error log safely for JSON output
  ESCAPED_REASON=$(echo -e "Proof Before Done Violation: Verification suite failed. You cannot complete the task until all errors are resolved:\n\n$FAILURE_LOG" | jq -Rs .)

  # Return 'continue' directive to reject the Stop event
  echo "{\"decision\": \"continue\", \"reason\": $ESCAPED_REASON}"
  exit 0
fi

# All suites passed: allow agent to stop
echo '{"decision": "allow"}'
exit 0

Make the hook executable:

chmod +x .agents/hooks/goal-verifier.sh

2. Registering the Stop Hook in .agents/settings.json

Add the Stop event handler to your project’s existing hooks configuration alongside PreToolUse and PostToolUse [cite: 27, 32]:

{
  "permissions": {
    "allow": [
      "command(git diff)",
      "command(git status)",
      "command(npm test)",
      "command(npm run lint)",
      "command(swift test)",
      "command(./gradlew lint)"
    ],
    "deny": [
      "command(git push --force)",
      "command(git reset --hard)"
    ]
  },
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "run_command",
        "script": ".agents/hooks/gemini-shield.sh"
      }
    ],
    "PostToolUse": [
      {
        "matcher": "replace_file_content",
        "command": "npx prettier --write \"$FILE_PATH\""
      }
    ],
    "Stop": [
      {
        "script": ".agents/hooks/goal-verifier.sh"
      }
    ]
  }
}

3. Execution Lifecycle

       Agent Attempts Completion (Stop Event)
                         │
                         ▼
           [.agents/hooks/goal-verifier.sh]
                         │
            ┌────────────┴────────────┐
       [Tests Pass]             [Tests Fail]
            │                         │
            ▼                         ▼
  {"decision": "allow"}     {"decision": "continue",
            │                "reason": "<error_logs>"}
            ▼                         │
   Sub-agent enters Idle              ▼
   Diff sent to Parent     Agent forced back to active;
   & Agent Manager         reads logs and self-corrects
  1. Trigger on Completion: When a sub-agent (e.g., web-compliance-auditor) finishes editing files and attempts to declare its work complete, Antigravity fires the Stop hook [cite: 32].
  2. Rejection & Log Injection: If a TypeScript compilation error or failing unit test is detected, the script returns decision: "continue" with the error tail [cite: 32].
  3. Autonomous Self-Healing: Antigravity rejects the stop attempt and feeds the failure message directly into the agent’s context [cite: 11, 32]. The sub-agent immediately re-evaluates the failure, uses replace_file_content to fix the regression, re-runs tests, and only stops once the verification gate exits with code 0 [cite: 11].

To deploy the multi-agent compliance fleet as an automated nightly cron maintenance pipeline, you can run Google Antigravity CLI (agy) in headless mode (-p / --print) within a GitHub Actions workflow [cite: 1, 4, 16].

In this setup, the workflow authenticates via Google Cloud Workload Identity Federation (WIF) and Application Default Credentials (ADC) using AGY_ADC_AUTH=1, executes the fleet in an isolated sandbox, and automatically raises a structured Pull Request if any compliance refactoring occurs [cite: 3, 16, 17].

1. GitHub Actions Workflow File

File location: .github/workflows/nightly-compliance-factory.yml

name: Nightly Multi-Agent Compliance Sweep

on:
  schedule:
    # Runs every morning at 02:00 UTC (02:00 AM)
    - cron: '0 2 * * *'
  workflow_dispatch: # Allows manual trigger from the GitHub Actions tab

permissions:
  contents: write
  pull-requests: write
  id-token: write # Required for Google Cloud Workload Identity Federation

jobs:
  software-factory-audit:
    runs-on: ubuntu-latest
    timeout-minutes: 45

    steps:
      - name: Checkout Repository
        uses: actions/checkout@v5
        with:
          fetch-depth: 0 # Full git history for worktree branch management

      # 1. Passwordless Cloud Authentication via WIF & ADC
      - name: Authenticate to Google Cloud
        uses: google-github-actions/auth@v3
        with:
          workload_identity_provider: 'projects/123456789012/locations/global/workloadIdentityPools/github-actions-pool/providers/github-provider'
          service_account: '[email protected]'

      # 2. Install Official Antigravity CLI (agy)
      - name: Install Antigravity CLI
        run: |
          curl -fsSL https://antigravity.google/cli/install.sh | bash
          echo "$HOME/.antigravity/bin" >> $GITHUB_PATH

      # 3. Environment & Tooling Setup
      - name: Setup Node.js Environment
        uses: actions/setup-node@v4
        with:
          node-version: '22'
          cache: 'npm'

      - name: Install Dependencies
        run: npm ci

      # 4. Dispatch the Multi-Agent Fleet in Headless Mode
      - name: Run Headless Autonomous Audit Fleet
        env:
          AGY_ADC_AUTH: "1"
        run: |
          # Prompt the orchestrator defined in AGENTS.md to dispatch sub-agents
          agy -p "Execute the automated nightly compliance sweep across Web, iOS, and Android scopes using your designated sub-agents. Prune dead code, remove deprecated polyfills, and modernize trailing-edge APIs in isolated branch worktrees. Ensure all test suites pass before completing." \
              --mode accept-edits \
              --sandbox \
              --output-format json > sweep_output.json

      # 5. Check Diffs & Create Maintenance PR
      - name: Create Pull Request with Verified Diffs
        uses: peter-evans/create-pull-request@v6
        with:
          commit-message: "chore(factory): automated nightly compliance & dead code cleanup"
          branch: "factory/nightly-compliance-audit"
          delete-branch: true
          title: "🤖 Software Factory: Automated Platform Compliance & Debt Pruning"
          body: |
            ### Automated Codebase Compliance & Health Audit
            This Pull Request was generated autonomously by the **Antigravity Software Factory Fleet**.

            #### What Changed:
            - **Web Compliance (`web-compliance-auditor`)**: Checked React/Next.js client-server boundaries, pruned unused dependencies, and audited bundle size.
            - **iOS Compliance (`ios-compliance-auditor`)**: Checked UIKit deprecations and modernized Swift Concurrency.
            - **Android Compliance (`android-compliance-auditor`)**: Audited Jetpack dependencies and permission bounds.

            #### Safety Gates & Verification:
            - Verified against project `.agents/hooks/gemini-shield.sh` (PreToolUse)
            - Blocked premature termination via `.agents/hooks/goal-verifier.sh` (Stop Hook)
            - All test suites (`npm test`, linting, and build steps) passed in sandbox before completion.
          labels: |
            automated-pr
            technical-debt
            software-factory

2. Key Architecture & Operational Mechanics

  1. Zero Long-Lived Secrets (AGY_ADC_AUTH: "1"): Rather than storing static API keys or long-lived service account JSON files in GitHub Secrets, GitHub Actions exchanges short-lived OIDC tokens with Google Cloud via Workload Identity Federation (WIF) [cite: 16, 17]. Setting AGY_ADC_AUTH: "1" signals the CLI to consume Application Default Credentials natively [cite: 16, 17].
  2. Headless Execution (agy -p --mode accept-edits): The -p flag launches the CLI without an interactive terminal GUI [cite: 2, 4]. Supplying --mode accept-edits permits sub-agents to stage modifications directly, while --sandbox isolates command execution [cite: 3, 17].
  3. Triggering the Fleet: Because the repository root contains AGENTS.md and .agents/agents/, the headless orchestrator parses the prompt and invokes web-compliance-auditor, ios-compliance-auditor, and android-compliance-auditor into their isolated Git worktrees [cite: 8, 15, 20].
  4. Hook Protection in CI: Even in headless CI/CD, Antigravity respects .agents/settings.json [cite: 4, 33]. gemini-shield.sh will block any destructive terminal actions (exit 2), and goal-verifier.sh will reject the Stop event if tests or linting fail, ensuring broken code is never submitted into the PR [cite: 11, 23, 32].
  5. Terms of Service Compliance (Section 6): Running agy -p directly from first-party shell scripts and official CI runners (like GitHub Actions) is explicitly supported under Antigravity guidelines [cite: 18, 41].

To give your team full visibility into what the autonomous fleet accomplished, we can parse sweep_output.json directly inside the workflow and combine it with git statistics [cite: 3, 17].

Below is the complete update to your GitHub Actions workflow, including a metrics-extraction script that calculates lines dropped, bundle size deltas, and platform-by-platform summaries, injecting them directly into the Pull Request description [cite: 17, 20].

1. Updated GitHub Actions Workflow with Dynamic PR Metrics

File location: .github/workflows/nightly-compliance-factory.yml

name: Nightly Multi-Agent Compliance Sweep

on:
  schedule:
    # Runs every morning at 02:00 UTC (02:00 AM)
    - cron: '0 2 * * *'
  workflow_dispatch:

permissions:
  contents: write
  pull-requests: write
  id-token: write

jobs:
  software-factory-audit:
    runs-on: ubuntu-latest
    timeout-minutes: 45

    steps:
      - name: Checkout Repository
        uses: actions/checkout@v5
        with:
          fetch-depth: 0

      - name: Authenticate to Google Cloud via WIF
        uses: google-github-actions/auth@v3
        with:
          workload_identity_provider: 'projects/123456789012/locations/global/workloadIdentityPools/github-actions-pool/providers/github-provider'
          service_account: '[email protected]'

      - name: Install Antigravity CLI (agy)
        run: |
          curl -fsSL https://antigravity.google/cli/install.sh | bash
          echo "$HOME/.antigravity/bin" >> $GITHUB_PATH

      - name: Setup Node.js Environment
        uses: actions/setup-node@v4
        with:
          node-version: '22'
          cache: 'npm'

      - name: Install Dependencies & Record Baseline Web Bundle
        id: baseline-metrics
        run: |
          npm ci
          # Record baseline production bundle size if build directory exists
          npm run build --if-present
          BASELINE_BUNDLE_KB=$(du -sk .next/static 2>/dev/null | awk '{print $1}' || echo "0")
          echo "BASELINE_BUNDLE_KB=${BASELINE_BUNDLE_KB}" >> $GITHUB_ENV

      # -------------------------------------------------------------
      # Dispatch the Multi-Agent Fleet in Headless Mode
      # -------------------------------------------------------------
      - name: Run Headless Autonomous Audit Fleet
        env:
          AGY_ADC_AUTH: "1"
        run: |
          agy -p "Execute the automated nightly compliance sweep across Web, iOS, and Android scopes using your designated sub-agents. Prune dead code, remove deprecated polyfills, and modernize trailing-edge APIs in isolated branch worktrees. Ensure all test suites pass before completing." \
              --mode accept-edits \
              --sandbox \
              --output-format json > sweep_output.json

      # -------------------------------------------------------------
      # Extract Quantitative Health & Bloat Metrics
      # -------------------------------------------------------------
      - name: Generate PR Body Metrics
        id: parse-metrics
        run: |
          # 1. Measure Code Lines Delta
          INSERTIONS=$(git diff --shortstat | grep -o -E '+ insertion' | cut -d ' ' -f 1 || echo 0)
          DELETIONS=$(git diff --shortstat | grep -o -E '+ deletion' | cut -d ' ' -f 1 || echo 0)
          NET_LINES=$(( INSERTIONS - DELETIONS ))

          # 2. Re-measure bundle after agent refactoring
          npm run build --if-present
          NEW_BUNDLE_KB=$(du -sk .next/static 2>/dev/null | awk '{print $1}' || echo "0")
          BUNDLE_DELTA_KB=$(( NEW_BUNDLE_KB - BASELINE_BUNDLE_KB ))

          # 3. Parse Sub-Agent Executive Summary from agy JSON output
          AGENT_SUMMARY=$(jq -r '.response // .summary // "Sub-agents completed routine maintenance without high-level remarks."' sweep_output.json)

          # Export into GITHUB_ENV as a multi-line markdown block
          {
            echo "PR_BODY<<EOF"
            echo "## 🤖 Software Factory: Automated Nightly Maintenance"
            echo ""
            echo "### 📊 Codebase Health Delta"
            echo "| Metric | Baseline / Before | After Clean-up | Net Impact |"
            echo "| :--- | :--- | :--- | :--- |"
            echo "| **Lines of Code** | +${INSERTIONS} | -${DELETIONS} | **${NET_LINES} lines** |"
            echo "| **Web Client Bundle (.next/static)** | ${BASELINE_BUNDLE_KB} KB | ${NEW_BUNDLE_KB} KB | **${BUNDLE_DELTA_KB} KB** |"
            echo ""
            echo "### 🛠️ Sub-Agent Actions & Highlights"
            echo "${AGENT_SUMMARY}"
            echo ""
            echo "---"
            echo "### 🛡️ Safety & Verification Gates"
            echo "- ✅ **PreToolUse Shell Firewall (`gemini-shield.sh`)**: Intercepted destructive commands; 0 policy violations."
            echo "- ✅ **Stop Event Goal Verifier (`goal-verifier.sh`)**: Enforced unit tests, lint checks, and builds across all modified worktrees before permitting completion."
            echo "- ✅ **Isolation**: Sub-agents executed on isolated git worktree branches; zero main working tree pollution."
            echo "EOF"
          } >> $GITHUB_ENV

      # -------------------------------------------------------------
      # Create Pull Request with Dynamically Generated Telemetry
      # -------------------------------------------------------------
      - name: Create Pull Request
        uses: peter-evans/create-pull-request@v6
        with:
          commit-message: "chore(factory): nightly compliance audit & dead code elimination"
          branch: "factory/nightly-compliance-audit"
          delete-branch: true
          title: "🤖 Software Factory: Nightly Compliance & Debt Pruning (${{ env.DELETIONS }} lines removed)"
          body: ${{ env.PR_BODY }}
          labels: |
            automated-pr
            technical-debt
            software-factory

2. How the Pull Request Looks to Developers

When human engineers log in the next morning, the generated PR clearly visualizes the debt reduction:

## 🤖 Software Factory: Automated Nightly Maintenance

### 📊 Codebase Health Delta
| Metric | Baseline / Before | After Clean-up | Net Impact |
| :--- | :--- | :--- | :--- |
| **Lines of Code** | +42 | -589 | **-547 lines** |
| **Web Client Bundle (.next/static)** | 14,280 KB | 13,912 KB | **-368 KB** |

### 🛠️ Sub-Agent Actions & Highlights
- **web-compliance-auditor**: Removed obsolete `core-js` polyfills, converted 4 legacy React components from `'use client'` to Server Components, and pruned unused `lodash` helpers.
- **ios-compliance-auditor**: Modernized completion handlers in `NetworkManager.swift` to Swift 6 `async/await`.
- **android-compliance-auditor**: Bumped target SDK support and stripped redundant XML drawables replaced by Jetpack Compose icons.

---
### 🛡️ Safety & Verification Gates
- ✅ **PreToolUse Shell Firewall (`gemini-shield.sh`)**: Intercepted destructive commands; 0 policy violations.
- ✅ **Stop Event Goal Verifier (`goal-verifier.sh`)**: Enforced unit tests, lint checks, and builds across all modified worktrees before permitting completion.
- ✅ **Isolation**: Sub-agents executed on isolated git worktree branches; zero main working tree pollution.
 

To notify your engineering team immediately when the factory opens a maintenance PR, you can append a webhook step to your GitHub Actions workflow. This sends a formatted summary card with line deltas, bundle savings, and a direct link to the pull request.

Here are the configuration snippets for both Slack and Google Chat.

Option A: Slack Incoming Webhook (Block Kit Card)

Store your webhook URL in your GitHub repository secrets as SLACK_WEBHOOK_URL (Settings > Secrets and variables > Actions).

Add this step directly after the Create Pull Request step in .github/workflows/nightly-compliance-factory.yml:

      # -------------------------------------------------------------
      # Dispatch Slack Alert on New PR
      # -------------------------------------------------------------
      - name: Send Slack Notification
        if: steps.cpr.outputs.pull-request-number != ''
        env:
          SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
          PR_URL: ${{ steps.cpr.outputs.pull-request-url }}
          PR_NUM: ${{ steps.cpr.outputs.pull-request-number }}
          INSERTIONS: ${{ env.INSERTIONS }}
          DELETIONS: ${{ env.DELETIONS }}
          BUNDLE_DELTA_KB: ${{ env.BUNDLE_DELTA_KB }}
        run: |
          curl -s -X POST -H 'Content-type: application/json' \
            --data "{
              \"blocks\": [
                {
                  \"type\": \"header\",
                  \"text\": {
                    \"type\": \"plain_text\",
                    \"text\": \"🤖 Software Factory: Nightly Pruning PR #${PR_NUM}\",
                    \"emoji\": true
                  }
                },
                {
                  \"type\": \"section\",
                  \"fields\": [
                    {\"type\": \"mrkdwn\", \"text\": \"*Lines Pruned:*\n-${DELETIONS} (+${INSERTIONS})\"},
                    {\"type\": \"mrkdwn\", \"text\": \"*Bundle Impact:*\n${BUNDLE_DELTA_KB} KB\"}
                  ]
                },
                {
                  \"type\": \"section\",
                  \"text\": {
                    \"type\": \"mrkdwn\",
                    \"text\": \"Autonomous sub-agents (*Web*, *iOS*, *Android*) finished auditing and verified all unit tests in isolated sandboxes.\"
                  }
                },
                {
                  \"type\": \"actions\",
                  \"elements\": [
                    {
                      \"type\": \"button\",
                      \"text\": {\"type\": \"plain_text\", \"text\": \"Review Pull Request\"},
                      \"url\": \"${PR_URL}\",
                      \"style\": \"primary\"
                    }
                  ]
                }
              ]
            }" "$SLACK_WEBHOOK_URL"

Option B: Google Chat Webhook (Cards v2 Format)

Store your space’s webhook URL in GitHub Secrets as GOOGLE_CHAT_WEBHOOK_URL.

      # -------------------------------------------------------------
      # Dispatch Google Chat Alert on New PR
      # -------------------------------------------------------------
      - name: Send Google Chat Notification
        if: steps.cpr.outputs.pull-request-number != ''
        env:
          CHAT_WEBHOOK_URL: ${{ secrets.GOOGLE_CHAT_WEBHOOK_URL }}
          PR_URL: ${{ steps.cpr.outputs.pull-request-url }}
          PR_NUM: ${{ steps.cpr.outputs.pull-request-number }}
          INSERTIONS: ${{ env.INSERTIONS }}
          DELETIONS: ${{ env.DELETIONS }}
          BUNDLE_DELTA_KB: ${{ env.BUNDLE_DELTA_KB }}
        run: |
          curl -s -X POST -H 'Content-Type: application/json; charset=UTF-8' \
            --data "{
              \"cardsV2\": [
                {
                  \"cardId\": \"compliance-pr-${PR_NUM}\",
                  \"card\": {
                    \"header\": {
                      \"title\": \"🤖 Software Factory: Automated Pruning PR #${PR_NUM}\",
                      \"subtitle\": \"Nightly Codebase Health & Platform Compliance Sweep\"
                    },
                    \"sections\": [
                      {
                        \"header\": \"Impact Telemetry\",
                        \"widgets\": [
                          {
                            \"decoratedText\": {
                              \"topLabel\": \"Lines Dropped\",
                              \"text\": \"<b>-${DELETIONS}</b> (+${INSERTIONS})\"
                            }
                          },
                          {
                            \"decoratedText\": {
                              \"topLabel\": \"Client Bundle Delta\",
                              \"text\": \"<b>${BUNDLE_DELTA_KB} KB</b>\"
                            }
                          }
                        ]
                      },
                      {
                        \"widgets\": [
                          {
                            \"buttonList\": {
                              \"buttons\": [
                                {
                                  \"text\": \"Review PR in GitHub\",
                                  \"onClick\": {
                                    \"openLink\": { \"url\": \"${PR_URL}\" }
                                  }
                                }
                              ]
                            }
                          }
                        ]
                      }
                    ]
                  }
                }
              ]
            }" "$CHAT_WEBHOOK_URL"

Operational Details

  1. Conditional Dispatch (if: steps.cpr.outputs.pull-request-number != ''): Ensure your create-pull-request step has id: cpr. The alert step will only run if modifications were staged and a new or updated PR was generated. If the repository was already compliant and no changes were made, no alert is sent.
  2. Actionable Cards: Team members get the exact lines and bundle size shaved directly in their chat feed, with a direct button leading straight to the GitHub review interface.

Enterprise Runbook: Deploying the Autonomous Software Factory

This runbook brings together the complete architecture for an autonomous codebase compliance and maintenance fleet powered by Google Antigravity and the Gemini model family [cite: 14, 21].


1. Unified Workspace Hierarchy

Antigravity traverses configuration files hierarchically, resolving universal project rules first before activating scoped agents and skills [cite: 2, 16]:

\[\text{AGENTS.md (Universal Standard)} \longrightarrow \text{GEMINI.md (Native Config)} \longrightarrow \text{Scoped Rules (.agents/rules/*.md)} \text{ }\] [cite: 16]

Organize your target repository with the following layout [cite: 2, 5, 13]:

your-repository/
├── AGENTS.md                                # Root orchestrator instructions & delegation matrix
├── .agents/
│   ├── settings.json                        # Declarative tool permissions & lifecycle hook bindings
│   ├── hooks/
│   │   ├── gemini-shield.sh                 # PreToolUse shell command firewall
│   │   └── goal-verifier.sh                 # Stop lifecycle completion verifier
│   └── agents/
│       ├── web-compliance-auditor.md        # Next.js / TypeScript auditor
│       ├── ios-compliance-auditor.md        # Swift / SwiftUI auditor
│       └── android-compliance-auditor.md    # Android Jetpack / Gradle auditor
└── .github/
    └── workflows/
        └── nightly-compliance-factory.yml   # Headless Antigravity CLI (agy -p) cron pipeline

2. Universal Root Orchestrator: AGENTS.md

Save this file in your repository root [cite: 2, 6]. It acts as the cross-platform contract defining the orchestrator role, platform policies, and delegation heuristics [cite: 6, 7, 16].

# AGENTS.md — Autonomous Software Factory Orchestrator

## 1. Role & Architectural Boundaries
You are the **Lead Software Factory Orchestrator**. Your mandate is to maintain repository health, eliminate technical debt, prune obsolete polyfills, and enforce cross-platform compliance without creating AI-generated code bloat or working-tree lockouts.

Never perform large-scale multi-file refactors directly within the primary context window. Act as the architectural dispatch: diagnose objectives, break them into orthogonal tasks, and delegate to specialized sub-agents.

## 2. Trailing-Edge Platform Support Policy
Flag and prune code, polyfills, and backward-compatibility shims supporting versions older than:
- **Web**: Modern Evergreen browsers within trailing 2 major versions. Strip obsolete ECMAScript polyfills and legacy browser vendor prefixes.
- **iOS**: Minimum deployment target: iOS 17.0+ (SwiftUI, Swift 6 Concurrency).
- **Android**: Minimum SDK: API 28 (Android 9.0 Pie), Target SDK: Current stable API. Modern Android Architecture (BOM) required.

## 3. Sub-Agent Delegation Matrix
Delegate maintenance tasks using `invoke_subagent` with `workspace_mode: "branch"`:

| Objective / File Scope | Sub-Agent | Invocation Mode | Verification Gate |
| :--- | :--- | :--- | :--- |
| Next.js, React, TypeScript, CSS modules, bundle bloat | `web-compliance-auditor` | `branch` (Worktree) | `npm run lint && npm run build` |
| Swift, SwiftUI, Xcode targets, SPM, memory leaks | `ios-compliance-auditor` | `branch` (Worktree) | `swift test` or `xcodebuild test` |
| Kotlin, Jetpack Compose, Gradle (`build.gradle.kts`) | `android-compliance-auditor` | `branch` (Worktree) | `./gradlew lint` |
| Repository search and documentation indexing | `research` (Built-in) | `inherit` (Read-only) | N/A |

### Dispatch Rules:
1. **Parallel Worktrees**: Multiple platform sub-agents may run concurrently in isolated Git worktrees. Assign distinct file scopes to avoid merge conflicts.
2. **Context Freshness**: Pass self-contained prompts to sub-agents (target paths, platform constraints, verification commands). Do not forward monolithic transcripts.
3. **Isolation Guarantee**: Never invoke modifying sub-agents with `workspace_mode: "inherit"`. Enforce `branch` mode.

## 4. Operational Guardrails
1. **Destructive Actions**: Never execute or approve `rm -rf`, `git push --force`, or schema dropping without explicit human confirmation.
2. **Permission Boundary**: Modification tools (`replace_file_content`, `write_file`) must only be exercised by sub-agents inside sandbox worktrees.

## 5. Verification Gate ("Proof Before Done")
Before presenting changes for human sign-off:
1. Verify each sub-agent returned a clean unified git diff scoped to its target.
2. Confirm the sub-agent’s verification command exited cleanly (`exit code 0`).

3. Specialized Sub-Agent Fleet (.agents/agents/)

Antigravity auto-discovers custom agents defined in Markdown with structured YAML frontmatter [cite: 12, 13, 15]. The metadata is loaded via progressive disclosure to conserve tokens until invoked [cite: 3, 37, 40].

A. Web Auditor (.agents/agents/web-compliance-auditor.md)

---
name: web-compliance-auditor
description: Specialized subagent that audits React, Next.js, and TypeScript codebases for server/client boundary violations, dead code, bundle bloat, and accessibility standards.
tools:
  - view_file
  - replace_file_content
  - grep_search
  - run_command
subagent: true
mainAgent: false
model: pro
commandExecutionPolicy: sandbox
---

# Web Compliance Instructions
1. Inspect Next.js routes to ensure `'use client'` and `'use server'` boundaries are respected.
2. Identify and remove unused npm dependencies, obsolete polyfills, and orphaned CSS modules.
3. Eliminate duplicate utility abstractions and audit UI components against WCAG AA standards.
4. Execute `npm run lint && npm run build` inside the sandbox before returning diffs.

B. iOS Auditor (.agents/agents/ios-compliance-auditor.md)

---
name: ios-compliance-auditor
description: Specialized subagent that audits iOS Swift and SwiftUI codebases for deprecated UIKit patterns, memory leaks, retain cycles, and Swift Concurrency safety.
tools:
  - view_file
  - replace_file_content
  - grep_search
  - run_command
subagent: true
mainAgent: false
model: pro
commandExecutionPolicy: sandbox
---

# iOS Compliance Instructions
1. Refactor legacy UIKit delegates, deprecated Combine pipelines, and closure-based handlers into modern Swift Concurrency (`async/await`).
2. Audit closures for strong reference cycles, unowned self-references, and unmanaged observers.
3. Prune unreferenced SwiftUI views, orphaned asset catalog items, and dead feature flags.
4. Execute `swift test` or `xcodebuild test` in the sandbox to verify zero regressions.

C. Android Auditor (.agents/agents/android-compliance-auditor.md)

---
name: android-compliance-auditor
description: Specialized subagent that audits Android repositories for deprecated APIs, Jetpack compliance, Gradle configuration health, and permission security boundaries.
tools:
  - view_file
  - replace_file_content
  - grep_search
  - run_command
subagent: true
mainAgent: false
model: pro
commandExecutionPolicy: sandbox
---

# Android Compliance Instructions
1. Audit `build.gradle.kts` and Kotlin files to migrate legacy components to modern Android Jetpack/AndroidX BOM standards.
2. Validate that runtime permissions in `AndroidManifest.xml` adhere to least-privilege security policies.
3. Remove outdated support libraries, duplicate XML drawables, and unused view bindings.
4. Execute `./gradlew lint` in the sandbox to confirm compilation and lint compliance.

4. Deterministic Lifecycle Hooks & Permissions

While Markdown provides behavioral instructions, lifecycle hooks operate as deterministic firewalls [cite: 37, 39]. A PreToolUse hook blocks forbidden commands before shell execution, while a Stop hook prevents termination until tests pass [cite: 37, 39].

A. Settings & Permissions (.agents/settings.json)

{
  "permissions": {
    "allow": [
      "command(git diff)",
      "command(git status)",
      "command(npm test)",
      "command(npm run lint)",
      "command(swift test)",
      "command(./gradlew lint)"
    ],
    "deny": [
      "command(git push --force)",
      "command(git reset --hard)",
      "file_read(./.env)",
      "file_read(./.env.*)"
    ]
  },
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "run_command",
        "script": ".agents/hooks/gemini-shield.sh"
      }
    ],
    "PostToolUse": [
      {
        "matcher": "replace_file_content",
        "command": "npx prettier --write \"$FILE_PATH\""
      }
    ],
    "Stop": [
      {
        "script": ".agents/hooks/goal-verifier.sh"
      }
    ]
  }
}

B. PreToolUse Shell Guardrail (.agents/hooks/gemini-shield.sh)

#!/usr/bin/env bash
set -euo pipefail

PAYLOAD=$(cat)
TOOL_NAME=$(echo "$PAYLOAD" | jq -r '.tool // .tool_name // empty')
COMMAND=$(echo "$PAYLOAD" | jq -r '.tool_input.command // .tool_input.CommandLine // empty')

if [[ "$TOOL_NAME" != "run_command" && "$TOOL_NAME" != "Bash" && "$TOOL_NAME" != "command" ]]; then
  exit 0
fi

# Block destructive file system deletions
if echo "$COMMAND" | grep -E -q '(rm[[:space:]]+-[rfR]{1,3}[[:space:]]+(/|~|\.|\*|\$HOME))|(mkfs|dd[[:space:]]+if=)'; then
  echo '{"decision": "block", "reason": "Destructive filesystem deletion commands are prohibited."}' >&2
  exit 2
fi

# Block force push operations
if echo "$COMMAND" | grep -E -q 'git[[:space:]]+push[[:space:]]+.*(--force|-f)'; then
  echo '{"decision": "block", "reason": "Force pushing to remote branches is blocked by policy."}' >&2
  exit 2
fi

# Block destructive database operations
if echo "$COMMAND" | grep -E -i -q '(drop[[:space:]]+database|drop[[:space:]]+table|truncate[[:space:]]+table)'; then
  echo '{"decision": "block", "reason": "Destructive SQL operations are restricted."}' >&2
  exit 2
fi

exit 0

C. Stop Event Goal Verifier (.agents/hooks/goal-verifier.sh)

#!/usr/bin/env bash
set -euo pipefail

PAYLOAD=$(cat)
GIT_DIFF=$(git status --porcelain)

if [[ -z "$GIT_DIFF" ]]; then
  echo '{"decision": "allow"}'
  exit 0
fi

FAILURE_LOG=""

if [[ -f "package.json" ]]; then
  if ! npm run lint > /tmp/web_lint.log 2>&1; then
    FAILURE_LOG+="[Web Lint Failure]:\n$(tail -n 20 /tmp/web_lint.log)\n\n"
  fi
  if ! npm test -- --passWithNoTests > /tmp/web_test.log 2>&1; then
    FAILURE_LOG+="[Web Test Failure]:\n$(tail -n 20 /tmp/web_test.log)\n\n"
  fi
fi

if [[ -f "Package.swift" ]]; then
  if ! swift test > /tmp/swift_test.log 2>&1; then
    FAILURE_LOG+="[Swift Test Failure]:\n$(tail -n 20 /tmp/swift_test.log)\n\n"
  fi
fi

if [[ -f "build.gradle.kts" || -f "build.gradle" ]]; then
  if ! ./gradlew lint test --daemon > /tmp/android_test.log 2>&1; then
    FAILURE_LOG+="[Android Test Failure]:\n$(tail -n 20 /tmp/android_test.log)\n\n"
  fi
fi

if [[ -n "$FAILURE_LOG" ]]; then
  ESCAPED_REASON=$(echo -e "Proof Before Done Violation: Test suites failed. Fix all errors before completing:\n\n$FAILURE_LOG" | jq -Rs .)
  echo "{\"decision\": \"continue\", \"reason\": $ESCAPED_REASON}"
  exit 0
fi

echo '{"decision": "allow"}'
exit 0

Make scripts executable:

chmod +x .agents/hooks/gemini-shield.sh .agents/hooks/goal-verifier.sh

5. Headless CI/CD Pipeline & Quantitative Telemetry

File location: .github/workflows/nightly-compliance-factory.yml [cite: 18, 19]

This workflow authenticates with Google Cloud via Workload Identity Federation (WIF) and Application Default Credentials (ADC) using AGY_ADC_AUTH=1 [cite: 18]. It executes agy -p in headless mode and extracts quantitative metrics (lines dropped, bundle byte delta) directly into the generated pull request [cite: 10, 18, 19].

name: Nightly Multi-Agent Compliance Sweep

on:
  schedule:
    - cron: '0 2 * * *'
  workflow_dispatch:

permissions:
  contents: write
  pull-requests: write
  id-token: write

jobs:
  software-factory-audit:
    runs-on: ubuntu-latest
    timeout-minutes: 45

    steps:
      - name: Checkout Repository
        uses: actions/checkout@v5
        with:
          fetch-depth: 0

      - name: Authenticate to Google Cloud via WIF
        uses: google-github-actions/auth@v3
        with:
          workload_identity_provider: 'projects/123456789012/locations/global/workloadIdentityPools/github-actions-pool/providers/github-provider'
          service_account: '[email protected]'

      - name: Install Antigravity CLI (agy)
        run: |
          curl -fsSL https://antigravity.google/cli/install.sh | bash
          echo "$HOME/.antigravity/bin" >> $GITHUB_PATH

      - name: Setup Node.js Environment
        uses: actions/setup-node@v4
        with:
          node-version: '22'
          cache: 'npm'

      - name: Install Dependencies & Record Baseline Web Bundle
        run: |
          npm ci
          npm run build --if-present
          BASELINE_BUNDLE_KB=$(du -sk .next/static 2>/dev/null | awk '{print $1}' || echo "0")
          echo "BASELINE_BUNDLE_KB=${BASELINE_BUNDLE_KB}" >> $GITHUB_ENV

      - name: Run Headless Autonomous Audit Fleet
        env:
          AGY_ADC_AUTH: "1"
        run: |
          agy -p "Execute the automated nightly compliance sweep across Web, iOS, and Android scopes using your designated sub-agents. Prune dead code, remove deprecated polyfills, and modernize trailing-edge APIs in isolated branch worktrees. Ensure all test suites pass before completing." \
              --mode accept-edits \
              --sandbox \
              --output-format json > sweep_output.json

      - name: Extract Metrics & Formulate PR Body
        run: |
          INSERTIONS=$(git diff --shortstat | grep -o -E '+ insertion' | cut -d ' ' -f 1 || echo 0)
          DELETIONS=$(git diff --shortstat | grep -o -E '+ deletion' | cut -d ' ' -f 1 || echo 0)
          NET_LINES=$(( INSERTIONS - DELETIONS ))

          npm run build --if-present
          NEW_BUNDLE_KB=$(du -sk .next/static 2>/dev/null | awk '{print $1}' || echo "0")
          BUNDLE_DELTA_KB=$(( NEW_BUNDLE_KB - BASELINE_BUNDLE_KB ))
          AGENT_SUMMARY=$(jq -r '.response // .summary // "Routine maintenance completed."' sweep_output.json)

          echo "INSERTIONS=${INSERTIONS}" >> $GITHUB_ENV
          echo "DELETIONS=${DELETIONS}" >> $GITHUB_ENV
          echo "BUNDLE_DELTA_KB=${BUNDLE_DELTA_KB}" >> $GITHUB_ENV

          {
            echo "PR_BODY<<EOF"
            echo "## 🤖 Software Factory: Automated Nightly Maintenance"
            echo ""
            echo "### 📊 Codebase Health Delta"
            echo "| Metric | Baseline | After Clean-up | Net Impact |"
            echo "| :--- | :--- | :--- | :--- |"
            echo "| **Lines of Code** | +${INSERTIONS} | -${DELETIONS} | **${NET_LINES} lines** |"
            echo "| **Web Client Bundle** | ${BASELINE_BUNDLE_KB} KB | ${NEW_BUNDLE_KB} KB | **${BUNDLE_DELTA_KB} KB** |"
            echo ""
            echo "### 🛠️ Sub-Agent Actions & Highlights"
            echo "${AGENT_SUMMARY}"
            echo ""
            echo "---"
            echo "### 🛡️ Safety & Verification Gates"
            echo "- ✅ **PreToolUse Shell Firewall (`gemini-shield.sh`)**: Intercepted destructive commands; 0 policy violations."
            echo "- ✅ **Stop Event Goal Verifier (`goal-verifier.sh`)**: All test suites and builds passed in sandbox."
            echo "- ✅ **Isolation**: Sub-agents executed on isolated git worktrees; zero main working tree pollution."
            echo "EOF"
          } >> $GITHUB_ENV

      - name: Create Pull Request
        id: cpr
        uses: peter-evans/create-pull-request@v6
        with:
          commit-message: "chore(factory): nightly compliance audit & dead code elimination"
          branch: "factory/nightly-compliance-audit"
          delete-branch: true
          title: "🤖 Software Factory: Nightly Compliance & Debt Pruning (-${{ env.DELETIONS }} lines)"
          body: ${{ env.PR_BODY }}
          labels: |
            automated-pr
            technical-debt
            software-factory

      # Alert integration: Slack
      - name: Send Slack Notification
        if: steps.cpr.outputs.pull-request-number != ''
        env:
          SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
          PR_URL: ${{ steps.cpr.outputs.pull-request-url }}
          PR_NUM: ${{ steps.cpr.outputs.pull-request-number }}
          INSERTIONS: ${{ env.INSERTIONS }}
          DELETIONS: ${{ env.DELETIONS }}
          BUNDLE_DELTA_KB: ${{ env.BUNDLE_DELTA_KB }}
        run: |
          curl -s -X POST -H 'Content-type: application/json' \
            --data "{
              \"blocks\": [
                {
                  \"type\": \"header\",
                  \"text\": {\"type\": \"plain_text\", \"text\": \"🤖 Software Factory: Nightly Pruning PR #${PR_NUM}\"}
                },
                {
                  \"type\": \"section\",
                  \"fields\": [
                    {\"type\": \"mrkdwn\", \"text\": \"*Lines Pruned:*\n-${DELETIONS} (+${INSERTIONS})\"},
                    {\"type\": \"mrkdwn\", \"text\": \"*Bundle Impact:*\n${BUNDLE_DELTA_KB} KB\"}
                  ]
                },
                {
                  \"type\": \"actions\",
                  \"elements\": [
                    {
                      \"type\": \"button\",
                      \"text\": {\"type\": \"plain_text\", \"text\": \"Review Pull Request\"},
                      \"url\": \"${PR_URL}\",
                      \"style\": \"primary\"
                    }
                  ]
                }
              ]
            }" "$SLACK_WEBHOOK_URL"

6. Deployment & Verification Checklist

  1. Verify Local Hooks:
    # Test the PreToolUse hook by feeding a simulated dangerous command:
    echo '{"tool": "run_command", "tool_input": {"command": "rm -rf /"}}' | .agents/hooks/gemini-shield.sh
    # Expected output: exits with code 2 and outputs blocking JSON to stderr
    
  2. Verify Agent Discovery:
    # Confirm that Antigravity discovers your custom sub-agents
    agy /agents
    

    Confirm that web-compliance-auditor, ios-compliance-auditor, and android-compliance-auditor appear in the registry [cite: 11, 13].

  3. Verify CI Authentication: Confirm that Google Cloud Workload Identity Federation is configured to accept tokens issued by your GitHub repository and mapped to the runner service account with appropriate Vertex AI / Gemini invocation roles [cite: 18].

Stop Using AI Just to Write Code: 5 Surprising Lessons from Building an AI-Powered “Software Factory”

We’ve all seen it happen: an AI coding assistant churns out 500 lines of syntactically valid code in ten seconds flat. Feature velocity skyrockets, pull requests stack up, and engineering leads start celebrating—until code review bottlenecks hit. Before long, your repository is burdened by subtle bloat, unmaintained abstractions, and low-quality  “AI slop.”

If we only use artificial intelligence to write  more  code, we are simply accelerating technical debt.

The real magic happens when you shift AI from front-line code generation to  “trailing edge”  maintenance. Instead of asking agents to draft your next feature, what if you tasked them with hunting down legacy APIs, stripping out redundant polyfills, and keeping your dependencies pristine?

By pairing  anti-gravity  (the agentic development platform) with  Gemini for Argonne  (the underlying intelligence engine capable of long-horizon reasoning), you can construct a fully automated, agentic  “software factory.”  Powered by specialized sub-agents defined in simple Markdown, this approach turns AI from an unchecked code generator into a tireless janitor for your codebase.

Here are five key lessons learned from building an automated software factory designed to eliminate code rot.

1. Use AI to  Delete  Code, Not Just Write It

Every modern codebase carries historical weight. Years ago, your web app might have needed complex polyfills or custom helpers to handle cross-browser inconsistencies. Today, native web APIs and modern mobile SDKs handle those exact capabilities out of the box. Yet, those legacy fallbacks sit untouched in your source tree because nobody wants to break a legacy production path.

Clearing out this dead weight delivers immediate engineering ROI: it speeds up user load times, shrinks bundle sizes, and dramatically reduces the surface area that future AI agents have to analyze. Fewer lines of code mean smaller token counts and fewer hallucinations during downstream tasks.

Within anti-gravity, you govern code elimination using a  platform config . This central policy file establishes your company’s exact operational baseline:

  • Indie Projects / Bleeding-Edge Apps:  Configured to target only the latest platform and browser releases, allowing sub-agents to ruthlessly prune legacy code paths.
  • Enterprise Applications:  Mandated to maintain backward compatibility across  2–3 browser or mobile versions , giving agents strict boundaries on what can be safely removed.

Once this policy is defined, your factory automatically audits source files against platform standards, identifying redundant polyfills and obsolete method signatures for removal.

Rhodey, a developer on the anti-gravity team, puts the problem into sharp perspective:

“There are probably so many APIs in your code base that are there in your code for legacy reasons that haven’t been invoked in years… Take a look today in your code base, see what you can remove…”

2. Modular Sub-Agents Outperform Single-Prompt Chat Sessions

If you drop an entire multi-platform application into a single long-running chat session and ask it to perform a full codebase audit, performance degrades rapidly. Large prompt context windows inevitably suffer from  context window compaction . As the conversation history swells, the model forgets earlier system constraints, drops minor edge-case rules, and begins hallucinating fixes.

The solution is to replace mega-prompts with a structured assembly line of modular  custom sub-agents , defined in Markdown inside anti-gravity. Each worker operates within its own  isolated context window  and executes tasks across a clear 3-phase pipeline:

[ Incoming Issues / GitHub Tickets ]

                 │

                 ▼

    Phase 1: Intake Sub-Agent

                 │

  ┌──────────────┼──────────────┐

  ▼              ▼              ▼

Phase 2:      Phase 2:      Phase 2:

Node/Web     Android/Jet    iOS/SwiftUI

Sub-Agent     Sub-Agent      Sub-Agent

  │              │              │

  └──────────────┼──────────────┘

                 ▼

    Phase 3: Read-Only Auditor

                 │

                 ▼

   [ Verified PR / Code Cleanup ]

The 3-Phase Pipeline Breakdown
  1. Phase 1: Intake & Policy Parsing:  The  Intake Sub-Agent  ingests raw materials—such as reported technical debt issues wired directly to your  GitHub  repo or internal ticketing system—and evaluates them against your corporate platform config.
  2. Phase 2: Parallel Execution & Modifications:  Tasks are dispatched simultaneously to specialized sub-agents ( Web/Node ,  Android/Jetpack Compose , and  iOS/SwiftUI ). Because each sub-agent runs in parallel with an isolated context window, multi-platform updates complete rapidly without cluttering the primary orchestration session.
  3. Phase 3: Review & Audit Reporting:  The final output is aggregated into structured audit reports, verified code diffs, or clean pull requests ready for human approval.

By isolating worker contexts, anti-gravity keeps main session history lean while allowing parallel workers to analyze large, multi-repository platforms simultaneously.

3. You Are the “Floor Manager”—Enforce Read-Only Guardrails

Fully autonomous agents sound great in marketing demos, but production codebases require hard safety boundaries. In an anti-gravity software factory, the developer steps out of the raw coding trench and into the role of a  “Floor Manager.”

As the Floor Manager, your job is to observe, direct, and enforce security guardrails across your agent workforce.

┌─────────────────────────────────────────────────────────────────┐

│                      FLOOR MANAGER DASHBOARD                    │

│                                                                 │

│  [Main Orchestrator] ──> Real-Time Chat Log Inspection          │

│                      ──> Direct Message / Mid-Flight Steering   │

│                      ──> Intercept & Repair via /learn Command   │

└─────────────────────────────────────────────────────────────────┘

Deterministic Tool Exclusion

How do you stop an auditing agent from accidentally rewriting core business logic? In anti-gravity, sub-agent skills are configured via Markdown, allowing you to  explicitly exclude code-writing tools  from Phase 3 reviewer workers. By stripping file-write capabilities, your audit sub-agents are strictly locked into  read-only mode . They can analyze syntax, trace dependency graphs, and flag deprecations, but they cannot alter a single line of code without authorization.

Real-Time Observability & Steering
  • Live Chat Inspection:  Click into any sub-agent’s active thread mid-execution to observe its step-by-step reasoning.
  • Direct Messaging:  Intervene immediately if a worker drifts off course. You can message sub-agents directly while they run to refine their focus or halt execution entirely.
  • System Procedure Repair (  /learn  ):  If a worker produces a sub-optimal review or misses a structural rule, invoke the built-in /learn command. The factory pauses, analyzes the mistake, updates the worker’s underlying procedural Markdown rules, and ensures the error isn’t repeated in future runs.

4. Automate Code “Freshness Audits” Around Major Tech Events

Technical debt rarely arrives with a loud bang; it accumulates silently as external web and mobile ecosystems evolve around your application. To combat silent rot, anti-gravity features an  automation panel  to trigger recurring, background  freshness audits .

Audit Metric,Evaluated Criteria,Factory Action

Git Edit Recency,Scans commit timestamps across modules to flag unmaintained code paths.,Identifies stale modules that haven’t been audited in 12+ months.

API Recency Check,Compares current codebase syntax against modern platform SDK baselines.,Highlights deprecated methods eligible for immediate refactoring.

External Standards,”Queries external documentation platforms (e.g., MDN compatibility matrices).”,Flags polyfills whose target APIs are now natively supported across all browsers.

Strategic Triggering: The Conference-Driven Audit

While scheduled monthly audits are useful, the most effective time to spin up your software factory is immediately following major tech events like  Apple WWDC  or  Google I/O .

When Apple or Google announces sweeping SDK updates, platform deprecations, and modern syntax patterns, your code base is instantly hit with new debt. By combining anti-gravity’s  native web search  and  multimodal reasoning capabilities , sub-agents can ingest live documentation—such as updated  MDN browser compatibility tables  or newly published API specs—the moment they go live.

Running automated freshness sweeps directly after major platform keynotes lets your factory identify newly redundant polyfills and flag breaking changes long before tech debt settles into your master branch.

5. Balance Hands-On Control with “Long Horizon” Hands-Off Modes

Not every engineering task fits neatly into a rigid, step-by-step sub-agent pipeline. Sometimes you want granular, deterministic control over code deletion; other times you need an agent to autonomously navigate a complex, ambiguous refactoring task across dozens of files.

Anti-gravity leverages  Gemini for Argonne  to provide a dynamic spectrum of execution modes built specifically for complex, long-horizon tasks:

┌─────────────────────────────────────────────────────────────────┐

│                    EXECUTION CONTROL SPECTRUM                   │

│                                                                 │

│  Custom Sub-Agents   ───>   Teamwork Preview   ───>   /boost    │

│  (Granular Control)         (Mini-Teams)           (Linear)     │

└─────────────────────────────────────────────────────────────────┘

  1. Custom Sub-Agent Pipelines (Granular Control):  Fully customizable. You manually define skills, isolated tool permissions (such as read-only mode), and phase structures in Markdown. Ideal for routine, policy-driven code cleanup.
  2. Teamwork Preview (Autonomous Collaboration):  Gemini for Argonne automatically spins up dynamic mini-teams of sub-agents that collaborate, cross-check work, and divide responsibilities to solve broad, loosely defined architecture goals.
  3. The  /boost  Command (Linear Autonomous Execution):  An opinionated, high-velocity execution mode. When triggered, Gemini for Argonne spins up ad-hoc sub-agents on the fly to solve multi-file tasks in a streamlined, linear sequence—eliminating setup overhead entirely.

This flexibility ensures you retain strict procedural control when auditing compliance policies, while unlocking long-horizon autonomy when executing complex codebase overhauls.

Redefine Your AI Workflow Today

The measure of a modern engineering team isn’t how many thousands of lines of AI code they push to production each week. It’s how cleanly and efficiently they maintain their system’s core core architecture over time.

By shifting your mindset from code generation to automated debt reduction—using anti-gravity and Gemini for Argonne to orchestrate parallel sub-agents, enforce read-only guardrails, and trigger event-driven freshness audits—you can stop drowning in AI slop and build a software factory that keeps your code lean, fast, and modern.

Take a look at your main repository today:  Which legacy APIs and outdated polyfills are still running in your system simply because no one has taken the time to delete them?

Open anti-gravity, configure your sub-agents, and let your software factory start cleaning up today.