Metadata-Version: 2.5
Name: vectl
Version: 0.9.3
Summary: Execution control plane for AI agents — structure agents, save tokens.
Project-URL: Homepage, https://github.com/Tefx/vectl
Project-URL: Repository, https://github.com/Tefx/vectl
Project-URL: Issues, https://github.com/Tefx/vectl/issues
Author-email: Tefx <zhaomeng.zhu@gmail.com>
License: 
                                         Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to the Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by the Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding any notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           Copyright 2025 Tefx
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
License-File: LICENSE
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Build Tools
Classifier: Typing :: Typed
Requires-Python: >=3.12
Requires-Dist: deal>=4.24.6
Requires-Dist: fastmcp>=2.0.0
Requires-Dist: invar-runtime>=1.3.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: pyyaml>=6.0
Requires-Dist: returns>=0.27.0
Requires-Dist: rich>=13.0.0
Requires-Dist: typer>=0.9.0
Requires-Dist: typing-extensions>=4.15.0
Requires-Dist: watchfiles>=1.1.0
Description-Content-Type: text/markdown

# vectl — execution control plane for AI agents

[中文文档](README_zh.md) | [**Read the Introduction**](https://tefx.one/posts/vectl-intro/)

**Structure agents. Enforce discipline.**

[![PyPI](https://img.shields.io/pypi/v/vectl)](https://pypi.org/project/vectl/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)

```bash
uvx vectl --help
```

## Markdown Can't Control Your Agent

A 200-step plan in TODO.md. You expect the agent to follow the order, check off completed items, and never skip ahead.

In practice? **Agents treat TODO.md as a suggestion, not a rule.** They skip steps, forget to mark things done, or get lost in a 1000-line plan and redo work that's already finished. The more you try to hint at structure with comments, bold text, and separators, the worse it gets — because Markdown is just natural language text, and agents have zero obligation to obey it.

The core problem: **TODO.md is advice, not enforcement. You can't force an agent to claim a step before starting, or submit evidence before marking it complete.**

This is a structural defect in Markdown, not a flaw in your agent:

- **No enforcement**: you can't prevent agents from skipping steps or require proof of completion
- **No dependencies**: "Deploy DB" before "Config App" — the agent can only guess the ordering, and nothing stops it from guessing wrong
- **Multi-agent conflicts**: multiple agents online with no coordination — they can't tell which steps are parallelizable, and simultaneous edits silently overwrite each other
- **Completion by self-declaration**: the agent says "Done" and that's it — you can't require it to prove tests actually passed

These problems are tolerable at 10-20 steps. At hundreds of steps with multiple agents, TODO.md falls apart completely.

> TODO.md can't say no. vectl can.

## Control Plane, Not a Framework

Agent frameworks manage how agents think. vectl manages **what agents see, when they see it, and what they must prove**.

| Capability | Problem Solved | Mechanism |
| :--- | :--- | :--- |
| **DAG Enforcement** | Agents skip dependencies, guess ordering | Blocked steps are invisible — agents literally *cannot* claim them |
| **Evidence Required** | Agent says "Fixed" and moves on | `evidence_template` forces fill-in-the-blank proof: command, output, PR link |
| **Safe Parallelism** | Multiple agents step on each other | `claim` locking + CAS atomic writes |
| **Auto-Dispatch** | Someone must watch and assign tasks | `next` computes all unblocked steps and sorts them; rejected steps float to top |
| **Token Budget** | Agent re-reads hundreds of completed lines | Hard limits across the board: next ≤3, context ≤120 chars, evidence ≤900 chars |
| **Context Compaction** | Long conversations cause agent amnesia | `checkpoint` generates a deterministic JSON snapshot — inject into new session for instant recovery |
| **Handoff Notes** | Agents lose state between hosts/sessions | `clipboard-write/read/clear` stores short notes in `plan.yaml` (with TTL) |
| **Agent Affinity** | Different agents are good at different tasks | Steps can suggest an agent; `next` sorts by affinity |

## Claiming: single-step vs batch claim

Single-step `claim` remains the normal path for one worker taking one step. Use
CLI `vectl claim <step-id>` or MCP `vectl_claim` when the caller is claiming a
single decided step.

Batch claim is only for orchestrators that have already decided explicit
step-to-agent assignments and need one atomic commit. Use CLI `vectl claim-many`
or MCP `vectl_claim_many` with an explicit list of `{step_id, agent}` requests.
It is not dispatch, selection, or reservation. Non-goals: no count,
no auto-select, no dispatch policy, no reserve_steps. Batch persistence is
CAS-guarded and uses the existing best-effort Git commit path.

`refs` are advisory context. Vectl persists supplied references and
`validate --check-refs` may report warnings, but references do not block a
claim or Plan mutation.

## Linked Git worktrees

An implicit CLI command or MCP request started in a linked worktree targets the
main worktree's `plan.yaml`. Vectl fixes the Plan path, shared claims path, and
branch from that integration worktree before the operation starts. Claims,
completion/defer/skip cleanup, diagnostics, repair, duplicate-ID migration,
batch claim, Git commits, and backups therefore use one authority.

Use `--plan` or `VECTL_PLAN_PATH` only when intentionally targeting another
Plan. A CLI command targeting a Plan in another Git repository writes that Plan
without autosaving a commit in the caller's repository. MCP commits, when
configured, remain attached to its resolved target Plan repository.

## Quick Start

### 1. Initialize

```bash
uvx vectl init --project my-project
```

Creates `plan.yaml` and appends a vectl section to the agent instruction file (`CLAUDE.md` or `AGENTS.md`). If the file already exists, your existing content is preserved — vectl only adds its own section.

> Commit `plan.yaml` + `AGENTS.md`/`CLAUDE.md` together. The plan is the state machine; the instructions file is the agent entry point.

### 2. Connect Your Agent

Recommended: connect via MCP for structured tool access.

<details>
<summary>⚡ MCP (recommended)</summary>

```json
{
  "mcpServers": {
    "vectl": {
      "command": "uvx",
      "args": ["vectl", "mcp"]
    }
  }
}
```

vectl exposes 20 MCP tools. Agents call `vectl_status`, `vectl_claim`, `vectl_complete`, `vectl_decide`, etc. directly — structured data in, structured data out.

For OpenCode, add to your `opencode.jsonc`:

```jsonc
{
  "mcp": {
    "vectl": {
      "type": "local",
      "command": ["uvx", "vectl", "mcp"]
    }
  }
}
```

See [OpenCode MCP docs](https://opencode.ai/docs/mcp-servers/) for details.
</details>

<details>
<summary>⌨️ CLI (no MCP)</summary>

No setup needed — agents call `uvx vectl ...` directly. Works everywhere, but agents must parse text output instead of structured data.

> `uvx vectl init` already creates/updates the agent instructions file.
> To update later: `uvx vectl agents-md` (use `--target claude` if needed).
</details>

#### Agent Instruction Files

`vectl init` and `vectl agents-md` manage the agent instruction file in your repo.

That file is the *entry point* for agents: it points to `uvx vectl guide` topics and sets the rules (one claimed step at a time, evidence required, don't guess specs).

```bash
uvx vectl agents-md                 # Update AGENTS.md / CLAUDE.md with vectl section
uvx vectl agents-md --target claude # Force CLAUDE.md
```

### 3. Write the Plan

Tell your agent what you need — it will generate and modify the plan through vectl's `mutate` tool. **Do not hand-edit `plan.yaml` or let agents edit it directly** — all modifications must go through vectl tools to ensure validation, lock recalculation, and concurrency safety.

### 4. Migrate (Optional)

If your project already tracks work in a markdown file, issue tracker, or spreadsheet, tell your agent:

```
Read the migration guide (via `uvx vectl guide --on migration` or `vectl_guide` MCP tool).
Migrate our existing plan to plan.yaml.
Prefer MCP tools (`vectl_mutate`, `vectl_guide`) over CLI if available.
```

### 5. Monitor Progress
As a user, your main job is to **review progress** and **make decisions**:

```bash
uvx vectl top              # Live terminal progress panel (auto-updates on plan changes)
uvx vectl render           # Markdown progress report
uvx vectl dashboard --open # Visual HTML dashboard (static, no server)
```

`vectl top` is the lightweight terminal view for keeping a panel open while agents work. It watches the plan files and redraws only when the plan changes, so it avoids high-frequency repainting. To stay readable in normal terminal panes, it automatically folds earlier completed phases, keeps the latest and not-done phases visible, and exits with `q` or Ctrl-C.

![Dashboard Overview](docs/dashboard-overview.png)

The dashboard includes progress overview, phase status, and DAG dependency graphs. Open in any browser — no server required. The DAG view loads Mermaid.js from a CDN (network required for that tab).

Everything else is in the guide:

- Architect protocol: `uvx vectl guide --on planning`
- Getting unstuck: `uvx vectl guide --on stuck`
- Review / validation: `uvx vectl guide --on review`
- Migration: `uvx vectl guide --on migration`

## Handoffs: Clipboard (Notes) vs Checkpoint (State)

If you're switching agent hosts (Claude Code ↔ OpenCode ↔ Claude Desktop) or handing work between agents, use both:

- **Clipboard**: short, human-readable notes that live in `plan.yaml` (with TTL).
- **Checkpoint**: compact, machine-readable state snapshot for context injection.

### Clipboard (recommended for handoffs)

Use this when you want to pass **actionable notes** between agent hosts/sessions without creating extra files.

Example: Claude Code did a detailed code review, found a few small issues, and you want OpenCode to patch them.
Drop the review notes into the clipboard — the other agent reads and applies.

```bash
uvx vectl clipboard-write \
  --author "claude-code" \
  --summary "Code review: small fixes" \
  --content "
Target: src/foo.py

Issues:
- Rename X to Y (see comment in function bar)
- Add missing test for edge case Z
- Run: uv run pytest tests/test_foo.py
"

uvx vectl clipboard-read
uvx vectl clipboard-clear
```

MCP equivalent:

```python
vectl_clipboard(action="write", author="claude-code", summary="Code review: small fixes", content="...")
vectl_clipboard(action="read")
vectl_clipboard(action="clear")
```

### Checkpoint

```bash
uvx vectl checkpoint
```

Paste the JSON into the next session's system prompt.

## Data Model (`plan.yaml`)

```yaml
version: 1
project: my-project
phases:
  - id: auth
    name: Auth Module
    context: |
      All auth steps must follow OWASP guidelines.
      Test with both valid and malformed JWTs.
    depends_on: [core]
    steps:
      - id: auth.user-model
        name: User Model
        status: claimed
        claimed_by: engineer-1
```

A YAML file. In your git repo.

No database. No SaaS. `git blame` it. Review it in PRs. `git diff` it.

**Phase Context**: Set `context` on a phase to give agents guidance that applies to all steps within it. When an agent runs `vectl show <step>` or `vectl claim`, phase context appears automatically in the output.

Full schema, ID rules, and ordering semantics: [docs/DESIGN.md](docs/DESIGN.md).

## Checklist Updates: Human Toggle vs Deterministic Receipts

vectl supports two separate checklist update paths:

1. **Legacy human keyword toggle** — for interactive use:
   ```bash
   uvx vectl check STEP_ID KEYWORD
   ```
   The keyword path does a case-insensitive human match, toggles the matched
   item, prints `Updated checklist: <step>`, and points follow-up review at
   `vectl show <step>`. It does not use item IDs, revisions, or a target
   `checked` value.

2. **Deterministic inventory/mutation** — for orchestrators and automation:
   ```bash
   uvx vectl check-inventory STEP_ID --json
   uvx vectl check STEP_ID \
     --revision <checklist_inventory_revision> \
     --item-id <item_id> \
     --checked true \
     --json
   ```
   `check-inventory --json` returns parseable JSON with
   `checklist_inventory_revision`, `items`, and each item's `item_id`, `field`,
   `index`, `text`, and `checked` values. Deterministic mutation changes only the
   `- [ ]` / `- [x]` marker for the exact item; surrounding text and ordering are
   preserved.

First-version deterministic checklist support is intentionally limited to the
`description` and `verification` step fields. `evidence_template` checklists are
deferred/unsupported for deterministic inventory and mutation.

The revision is scoped to the current checklist inventory for the supported
fields. If the revision is stale, deterministic mutation fails without changing
state and returns a structured `stale_revision` error with retry action
`refresh_inventory`.

Batch deterministic mutation is also supported and is all-or-nothing:

```bash
uvx vectl check STEP_ID \
  --revision <checklist_inventory_revision> \
  --batch '[{"item_id":"description:0:<hash>","checked":true}]' \
  --json
```

Any stale, invalid, unsupported, or ambiguous selector prevents partial mutation
and returns structured diagnostics. Machine-readable CLI JSON is emitted without
Rich/ANSI styling.

MCP exposes the same deterministic fields through `vectl_check`: use
`inventory=true` to read inventory, or pass `revision` plus either `item_id` or
`field`/`index` with boolean `checked` to mutate. Batch MCP calls use `requests`.

### Worker/orchestrator receipt flow

In orchestrated work, the orchestrator owns actual checklist mutation. Workers
must not call vectl checklist tools or perform natural-language fuzzy mapping.
Instead, workers return exact receipts using item IDs and the inventory revision
they were given:

```yaml
checklist_receipt:
  - item_id: "description:0:<hash>"
    revision: "<checklist_inventory_revision>"
    checked: true
```

The orchestrator validates the receipt schema, refreshes current inventory when
needed, rejects stale receipt revisions, and applies only valid item-id/revision
requests.

## Lock Consistency
Lock status is automatically maintained — agents do not need to manage it. After any write operation (`claim`, `complete`, `mutate`, etc.), vectl recalculates lock status automatically. When a recalculation changes a phase's lock state, vectl emits an informational message:

```
[vectl] Lock status updated: phase-a (pending)
```

### Atomic MCP mutation batches
The MCP `vectl_mutate` tool accepts either its single-action form or a non-empty `requests` list; callers must select exactly one mode. Every batch request is selected by `action`, and create operations require an explicit ID: `add-phase` uses `phase_id`, `add-step` uses `step_id`, and each `add-steps` entry uses `id`.

| Batch action | Allowed fields after `action` |
|---|---|
| `add-phase` | `phase_id`, `name`, `depends_on`, `gate` |
| `add-step` | `phase_id`, `step_id`, `name`, `description`, `depends_on`, `verification`, `evidence_template`, `refs`, `status`, `evidence`, `skipped_reason`, `agent` |
| `add-steps` | `phase_id`, `steps` (`id` and `name` required per entry) |
| `edit-phase` | `phase_id`, `name`, `context`, `gate`, `depends_on` |
| `edit-step` | `step_id`, `new_step_id`, `name`, `description`, `depends_on`, `verification`, `evidence_template`, `agent`, `add_refs`, `remove_refs`, `refs` |
| `remove-step` | `step_id`, `force` |
| `move-step` | `step_id`, `target_phase` |
| `edit-plan` | `project_guidance`, `strategy_ref`, `plan_context` |

This complete payload creates a phase and two ordered steps. The first step persists file references through `refs`; `add_refs` and `remove_refs` apply only to `edit-step`.

<!-- vectl-mutate-batch-example:start -->
```json
{
  "requests": [
    {
      "action": "add-phase",
      "phase_id": "mcp-contract-example",
      "name": "MCP Contract Example"
    },
    {
      "action": "add-step",
      "phase_id": "mcp-contract-example",
      "step_id": "mcp-contract-example.implement",
      "name": "Implement the contract",
      "refs": [
        "src/vectl/mcp_core_mutation_tools.py",
        "README.md"
      ]
    },
    {
      "action": "add-step",
      "phase_id": "mcp-contract-example",
      "step_id": "mcp-contract-example.verify",
      "name": "Verify the contract",
      "depends_on": ["mcp-contract-example.implement"],
      "refs": ["tests/test_mcp_mutate_batch.py"]
    }
  ]
}
```
<!-- vectl-mutate-batch-example:end -->

Requests run in order against one deep working copy. Shape errors are rejected before Plan load and identify the zero-based request index, action, allowed fields, and common field-remediation hints. Any request or final-validation failure discards the working copy without writing Plan or claim state. Both single-action and batch final validation collect every non-warning issue in validator order before the admitted save boundary. Canonical Pydantic diagnostics retain a location component only when the expected `Plan`, `Phase`, `Step`, `Clipboard`, or `RejectionEntry` schema admits that field or list index, and retain an error type only when Pydantic Core declares it as built-in; unknown locations become `<field>` and unknown/custom types become `validation_error`. Pydantic `msg`, raw input, context, and documentation URLs are never copied. An unexpected canonical extraction/normalization failure or structural-validator exception returns one fixed pre-save `unexpected_validation_error` issue without exception or candidate text. Ordinary structural diagnostics keep their actionable identifiers, with controls escaped and each issue capped at 512 codepoints. The response reports `validation_source` (`canonical_model` or `structural`), full/rendered counts, `issues_truncated`, and `issue_values_truncated`. `max_issues=N` renders at most N issue rows; `max_issues=None` renders every row. Success performs one lock recalculation and one CAS save, then returns ordered request results, `plan_hash`, and any lock notice. Plan-file persistence remains authoritative; the following Git commit attempt is best effort and has no transactional rollback guarantee. This batch form is MCP-only and does not add a generic CLI batch command.

### Scoped MCP review diagnostics

`vectl_review` keeps `scope="global"` as its compatibility default. `scope="phase"` requires `phase_id`; its render projection stays target-only while validation includes the target's transitive phase dependencies. `scope="active_dependency_closure"` includes executable or recoverable phases, their transitive phase dependencies, and declared dependencies of pending, claimed, or rejected steps. Scoped validation also retains Plan-wide duplicate phase/step-ID blockers. `description`, `verification`, `evidence`, `Phase.gate`, and legacy `<vectl_gate_scope>` blocks are ordinary displayed text: they neither create validation issues nor expand review scope or gate readiness. Global review remains the complete full-history path.

With `max_issues=N`, each bounded collection gets its own N-row budget: L1 issues; L2 phase rows; L3 phase headers and one global step-row budget; L3 phase-dependency and step-dependency links, each with a global N-link budget; L4 ref rows and one global N-link budget; and gate pending-step and downstream-phase rows. Current errors render first, then current warnings and historical warnings. Every rendered user-controlled scalar is control/newline escaped and capped at 160 codepoints after escaping; L1 issue messages use 512. The complete response has a fixed 65,536-codepoint cap. If that final guard triggers, Vectl returns a metadata-only safety summary, sets every detail `rendered_*` count to zero, and sets `output_safety_truncated: true`.

Every affected section publishes pre-bound `total_*`, actual surviving `rendered_*`, count-truncation flags, and section value-truncation flags; L4 also publishes `ref_detail_truncated`. Count flags compare total with actual rendered rows/links. Value flags describe clipping among rendered values, while omitted rows are represented by count flags. `max_issues=None` preserves every review row, link, and value and does not apply the bounded review scalar or 65,536-codepoint caps.

If you edit `plan.yaml` directly (outside of vectl commands), run `uvx vectl recalc-lock` to manually diagnose and repair any lock inconsistencies.

### Optional Plan mutation admission

Vectl supports a startup-frozen local adapter for covered Plan-definition mutations. Leave all three variables absent for the default `not_configured` behavior, or set the complete tuple before starting the CLI/MCP process:

```bash
export VECTL_PLAN_ADMISSION_EXECUTABLE=/absolute/path/to/adapter
export VECTL_PLAN_ADMISSION_EXECUTABLE_SHA256=sha256:<64-lowercase-hex>
export VECTL_PLAN_ADMISSION_TIMEOUT_SECONDS=30
```

A partial or invalid tuple fails closed. The private transaction hashes the authoritative raw Plan bytes for CAS, serializes the finalized candidate once, requires adapter approval bound to `candidate_sha256`, and atomically persists those identical bytes. MCP `vectl_mutate` (single and batch) and CLI `add-step`, `add-steps`, `edit-step`, `remove-step`, `move-step`, `add-phase`, `edit-phase`, and `edit-plan` use this transaction. Successful covered mutations expose `mutation_receipt: <JSON>` with schema `vectl.plan-mutation.receipt.v1`; its `plan_applied` and `git_committed` fields remain separate because Git is best effort. Each successful CLI route prints its existing command-specific human-readable prefix first, preserves its notices, details, and hints, and emits exactly one complete receipt line as the final output record. Validation, configured admission, CAS, persistence, and receipt-validation failures emit no receipt. Explicit CLI Plan paths outside the current repository remain Plan-only and report `git_attempted: false`.

The adapter is trusted same-UID local operator configuration. Diagnostic sanitization provides best-effort bounded hygiene against accidental disclosure in ordinary adapter errors. It does not provide sandboxing, credential isolation, or containment against a malicious or compromised adapter, which can already read same-UID resources and mutate repository state. Deliberately control-split fields, multiple-`@` malformed authorities, double-percent encoding, arbitrary Unicode whitespace obfuscation, and parser ambiguities are outside this diagnostic contract.

The sanitizer returns fixed `admission diagnostic unavailable` when raw bytes or decoded text exceed 8192 units or a Python `str` contains a surrogate code point. Otherwise it captures ordinary complete `Authorization: Bearer <payload>`, `Authorization: Basic <payload>`, and `Authorization: Digest <payload>` fields and common `authorization`, token/password/passwd, `api_key`/`api-key`/`apikey`, credential, and secret assignments before protected Plan matching; captured values become `<redacted>`. Obvious opaque tokens, exact or distinctive Plan-derived scalar values, temporary paths, and absolute POSIX path tails are also replaced. Stable error codes, contract field paths, and violation classes remain useful; diagnostic subjects become `<step-id>`, protected values become `<plan-content>`, and normalized output is capped at 1024 codepoints.

URLs use ordinary lexical matching and one percent-decoding pass. Syntactically ordinary userinfo and common secret-like path, query, or fragment components redact the entire URL. Genuinely safe URLs remain byte-for-codepoint unchanged, including when later prose contains an email address or `@mention`. Semantic placeholders are restored in reverse creation order so `<admission-temp>` remains correct when nested in a preserved safe URL. Before creating the workspace, Vectl rejects a repository-local temporary parent. Workspace/private-file failures use `admission private file setup or write failed`; non-string decisions use `admission verdict decision is invalid`; read failures use `admission verdict file is unavailable`. Initial base/candidate identity setup failures use fixed text, and inputs that are missing, unreadable, replaced, or no longer regular produce a fixed zero-write identity failure. The complete boundary is in [the admitted mutation RFC](docs/RFC-admitted-plan-mutation.md).

For selected-execution checks, `tests/expected_red.py run` emits pytest's real nonzero `exit_code` and `outcome: "red"` in the inner evidence envelope, then the outer adapter process exits 0 so the production Gate can parse the result. Outer 0 confirms transport only; the inner fields remain the test outcome.

## Claim Recovery (Ghost Claims & Split-Brain)

When claim state diverges from plan state, you may encounter errors like:
```
Step 'foo.bar' is already claimed on branch 'main'
```
But `vectl show foo.bar` shows it unclaimed — or shows a different owner. This is a **ghost claim** or **split-brain** state.

### Symptom Recognition

| Symptom | Likely Cause |
|---------|-------------|
| Claim rejected, `show` says unclaimed | Ghost claim in `claims.json` (stale or orphaned entry) |
| Claim rejected, `show` shows different owner | Split-brain: claims.json and plan.yaml disagree |
| `status` shows claimed, but no agent is working | Stale claim entry (agent crashed/left) |

### Recovery Commands

```bash
# 1. Diagnose: preview what would change (safe, read-only)
uvx vectl repair claims --dry-run

# 2. Diagnose with JSON (machine-parseable output)
uvx vectl repair claims --dry-run --json

# 3. Repair all claims on current branch
uvx vectl repair claims

# 4. Repair only a specific step (scoped repair)
uvx vectl repair claims --step foo.bar

# 5. Verify: check status again
uvx vectl status
uvx vectl show <step-id>
```

### Flags Explained

| Flag | Purpose |
|------|---------|
| `--dry-run` | Preview changes without writing. Always run this first. |
| `--step <id>` | Repair only this step's claim. Preserves all other claims. |
| `--json` | Machine-readable output. Useful for scripting/CI. |

### Policy

`vectl repair claims` follows **plan precedence**:
- `plan.yaml` is the source of truth for claim-visible state
- For current branch, claims.json is repaired to match plan step status/owner
- Out-of-scope entries (other branches, unrelated steps) are preserved

### When Repo is Healthy (No-Op)

If the repo is consistent, `--dry-run` shows:
```
Policy: plan_precedence: ...
changed: false
actions: []
```

A normal CLI or MCP claim writes one canonical UTC timestamp unchanged to both
`plan.yaml` and `claims.json`. The owner and timestamp fields must match
immediately, so `repair claims --dry-run` is a no-op without an intervening
repair. If plan persistence fails, Vectl conditionally removes only the exact
claim entry created by that failed operation.

This means claims.json matches plan.yaml — no repair needed.
### Anima-Style Example

```bash
# You try to claim but get rejected
$ uvx vectl claim auth.user-model
Error: Step 'auth.user-model' is already claimed on branch 'main'

# But status shows something different
$ uvx vectl show auth.user-model
status: pending
claimed_by: null
```

**Recovery**:
```bash
# Preview the fix
$ uvx vectl repair claims --dry-run --json
{
  "changed": true,
  "actions": [
    {"action": "remove", "key": "main:auth.user-model", "reason": "ghost_claim_or_non_claimed_step"}
  ]
}

# Apply the fix
$ uvx vectl repair claims
[vectl] Repair claims (main)
  removed: main:auth.user-model

# Now claim works
$ uvx vectl claim auth.user-model
```

### Post-Repair Verification

After running repair, always verify:
```bash
uvx vectl status              # Confirm expected claim state
uvx vectl show <step-id>      # Check specific step
uvx vectl repair claims --dry-run  # Should now show no changes
```

---

## Development checks

Use Python 3.12 or newer. Install the locked development dependencies and run:

```bash
uv sync --frozen
uv run --frozen pytest tests/ -q
uv run --frozen ruff check src/ tests/
uv run --frozen invar guard
```

The test workflow runs on pushes and pull requests targeting `Main` (case-sensitive),
using Python 3.12. Ruff is pinned in the development dependency group.
`invar guard` checks changed files by default; use `--all` for a repository-wide scan.

## Technical Details

Architecture, CAS safety, and test coverage (Hypothesis state machine verification): [docs/DESIGN.md](docs/DESIGN.md).
