<!-- BEGIN mgf-common auto-generated — managed by `mgf-fed catch-up`.
Edit only between this block's BEGIN/END markers if you want catch-up to
refresh your changes; project-specific content goes BELOW the END marker
in the "Project-specific lookup" section. -->

Project-specific lookup for Claude sessions. Cross-project
engineering standards live in `mgf-common`; run
`mgf-fed standards <topic>` to read any one of them.

**▶ First, run `mgf-fed agents`** — it prints the canonical
federation-wide agent briefing (always installed; `mgf-common` is a
dependency of this project). The briefing covers the federation
shape, using the library + its siblings instead of reinventing
them, the standards + docs layout, keeping this project in sync with
`mgf-fed catch-up`, and filing feedback in the relevant library's
`FEEDBACK.md` when you hit friction so the library itself can improve.

> **Project kind:** library
> **Cornerstone library:** `mgf-common` (this project depends on it).
> **Conformance level:** declare yours in
> `docs/inprogress/MGF_STANDARDS_CONFORMANCE.md` (L1 / L2 / L3) — see
> `mgf-fed standards README` §"Conformance levels for projects".

---

## Standing instructions — every session

Claude reads this file on every session start. The rules below are
canonical; the full text lives in `mgf-common` standards docs and
is accessible via:

```bash
mgf-fed standards            # list all topics
mgf-fed standards LOGGING    # print the full doc
mgf-fed standards security   # alias also works
```

**Before writing or editing code in any of these areas, read the
corresponding topic doc:**

| Area | Topic | Run |
|---|---|---|
| API surface (public functions, modules) | API_DESIGN | `mgf-fed standards api` |
| Error handling, exceptions, retries | ERROR_HANDLING | `mgf-fed standards errors` |
| Logging, redaction, OTel | LOGGING | `mgf-fed standards logging` |
| Configuration, settings, env vars | CONFIGURATION | `mgf-fed standards config` |
| Secrets, TLS, subprocess, crypto | SECURITY | `mgf-fed standards security` |
| Tests, fixtures, isolation | TESTING | `mgf-fed standards testing` |
| Architecture, layering, replaceability | DESIGN_PRINCIPLES | `mgf-fed standards design` |
| Scope (what belongs in this project) | SCOPE | `mgf-fed standards scope` |

---

## The top-30 most-violated rules (inline so they're always in context)

These are the rules that come up most often in code review. Treat
every MUST as non-negotiable. The ID prefix tells you which doc
the full rationale lives in (DP- = DESIGN_PRINCIPLES, EH- =
ERROR_HANDLING, etc.).

### Architecture (DP-)

- **DP-01** Layering MUST be enforced: UI MUST NOT be imported by
  core; core MUST NOT import third-party SDKs that have a provider
  in front of them.
- **DP-02** Every third-party I/O dep MUST sit behind an ABC with
  a production AND a mock implementation.
- **DP-03** Domain types passed between modules MUST be frozen
  dataclasses (or pydantic `frozen=True`); never bare strings/dicts.
- **DP-04** Every public function MUST have a typed signature;
  `mypy --strict` MUST pass on `src/`.
- **DP-09** Cancellation MUST be explicit. Long-running ops take
  an explicit `CancellationToken`-like parameter; never thread-global.
- **DP-11** Async tasks MUST have an owner. Bare
  `asyncio.create_task(...)` without retention is a defect.
- **DP-12** Time MUST be UTC at every boundary. `datetime.now()`
  is forbidden; use `datetime.now(UTC)`. Naive datetimes never
  cross module boundaries.
- **DP-13** Every owned external resource MUST be released
  deterministically via context manager or `try / finally`.
  GC-based cleanup is a defect.

### Error handling (EH-)

- **EH-01** Every exception raised by app code MUST be a subclass
  of the application's base error class (typically
  `mgf.common.exceptions.AppError`).
- **EH-02** Third-party exceptions MUST be translated to typed
  application exceptions at the boundary. Use
  `mgf.common.providers.ProviderABC` + `@translate_at_seam` for
  this.
- **EH-03** When re-raising a translated exception, the original
  cause MUST be chained via `raise NewError(...) from original`.
- **EH-04** Every entry point MUST install a top-level handler
  (folded into `mgf.common.bootstrap()` automatically).
