packages feed

canontra-0.4.0.0: HARNESS.md

# Canontra AI Harness Sub-Versioning (`canontra snap`)

> [!IMPORTANT]
> **Alpha Feature Notice (`schema_version: "0.1-alpha"`, `stability: "alpha"`)**  
> `canontra snap` is an **experimental Alpha** subsystem introduced in Canontra `v0.4.0`. Command flags and JSON response fields (`0.1-alpha`) may evolve prior to `v1.0`. It is designed strictly as a **local, stateless CLI tool** for developer machines and local AI coding agent workspaces, never as a network service or background daemon.

## Overview

`canontra snap` gives AI coding agents, CLI wrappers, and automated refactoring loops sub-commit semantic checkpoints without touching `.git/index`, creating noisy WIP commits, or spawning background IPC daemons.

Each invocation runs synchronously as a short-lived CLI process, reads or updates local content-addressed state inside `.canontra/snaps/`, emits human-readable or `--json` output, and exits immediately with deterministic POSIX exit codes.

### Core Design Guarantees

* **Zero Background Daemons & Zero IPC**: Every `canontra snap` call starts, executes, and exits cleanly with no resident server, named pipe, or port binding.
* **Zero `.git` Mutation**: Never runs `git add`, `git commit`, `git stash`, or `git reset`. User git history and staging state remain completely untouched.
* **Auto-Excluded Storage**: `canontra snap init` automatically creates `.canontra/.gitignore` so local CAS blobs, manifests, and slab caches never appear as untracked git noise.
* **Air-Gapped & Pure Haskell**: Zero C-FFI bindings, zero network sockets, and zero telemetry.
* **9-Tier Semantic Triage**: Distinguishes formatting/comment churn (`semantic_noop`) from private implementation edits (`internal_logic`) and public signature/dependency/contract changes (`contract_change`).

## On-Disk Storage Layout

All harness state resides under `.canontra/snaps/` relative to the repository root (`--dir`):

```text
.canontra/
├── .gitignore                 # Auto-created ("*") to keep local state out of Git
├── cache.bin                  # Shared CNTR\x07 incremental slab + FileGraphSummary cache
└── snaps/
    ├── HEAD                   # Active snap_id (atomic swap on write)
    ├── ledger.jsonl           # Append-only chronological turn metadata log
    ├── objects/
    │   └── <aa>/
    │       └── <sha256>       # Deduplicated raw source blobs keyed by F0 SHA-256
    └── manifests/
        ├── snap_0.json        # Immutable initial baseline snapshot
        └── snap_<ts>_<hash>.json
```

## Subcommand Reference

All subcommands accept `-d, --dir DIR` (repository root, defaults to `.`) and `--json` (machine-readable output), either before or after the subcommand name.

| Subcommand | Purpose | Key Options |
| :--- | :--- | :--- |
| `canontra snap init` | Create `.canontra/snaps/`, auto-create `.canontra/.gitignore`, and record baseline `snap_0` | `--dir DIR`, `--json` |
| `canontra snap mark` | Re-scan workspace via warm `CNTR\x07` cache, store new `F0` blobs, classify changes, advance `HEAD` | `-l/--label LABEL`, `-a/--agent AGENT`, `--skip-noop`, `--dir DIR`, `--json` |
| `canontra snap diff` | Compare `[FROM]` against `[TO]` (`HEAD` or `WORKTREE`) with symbol diffs and test slices | `[FROM]` (default `HEAD`), `[TO]` (default `WORKTREE`), `--compact`, `--dir DIR`, `--json` |
| `canontra snap guard` | Enforce semantic boundary policy against `--against` by forbidding specified tier mutations | `--against SNAP_ID`, `--forbid TIERS`, `--allow-paths GLOB` (repeatable), `--dir DIR`, `--json` |
| `canontra snap rewind` | Restore workspace (or specific files) to `SNAP_ID` after preflight path + SHA-256 verification | `SNAP_ID`, `-f/--file PATH` or `[FILES...]`, `--dry-run`, `--dir DIR`, `--json` |
| `canontra snap log` | Print reverse-chronological turn history from `ledger.jsonl` and current `HEAD` | `-n/--limit N` (default `20`), `--dir DIR`, `--json` |
| `canontra snap gc` | Prune older manifests (always preserving `snap_0` and `HEAD`) and sweep unreferenced CAS blobs | `--keep-last N` (default `50`), `--dir DIR`, `--json` |

### Semantic Classifications & Severity Levels

Every snapshot checkpoint and diff computes one of four turn-level classifications:

| Classification | Condition | Default File Severity Tiers Included |
| :--- | :--- | :--- |
| `no_change` | Identical `F0` source hashes across every tracked file | None |
| `semantic_noop` | `F0` changed, but `F1..F4` and `F_T` remained invariant (formatting, comments, docstrings, pure local $\alpha$-renaming) | `Level1_Trivia` |
| `internal_logic` | Body semantics (`F1`, `F_CG`, `F_CF`, `F_DF`, `F4`) changed without altering public APIs or dependencies | `Level2_Logic` |
| `contract_change` | Files added/deleted or public declarations (`F2`), dependencies (`F3`), or structural types (`F_T`) changed | `Level3_Contract` |

### Guard Tiers (`--forbid`)

