---
name: semantics-contracts
description: Methodology reference: Design by Contract enforcement, Fractal Decision Memory (ADR), Zero-Erosion rules, Verifiable Edit Loop, and Search Discipline. Load when implementing C4+ contracts or when your agent prompt says "READ → REASON → ACT → REFLECT → UPDATE" and you need the detailed version.
---

#region Std.Semantics.Contracts [C:5] [TYPE Skill] [SEMANTICS methodology,contracts,adr,decision-memory,anti-erosion]
@BRIEF HOW to enforce PRE/POST, write ADRs, prevent structural erosion, execute verifiable edit loops, and maintain anchor safety (anti-corruption) across Python + Svelte.
@RELATION DEPENDS_ON -> [Std.Semantics.Core]

**Protocol Reference:** Tier definitions, tag catalog, and anchor syntax are defined in `semantics-core`. This skill assumes you have loaded it. All rules below reference `semantics-core` §III for tier semantics — tiers are descriptive, not tag-gating.

## I. DECISION MEMORY (ADR PROTOCOL)

Decision memory prevents architectural drift. It records the *Decision Space* — why we chose a path, and what we abandoned.

- **`@RATIONALE`** — The reasoning behind the chosen implementation.
- **`@REJECTED`** — The alternative path that was considered but FORBIDDEN, and the exact risk/disqualification.

**Three layers of decision memory:**
1. **Global ADR** — Standalone nodes defining repo-shaping decisions (e.g., "Use lingua, not fasttext"). Cannot be overridden locally.
2. **Task Guardrails** — Preventive `@REJECTED` tags injected by the Orchestrator to keep agents away from known LLM pitfalls.
3. **Reactive Micro-ADR** — If you encounter a runtime failure and invent a valid workaround, document it via `@RATIONALE` + `@REJECTED` BEFORE closing the task. This prevents regression loops.

**Resurrection Ban:** Silently reintroducing a pattern or library marked as `@REJECTED` is a fatal regression. If the rejected path must be revived, emit `<ESCALATION>`.

**`@RATIONALE`/`@REJECTED` are universally allowed at ALL tiers (C1-C5).** They prevent regression loops regardless of complexity.

## II. CORE CONTRACT ENFORCEMENT (C4-C5)

- **`@PRE`** — Execution prerequisites. Enforce via explicit `if/raise` guards. NEVER use `assert`.
- **`@POST`** — Strict output guarantees. **Cascading Protection:** You CANNOT alter a `@POST` without verifying upstream `@RELATION CALLS` consumers won't break.
- **`@SIDE_EFFECT`** — Explicit declaration of state mutations, I/O, DB writes, network calls.
- **`@DATA_CONTRACT`** — DTO mappings (e.g., `Input: UserCreateDTO → Output: UserResponseDTO`).

## III. ZERO-EROSION & ANTI-VERBOSITY

Long-horizon AI coding accumulates "slop":
1. **Structural Erosion:** If modifications push a contract's CC above 10, decompose into smaller helpers linked via `@RELATION CALLS`.
2. **Verbosity:** Don't write identity-wrappers, useless intermediate variables, or defensive checks for impossible states if `@PRE` already guarantees validity. Trust the contract.

## IV. VERIFIABLE EDIT LOOP

1. **Define verifier first.** What pytest or browser check proves the `@POST`?
2. **Build bounded working packet** from semantic context, impact analysis, and related tests.
3. **Preview-first mutation.** Prefer `simulate`/`guarded_preview` before `apply`.
4. **Run the smallest falsifiable verifier** against the intended `@POST`.
5. **Apply only after preview + verifier agree.**
6. **Re-run verification after apply.** Record the result.

**Shortcut Ban:** A patch that "looks right" without an executable verifier is incomplete.

## V. SEARCH DISCIPLINE

- Default to ONE primary hypothesis + explicit verification.
- Use multiple branches only for ambiguous high-impact changes where the verifier can't discriminate.
- Don't spend additional search budget on low-impact edits once the verifier passes.
- Overthinking is also a bug: avoid Best-of-N patch churn when one verified path suffices.

## VI. RUBRIC REFINEMENT

- Convert repeated failures into explicit rule updates: which invariant was missed, which verifier was weak.
- Treat failed previews, blocked mutations, and failing test outputs as early experience.
- If the same failure repeats, improve the rubric or verifier BEFORE editing again.
- When unblock requires a higher-level change, escalate with the refined rubric.

## VII. LANGUAGE-SPECIFIC VERIFICATION

```bash
# Python
cd backend && source .venv/bin/activate && python -m pytest -v

# Svelte
cd frontend && npm run test

# Linting
python -m ruff check .   # Python
npm run lint              # Frontend
```

## VIII. ANTI-CORRUPTION PROTOCOL (Anchor Safety)

This is the **canonical** anti-corruption protocol. Agent prompts reference this section — they do NOT duplicate these rules.

The `#region`/`#endregion` markers are AST boundaries. If you break a pair, the semantic index breaks and ALL downstream agents hallucinate.

### Before editing any file with anchors
1. **Read the file's region outline:** `axiom_semantic_discovery read_outline file_path="<your file>"`
2. **Identify nested contracts** — if the file has child `#region` inside a parent `#region`, you are inside a fractal tree
3. **Never:**
   - Insert code between `#region` and the first metadata tag line (breaks INV_4)
   - Remove, move, or duplicate ANY `#endregion` line
   - Add `@COMPLEXITY N` — complexity goes in the anchor: `[C:N]`
   - Add `@C N` — this is a non-standard legacy artifact, never create it
   - Put code outside all regions — every line must be inside a `#region`/`#endregion` pair
   - Start a new `#region` before closing the previous one

### After every edit
4. **Verify:** run `read_outline` on the file — confirm all `#region`/`#endregion` pairs match
5. **If a `#endregion` is missing** → the file is corrupted, roll back immediately via `axiom_workspace_checkpoint rollback_apply`
6. **If you changed anchors** → run `axiom_semantic_index rebuild rebuild_mode="full"`

### When adding new contracts
7. Always add BOTH `#region Id [C:N] [TYPE Type]` and its matching `# #endregion Id`
8. Complexity `[C:N]` goes in the ANCHOR line, never as a separate `@` tag
9. If the new contract is nested inside another → DO NOT close the parent until after your child's `#endregion`

### Language-specific anchor formats
- **Python:** `# #region ContractId [C:N] [TYPE TypeName] [SEMANTICS tags]` / `# #endregion ContractId`
- **Svelte HTML:** `<!-- #region ContractId [C:N] [TYPE Component] [SEMANTICS tags] -->` / `<!-- #endregion ContractId -->`
- **Svelte JS/TS (script block):** `// #region ContractId [C:N] ...` / `// #endregion ContractId`
- **Markdown/ADR:** `## @{ ContractId [C:N] [TYPE TypeName]` / `## @} ContractId`

### Batch semantic work
- **ONE file at a time.** Verify each file before moving to the next.
- Never dispatch multiple agents to edit the same file simultaneously.
- For >3 files: process sequentially, with `read_outline` verification between each.
- **Forbidden operations** (immediate `<ESCALATION>`):
  - Duplicating ANY `#region` or `#endregion` line
  - Editing a contract with nested children without `destructive_intent=true`
  - Batch-editing multiple files without per-file verification

### Verification loop (every file, every edit)
```
read_outline(file) → identify boundaries → apply ONE patch → read_outline(file) → rebuild index
```
If ANY step fails — stop and fix before next file. Never chain patches without verification.

#endregion Std.Semantics.Contracts
