Metadata-Version: 2.4
Name: exec-kernel
Version: 0.2.0
Summary: Deterministic task lifecycle enforcement for multi-agent systems
Author: Autonomous Ventures
License-Expression: MIT
Project-URL: Homepage, https://github.com/AutonomousVentures/exec-kernel
Project-URL: Source, https://github.com/AutonomousVentures/exec-kernel
Project-URL: BugTracker, https://github.com/AutonomousVentures/exec-kernel/issues
Project-URL: Documentation, https://github.com/AutonomousVentures/exec-kernel
Keywords: agent,lifecycle,state-machine,task-management,workflow
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.31.0
Requires-Dist: pyyaml>=6.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-cov>=4.1; extra == "dev"
Provides-Extra: coordination
Requires-Dist: coordination>=0.1.0; python_version >= "3.12" and extra == "coordination"
Dynamic: license-file

# Execution Kernel

Deterministic task lifecycle enforcement for multi-agent systems.

## Overview

The execution kernel is a lightweight Python library and CLI tool that enforces
strict task lifecycle semantics across agent operations. It prevents infinite
work loops, skipped lifecycle states, and speculative busywork — ensuring
agents produce only valid, bounded, externally-valuable work.

The package is **lean by design** (~39 KB, ~1,050 LOC across 8 source files).
It focuses on one problem — task lifecycle discipline — and solves it without
framework lock-in or heavy dependencies. Only `requests` and `pyyaml` are required.

## Components

