# Agent Continuity Protocol

## Persistence hierarchy

1. `messages`: portable user and assistant-visible content; the primary record.
2. `events`: append-only run, tool, checkpoint, and recovery events.
3. `checkpoints`: regenerable, cross-agent task summaries.
4. `native_states`: optional provider-specific continuation data.
5. indexes and caches: rebuildable and never authoritative.

A branch copies a portable-history starting point. A lease coordinates short-lived writes. An artifact record stores only path, hash, size, and metadata.

## Message reliability

Persist in this order:

```text
user message -> model call -> assistant result -> checkpoint
```

Assistant status is `complete`, `partial`, `failed`, or `pending`. A checkpoint or native-state failure must not roll back a successfully stored message.

## Recovery hierarchy

```text
probe manifest
  -> latest checkpoint and branch events
  -> expand(cursor, query, budget)
  -> older relevant events and artifacts
  -> full history as the last resort
```

A recovery response reports estimated `selected_tokens`, `more_available`, `next_cursor`, and coverage of goals, constraints, decisions, blockers, and next steps. Token estimates are conservative cross-provider approximations, not a model-specific tokenizer result.

Without an external summarizer, generate a local checkpoint from recent branch messages and preserve source message IDs. `--summary-json` may provide a better external summary.

## SQLite, spool, and maintenance

- Use WAL, foreign keys, and transactions. Commit a message and its `message.recorded` event together.
- When run, message, or finish persistence fails, append a complete record to `spool/<session_id>.jsonl` and `fsync` it.
- Recover the run before dependent records when possible, but preserve messages even if a run record is unavailable.
- Move successfully imported spool files to `spool/processed/` for auditability.
- Use event hashes plus message IDs or idempotency keys to prevent duplicate imports.
- `backup` uses SQLite online backup and applies configured retention.
- `prune` is dry-run unless `--apply` is explicit.

## Wrapper lifecycle

```text
begin-run
append-user
invoke Agent
append-assistant [--status partial]
finish-run
```

Manual skill calls cannot capture desktop messages that the integration never exposes.
