# mgf-http — Claude Reference

<!-- BEGIN mgf-common auto-generated — managed by `mgf-common 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-common standards <topic>` to read any one of them.

> **Project kind:** library
> **Cornerstone library:** `mgf-common` (this project depends on it).
> **Conformance level:** L1 (production-ready) by default. See
> `mgf-common standards README` §"Conformance levels".

---

## 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-common standards            # list all topics
mgf-common standards LOGGING    # print the full doc
mgf-common 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-common standards api` |
| Error handling, exceptions, retries | ERROR_HANDLING | `mgf-common standards errors` |
| Logging, redaction, OTel | LOGGING | `mgf-common standards logging` |
| Configuration, settings, env vars | CONFIGURATION | `mgf-common standards config` |
| Secrets, TLS, subprocess, crypto | SECURITY | `mgf-common standards security` |
| Tests, fixtures, isolation | TESTING | `mgf-common standards testing` |
| Architecture, layering, replaceability | DESIGN_PRINCIPLES | `mgf-common standards design` |
| Scope (what belongs in this project) | SCOPE | `mgf-common 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-http/__init__.py
"""mgf-http — 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-common 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-standard/docs/standards/DOCUMENTATION.md`](https://codeberg.org/magogi-admin/mgf-standard/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-common feedback              # how to submit + severity guide
mgf-common feedback --template   # entry template, ready to paste
mgf-common feedback --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-common/docs/recipes/mgf-adoption-md-template.md](https://codeberg.org/magogi-admin/mgf-common/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-common/docs/recipes/mgf-standards-conformance-md-template.md](https://codeberg.org/magogi-admin/mgf-common/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
this marker is preserved across `mgf-common catch-up --apply` runs. -->

---

## Project-specific lookup

*(Add project-specific facts here as the project grows: gotchas,
non-obvious design decisions, fixed bugs, performance budgets,
etc. Keep this section the canonical "what will burn you"
reference. Do NOT add ephemeral state — current branch, in-progress
tasks — those belong in the task tracker.)*

---

*Generated by `mgf-common init-project`. Re-run with `--force` to
regenerate (your project-specific sections will be overwritten —
back them up first).*