- **EH-07** Bare `except Exception:` (without re-raise or typed
  translation) MUST NOT appear except in narrow cleanup paths.
- **EH-11** Retries MUST use exponential backoff with full jitter
  and a finite cap. Use `mgf.http.RetryPolicy` (sibling `mgf-http`).

### Logging (LG-)

- **LG-01** Every module MUST acquire its logger via
  `logging.getLogger(__name__)`. No bare `logging.info(...)`.
- **LG-04** Sensitive fields MUST be redacted by the formatter
  before any sink sees them. The default
  `mgf.common.observability.Redactor` covers the canonical set.
- **LG-05** Error-level logs MUST include the exception via
  `LOG.exception(...)` or `exc_info=True`.
- **LG-08** Log messages MUST use lazy `%`-style formatting
  (`LOG.info("processing %s", x)`), NOT f-strings.
- **LG-09** Structured fields MUST be passed via `extra={...}`.
- **LG-12** Log emission MUST be cheap (≤100 µs per record).
  Heavy work belongs in the handler, not the call site. Use
  `mgf.common.observability.AsyncJsonHandler` for non-blocking I/O.

### Configuration (CF-)

- **CF-01** Application config MUST live in a single typed object
  (`mgf.common.config.BaseAppSettings`-derived). No module reads
  config files / env vars directly.
- **CF-02** Precedence: CLI flags → env vars → `.env` → on-disk
  config → typed defaults.
- **CF-05** Secrets MUST NOT live in the config file; they live in
  a vault. Use `mgf.common.vault.VaultProtocol`.
- **CF-08** `Settings` is loaded once at the entry point and
  passed down by constructor injection. No module-global singletons.
- **CF-10** Tests MUST construct `Settings` with explicit values
  (no env-var leakage).

### Security (SC-)

- **SC-01** Secrets MUST live in a Vault, never in config / env /
  source / logs / crash reports.
- **SC-02** Subprocess invocation MUST use `argv` lists with
  `shell=False`.
- **SC-06** TLS verification MUST be enabled on every outbound
  connection.
- **SC-07** Every external request MUST carry a finite timeout.
- **SC-15** Filesystem operations MUST validate against directory
  traversal via `Path.resolve()` + `is_relative_to()`.

### Testing (TS-)

- **TS-01** `tests/` MUST mirror `src/` 1:1.
- **TS-02** The unit suite MUST run with no production
  credentials, no network, no real third-party daemon.
- **TS-04** `filterwarnings = ["error"]` MUST be set in
  `pyproject.toml`.
- **TS-06** Coverage gate ≥80% project-wide; ≥90% on changed
  lines.

### API design (AP-)

- **AP-01** Public API surface MUST be enumerated explicitly via
  `__all__` at every package and module boundary.
- **AP-04** Deprecation cycle MUST be: announce → still works
  (≥1 MINOR) → removed; deprecated names emit
  `DeprecationWarning`.
- **AP-08** Public modules MUST use
  `from __future__ import annotations`; runtime-unused imports go
  in `if TYPE_CHECKING:`.
- **AP-14** Internal modules MUST NOT be imported by consumers.
  Single-underscore module names are private.

---

## Quick start — bootstrapping this project

This project depends on `mgf-common`. The canonical entry point
is `mgf.common.bootstrap()`:

```python
# src/mgf-standard/__init__.py
"""mgf-standard — library shape; do NOT call bootstrap() here."""
from mgf.common.observability import get_logger, operation_span

LOG = get_logger(__name__)

# Library code uses get_logger + operation_span (no-op-safe when no
# host has bootstrapped). The host app calls mgf.common.bootstrap().
```

For test fixtures, use `mgf.common.bootstrap_for_test()`:

```python
import pytest
from mgf.common import bootstrap_for_test, AppContext

@pytest.fixture
def app_ctx() -> AppContext:
    with bootstrap_for_test() as ctx:
        yield ctx
```

For the full integration shape (settings, exceptions, observability,
recipes), see `mgf-common`'s
`docs/recipes/library.md` (run `mgf-fed standards
components` to find it).

---

## Four green gates — every PR

Before any commit, all four MUST pass:

```bash
ruff check src tests
mypy --strict src/
pytest --cov --cov-fail-under=80
lint-imports
```

