Metadata-Version: 2.4
Name: agentic-paradigm-ladder
Version: 0.1.0
Summary: The Agentic Paradigm Ladder — executable, tested implementations of agent-engineering Levels 5-14 (genomes, evolution, capability contracts, a workflow compiler, and a skill-contract test harness).
Author: Duc Nguyen
License: MIT
Project-URL: Homepage, https://github.com/nguyenminhduc9988/agentic-paradigm-ladder
Project-URL: Repository, https://github.com/nguyenminhduc9988/agentic-paradigm-ladder
Keywords: agents,llm,evolution,workflow-compiler,skills,agent-engineering
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pyyaml>=5.1
Provides-Extra: test
Requires-Dist: pytest>=7.0; extra == "test"
Provides-Extra: build
Requires-Dist: build>=1.0; extra == "build"
Requires-Dist: twine>=5.0; extra == "build"
Dynamic: license-file

<!-- ══════════════════════════════════════════════════════════════════ -->
<div align="center">

<img src="assets/hero.svg" alt="The Agentic Paradigm Ladder — agentic AI is writing assembly; Levels 5→14 as real, tested code" width="100%"/>

<h1>🪜 The Agentic Paradigm Ladder</h1>

<p><strong>Agent development is stuck writing assembly.</strong><br/>
This repo builds the missing abstraction ladder — Levels 5→14 — as <em>real, tested, running</em> code.</p>

