# Circuits, CEGIS, and MCP server

> Compile zero-parameter exact circuits, decompile networks into portable symbolic IR, run Statistical CEGIS, mine repair procedures, and serve 12 sandboxed MCP tools.

Source: https://kucinglabs.com/docs/circuits-mcp
Markdown: https://kucinglabs.com/docs/circuits-mcp.md

## Zero-parameter exact circuits and portable inverse compiler

Some sub-tasks have exact algebraic solutions that need zero learned weights. `arah.src_comp.circuits` ships `SE3FrameCircuit` (3D rotation and translation-equivariant coordinate canonicalization with zero parameters), `POCSProjectionLayer` (iterative projection onto rigid distance and clearance bounds), and closed-form discrete circuits.

Its inverse compiler extracts compact `SymbolicProgramIR` from trained or authored models and recompiles to portable Python or exact Torch recipes with exhaustive domain checks.

| Circuit or compiler API | Role |
| --- | --- |
| `SE3FrameCircuit`, `verify_se3_equivariance` | Zero-parameter Gram-Schmidt SO(3) frames and SE(3)-equivariant coordinate projection |
| `POCSProjectionLayer` | Alternating projections enforcing rigid distance constraints and minimum clearance bounds |
| `FourierModAddCircuit` | Exact modular addition circuit over Z_p x Z_p using Fourier harmonics |
| `LinearThresholdCircuit`, `FiniteStateTransitionCircuit` | Exact threshold classifiers and deterministic finite-state transition machines |
| `decompile_mod_add_circuit`, `decompile_to_symbolic_ir` | Extract compact `SymbolicProgramIR` (`mod_add_fourier`, `linear_threshold`, `finite_state_transition`) |
| `recompile_portable` | Recompile IR to `target="python"` or `target="torch_exact_recipe"` with exhaustive domain checks |

**Verify SE(3) equivariance, project rigid constraints, and inverse-compile Fourier mod-add**

```python
import torch
import arah
from arah.eval import FiniteDomain
from arah.src_comp import (
    FourierModAddCircuit,
    POCSProjectionLayer,
    SE3FrameCircuit,
    decompile_to_symbolic_ir,
    recompile_portable,
    verify_se3_equivariance,
)

# 1. Zero-parameter SE(3) frame circuit + POCS rigid-distance projection
torch.manual_seed(0)
se3 = SE3FrameCircuit()
pts = torch.randn(4, 3, 3, dtype=torch.float64)
se3_rep = verify_se3_equivariance(se3, [pts[i] for i in range(4)], seed=0)
pocs = POCSProjectionLayer(distance_constraints=[(0, 1, 1.5), (1, 2, 1.5)], min_clearance=0.6, n_iters=18)
projected = pocs(se3(pts))
d01 = torch.linalg.norm(projected[:, 1] - projected[:, 0], dim=-1)
assert se3_rep.passed and se3_rep.max_abs_err < 1e-10
assert torch.allclose(d01, torch.full_like(d01, 1.5), atol=1e-4)

# 2. Decompile FourierModAddCircuit -> SymbolicProgramIR -> portable Python and exact Torch recipe
p = 7
circuit = FourierModAddCircuit(modulus_p=p)
decomp = arah.decompile_mod_add_circuit(circuit, modulus_p=p)
ir = decompile_to_symbolic_ir(circuit, "mod_add_fourier", modulus_p=p)
all_pairs = [(a, b) for a in range(p) for b in range(p)]
dom = FiniteDomain("Z_7_x_Z_7", len(all_pairs))
ref = lambda pair: (pair[0] + pair[1]) % p

# exhaustive finite domain: all 49 Z_7 x Z_7 pairs verified
py_out = recompile_portable(
    ir, target="python", verify_inputs=all_pairs, reference_fn=ref, held_out_inputs=all_pairs, held_out_reference_fn=ref, exact_domain=dom
)
torch_out = recompile_portable(
    ir, target="torch_exact_recipe", verify_inputs=all_pairs, reference_fn=ref, held_out_inputs=all_pairs, held_out_reference_fn=ref, exact_domain=dom
)
assert decomp.round_trip_exact and py_out.exact_on_domain and torch_out.recipe_spec is not None
```

## Statistical CEGIS and cross-family ProcedureLibrary

`run_cegis` implements Statistical CEGIS (Counterexample-Guided Inductive Synthesis) for neural modules. On each round, Arah checks your contract, computes a McShane-Whitney Lipschitz failing ball (`CounterexampleRegion`, the guaranteed radius around a failing probe where nearby inputs can violate the contract), passes that region to your repair callback, and promotes passing models through `verify_contract_claim`.

`ProcedureLibrary` turns winning `AuthoringRun` logs into reusable `RepairProcedure` recipes. It forbids raw weight deltas, keeping mined diagnostic-and-edit pipelines model-agnostic so you can match them on unseen architectures and lock the library with `.freeze()`.

**Run Statistical CEGIS repair and mine cross-family repair procedures**

