# FEDERATION — the Magogi federation contract

> **One sentence:** if you depend on `mgf-common` (or any `mgf-*` sibling),
> read this page once; it tells you everything you owe the federation
> in exchange for what the federation gives you.
>
> **Audience:** every consumer project (CLI tool, FastAPI service, Django
> app, library) AND every federation sibling. Humans + AI agents.
> **AI agents:** run `mgf-fed agents` for the single canonical
> agent briefing (always installed — `mgf-common` is a dependency of
> every Magogi project; the same text is in
> [`STARTHERE.md`](STARTHERE.md) §"For the AI agent"). For the rules,
> contract, design, and the live federation map, first install the corpus
> extra: `pip install -U 'mgf-common[standards]'` (AG-16) — a plain
> `mgf-common` install does not carry it. Then read
> this contract.
> **Status:** v2.0 of this contract — **LOCKED** (LOCK v1, 2026-07-04; amendment
> classes + locked surfaces in [LOCK.md](LOCK.md)) (contract version; the standards corpus
> versions independently — see [docs/standards/README.md](docs/standards/README.md)).
> **Authority:** **mgf-standard** owns this file — it is the
> federation's standards + contract source of truth. Every other repo
> (including the `mgf-common` cornerstone) links here; none maintains its
> own copy (DOC-17).

---

## §1 What is the Magogi Foundation?

The **Magogi Foundation** is a family of Python projects that share one
engineering bar — typed exceptions, structured logging + OTel, layered
configuration, four-gate CI (ruff + mypy --strict + pytest + coverage),
crash reporting, vault, the AP/EH/LG/CF/SC/TS/DP rule discipline, and a
single feedback channel.

The foundation is split into three concentric rings:

  1. **The cornerstone** — `mgf-common`. The reference implementation
     every sibling and consumer depends on, and the home of the
     `mgf-common` CLI. The **standards corpus, this federation contract,
     and the library registry** live one level below it in the
     `mgf-standard` data package — `mgf-common` depends on it and
     surfaces the rules via `mgf-fed standards`. `mgf-standard` is
     the federation's standards + contract source of truth (this file
     lives there).
  2. **The siblings** — every `mgf-*` package. They depend on
     `mgf-common`, conform to its standards, and add domain-specific
     surfaces (HTTP, SQLAlchemy, Alembic, FastAPI, Django, apiprobe,
     website-template). The authoritative registry of every
     library is [`MGF_LIBRARIES.md`](MGF_LIBRARIES.md) (generated by
     `scripts/gen_mgf_libraries.py`, kept current per **REL-13**; each
     library name links to its `DEPS.md`). **Only the mgf-common
     supervisor changes a library** — other projects file update
     requests in the target's `FEEDBACK.md` (**AG-13**), never edit it
     directly. See [`DEPS.md`](DEPS.md) §2 for this repo's roster.
  3. **The consumers** — your project. End applications that adopt
     `mgf-common` and one or more siblings to get the federation's
     quality bar without rewriting it.

### §1.1 The library-first strategy — how the foundation grows

The rings above describe the *structure*. **Library-first** is the
*habit* that builds it, and it is the foundation's core strategy:

> **Domain logic is built as a standalone `mgf-*` library first.
> Applications consume libraries; they never embed reusable domain
> logic.**

When a new domain of capability appears, the foundation grows in
two deliberate steps:

  1. **Build the capability as a library.** The domain logic ships
     as its own `mgf-*` sibling — pure logic, no UI, independently
     versioned, reusable. Example: `mgf-usb` (planned — not yet in
     the registry) would own USB bus / device enumeration,
     classification, and libvirt passthrough.
  2. **Build applications on top.** A UI, CLI, or service that needs
     that capability is a **separate consumer project** depending on
     the library. Example: a USB-management UI is its own
     application that imports `mgf-usb` (planned) — the library does
     the work, the app only presents it.

**The test for where code belongs:** if a second project would ever
need it, it belongs in a library, not an app. Domain logic trapped
inside one application can't be reused without copy-paste, and
extracting it later is breaking work for whoever already shipped on
top of it. Build the library first — even when there's only one
consumer today.

This is why the `mgf-*` namespace is reserved for **libraries**:
consumer applications get their own product names (vm-vmanager-app,
TelePlasma, …) and are never `mgf-*`. A library and the app that
drives it are always two separate projects.

