Metadata-Version: 2.4
Name: jbr
Version: 1.0.1
Summary: JBR: Enterprise 6-Layer Production Agent Harness Framework
License: Apache-2.0
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: aiohttp!=3.14.2
Requires-Dist: aiosqlite>=0.21
Requires-Dist: authlib<2,>=1.6.6
Requires-Dist: click<9,>=8.1.8
Requires-Dist: fastapi<1,>=0.115
Requires-Dist: google-auth[pyopenssl]>=2.47
Requires-Dist: google-genai<3,>=2.19
Requires-Dist: httpx<1,>=0.27
Requires-Dist: jsonschema<5,>=4.23
Requires-Dist: pydantic<3,>=2.10
Requires-Dist: python-dotenv<2,>=1
Requires-Dist: pyyaml<7,>=6.0.2
Requires-Dist: requests<3,>=2.32.4
Requires-Dist: starlette<2,>=0.38
Requires-Dist: tenacity<10,>=8.5
Requires-Dist: typing-extensions<5,>=4.12
Requires-Dist: websockets<17,>=13.0
Dynamic: license-file

# JBR (`jbr`)

[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)
[![Python versions](https://img.shields.io/badge/Python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue.svg)](pyproject.toml)
[![Tests](https://img.shields.io/badge/Tests-32%20passed%20(100%25)-brightgreen.svg)](tests/harness/)
[![Architecture](https://img.shields.io/badge/Architecture-6--Layer%20Harness-purple.svg)](#1-architectural-overview)

**`jbr`** is an enterprise-grade, 6-layer agent harness framework. It operationalizes the core architectural paradigm of production AI systems:

$$\mathbf{\text{Production Agent}} = \mathbf{\text{Model}} + \mathbf{\text{6-Layer Harness}}$$

`jbr` transforms raw foundation LLMs into deterministic, safe, verifiable, and crash-resilient autonomous engineering agents by wrapping execution in an impenetrable computational governance barrier.

---

## 1. Architectural Overview

```mermaid
graph TD
    subgraph "External World & System of Record"
        Guides["AGENTS.md / CLAUDE.md / .cursorrules"]
        Sensors["Deterministic Sensors: Ruff / Mypy / Pytest / AST"]
        Storage["Durable Checkpoints (checkpoint.json, plan.md)"]
    end

    subgraph "JBR (6-Layer Architecture)"
        subgraph "Layer 1: Guides (Feedforward Rules)"
            L1["GuideParser & GuidePlugin<br/>(System of Record -> Agent.instruction)"]
        end

        subgraph "Layer 5: Permissions & Budgets (Capability Gate)"
            L5["CapabilityBudgetPlugin<br/>(RBAC, Rate Limits, Path & Shell Sanitizers)"]
        end

        subgraph "Layer 3: Agentic Loop (Cyclic Bounded Workflow)"
            L3_Plan["PlanNode"]
            L3_Exec["ExecuteNode"]
            L3_Verify["VerifyNode (Sensors)"]
            L3_Fix["FixNode"]
            L3_Escalate["EscalateNode (EscalationPacket)"]
            
            L3_Plan --> L3_Exec
            L3_Exec --> L3_Verify
            L3_Verify -- "Passed (0 errors)" --> L3_Done["Workflow Completed"]
            L3_Verify -- "Failed (Retries < 3)" --> L3_Fix
            L3_Fix --> L3_Verify
            L3_Verify -- "Failed (Retries >= 3 or Budget Breached)" --> L3_Escalate
        end

        subgraph "Layer 2: Sensors (Verification Barrier)"
            L2["SensorRunner & CommandSensors<br/>(AST / Ruff / Mypy / Pytest Diagnostics)"]
        end

        subgraph "Layer 4: Memory & State (Durable Checkpoints)"
            L4["DurableSessionService & DurableArtifactService<br/>(Atomic WAL Engine & Recovery Test)"]
        end

        subgraph "Layer 6: Observability & Telemetry (Trip-Wires)"
            L6["TripwireTelemetryPlugin & CostExporter<br/>(Prometheus Metrics, Cost-Per-Task, 3x Loop Breaker)"]
        end
    end

    Guides --> L1
    L1 --> L3_Plan
    L5 --> L3_Exec
    L3_Verify --> L2
    L2 --> Sensors
    L4 --> Storage
    L3 --> L4
    L3 --> L6
```

---

## 2. Key Features & Guarantees

| Layer | Component | Guarantees & Implementation |
|---|---|---|
| **Layer 1** | **Guides** (Feedforward) | Discovers `AGENTS.md`, `CLAUDE.md`, and `.cursorrules`; performs topological priority sorting (`SYSTEM_CRITICAL` > `PROJECT_LEVEL`) and injects immutable constraints into agent instructions overriding conversational drift. |
| **Layer 2** | **Sensors** (Verification Barrier) | **Zero-Unverified-Edits Rule**: Executes deterministic static gates (`PythonSyntaxSensor`, `RuffSensor`, `MypySensor`, `PytestSensor`) before output acceptance; parses exact line numbers and rule IDs into structured `SensorDiagnostic` objects. |
| **Layer 3** | **Agentic Loop** (Bounded Workflow) | Enforces the canonical cyclic loop (`Plan -> Execute -> Verify -> Fix -> Escalate`) with a **hard cap of $\le 3$ retries**. If unresolved, immediately halts and generates a structured `EscalationPacket` for human operators. |
| **Layer 4** | **Memory & State** (Checkpoints) | Synchronous Write-Ahead Logging (WAL) and SHA256 checksums (`checkpoint.json`, `plan.md`). Passes the **Recovery Test** across process terminations and restarts with zero data corruption. |
| **Layer 5** | **Permissions & Budgets** (Capability Gate) | Middleware gate (`CapabilityBudgetPlugin`, `PermissionGuardedTool`) enforcing least-privilege RBAC (`READ_ONLY`, `WORKSPACE_WRITE`, `ADMIN`), per-tool rate limits, global invocation caps, path traversal scrubbing (`../`, `.git/`, `.env`), and secret redaction. |
| **Layer 6** | **Observability & Telemetry** (Trip-Wires) | Real-time unit task cost accounting (`CostExporter`), Prometheus format metric emission (`.jbr/metrics.prom`), OpenTelemetry payloads, and automated circuit breakers (3x consecutive repeating error trips or cost spike halts). |

---

## 3. Quick Start & Installation

### Installation

#### Option 1: Install from PyPI
```bash
pip install jbr
```

#### Option 2: Local Editable Installation
```bash
# Clone or navigate to the repository
git clone <repository-url>/jbr.git
cd jbr
pip install -e .
```

---

### Python API Usage (Single-Namespace Surface)

Developers only need to import from `jbr`:

```python
import asyncio
from jbr import (
    # Re-exported Core Primitives
    Agent, Workflow, Runner, Session, Tool, BaseNode, START,
    # 6-Layer Harness Primitives
    JbrRunnerFactory, GuideParser, SensorRunner, DurableSessionService,
    CapabilityBudgetPlugin, TripwireTelemetryPlugin,
    # Factory Convenience Helpers
    create_jbr_agent, create_jbr_runner, create_jbr_workflow,
)

async def main():
    # 1. Create a governed agent
    agent = create_jbr_agent(
        name="software_engineer",
        model="gemini-1.5-flash",
        instruction="You are a senior engineer adhering strictly to AGENTS.md.",
    )

    # 2. Instantiate an enterprise 6-layer Runner
    runner = create_jbr_runner(agent=agent)

    # 3. Create a crash-resilient session
    session = await runner.session_service.create_session(
        app_name="enterprise_app",
        user_id="eng_user",
        state={"task": "Implement secure authentication middleware"},
    )
    print(f"Session initialized with durable WAL: {session.id}")

if __name__ == "__main__":
    asyncio.run(main())
```

---

### Command Line Interface (CLI)

The package installs a standalone console script `jbr`:

```bash
# Run an autonomous task governed by all 6 harness layers
jbr \
  --task "Refactor authentication middleware with least privilege and sensor validation" \
  --workspace-root "." \
  --max-retries 3 \
  --cost-limit 5.00 \
  --export-telemetry ".jbr/telemetry.jsonl" \
  --metrics-prom ".jbr/metrics.prom"
```

#### CLI Execution Output:
```text
======================================================================
[JBR] ENTERPRISE 6-LAYER HARNESS RUNNER
======================================================================
  Workspace:    /path/to/workspace
  Task:         Refactor authentication middleware with least privilege and sensor validation
  Max Retries:  3
  Cost Limit:   $5.00
----------------------------------------------------------------------
[Layer 1 - Guides] Discovered 1 authoritative guide(s):
   - AGENTS.md
[Layer 3 - Loop] Initializing Bounded Cyclic Workflow...
[Layer 4 - State] Session created: b6a525d6-27c6-45f9-b5b3-182877f6836b
   > Stage: [PLANNING] 
   > Stage: [EXECUTING] 
   > Stage: [VERIFYING] 
   > Stage: [COMPLETED] SUCCESS
[Layer 4 - State] Checkpoint saved successfully.
----------------------------------------------------------------------
[Layer 6 - Telemetry & Metrics]
   - Task Duration:       3.082s
   - Total Tokens:        1670
   - Estimated Cost:      $0.003663
   - Outcome:             [PASSED]
   - Telemetry File:      .jbr/telemetry.jsonl
   - Prometheus Metrics:  .jbr/metrics.prom
======================================================================
```

---

## 4. System of Record Template (`AGENTS.md`)

Consuming projects place an `AGENTS.md` at their repository root to establish authoritative feedforward governance:

```markdown
---
title: Repository Governance & System of Record
priority: SYSTEM_CRITICAL
tags: [governance, constraints, jbr]
version: 1.0.0
---

# SYSTEM FEEDFORWARD CONSTRAINTS

## 1. Mandatory Commands & Quality Gates
- Test Suite: `pytest tests/harness/ -v`
- Python Syntax Check: `python -m py_compile <file.py>`
- Linter & Formatting: `ruff check src/ tests/`
- Type Verification: `mypy src/ --no-error-summary`

## 2. Hard Governance Constraints
- Zero-Unverified-Edits: All code modifications must pass Layer 2 verification sensors.
- Maximum 3 Retries: If sensor failures persist after 3 cycles, escalate immediately.
- Least Privilege (RBAC): Never request admin execution when read/write capabilities suffice.
- Secrets Isolation: Never log or emit raw API credentials in persistent artifacts.
```

---

## 5. Verification & Test Suite

`jbr` includes a comprehensive 32-test verification suite covering individual layers, CLI behavior, Prometheus telemetry, and the complete **12-Point Compliance Matrix** (including the Recovery Test and 3x repeat error tripwire):

```bash
# Run the complete test suite
pytest tests/harness/ -v

# Run the 12-point compliance integration suite specifically
pytest tests/harness/test_12_point_compliance.py -v
```

### Test Summary:
```text
======================== 32 passed, 1 warning in 2.41s ========================
```

---

## 6. License

This project is licensed under the [Apache License, Version 2.0](LICENSE).
