Metadata-Version: 2.4
Name: antigravity-context-shield
Version: 0.1.0
Summary: Dynamic Context Compactor & Semantic State Graph for Long-Running Autonomous Agents
Author: Principal Staff AI/Systems Architect
License-Expression: MIT
License-File: LICENSE
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.11
Requires-Dist: pydantic>=2.0.0
Provides-Extra: dev
Requires-Dist: pytest-asyncio>=0.20.0; extra == 'dev'
Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
Requires-Dist: pytest>=7.0.0; extra == 'dev'
Description-Content-Type: text/markdown

<p align="center">
  <img src="docs/assets/banner.png" alt="Antigravity Context Shield Banner" width="100%" />
</p>

# 🛡️ Antigravity Context Shield (`antigravity-context-shield`)

[![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![CI](https://github.com/Jivan-hero/antigravity-context-shield/actions/workflows/ci.yml/badge.svg)](https://github.com/Jivan-hero/antigravity-context-shield/actions)
[![Coverage](https://img.shields.io/badge/coverage-90%25-brightgreen.svg)]()
[![Code Style: Black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)

**Dynamic Context Compactor & Semantic State Graph for Long-Running Autonomous AI Agents.**

`antigravity-context-shield` is an open-source, production-ready Python library engineered to eliminate **Context Degradation ("Context Rot"), Silent Context Drift, and Hallucination Accumulation** in long-running agent loops (e.g. software engineering agents, browser automation, long task loops).

---

## 🎯 The Problem

As autonomous agent loops execute over hours or days, context windows fill up with raw tool outputs (e.g., thousands of lines of terminal stdout, large file reads) and stale reasoning paths. Standard implementations suffer from:
1. **Naive Truncation**: Drops crucial initial instructions, setup parameters, or system constraints.
2. **Raw RAG Dumping**: Loses temporal ordering, state mutations, and causal dependencies.
3. **Infinite Error Loops**: Agents repeatedly attempt failing tool commands with identical parameters without realizing system state hasn't changed.

---

## 🚀 Key Features

- **⚡ Active Context Pruning Engine**: Automatically compresses long terminal outputs and raw file reads while preserving stack traces and structural signatures. Collapses duplicate/polling action sequences into high-level notices.
- **🕸️ Semantic State Graph (SSG)**: Models multi-turn execution as a Directed Acyclic Graph (DAG) of Turns, Tools, and State updates. Extracts the minimal *active causal execution path*, discarding failed/abandoned attempts.
- **🛡️ Anti-Hallucination Guardrails**: Pre-turn middleware that cross-references proposed prompt claims against active state nodes to detect state drift and block action redundancy.
- **🔌 Framework Agnostic & SDK Adapters**: Native hooks for **Google Antigravity SDK (`google-antigravity`)**, **LangChain**, and **LlamaIndex**.

---

## 📊 Benchmarks

| Metric | Without Shield | With `antigravity-context-shield` | Improvement |
| :--- | :--- | :--- | :--- |
| **5-Turn Agent History** | 8,605 chars (~2,150 tokens) | 1,383 chars (~345 tokens) | **83.93% Reduction** |
| **Redundant Tool Loop Deflection** | 0% (Loops indefinitely) | 100% (Pre-emptively blocked) | **Zero Hallucination Loops** |
| **Test Coverage** | N/A | **90% Unit Test Coverage** | **Production Ready** |

---

## 📐 Architecture

```mermaid
flowchart LR
    subgraph Execution Loop
        User[User Goal] --> Agent[Autonomous Agent]
        Agent --> Shield[Context Shield Middleware]
        Shield --> Guard[Anti-Hallucination Guardrails]
        Guard --> Model[LLM / Gemini Dispatch]
    end

    subgraph Memory Architecture
        Model --> Tools[Tool Executions]
        Tools --> Pruner[Active Context Pruner]
        Tools --> SSG[Semantic State Graph DAG]
        Pruner --> ActiveContext[Compacted Active History]
        SSG --> ActiveContext
        ActiveContext --> Agent
    end
```

---

## 🛠️ Quickstart

### Installation

```bash
pip install antigravity-context-shield
```

### 1. Integrating with Google Antigravity SDK

```python
from google.antigravity import LocalAgentConfig
from antigravity_context_shield import ContextShieldAntigravityAdapter, ContextShieldConfig

# Instantiate Shield Config & Adapter
shield_config = ContextShieldConfig(
    max_message_length=1000,
    enable_terminal_pruning=True,
    enable_file_read_pruning=True,
    enable_duplicate_run_pruning=True,
    enable_guardrails=True
)

shield_adapter = ContextShieldAntigravityAdapter(config=shield_config)

# Register hooks with LocalAgentConfig
agent_config = LocalAgentConfig(
    hooks=shield_adapter.get_registered_hooks()
)
```

### 2. Standalone Compaction Engine

```python
from antigravity_context_shield import ContextCompactorEngine, Message, MessageRole, ToolCall

engine = ContextCompactorEngine()

messages = [
    Message(role=MessageRole.USER, content="Run build tests."),
    Message(
        role=MessageRole.ASSISTANT, 
        content="Running pytest...", 
        tool_calls=[ToolCall(id="tc1", name="bash", arguments={"cmd": "pytest"}, output="VERY LONG STDOUT LOG...")]
    )
]

compacted_messages = engine.compact_messages(messages)
```

### 3. LangChain & LlamaIndex Callback Handlers

```python
from antigravity_context_shield import ContextShieldLangChainCallbackHandler

handler = ContextShieldLangChainCallbackHandler()
# Pass `handler` into LangChain agent callbacks: agent.run(..., callbacks=[handler])
```

---

## 🧪 Running Examples & Tests

### Run Unit Tests
```bash
pytest -v --cov=src/antigravity_context_shield tests/
```

### Run Benchmark Demonstration Scripts
```bash
# Baseline without shield (watch context size grow)
python3 examples/run_without_shield.py

# With Shield enabled (watch >80% token reduction)
python3 examples/run_with_shield.py
```

---

## 📄 License

Distributed under the MIT License. See `LICENSE` for details.
