---
name: ctxfw-sovereign-twin
description: Deterministic AST Context Firewall, Axiomatic Spec Synthesizer (Role A: ACI >= 0.9000), and Pre-Commit CI Patch & Ledger Auditor (Role B: SWE-Gate + TraceKit) powered by the ctxfw v4.0.0 MCP server. Activate when designing specifications, pruning multi-module context, auditing git diffs before commit, or verifying SHA-256 audit ledgers.
---
<!-- manifest_hash: 1e59ec214f0027b64ac52c447dbeb1a9764f31dc50c277a075af60c092ed5e7a -->

# CTXFW v4.0.0 // Sovereign Twin Deterministic Skill (`ctxfw-sentry` + `ctxfw-architect`)

> [!IMPORTANT]
> **Inviolable Closed-Loop Protocol**: This skill operates in two deterministic modes over the 5 canonical tools of the `ctxfw v4.0.0` MCP server (`python -m ctxfw.mcp`):
> 1. **Mode 1 — `ctxfw-sentry` (Role B: `precommit_audit_proxy_agent` / Exit Gate)**: Activated before every `git commit` or PR review (`< 2 ms`).
> 2. **Mode 2 — `ctxfw-architect` (Role A: `axiomatic_spec_synthesizer` / Entry Gate)**: Activated before writing any backend code, DDL schema, or architectural contract (`ACI >= 0.9000`).

---

## 1. MCP Server Prerequisite (`mcp.json` / `.cursor/mcp.json`)

Ensure the `ctxfw` MCP server (`v4.0.0+`, `pip install --upgrade ctxfw`) is registered in your agent runtime:

```json
{
  "mcpServers": {
    "ctxfw": {
      "command": "python",
      "args": ["-m", "ctxfw.mcp"],
      "env": { "PYTHONUTF8": "1" }
    }
  }
}
```

---

## 2. MODE 1 (DEFAULT WEDGE): `ctxfw-sentry` — Pre-Commit & Proxy Audit Agent (`Role B`)

### When to Trigger
- Automatically before any `git commit`, PR creation, or patch finalization.
- Whenever the user asks to verify repository health, inspect a `git diff`, or audit the immutable ledger.

### Deterministic Execution Sequence
```mermaid
flowchart LR
    Diff["Staged Patch (git diff --cached)"] --> Doctor["1. ctxfw doctor (<80ms)"]
    Doctor --> SweGate["2. ctxfw.evaluate_patch (<1ms)"]
    SweGate -->|ALLOW_MERGE| Ledger["3. ctxfw.query_audit_ledger (SHA-256)"]
    SweGate -->|REJECT_ARCHITECTURAL_VIOLATION| Block["ABORT COMMIT + Remediate Line"]
    Ledger -->|chain_intact: true| Commit["COMMIT ATTESTED"]
```

1. **Step 1 — Runtime & Stream Hygiene Check**:
   - Run `ctxfw doctor` (if CLI is available) or verify MCP connectivity. Confirm 100% pure JSON-RPC `stdout` and healthy SQLite WAL stores.
2. **Step 2 — Static Diff & Complexity Gate (`ctxfw.evaluate_patch`)**:
   - Extract the unified diff (`git diff --cached` or candidate patch) and its exact UTF-8 byte length (`diff_size_bytes = len(diff_text.encode("utf-8"))`).
   - Invoke `ctxfw.evaluate_patch` with:
     * `commit_sha`: 40-char hex SHA (or candidate staging SHA).
     * `pr_id`: PR/session identifier (`>= 1`).
     * `author_kind`: `"AGENT"`.
     * `diff_size_bytes`: exact UTF-8 byte length.
     * `diff_text`: unified diff string.
     * `tests_passed` / `tests_failed` / `functional_verdict` (`"PASSED"` or `"FAILED"`).
     * `forbid_type_ignores`: `true`.
     * `max_cyclomatic_delta`: `10` (or project-configured ceiling).
     * `disallowed_import_modules`: list of banned modules (e.g., `["pickle", "telnetlib"]`).
   - **Enforcement Rule**:
     * If `gate_verdict == "REJECT_ARCHITECTURAL_VIOLATION"`, **STOP IMMEDIATELY**. Do not commit. Parse `architectural_violations` (`TYPE_IGNORE|<file>:<line>`, `DISALLOWED_IMPORT|<mod>@<file>:<line>`, `CYCLOMATIC_DELTA|total:<d>><max>`) and fix the offending lines without using `# type: ignore`.
3. **Step 3 — Cryptographic Ledger Attestation (`ctxfw.query_audit_ledger`)**:
   - Invoke `ctxfw.query_audit_ledger` with `ledger_surface="SWEGATE_EVALUATIONS"` and `verify_integrity=true`.
   - Confirm `integrity.chain_intact == true` and include the resulting `evaluation_id` (`EVL-...`) in the commit or PR summary.

---

## 3. MODE 2 (ARCHITECTURAL GATE): `ctxfw-architect` — Axiomatic Spec Synthesizer (`Role A`)

### When to Trigger
- Before writing or modifying any backend code, database schema (`DDL`/`SQL`), API contract, or security boundary.
- Whenever a user requirement is ambiguous or lacks explicit numeric bounds, state transitions, or negative invariants.

### Deterministic Synthesis Protocol (The 4 Axiomatic Pillars)
1. **Pillar 1 — Bounded Variables**:
   - Every domain variable must declare explicit numeric bounds (`>= min and <= max`), byte/length limits, or anchored regex patterns (`^...$`).
2. **Pillar 2 — Total Deterministic Finite State Machine ($\delta(S, E) \to S$)**:
   - Define `States:`, `Terminal States:`, and explicit `Transition delta(STATE, EVENT) -> NEXT_STATE` rules, routing any invalid/unexpected input to `REJECTED_INVALID` or `QUARANTINED`.
3. **Pillar 3 — 4-Class Error Taxonomy**:
   - Isolate failures into:
     * `Class 1 (Transient Fault)` (bounded exponential retry).
     * `Class 2 (Deterministic Validation Fault)` (`0` retries, immediate schema rejection).
     * `Class 3 (Business Invariant Violation)` (`0` retries, domain quarantine).
     * `Class 4 (Security & Isolation Violation)` (`0` retries, immediate halt + `TraceKit` seal).
4. **Pillar 4 — Non-Negotiable Negative Invariants (`>= 5` `never` / `shall never` clauses)**:
   - Include at least 5 explicit negative invariants using `never` or `shall never`.

### Closed-Loop Verification (`ctxfw.evaluate_spec_axioms`)
- Call `ctxfw.evaluate_spec_axioms(brief_text=...)`.
- If `status == "QUARANTINED"` (`aci_score < 0.9000` or `negative_invariants_count < 5`), **halt code generation** and remediate the missing pillar.
- Only when `status == "VERIFIED"`, stamp `# manifest_hash: <manifest_hash>` on Line 1 of every synthesized code file.

---

## 4. Context Assembly Protocol (`resolve_context_bundle` & `prune_file`)

When exploring multi-file dependencies or large Python modules:
- Prefer `ctxfw.resolve_context_bundle(target_file=..., project_root=...)` over reading entire dependency trees raw. It automatically applies $D_0 \to D_3$ topological AST pruning (`-74.4%` token reduction), `TokenCast` budget protection (`-89.8%` reactive $D_3$ collapse when `TRIPPED`), `RulesEnforcer` path traversal guards, and `SARA` indirect prompt injection sanitization.
- Use `ctxfw.prune_file(path=..., depth="interface")` when you only need the public signatures, types, and docstrings of a single peripheral module.