<!-- ── badges ───────────────────────────────────────────────────── -->
[![Skills CI](https://github.com/nguyenminhduc9988/agentic-paradigm-ladder/actions/workflows/skills-ci.yml/badge.svg)](https://github.com/nguyenminhduc9988/agentic-paradigm-ladder/actions/workflows/skills-ci.yml)
[![Tests](https://img.shields.io/badge/tests-72%20passing-brightgreen.svg)](docs/VERIFICATION-REPORT.md)
[![License: MIT](https://img.shields.io/badge/license-MIT-22c55e.svg)](LICENSE)
[![Python](https://img.shields.io/badge/python-3.9%2B-4f8cff.svg?logo=python&logoColor=white)](pyproject.toml)
[![Components](https://img.shields.io/badge/components-C1–C10-7c3aed.svg)](docs/COMPONENTS.md)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-ff69b4.svg)](#-contributing)

<h3><code>pip install -e . && apl demo</code></h3>
<sub>One command. No <code>PYTHONPATH</code> wiring. Runs the Level-11 workflow compiler end-to-end and exits 0.</sub>

</div>

<!-- ══════════════════════════════════════════════════════════════════ -->

---

## ⚡ Quickstart

Clone → install → run, in a single line:

```bash
git clone https://github.com/nguyenminhduc9988/agentic-paradigm-ladder && cd agentic-paradigm-ladder && pip install -e . && apl demo
```

Already cloned? Just:

```bash
pip install -e . && apl demo
```

<details>
<summary><strong>▶ What <code>apl demo</code> prints</strong> (click to expand)</summary>

```text
apl demo — compiling bundled workflow: examples/example_workflow.json

  Workflow: research-digest-pipeline v1.0.0
  Nodes before: 6  →  after: 5

  [dead_task_elimination]
    - Removed 1 dead tasks: Legacy debug dump (unconsumed) (id=stale_debug)
  [model_reroute]
    - Summarize each document: summarize — rerouted from ~$0.0257 to ~$0.0000 (using glm-5-turbo)
    - Analyze market signals: analyze — rerouted from ~$0.0085 to ~$0.0005 (using glm-5.1)
    - Total savings: ~$0.0569 per cycle
  [batch_detection]
    - Found 1 batch opportunities: {analyze_market,analyze_risk}
  [checkpoint_insertion]
    - Inserted 2 checkpoint(s): ingest, report
  SUMMARY
    original_cost: $0.1208
    optimized_cost: $0.0017
    savings: 98.6%

  ✅ Demo complete — the Level 11 compiler optimized the workflow end-to-end.
  💰 Cost $0.1208 → $0.0017 (98.6% saved)
```

</details>

### The `apl` command line

| Command | What it does |
|---|---|
| `apl demo` | 🚀 Self-contained end-to-end demo — the Level-11 workflow compiler. |
| `apl compile FILE` | Compile & optimize any workflow (`.yaml` / `.json`). |
| `apl cost FILE` | Estimate a workflow's per-cycle cost. |
| `apl graph FILE` | Print a workflow as a text dependency graph. |
| `apl evolve` | 🧬 Run the evolutionary skill-discovery dry-run (Levels 12–14). |
| `apl integrate` | 🔌 Attach the ladder to a plain agent and guide it end-to-end. |
| `apl test` | ✅ Run the full test suite — **72 tests** across all packages. |
| `apl info` | Print the paradigm ladder this repo implements. |

> Run the tests yourself: `pip install -e '.[test]' && apl test`

---

## 🔌 Integrate into any agent

The ladder isn't just a library to read — it's a **drop-in governor** for *any* AI agent. One object, `AgentIntegration`, plugs into a bare `async` function or a LangChain / LlamaIndex / CrewAI / Autogen agent alike, and guides **every aspect** of its work: configuration, planning, compilation, contract validation, composition, observability, and evolution.

**See it in one command:**

```bash
apl integrate
```

That attaches the ladder to a plain agent and drives it across all seven lifecycle stages — here's the actual output:

```text
①  configure : genome=researcher model=claude-sonnet-5 tools=['web_search', 'read_file', 'summarize']
②③ plan+compile : 2 node(s), cost $0.0257 -> $0.0001 (99.7% saved)
④  validate : rejected a contract-violating task (ContractMismatchError)
⑤b patterns : strategy->premium, chain->fallback
⑤a compose  : budget guard active, remaining=$0.08, critic approved=True
⑥  observe  : 1 observer event(s); trace() fail-safe with no tracer = True
⑦  record   : 1 TaskResult(s) captured as fitness signal
⑦  evolve   : best_fitness [0.98, 0.98, 0.98, 0.98] (non-decreasing=True)
✅ The ladder guided the agent across all 7 lifecycle stages.
```

**Wire it into your own agent in 3 lines** — any `async (task: dict) -> dict` callable works:

```python
from agentlib.integration import AgentIntegration, FitnessEvaluator

async def my_agent(task: dict) -> dict:                 # ← YOUR agent (any framework)
    return {"answer": f"handled: {task['query']}", "cost": 0.02, "revenue": 1.0, "success": True}

guided = AgentIntegration(genome="researcher", budget=0.10,
                          fitness=FitnessEvaluator()).integrate(my_agent)
# `guided` is now a drop-in agent: contract-checked, budget-capped, traced, and self-recording.
```

### What each hook guides

| Aspect of work | Hook | Ladder level |
|---|---|:-:|
| 🧬 Identity / config | `.configure()` | L5 |
| 🗺️ Planning | `.plan()` | L10 |
| ⚙️ Workflow compilation | `.compile_plan()` | L11 |
| 🔒 Capability contracts | `.check_contracts()` · `.guard_step()` | L7–8 |
| 🧩 Composition | `.wrap()` | L6 |
| 🎛️ Design patterns | `.strategy()` · `.chain()` · `.observe()` | L9 |
| 🔭 Observability | `.trace()` | C1 |
| ♻️ Evolution | `.record()` · `.evolve()` | L12–14 |
| ⭐ **All at once** | `.integrate(agent, plan=…)` | — |

> Full contract, adapters for popular frameworks, and precise hook signatures: **[`docs/INTEGRATION.md`](docs/INTEGRATION.md)**. Runnable reference: **[`examples/integration_demo.py`](examples/integration_demo.py)**.

---

## 🎯 The claim, and the proof

The [interactive research page](index.html) argues: **agent development is stuck below Level 5** (the OOP-equivalent rung), while mainstream software engineering has built on Levels 5–11 — inheritance, functional composition, generics, interfaces, design patterns, metaprogramming, compilers — *for decades*. Levels 12–14 (agent OS, agent economy, autonomous discovery) are "nobody is building" territory.

This repo closes that gap with **code, not more prose** — every rung is an importable module with an automated test suite.

---

## 🪜 The ladder — what's implemented

```mermaid
flowchart TB
    subgraph L0_4 ["🟥 Levels 0–4 · below the abstraction floor"]
        direction TB
        A0["L0–L4 · prompts, loops, tools<br/><i>where most agents live today</i>"]
    end
    subgraph L5_11 ["🟩 Levels 5–11 · IMPLEMENTED here"]
        direction TB
        A5["L5 · Genomes &amp; inheritance<br/><code>agentlib/genome.py</code>"]
        A6["L6 · Functional composition<br/><code>agentlib/compose.py</code>"]
        A7["L7–8 · Contracts &amp; interfaces<br/><code>agentlib/contracts.py</code>"]
        A9["L9 · Design patterns<br/><code>agentlib/patterns.py</code>"]
        A11["L10–11 · Workflow compiler<br/><code>paradigm/agent_workflow_compiler.py</code>"]
        A5 --> A6 --> A7 --> A9 --> A11
    end
    subgraph L12_14 ["🟪 Levels 12–14 · 'nobody is building' — IMPLEMENTED here"]
        direction TB
        A12["L12–14 · Discovery loop<br/><code>agentlib/evolution.py</code>"]
    end
    L0_4 --> L5_11 --> L12_14
```

---

## 🏗️ How it fits together

```mermaid
flowchart LR
    G["🧬 AgentGenome<br/>(L5 · evolvable config)"] -->|specialize / mutate| C["🔧 Workflow Compiler<br/>(L11)"]
    C -->|dead-task elim<br/>model reroute<br/>batch · checkpoint · cache| P["📦 ExecutionPlan<br/>(optimized + priced)"]
    K["📇 Skill corpus<br/>(SKILL.md files)"] -->|discover + validate| H["🧪 Contract Harness<br/>(C2/C3)"]
    H -->|fitness signal| E["♻️ DiscoveryLoop<br/>(L12–14 · populations, elitism)"]
    G --> E
    E -->|published strategies| P
    E -.->|traces| O["🔭 Langfuse<br/>observability (C1)"]
```

The compiler and the evolution loop share the same genome type, and the evolution loop's **selection pressure is real** — it scores genomes by running the *actual* skill-contract validators against files on disk, not a mocked reward.

---

## 🧩 Components — C1 → C10

Each component maps to a specific ladder level and ships with its own tests. Full breakdown: [`docs/COMPONENTS.md`](docs/COMPONENTS.md).

| # | Level(s) | Component | Code | Tests |
|:-:|:-:|---|---|:-:|
| **C1** | infra | 🔭 Observability smoke test vs. a live Langfuse backend | [`verify_tracing.py`](verify_tracing.py) | live · exit 0 |
| **C2** | infra | 🧪 Skill-contract harness — discovers & validates `SKILL.md` | [`skilltest/harness.py`](skilltest/harness.py) | 45 ✓ |
| **C3** | infra | 📐 Frontmatter schema linter (semver `version` + `dependencies`) | [`skilltest/schema.py`](skilltest/schema.py) | ✓ |
| **C4** | infra | 🪝 Code-review queue hook wired to a real agent-loop event | [`hooks/skill-codereview/`](hooks/skill-codereview/) | live ✓ |
| **C5** | 5 · 6 | 🧬 `AgentGenome` + composition decorators (`with_critic`, `with_budget`, `pipe`) | [`agentlib/genome.py`](agentlib/genome.py) · [`compose.py`](agentlib/compose.py) | 13 ✓ |
| **C6** | 7 · 8 | 🔒 `SkillContract` + pre-execution pipeline type-checking | [`agentlib/contracts.py`](agentlib/contracts.py) · [`type_check.py`](agentlib/type_check.py) | 6 ✓ |
| **C7** | 9 | 🎛️ Observer / Strategy / Chain-of-Responsibility wrappers | [`agentlib/patterns.py`](agentlib/patterns.py) | 4 ✓ |
| **C8** | 11 | 🚦 CI pipeline gating `skills/**` & `scripts/**` | [`.github/workflows/skills-ci.yml`](.github/workflows/skills-ci.yml) | validated |
| **C9** | 10 · 11 | ⚙️ `compile(genome_spec) → ExecutionPlan` — inline · checkpoint · type-check | [`paradigm/agent_workflow_compiler.py`](paradigm/agent_workflow_compiler.py) | 4 ✓ |
| **C10** | 12 · 13 · 14 | ♻️ `DiscoveryLoop` — populations, fitness, elitism, run vs. real files | [`agentlib/evolution.py`](agentlib/evolution.py) · [`evolution_demo.py`](agentlib/evolution_demo.py) | live ✓ |

<details>
<summary><strong>🔬 Component deep-dive</strong> (click to expand)</summary>

- **C5 · Genomes & composition (L5–L6).** `AgentGenome` gives agents an inheritable, mutable *config type* with a registry (Factory pattern). `compose.py` adds **pure** decorators — `with_critic`, `with_budget`, `with_memory`, `pipe` — so behaviour is composed functionally instead of copy-pasted.
- **C6 · Contracts & types (L7–L8).** `SkillContract` declares a skill's typed input/output. `check_pipeline()` runs a **pre-flight type check** over a chain of steps *before* any execution or optimization — catching mismatches statically.
- **C7 · Design patterns (L9).** Observer, Strategy and Chain-of-Responsibility as thin wrappers over agent callables — the same reuse vocabulary mainstream engineering has had since the '90s.
- **C9 · The compiler (L10–L11).** Eight optimization passes: dead-task elimination, adjacent-cheap-inline, model rerouting, simple-task inlining, batch detection, checkpoint insertion, cache-key generation, budget guarding. The bundled `apl demo` fires most of them and reports a modeled **98.6%** cost cut.
- **C10 · Discovery loop (L12–L14).** A real evolutionary loop: a population of genomes, fitness = *actually running the C2/C3 validators on disk*, elitism-preserving selection, and published high-fitness strategies. Every generation is logged as a real observability trace.

</details>

---

## 📂 Project layout

```
agentic-paradigm-ladder/
├── apl_cli.py            # the `apl` entry point (one-liner front door)
├── pyproject.toml        # pip install -e . → `apl` console script
├── index.html            # the original interactive research page
├── agentlib/             # C5–C7, C10 — genomes, composition, contracts, evolution
├── skilltest/            # C2–C3 — SKILL.md contract & schema validation
├── paradigm/             # C9 — the workflow compiler
├── hooks/                # C4 — code-review queue hook
├── examples/             # bundled demo workflow + mini skill corpus
└── docs/                 # spec, gap analysis, verification logs, components guide
```

---

## 🤝 Contributing

PRs welcome. The bar is simple and enforced by CI:

```bash
pip install -e '.[test]'
apl test          # 72 tests must stay green
```

Every new skill contract must carry semver `version:` + a `dependencies:` list (C3), and every new pipeline step should declare a `SkillContract` (C6).

---

## 📜 License

[MIT](LICENSE) — build on it freely.

<div align="center"><sub>Research page compiled June 28, 2026 · implementation Levels 5–14 verified in <a href="docs/VERIFICATION-REPORT.md">docs/VERIFICATION-REPORT.md</a></sub></div>