The pyproject.toml snippet generated alongside this file pre-tunes
ruff + mypy + pytest. Add `import-linter` rules for layering as
the project grows.

---

## Federation-discipline reminders (v2.8 DOC-13 / DOC-14 / DOC-15)

Three living disciplines apply to every consumer of mgf-common.
Each has a one-paragraph reminder below; the full rules live in
[`mgf-common/docs/standards/DOCUMENTATION.md`](https://codeberg.org/magogi-admin/mgf-common/src/branch/main/docs/standards/DOCUMENTATION.md).

<!-- BEGIN mgf-common: feedback-discipline -->

### Feedback discipline (DOC-13 + FB-01..FB-04)

Hit friction in mgf-common OR any federation sibling? **File a
`PAPER-NN` entry in the target repo's `FEEDBACK.md`** — not
ad-hoc emails, not lost one-off issues.

- Touches one library's surface (e.g., mgf-http retries,
  mgf-fastapi middleware) → file in that library's `FEEDBACK.md`
  (sibling-scoped per DOC-13).
- Touches federation-wide concerns (cross-sibling patterns,
  standards proposals, cornerstone APIs) → file in
  [mgf-common/FEEDBACK.md](https://codeberg.org/magogi-admin/mgf-common/src/branch/main/FEEDBACK.md).

```bash
mgf-fed feedback-howto              # how to submit + severity guide
mgf-fed feedback-howto --template   # entry template, ready to paste
mgf-fed feedback-howto --url        # canonical FEEDBACK.md URL
```

Severity guide:
- 🔴 **Blocker** — getting it wrong requires a breaking change later.
- 🟡 **High** — real quality-of-life pain, additive to fix.
- 🟢 **Nice-to-have** — real value, not urgent.
- 💭 **Aspirational** — long-term direction input.

Don't wait for permission. The maintainer triages.

<!-- END mgf-common: feedback-discipline -->

<!-- BEGIN mgf-common: adoption-discipline -->

### Adoption-tracker discipline (DOC-14 + ADP-01..ADP-04)

This project's adoption of mgf-common (which versions, which
features, which phase) lives in
`docs/inprogress/MGF_ADOPTION.md` (or `docs/MGF_ADOPTION.md`).
**Update it on every pin bump AND every closed FEEDBACK paper**
that touches this project's adoption surface (per ADP-03).