Valid comma-separated tier tokens accepted by `canontra snap guard --forbid`:
`F0`, `F1`, `F2`, `F3`, `F_CG` (`FCG`), `F_CF` (`FCF`), `F_DF` (`FDF`), `F_T` (`FT`), `F4`.

### POSIX Exit Codes

* `0`: Success (or `snap guard` policy passed with zero violations).
* `1`: Policy violation detected by `snap guard`.
* `2`: Invalid CLI flags or missing required options.
* `4`: Unsafe snapshot ID (`..`, `/`, `\`), path-traversal violation, missing snapshot/blob, or SHA-256 verification failure.

## Agent Loop Workflow Example

A coding harness wrapping an LLM edit loop typically follows this sequence:

```bash
# 1. Establish baseline before an agent session begins (zero Git changes)
canontra snap init --json

# 2. Agent applies an edit, then checkpoints its turn
canontra snap mark --label "refactor-helper" --agent "coding-agent" --skip-noop --json

# 3. Verify no forbidden public contract tiers (F2, F3, F_T) broke during a refactor
canontra snap guard --against snap_0 --forbid F2,F3,F_T --allow-paths "tests/**" --json

# 4. If guard returns exit code 1 or tests fail, inspect compact diff or roll back safely
canontra snap diff snap_0 HEAD --compact --json
canontra snap rewind snap_0 --dry-run --json
canontra snap rewind snap_0 --json

# 5. Audit turn history or prune obsolete snapshots at session end
canontra snap log -n 10 --json
canontra snap gc --keep-last 10 --json
```

### Example JSON Payloads (`0.1-alpha`)

#### `canontra snap guard --against snap_0 --forbid F2,F3,F_T --json` (Exit Code `1`)

```json
{
  "against_snap_id": "snap_0",
  "allow_paths": [],
  "allowed_skipped": [],
  "elapsed_ms": 5.3398,
  "forbidden_tiers": ["F2", "F3", "F_T"],
  "passed": false,
  "schema_version": "0.1-alpha",
  "stability": "alpha",
  "violations": [
    {
      "mutated_tiers": ["F0", "F1", "F2", "F_CF", "F_DF", "F4"],
      "path": "app.py",
      "severity": "Level3_Contract",
      "status": "modified",
      "violated_tiers": ["F2"]
    }
  ]
}
```

#### `canontra snap diff snap_0 HEAD --compact --json`

```json
{
  "classification": "contract_change",
  "compact": true,
  "elapsed_ms": 11.4,
  "from_snap": "snap_0",
  "level1_trivia_count": 0,
  "level2_logic": [],
  "level3_contract": [
    {
      "invariant_tiers": ["F3", "F_CG", "F_T"],
      "mutated_tiers": ["F0", "F1", "F2", "F_CF", "F_DF", "F4"],
      "path": "app.py",
      "severity": "Level3_Contract",
      "status": "modified"
    }
  ],
  "recommended_tests": [],
  "schema_version": "0.1-alpha",
  "stability": "alpha",
  "symbol_changes": [
    {
      "action": "signature_modified",
      "detail": "Function signature altered",
      "file": "app.py",
      "symbol": "Function: compute"
    }
  ],
  "to_snap": "snap_20261130T181733297Z_3809be13"
}
```

## Performance Characteristics (Measured on `v0.4.0`)

Measured with `-O2` binaries on Windows 11 x86_64:

* **In-Memory Kernel Microbenchmarks (RQ19, `tasty-bench`)**:
  * `diffFileBundles` (single-file 9-tier comparison): **`733.1 ns`**
  * `computeFileDeltas` (1,000 tracked files, 1 dirty): **`1.73 ms`**
  * `classifySnapDeltas`: **`19.9 ns`**
  * `parseGuardTiers`: **`733.1 ns`**
  * `matchesGlob`: **`5.9 us`**
* **End-to-End Warm CLI `snap mark --skip-noop` Across 15 Real Repositories** (includes process startup + full directory walk + `CNTR\x07` cache check + whole-repo graph/manifest check):
  * Small/Medium Python & JS repos (`chalk`, `requests`, `marshmallow`, `bottle`, `jinja`, `click`, `gin`, `flask`): **`143.61 ms` – `440.52 ms`**
  * Large Rust/Go monorepos (`ripgrep` `477.16 ms`, `deno_core` `1,352.99 ms`, 994-file / 408k-LOC `prometheus` `3,978.55 ms`, `hugo` `5,022.56 ms`).

## Security & Rollback Safety

Every `snap rewind` operation runs a two-phase preflight before modifying any workspace file:

1. **Snapshot ID & Path Containment**: `isSafeSnapId` rejects traversal tokens (`..`, `/`, `\`) with POSIX exit code `4`. Every restored or removed path is validated with both `isSafeRelativeFilePath` and `canonicalizeSafePath` against the repository root.
2. **Cryptographic CAS Integrity**: Every source blob required for rollback is read from `.canontra/snaps/objects/` and SHA-256 verified against the manifest's `f0` digest (`readVerifiedBlob`) **before** any file on disk is written or deleted.
3. **Untracked User File Preservation**: Full snapshot rewinds only delete files that were tracked in the current `HEAD` manifest and absent from the target snapshot, never deleting unrelated untracked user files.
4. **Atomic Writes**: File writes use temporary `.tmp.<pid>` staging files swapped atomically with exponential backoff retry (`atomicSwapWithRetry_`).

For full threat model and reporting instructions, see [SECURITY.md](SECURITY.md).