**Why this file exists.** Without a canonical contract, every new
project re-discovers what the federation expects from scratch, and
the maintainer has to remember to mention it. This file is the
single answer to "what do I owe by depending on mgf-common?"

---

## §2 The contract — what you owe

By depending on `mgf-common` (any version), your project commits to:

1. **Maintain the required docs layout** (see §3).
2. **Self-declare a standards-conformance level** (see §4).
3. **Prefer federation libraries over external alternatives** where
   one exists (see §5).
4. **Catch up with federation releases** on a known cadence (see §6).
5. **Use the federation feedback channel** for friction reports (see §7).
6. **Keep the standards corpus resolvable to your agents** — depend on
   `mgf-common[standards]` so the federation CLI resolves the rules, contract,
   and design (rule **AG-16**). The corpus is an *optional* extra resolved
   only from the federation devpi index (never public PyPI);
   a plain `mgf-common` install does not carry it, and the CLI degrades loudly
   without it. Resolve-don't-copy only works if the corpus is installed.

These are MUST-level commitments. The maintainer enforces them via
`mgf-fed catch-up` (a CLI command that audits your project — see §6) and
`mgf-fed app-doctor --standards` (the per-rule conformance + Index-of-MUSTs
completeness gate — see §4).

In exchange, the federation gives you:

- A 200+ public-name typed standard library you don't have to build.
- 13+ recipe documents covering common patterns.
- The four-gate CI shape pre-baked.
- A unified feedback channel (PAPERs at `mgf-common/FEEDBACK.md` for
  cross-cutting issues; sibling-scoped at the sibling repo).
- Coordinated release cadence + breaking-change deprecation cycles.

---

## §3 Required docs layout

Every project (cornerstone, sibling, AND consumer application) MUST
ship the **universal root-doc baseline** (DOC-01 v2.11, 2026-05-28) at
repo root — plus a `docs/` directory:

| File              | Purpose                                                    | Rule       |
|-------------------|------------------------------------------------------------|------------|
| `README.md`       | Project overview, audience routing, first-run instructions | DOC-01     |
| `LICENSE`         | License declaration                                        | DOC-01     |
| `CHANGELOG.md`    | Per-release notes (Keep-a-Changelog shape)                 | DOC-01     |
| `CONTRIBUTING.md` | Dev setup, gates, PR process                               | DOC-01     |
| `SECURITY.md`     | Vulnerability-report channel                               | DOC-01 / SC-12 |
| `FEEDBACK.md`     | Repo-scoped consumer feedback queue                        | DOC-01 / DOC-13 / FB-01..04 |
| `AGENTS.md`       | Cross-tool agent-discovery pointer (catch-up-managed)      | DOC-01 / DOC-07 |
| `STARTHERE.md`    | First-run / onboarding flow                                | DOC-01     |
| `DEPS.md`         | Bidirectional dependency manifest — §1 what I depend on + §2 who depends on me | DOC-01 / DOC-16 |
| `FEDERATION.md`   | The federation contract — **pointer stub** to this file for non-cornerstone projects (NOT a copy) | DOC-01 / DOC-17 |
| `docs/` (dir)     | Non-root docs bucket layout                                | DOC-01 / DOC-02 |
| `LESSON_LEARNED.md` | Append-only, dated log of non-obvious lessons learned *in this repo* (so the federation stops re-learning them); generalising lessons ALSO route to a `pending-feedback/<target>.md` paper. Presence is the bar — a seeded file is conformant | DOC-19 (**MUST since v2.21**; presence-gated by `doctor --standards`, PAPER-99) |

**Plus the federation trackers** (depending on your role):

| File                            | Required for                  | Purpose                                | Rule  |
|---------------------------------|-------------------------------|----------------------------------------|-------|
| `docs/inprogress/MGF_ADOPTION.md` | Consumer applications only (ADP-04 carves siblings out) | "I depend on mgf-* — here's how, where, and what phase I'm at." | DOC-14 / ADP-01..04 |
| `docs/inprogress/MGF_STANDARDS_CONFORMANCE.md` | **Both** consumers and siblings | "I declare conformance level L1/L2/L3 and audit each rule ✅/🚫/⏳/N/A." | DOC-15 / CFM-01..04 |