| Module | Responsibility |
|--------|---------------|
| `lifecycle.py` | State machine for task transitions (`todo` → `in_progress` → `done`, etc.) |
| `loop_detector.py` | Detection/prevention of self-generated work loops (depth, cycle, identity) |
| `budget.py` | Execution budget enforcement (steps, depth, wall-clock time) |
| `paperclip_adapter.py` | *Optional* adapter for the [Paperclip](https://opencode.ai) agent orchestration API. Provides `create_task`, `transition_task`, `checkout`, and idle enforcement that blocks speculative work when no tasks are available. Ships with the library so downstream projects can use it without an extra dependency, but is only activated when you construct a `PaperclipAdapter` — the CLI and core modules work without it. |
| `config.py` | YAML configuration loading with deep-merge defaults |
| `cli.py` | CLI entry point for shell/agent environments |
| `memory_hooks.py` | Memory-management hooks for tracking task context across sessions |

## Installation

```bash
pip install exec-kernel
```

With multi-agent coordination support:

```bash
pip install exec-kernel[coordination]
```

Or from source:

```bash
git clone <repo-url>
cd autonomous-ventures
pip install -e .
pip install -e ".[coordination]"   # include coordination support
```

## CLI Usage

Validate a state transition:

```bash
exec-kernel validate todo in_progress
# VALID: Work started

exec-kernel validate todo done
# INVALID: No valid transition from todo to done
```

Check for loops:

```bash
exec-kernel check-loop child-1 agent-1 feature --parent-task-id parent-1
# ALLOWED: depth=1
```

Check budget:

```bash
exec-kernel check-budget task-1 --steps 5 --max-steps 10
# OK: 5 steps, 0s elapsed (max 10 steps, 1800s)

exec-kernel check-budget task-1 --steps 15 --max-steps 10
# EXCEEDED: [steps] Task task-1 exceeded step budget: 15 steps taken, max 10
```

Enter idle sleep (no task generation allowed):

```bash
exec-kernel sleep --timeout 30 --agent-id agent-1
# SLEEP:idle agent=agent-1 reason=no_tasks timeout=30s
```

## Python API

### Lifecycle

```python
from kernel.lifecycle import TaskLifecycle, TaskState, InvalidTransitionError

task = TaskLifecycle(task_id="my-task")
task.transition(TaskState.IN_PROGRESS)   # "Work started"
task.transition(TaskState.DONE)          # "Work completed"

# Invalid transitions raise InvalidTransitionError
try:
    task.transition(TaskState.TODO)      # Terminal state — raises
except InvalidTransitionError as e:
    print(e.reason)                      # "Cannot transition from terminal state done"

# Safe checking
if task.can_transition_to(TaskState.BLOCKED):
    task.transition(TaskState.BLOCKED)
```

The full transition table:

| Current → | Allowed targets |
|-----------|----------------|
| `backlog` | `todo` |
| `todo` | `in_progress`, `cancelled`, `blocked` |
| `in_progress` | `done`, `blocked`, `cancelled`, `in_review` |
| `in_review` | `done`, `in_progress`, `blocked`, `cancelled` |
| `blocked` | `in_progress`, `cancelled`, `todo` |
| `done` | *(terminal — no transitions)* |
| `cancelled` | *(terminal — no transitions)* |

### Loop Detection

```python
from kernel.loop_detector import LoopDetector, WorkNode, LoopDetectionError

detector = LoopDetector(max_depth=10)

# Register the parent task first
detector.register_node(WorkNode(
    task_id="parent-1", agent_id="agent-1", task_type="research"
))

# Check a child — allowed within depth limit
depth = detector.check_new_task(
    "child-1", "agent-1", "research", parent_task_id="parent-1"
)
# depth=1

# Deep nesting past max_depth raises LoopDetectionError
try:
    detector.check_new_task(
        "deep-task", "agent-1", "research", parent_task_id="parent-1",
        created_by_task_id="parent-1"
    )
except LoopDetectionError as e:
    print(e.loop_type)  # "depth"
```

`LoopDetectionError` includes a `loop_type` field: `"depth"`, `"cycle"`, or `"identity"`.

### Budget Enforcement

```python
from kernel.budget import BudgetTracker, BudgetExceededError

tracker = BudgetTracker()
state = tracker.start_task("task-1", {"max_steps": 50})

# Record steps — raises if exceeded
for _ in range(50):
    tracker.record_step("task-1")  # Last one raises BudgetExceededError(budget_type="steps")

# Or check manually
state.check_all()          # checks steps + duration
state.check_depth(15)      # check proposed depth
```

When a budget is exceeded, `BudgetExceededError` is raised with:
- `.budget_type` — `"steps"`, `"depth"`, or `"duration"`
- Message with current vs. max values

### Paperclip Adapter (Optional)

The `PaperclipAdapter` integrates with [Paperclip](https://opencode.ai),
an open-source agent orchestration platform. It provides:

- `transition_task()` — atomically validate + apply lifecycle transitions via the Paperclip API
- `create_task()` — create new tasks with structured admission schema
- `sleep()` / `wake()` — idle enforcement that blocks speculative task generation
- `checkout()` — claim a task for execution

```python
from kernel.paperclip_adapter import PaperclipAdapter, TaskAdmission, TaskAdmissionError

adapter = PaperclipAdapter(
    api_url="https://api.example.com",
    api_key="...",
    agent_id="agent-1",
)

# Every task requires an admission schema — consumer, pain point, value, validation
admission = TaskAdmission(
    consumer="end-user",
    pain_point="login page is slow",
    expected_value="reduce load time by 40%",
    validation_path="benchmark test suite",
)
task = adapter.create_task("Optimize login", "performance", admission=admission)

# Idle enforcement: prevents task creation when no work is available
result = adapter.sleep()   # enter idle
# adapter.create_task(...)  # raises IdleEnforcementError
adapter.wake()             # resume
```

## Multi-Agent Coordination (Optional)

Install with the `coordination` extra to enable multi-agent message passing:

```bash
pip install exec-kernel[coordination]
```

The [coordination](https://github.com/AutonomousVentures/coordination) package provides
a FastAPI-based event queue and task dispatch system for connecting multiple agents.
When combined with exec-kernel's lifecycle enforcement, you get:

- **Deterministic task flow** — every agent transitions through `todo → in_progress → done`
- **Message passing** — agents enqueue and dequeue tasks via the coordination API
- **Escalation routing** — `EscalationHook` (included in exec-kernel) forwards blocked tasks
  to the coordination layer's escalation queue
- **Budget enforcement across agents** — each agent tracks its own budget independently

See the [getting-started tutorial](/AUT/issues/AUT-155#document-tutorial) for a complete
2-agent example.

## Configuration

Create `.exec-kernel.yml` in your project root:

```yaml
lifecycle:
  max_depth: 10
  max_heap_size: 1000

budget:
  max_steps: 50
  max_depth: 10
  max_duration_seconds: 1800
```

Values are deep-merged with defaults — omit any key to use the default.

## Architecture

```
┌─────────────────────────────────────────────┐
│  exec-kernel CLI / Python API               │
│  ┌──────────┐ ┌──────────────┐ ┌─────────┐  │
│  │Lifecycle │ │Loop Detector │ │ Budget  │  │
│  │State     │ │              │ │Enforce- │  │
│  │Machine   │ │              │ │ment     │  │
│  └──────────┘ └──────────────┘ └─────────┘  │
│  ┌────────────────────────────────────────┐  │
│  │ Paperclip API Adapter (optional)       │  │
│  └────────────────────────────────────────┘  │
└─────────────────────────────────────────────┘
```

### Error handling summary

| Operation | Failure | Exception | Exit code |
|-----------|---------|-----------|-----------|
| Invalid state transition | Transition not in table | `InvalidTransitionError` | 1 |
| Transition from terminal state | `done` or `cancelled` | `InvalidTransitionError` | 1 |
| Step budget exceeded | `steps_taken > max_steps` | `BudgetExceededError(budget_type="steps")` | 1 |
| Depth budget exceeded | `proposed_depth > max_depth` | `BudgetExceededError(budget_type="depth")` | 1 |
| Duration budget exceeded | `elapsed > max_duration_seconds` | `BudgetExceededError(budget_type="duration")` | 1 |
| Loop depth exceeded | Nesting past `max_depth` | `LoopDetectionError(loop_type="depth")` | 1 |
| Cycle detected | Task creates ancestor chain | `LoopDetectionError(loop_type="cycle")` | 1 |
| Identity match | Agent re-creates identical task | `LoopDetectionError(loop_type="identity")` | 1 |
| Task creation while idle | `sleep()` active | `IdleEnforcementError` | 1 |
| Incomplete admission schema | Missing required field | `TaskAdmissionError` | – |

On CLI failure, the exit code is always 1 with a descriptive message on stderr.

## Development

```bash
pip install -e ".[dev]"
pytest tests/ -v
```

## License

MIT — see [LICENSE](/LICENSE).

## Maintainer

Published by [Autonomous Ventures](https://github.com/AutonomousVentures).  
Latest release: v0.2.0 (May 2026) — adds `coordination` optional dependency.  
Initial release: v0.1.0 (May 2026). Beta — `Development Status :: 4 - Beta`.

This is a focused, minimal library (~39 KB, 1,050 LOC). It is designed to solve one
problem well rather than be a general-purpose framework. Contributions welcome.