Template:
[mgf-standard/docs/recipes/mgf-adoption-md-template.md](https://codeberg.org/magogi-admin/mgf-standard/src/branch/main/docs/recipes/mgf-adoption-md-template.md).

Federation siblings: the ADP-04 carve-out exempts you — your
adoption story is the federation_roadmap + your own CHANGELOG.

<!-- END mgf-common: adoption-discipline -->

<!-- BEGIN mgf-common: conformance-discipline -->

### Conformance-tracker discipline (DOC-15 + CFM-01..CFM-04)

This project's conformance to mgf-common's standards (per-rule
✅ / 🚫 / ⏳ / N/A status) lives in
`docs/inprogress/MGF_STANDARDS_CONFORMANCE.md`. **Update it on
every standards bump in mgf-common AND on every PR that changes
code touching a conformance rule** (per CFM-03).

Declared conformance level (L1 / L2 / L3 per CFM-02): see this
project's README. Decline-with-rationale (🚫) MUST carry a
paragraph per
[principles/non-adoption-is-valid.md](https://codeberg.org/magogi-admin/mgf-standard/src/branch/main/docs/standards/principles/non-adoption-is-valid.md).

Template:
[mgf-standard/docs/recipes/mgf-standards-conformance-md-template.md](https://codeberg.org/magogi-admin/mgf-standard/src/branch/main/docs/recipes/mgf-standards-conformance-md-template.md).

<!-- END mgf-common: conformance-discipline -->

<!-- END mgf-common auto-generated. Project-specific content below

# mgf-standard — Claude Reference

Dense lookup. Facts only. No prose narratives.

---

## What this repo is

Federation **standards source of truth + tiny resolver package**.

- `docs/standards/` — the engineering-standards corpus (AP / CF / EH / LG /
  SC / TS / DP / DOC / NM / OB / PF / AG / TM / … rules). Every `mgf-*` repo
  conforms to these rules.
- `FEDERATION.md` — the canonical federation contract. Every sibling ships a
  DOC-17 pointer stub pointing here.
- `MGF_LIBRARIES.md` — the always-current library registry (generated; REL-13
  gate).
- `src/mgf/standard/` — a tiny zero-dependency Python package that ships
  the corpus as wheel data and exposes three typed helpers.

`mgf-standard` is the **federation leaf-of-leaves**: `mgf-common` depends
on it; it depends on nothing in the `mgf.*` namespace. This keeps the runtime
dependency graph acyclic.

---

## Key paths

| Path | What |
|---|---|
| `FEDERATION.md` | Canonical federation contract |
| `MGF_LIBRARIES.md` | Library registry (generated; do not edit by hand) |
| `docs/standards/` | The engineering-standards corpus |
| `docs/standards/README.md` | Master index + MUSTs table |
| `docs/design/federation.md` | Federation-pattern architecture paper |
| `docs/recipes/` | Federation-operations recipes + governance templates |
| `scripts/gen_mgf_libraries.py` | Registry generator + REL-13 consistency gate |
| `src/mgf/standard/__init__.py` | Public resolver API: `standards_dir`/`list_standards`/`read_standard`, `recipes_dir`/`list_recipes`/`read_recipe`, `libraries` |
| `.importlinter` | Import-linter config — enforces the leaf-of-leaves invariant |

---

## Reading a standard

Normal path — through `mgf-common`'s CLI (installed in every federation project):

```sh
mgf-fed standards              # list all topics
mgf-fed standards LOGGING      # print LOGGING.md
mgf-fed agents                 # print the full AI-agent briefing
```

These resolve via `mgf.standard.standards_dir()`. A checkout of this repo
is not needed to read the rules.

Direct Python access:

```python
import mgf.standard as std
std.list_standards()              # ['API_DESIGN', 'CONFIGURATION', 'LOGGING', ...]
std.read_standard("LOGGING")      # full LOGGING.md text
```

---

## Regenerating the registry

```sh
# Run from the federation parent directory that holds all sibling checkouts:
python scripts/gen_mgf_libraries.py

# REL-13 gate (CI-safe, exits non-zero if registry is stale):
python scripts/gen_mgf_libraries.py --check
```

**REL-13 rule:** run `gen_mgf_libraries.py` before every release. Only changes
to `mgf-standard` (this repo) update `MGF_LIBRARIES.md`. Never edit
`MGF_LIBRARIES.md` by hand — it is generated.

---

## Dev setup + gates

```sh
uv sync --extra dev
uv run ruff check src tests scripts
uv run ruff format --check src tests scripts
uv run mypy --strict src/
uv run pytest
uv run lint-imports          # enforces .importlinter leaf-of-leaves rule
```

All five must be green before opening a PR.

---

## TS-23 carve-out — no mgf-test-supervisor

This repo does **not** dev-depend on `mgf-test-supervisor`. Reason: that edge
would be `mgf-standard` → `mgf-test-supervisor` → `mgf-common` →
`mgf-standard` — a cycle that the REL-13 generator records and that the
import-linter would flag. The test surface here is trivial (resolver helpers +
the registry-generator test), so we consciously decline TS-23 and run plain
`pytest`. Documented as a CFM-04 decline-with-rationale in
`docs/inprogress/MGF_STANDARDS_CONFORMANCE.md`.

---

## Hard rule: mgf.standard imports nothing from mgf.*

`src/mgf/standard/__init__.py` MUST NOT import from any `mgf.*` namespace.
`import-linter` (`.importlinter` at repo root) enforces this. Violating it
closes a dependency cycle and breaks `mgf-common`'s ability to depend on this
package.

---

## Standards-change propagation (DOC-18)

A change to `docs/standards/` MUST update in the same commit:
1. `docs/standards/README.md` MUSTs index (if a MUST is added or reworded).
2. Every dependent named in the changed doc's Propagation header — typically
   `mgf-common/docs/claude/CLAUDE.md` and consumer guides that cite the rule.

---

## Commit-trailer convention

Every commit MUST end with both trailers (AG-03; setup in
`docs/recipes/commit-signing.md`):

```
Signed-off-by: Bassam Alsanie <bassam@magogi.org>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
```

---

Last updated: 2026-06-01