```python
import torch
from torch import nn
import arah
from arah.eval import FiniteDomain, IdentityContract

true_w = torch.tensor([[2.0, -1.5]], dtype=torch.float64)

class BuggyLinear(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.w = nn.Parameter(torch.tensor([[0.4, 0.5]], dtype=torch.float64))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return x @ self.w.T

xs = [
    torch.tensor([[1.0, 0.0]], dtype=torch.float64),
    torch.tensor([[0.0, 1.0]], dtype=torch.float64),
    torch.tensor([[1.0, 1.0]], dtype=torch.float64),
]
contract = IdentityContract("linear_exact", reference=lambda x: x @ true_w.T, atol=1e-5, rtol=1e-5)

def repair(_verdict, _region):
    x_mat = torch.cat(xs, dim=0)
    fit = arah.ridge_fit(x_mat, x_mat @ true_w.T, lambdas=1e-12)
    fixed = BuggyLinear()
    with torch.no_grad():
        fixed.w.copy_(fit.weights.T.to(torch.float64))
    return fixed

cegis = arah.run_cegis(
    BuggyLinear(),
    contract,
    repair,
    xs,
    max_rounds=4,
    exact_domain=FiniteDomain("basis_probes", len(xs)),
    lipschitz=2.5,
    train_anchors=[[1.0, 0.0], [0.0, 1.0]],
    train_errors=[0.0, 0.0],
    claim_statement="Repaired linear readout matches target slope",
    exactness=arah.Exactness.approximate,
    error_bound=1e-5,
)
assert cegis.converged and cegis.claim is not None and cegis.claim.status is arah.Status.checked

# Mine a model-agnostic RepairProcedure from a winning run and transfer to an unseen family
run_a = arah.AuthoringRun(arah.RunLimits(max_epochs=4, max_forward_passes=50))
run_a.record_epoch(
    edit_family="null_space_fit",
    practice_metric=0.95,
    baseline_gate_scores=[0.30] * 36,
    edit_gate_scores=[0.90] * 36,
    matched_control_scores={"matched_random": [0.32] * 36},
    inference_only_scores=[0.35] * 36,
    mechanical_edit_scores=[0.33] * 36,
    forward_passes=3,
)
run_a.close_search(reason="solved")

lib = arah.ProcedureLibrary()
sig = {"capacity_verdict": "underfitting_head", "fault_pattern": "head_sign", "causal_share": 0.85, "epistasis_ratio": 0.08}
mined = lib.mine_from_run(run_a, model_family="mlp_v1", diagnostic_signature=sig, preservation_checks=("anchor_drift",))
matches = lib.match(sig)
lib.record_transfer_outcome(mined[0].procedure_id, target_family="transformer_v2", succeeded=True)
frozen = lib.freeze()
assert len(matches) == 1 and frozen.is_frozen
```

## Turnkey run_authoring_loop and 12-tool ArahMCPServer

`run_authoring_loop` drives an outer author callback (`edit`, `explore_branch`, `promote_branch`, `abort_branch`, `rollback_branch`, `acquire`, or `stop`) over bounded `EpochBrief` snapshots enriched by `ProcedureLibrary`. If you pass a `ProtocolSpec`, Arah runs `verify_run_protocol` on the full transcript and raises `SourceError` on any violation.

`ArahMCPServer` implements a zero-dependency JSON-RPC 2.0 server (`MCP_PROTOCOL_VERSION = "2024-11-05"`) supporting `initialize`, `tools/list`, `tools/call`, `handle_request`, `handle_json`, and custom `register_tool`. It enforces `additionalProperties: False`, finite UTF-8 JSON, 1 MiB payload limits (`DEFAULT_MAX_PAYLOAD_BYTES`), zero `eval` or shell access, and structured JSON-RPC error codes (`-32001` for `BudgetError`, `-32002` for `ArahError`).

| Built-in MCP tool | Arah capability |
| --- | --- |
| `arah_ridge_fit` | Float64 SVD/Woodbury ridge regression with exact PRESS/LOO lambda selection |
| `arah_null_space_fit` | AlphaEdit null-space weight update preserving anchor keys |
| `arah_exact_rational_ridge_fit` | Exact dyadic-rational Bareiss ridge regression in Q with one final rounding |
| `arah_diagnose_capacity` | Probe-class-scoped five-way capacity bottleneck diagnosis |
| `arah_check_shift` | Multi-covariate distribution shift, disjoint-support vacuity, and W1 Lipschitz audit |
| `arah_surrogate_paradox_check` | Exact 3x3 correlation-cone surrogate-paradox check and sign-preservation barrier |
| `arah_build_epoch_brief` | Deterministic, character-bounded, leak-free `EpochBrief` (JSON and Markdown) |
| `arah_render_report` | `ReportGuard` ledger-bound rendering audited for unlinked numbers and WSP-12 weight-space reporting disclosures |
| `arah_match_procedures` | Ranked lookup of model-agnostic `RepairProcedure` pipelines for a diagnostic signature |
| `arah_fit_noise_scaling` | 3-axis measurement-noise scaling law `I(SNR)` fit and optional 3-axis bottleneck diagnosis |
| `arah_diagnose_readout_vs_reasoning` | AUROC diagnosis separating recoverable readout failure from latent reasoning absence |
| `arah_verify_protocol` | Experimental Protocol Compiler trace verification returning a sealed compliance certificate |
