Files
ss-tools/.opencode/skills/semantics-contracts/SKILL.md
2026-08-26 13:13:02 +03:00

139 lines
10 KiB
Markdown

---
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]
@RELATION DISPATCHES -> [Std.Semantics.Python]
@RELATION DISPATCHES -> [Std.Semantics.Svelte]
@RATIONALE Design by Contract is the ONLY mechanism that prevents Transformer agents from silently corrupting code over long horizons. Without @PRE/@POST enforcement, agents optimize for token-likelihood rather than correctness — adding null checks where @PRE already guarantees non-null, re-implementing @REJECTED paths because KV-cache evicted the rejection, and growing functions past the CC=10 threshold because no structural limit is visible in the attention window. The anti-corruption protocol (§VIII) exists because a single broken #region/#endregion pair cascades silently through the entire semantic graph — rendering all downstream contracts invisible to every agent.
@REJECTED Trusting agents to self-police code quality without contracts was rejected — they optimize for immediate token likelihood, not long-term invariants. Linter-only enforcement was rejected — linters cannot see cross-file dependency graphs or detect rejected-path regression. Implicit contracts (naming conventions alone) were rejected — without explicit @PRE/@POST in the attention-dense header region, agents default to their pre-trained behavior of adding defensive checks everywhere.
**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 only when they record a real decision. Absence is valid. Synthetic decision memory (interchangeable "chosen because simpler", copy-paste across siblings, generic "rejected alternative approach") is a defect — delete it. If you cannot name the rejected path, the incident, or the ADR, **do not write the tags**.
**Synthetic-ban (all `@`-tags, not only decision memory):** no local fact → no tag. Do not invent `@PRE`/`@BRIEF`/`@RELATION`/`@UX_*`/`@TEST_*` from the typical-tier matrix. Empty is better than garbage. See `semantics-core` INV_9.
## 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. **Outline-first mutation.** `read_outline` (Axiom) or grep the `#region` tree, then `edit` one file. Axiom has no `simulate` / `guarded_preview` / `apply` / `destructive_intent`.
4. **Run the smallest falsifiable verifier** against the intended `@POST` (pytest, vitest, or a browser path). If there is no `@POST`, verify the behavior you actually changed.
5. **Re-read the outline** and confirm `#region`/`#endregion` pairs still match.
6. **Re-run the verifier after the edit.** Record the result. Rebuild the Axiom index only when Axiom is connected.
**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 `search operation="read_outline"` when available; otherwise grep `#region`/`#endregion` in that file.
2. **Identify nested contracts** — a child `#region` inside a parent `#region` is the fractal tree. Nesting is required, not a violation.
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
- Leave a **sibling** `#region` unclosed and start another sibling (nesting children is allowed; overlapping siblings are not)
- Invent `@`-tags to satisfy an audit (INV_9)
### 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 `git checkout` / `git restore`
6. **If you changed anchors and Axiom is connected**`search operation="rebuild" rebuild_mode="full"`. If Axiom is down, skip rebuild; pair-count via grep is the verifier.
### 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`
Doxygen HTML in this repo is a module→function navigation graph for agents (`semantics-core` §IX). After changing module-level `@defgroup`/`@ingroup` or contract IDs, regenerate with `make docs-nav`. Do not invent extra groups to make the tree look full (INV_9).
### 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 parent contract's body while ignoring nested children (read the full subtree first; there is no `destructive_intent` flag)
- Batch-editing multiple files without per-file verification
- Filling missing tags with boilerplate to close an audit list
### 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