Templates live in [`docs/recipes/`](docs/recipes/):

- `mgf-adoption-md-template.md`
- `mgf-standards-conformance-md-template.md`

The reference shape for `DEPS.md` is [this repo's `DEPS.md`](DEPS.md).

**For AI agents** working in your project: `docs/CLAUDE.md` SHOULD exist
with an auto-managed federation-discipline block (created and refreshed
by `mgf-fed catch-up`). The block embeds DOC-13/14/15/16 + FB-04 +
this file's pointer so agents file feedback against the right repo
without you having to remember.

Every project also ships an **`AGENTS.md`** at its root — the
cross-tool agent-discovery pointer. It is a thin, project-agnostic
file (identical in every federation project, fully managed by
`mgf-fed catch-up`) that routes any agent to its `CLAUDE.md` and
to the canonical briefing in
[`STARTHERE.md`](STARTHERE.md). `init-project` writes it; `catch-up`
creates or restores it.

---

## §4 Required standards conformance

The standards corpus lives at [`docs/standards/`](docs/standards/) (see
[`docs/standards/README.md`](docs/standards/README.md) for the current
corpus version). It contains — one row per rule family in
[`docs/standards/rules.json`](docs/standards/rules.json), the machine
index this table is derived from:

| Standard             | Rules            | What it covers                                  |
|----------------------|------------------|--------------------------------------------------|
| AG — Agents          | AG-01..AG-20     | AI-agent collaboration: canonical briefing, signing trailers, memory + owned-infra discipline |
| AP — API surface     | AP-01..AP-16     | Public API stability tiers, `__all__` discipline, SemVer + deprecation cycle |
| CF — Config          | CF-01..CF-12     | Layered config loader, env-var precedence, schema versioning, atomic writes |
| DEP — Deployment     | DEP-01..DEP-11   | Web-service deployment: IaC, immutable artefacts, reversible deploys |
| DOC — Docs           | DOC-01..DOC-19   | This contract + the docs layout above, trackers, CHANGELOG discipline |
| DP — Design          | DP-01..DP-13     | Design principles (layering, replaceability, deterministic cleanup, …) |
| EH — Errors          | EH-01..EH-13     | Typed exception hierarchy, translation seams, top-level handlers |
| FB — Feedback        | FB-05            | Cross-repo feedback relay (the indexed feedback-discipline rule) |
| GUI — GUI consumers  | GUI-01..GUI-10   | PySide6/Qt consumers: Qt in presentation only, worker pattern, excepthook bridge |
| LG — Logging         | LG-01..LG-17     | Structured logging, redaction, audit emission   |
| NM — Naming          | NM-01..NM-05     | Federation identity convention: dist names, dotted imports, slugs |
| OB — Observability   | OB-01..OB-11     | Three pillars beyond logging: metric naming, OTel traces, SLI/SLO/alerts |
| OP — Operability     | OP-01..OP-12     | Version visibility, self-diagnostic doctor, log access, production guards |
| PF — Performance     | PF-01..PF-08     | Relative regression budgets, baselines in tree, perf markers |
| PKG — Distribution   | PKG-01..PKG-12   | The self-hosted devpi index: publish, verify, single-index consumers |
| PR — Presentation    | PR-01..PR-07     | Framework-neutral SDK ↔ multi-UI app split (DRAFT pending second adopter) |
| REL — Release        | REL-01..REL-13   | Build-test-tag-push-upload order + registry regeneration |
| SC — Security        | SC-01..SC-18     | Atomic writes, secret redaction, audit trails, reproducible releases |
| SP — Scope           | SP-01..SP-06     | Scope policy: IN / OUT / adjacent, the scope-creep review question |
| TM — Time            | TM-01..TM-08     | UTC at boundaries, monotonic durations, injectable clocks |
| TS — Tests           | TS-01..TS-28     | Test discipline, four-gate CI, supervisor tiers |
| WF — Workflows       | WF-01..WF-13     | CI: four-gate baseline, tag-driven publish, generated `.woodpecker.yml` |

The tracker-discipline sub-rules (ADP-01..04, CFM-01..04, FB-01..04)
live inside [`DOCUMENTATION.md`](docs/standards/DOCUMENTATION.md) under
the DOC family — they bind via DOC-13/14/15 and are not separately
indexed families.

Run `mgf-fed standards --list` to print them all. Run `mgf-fed
standards <name>` to print one (e.g., `mgf-fed standards LOGGING`).

**Your `MGF_STANDARDS_CONFORMANCE.md` declares your level:**

- **L1 — Lite.** You conform to the spirit of the standards but apply
  them on a best-effort basis. Suitable for greenfield experiments.
- **L2 — Standard.** You conform to all MUST rules. Per-rule audit ✅
  required. **This is the default for federation siblings + production
  consumers.**
- **L3 — Strict.** You conform to all MUST + SHOULD rules. Run-time
  enforcement (audit-logs, redaction) is wired up. Suitable for
  high-stakes services + the cornerstone library (`mgf-common`
  itself holds to L3).

The level measures **how strictly you follow the rules**, not which
features you wire. This table is the **canonical definition** of the
L1 / L2 / L3 conformance levels (rule CFM-02); `docs/standards/README.md`
and the `MGF_STANDARDS_CONFORMANCE.md` template carry summaries and
link here.

A `🚫 Declined-with-rationale` row is acceptable per CFM-04 if the
rule's premise doesn't fit your project shape — but the rationale
must be written down, not just felt.

---

## §5 Federation-first principle

When you need a capability and a federation library provides it,
**use the federation library**. Don't pull in a competing third-party
package just because it's familiar.

| You need…                       | Use…                                                               |
|---------------------------------|--------------------------------------------------------------------|
| Identity + logging + crash + OTel bootstrap | `mgf.common.bootstrap()`                                            |
| Layered config (kwargs > env > .env > YAML > defaults) | `mgf.common.config.BaseAppSettings`                                  |
| Vault-backed secrets             | `mgf.common.vault`                                                  |
| Structured logging               | `mgf.common.observability.setup_logging`                            |
| HTTP client (incl. resumable download) | `mgf-http` (sibling)                                                |
| SQLAlchemy session + audit-trail + UUID v7 | `mgf-sqlalchemy` (sibling)                                          |
| Alembic helpers + drift detector | `mgf-alembic` (sibling)                                             |
| FastAPI middleware (rate-limit, webhook audit, security headers) | `mgf-fastapi` (sibling)                                              |
| Django middleware (throttle)     | `mgf-django` (sibling)                                              |
| External API verification        | `mgf-apiprobe` (sibling)                                            |
| Live push (Server-Sent Events) over a pub/sub broker + slot caps | `mgf-livepush` (sibling)                                            |
| Session-token + webhook-signature verification (Clerk / Svix-shape) | `mgf-auth` (sibling)                                                |
| Telematics device decoding (vendor-neutral seam + per-vendor codec) | `mgf-tele-core` + `mgf-tele-teltonika` (siblings)                   |
| Docs site scaffold (cookiecutter)| `mgf-website-template` (sibling)                                    |
| Feature flags                    | `mgf.common.flags` (since v0.35.0)                                  |
| Scheduler                        | `mgf.common.schedule` (since v0.35.0)                               |
| Plugin auto-discovery            | `mgf.common.plugins` (since v0.36.0)                                |
| Doctor / health-report bundles   | `mgf.common.doctor` / `mgf.common.health` (since v0.36.0 / v0.37.0) |
| Idempotency-key store            | `mgf.common.idempotency` (since v0.37.0)                            |
| Rate-limit / token-bucket primitive | `mgf.common.rate_limit` (since v0.37.0)                              |
| LRU + TTL cache                  | `mgf.common.cache` (since v0.37.0)                                  |
| Tiered test runs + auto-quarantine + structured JSONL outcomes + per-failure detail bundles | `mgf-fed test` CLI + `mgf.common.testing` (schema + tier model + parallel-safe paths) — since v0.40.0; spec at TS-22..TS-27 |

**When to deviate.** If a federation library doesn't fit your need
(missing feature, performance gap, API mismatch), **file a paper at
the appropriate repo's `FEEDBACK.md` BEFORE adopting an alternative**.
That paper is how the federation learns; your `MGF_STANDARDS_CONFORMANCE.md`
can carry a `🚫 Declined: see PAPER-NN` row pointing at it.

---

## §6 Catch-up cadence + the tool

The federation moves. You need a mechanical way to stay current
without reading 7 CHANGELOGs every Monday.

**The command:**

```sh
mgf-fed catch-up               # read-only audit (default)
mgf-fed catch-up --apply       # apply mechanical fixes
mgf-fed catch-up --path PATH   # target a project other than cwd
```

**What it audits:**

1. `pyproject.toml` pin freshness — flags stale `mgf-common` pin
   relative to the installed version.
2. Four-gate CI presence (ruff, mypy --strict, pytest, coverage).
3. `docs/CLAUDE.md` existence + auto-block freshness.
4. `.claude/settings.json` permission shape.
5. `AGENTS.md` existence + match against the canonical pointer.
6. v0.1-pattern leaks (legacy import paths).
7. Closed-box leaks (private `_*` imports across module boundaries).
8. **Federation contract** (DOC-17, this file). Required artifacts:
   the universal root-doc baseline (DOC-01 v2.11 — README, LICENSE,
   CHANGELOG, CONTRIBUTING, SECURITY, FEEDBACK, AGENTS, STARTHERE,
   FEDERATION, DEPS + a docs/ dir) + MGF_ADOPTION.md (consumers) +
   MGF_STANDARDS_CONFORMANCE.md (everyone). **Missing required artifacts cause
   a non-zero exit code** — wire `mgf-fed catch-up` into your CI
   pipeline if you want enforcement.

**Cadence.**

| Trigger                                        | Action                                                |
|------------------------------------------------|-------------------------------------------------------|
| Every mgf-common MINOR release                 | Run `mgf-fed catch-up`; pick up new auto-block.    |
| Quarterly                                      | Run regardless; standards drift is silent.            |
| Before any major refactor in your project      | Run; confirm your foundation is current.              |
| In CI on every PR (recommended for L2/L3)      | Run `mgf-fed catch-up`; fail the build on non-zero exit.    |

---

## §7 Feedback discipline

The federation has **one** feedback flow, repo-scoped per DOC-13 / FB-01..04.

| Friction type                                              | File at…                                              |
|------------------------------------------------------------|-------------------------------------------------------|
| Touches one sibling's public API or behavior               | That sibling's repo `FEEDBACK.md`                     |
| A standards rule, a new rule, or this contract             | [`mgf-standard/FEEDBACK.md`](FEEDBACK.md) (this repo) |
| A genuinely cross-sibling pattern (no single owner)        | [`mgf-common`'s `FEEDBACK.md`](https://codeberg.org/magogi-admin/mgf-common/src/branch/main/FEEDBACK.md) |
| Touches `mgf-common` library code or CLI directly          | [`mgf-common`'s `FEEDBACK.md`](https://codeberg.org/magogi-admin/mgf-common/src/branch/main/FEEDBACK.md) |

**The shape.** Every PAPER has:

- `PAPER-NN` numeric ID (monotonic per repo).
- Title.
- Severity: 🔴 Blocker / 🟡 Sharp edge / 🟢 Nice-to-have / 💭 Idea.
- Body: what hurts, why it hurts, what you'd want.

The full template + cadence is at `mgf-fed feedback-howto` (the CLI) or
in [`FEEDBACK.md`](FEEDBACK.md) (the live channel).

**For AI agents.** The auto-block in your `docs/CLAUDE.md` (managed
by `mgf-fed catch-up`) reminds Claude where to file what. You don't
need to.

---

## §8 Onboarding flows

> **Standard instruction for any new project (give this verbatim).**
> *"Before working in this project, point your AI agent at
> `mgf-common/STARTHERE.md` — start with the 'For the AI agent in
> any Magogi project' section."* One instruction, every project, no
> per-project variant.

### §8.1 You're starting a NEW project

```sh
mkdir my-new-app && cd my-new-app && git init
mgf-fed init-project --name my-new-app --kind <cli|fastapi|django|library|service>
# Paste the printed pyproject snippet into pyproject.toml
uv sync && uv run ruff check && uv run mypy --strict src/ && uv run pytest
```

What landed:
- `docs/CLAUDE.md` with the federation auto-block.
- `.claude/settings.json` with safe Claude permission defaults.
- Pyproject snippet pinning mgf-common + the four gates.

**Next:** create your `FEEDBACK.md`, `MGF_ADOPTION.md`, and
`MGF_STANDARDS_CONFORMANCE.md` from the templates in
[`docs/recipes/`](docs/recipes/). Then run `mgf-fed catch-up` to
verify the contract.

### §8.2 You're an EXISTING project adopting mgf-common

```sh
cd my-existing-app
# Add mgf-common>=<latest>,<<next-major> to pyproject.toml.
uv sync
mgf-fed catch-up                # audits drift
mgf-fed catch-up --apply        # creates docs/CLAUDE.md + .claude/settings.json
```

Then hand-create:
- `FEEDBACK.md` (if not already present).
- `docs/inprogress/MGF_ADOPTION.md` (from the template).
- `docs/inprogress/MGF_STANDARDS_CONFORMANCE.md` (from the template).

Re-run `mgf-fed catch-up` — should be clean.

### §8.3 You're a FEDERATION SIBLING (mgf-* library)

You're held to the same contract PLUS:

- `DEPS.md` §2 (DOC-16) — the "who depends on me" roster at repo root.
- Per-MINOR import-survey to keep `DEPS.md` §2 factual.
- No `MGF_ADOPTION.md` (ADP-04 carve-out — your adoption is documented
  in the federation roadmap).
- Test in your own `.venv`; pin `mgf-common>=X.Y,<X.(Y+1)` for the
  current cycle.

---

## §9 Cheat sheet (the whole contract on one screen)

| Thing            | Where it lives                                                  | Rule       |
|------------------|-----------------------------------------------------------------|------------|
| README.md        | repo root                                                       | DOC-01     |
| LICENSE          | repo root                                                       | DOC-01     |
| CHANGELOG.md     | repo root                                                       | DOC-01     |
| SECURITY.md      | repo root                                                       | DOC-01 / SC-12 |
| FEEDBACK.md      | repo root, repo-scoped                                          | DOC-13 / FB-01..04 |
| CONTRIBUTING.md  | repo root                                                       | DOC-01     |
| AGENTS.md        | repo root (catch-up-managed pointer)                            | DOC-01 / DOC-07 |
| STARTHERE.md     | repo root                                                       | DOC-01     |
| FEDERATION.md    | repo root (pointer stub for non-cornerstone)                    | DOC-01 / DOC-17 |
| docs/ (dir)      | repo root                                                       | DOC-01 / DOC-02 |
| MGF_ADOPTION.md  | `docs/inprogress/` (consumer apps)                              | DOC-14 / ADP-01..04 |
| MGF_STANDARDS_CONFORMANCE.md | `docs/inprogress/`                                  | DOC-15 / CFM-01..04 |
| DEPS.md          | repo root (every project — §1 deps + §2 dependents)             | DOC-01 / DOC-16 |
| docs/CLAUDE.md   | with auto-managed federation block                              | DOC-07     |
| `mgf-fed catch-up` | quarterly + every MINOR + CI                              | DOC-17 (this file) |
| `mgf-fed init-project` | new-project scaffold                                    | —          |
| `mgf-fed feedback-howto` | print FEEDBACK.md flow + template                          | —          |
| `mgf-fed standards [name]` | print standards doc(s)                              | —          |
| Standards corpus | [`docs/standards/`](docs/standards/)                            | DP-* etc.  |
| Templates        | [`docs/recipes/`](docs/recipes/)                                | —          |
| Federation roster| [`DEPS.md`](DEPS.md) §2 (mgf-common) + per-sibling DEPS.md       | DOC-16     |

---

## §10 How this document is maintained

- mgf-standard owns this file. Edits land here first; the
  `mgf-common` cornerstone, siblings, and consumers all link to it.
- Every standards-corpus bump MUST review this file for drift; if a
  new DOC / FB / ADP / CFM rule changes the contract, this file
  updates in the same commit.
- Every change to `mgf-fed catch-up`'s audit checks MUST update
  §6 to match.
- Major federation events (new sibling, new tracker requirement,
  changed catch-up cadence) belong here.

If you're reading this in a sibling or consumer project: you're reading
a link. The authoritative copy is at
[`mgf-standard/FEDERATION.md`](https://codeberg.org/magogi-admin/mgf-standard/src/branch/main/FEDERATION.md).
