<!-- 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:** django
> **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
# mgf-django/settings.py
INSTALLED_APPS = [
    # … your apps …
    "mgf.django",
]

MIDDLEWARE = [
    "mgf.django.MgfRequestIdMiddleware",
    "mgf.django.MgfContextMiddleware",
    # … your other middleware …
]

LOGGING = {
    "version": 1,
    "formatters": {"json": {"()": "mgf.django.JsonFormatter"}},
    "handlers": {
        "console": {"class": "logging.StreamHandler", "formatter": "json"},
    },
    "root": {"handlers": ["console"], "level": "INFO"},
}

MGF_COMMON_APP_NAME = "mgf-django"
MGF_COMMON_APP_VERSION = "0.1.0"
```

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/django.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

<!-- 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.

**▶ First, run `mgf-common 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-common catch-up`, and filing feedback in the relevant library's
`FEEDBACK.md` when you hit friction so the library itself can improve.

> **Project kind:** django
> **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-common 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-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
# mgf-django/settings.py
INSTALLED_APPS = [
    # … your apps …
    "mgf.django",
]

MIDDLEWARE = [
    "mgf.django.MgfRequestIdMiddleware",
    "mgf.django.MgfContextMiddleware",
    # … your other middleware …
]

LOGGING = {
    "version": 1,
    "formatters": {"json": {"()": "mgf.django.JsonFormatter"}},
    "handlers": {
        "console": {"class": "logging.StreamHandler", "formatter": "json"},
    },
    "root": {"handlers": ["console"], "level": "INFO"},
}

MGF_COMMON_APP_NAME = "mgf-django"
MGF_COMMON_APP_VERSION = "0.1.0"
```

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/django.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

# mgf-django — Claude Reference

Dense lookup document. No prose. Facts only.

> **See also:** [`mgf-common/docs/claude/CLAUDE.md`](https://codeberg.org/magogi-admin/mgf-common/src/branch/main/docs/claude/CLAUDE.md)
> — cornerstone reference shared across the federation. The
> cross-cutting patterns (atomic-write, never-raises observers,
> redaction layering) documented there apply to this sibling
> too. THIS file is the mgf-django-specific addenda.

---

## Project shape

- **Federation sibling** of `mgf-common` (per
  [`DOCUMENTATION.md`](https://codeberg.org/magogi-admin/mgf-standard/src/branch/main/docs/standards/DOCUMENTATION.md) §2.0).
- **Conformance target:** L2 — inherited via
  the `mgf-common` pin declared in `pyproject.toml`.
- **PyPI:** `mgf-django` (first published at v0.2.0;
  v0.1.0 was prepped but never published — see
  [`CHANGELOG.md`](../../CHANGELOG.md) for the rationale).
- **Codeberg:** `magogi-admin/mgf-django`; default branch `main`.

## File map (where things live)

| Path | Purpose |
|---|---|
| `src/mgf/django/__init__.py` | Re-exports the 5 public names from `_apps.py` / `_middleware.py` / `_logging.py` / `_settings.py`. PEP 420 namespace package — no top-level `mgf/__init__.py`. |
| `src/mgf/django/apps.py` | Imports `MgfCommonConfig` from `_apps.py` so Django's `INSTALLED_APPS` discovery (which walks for `apps.py` per package) finds it. Both `mgf.django.MgfCommonConfig` and `apps.py`-side import work; the canonical name is the dotted re-export. |
| `src/mgf/django/_apps.py` | `MgfCommonConfig(AppConfig)` — `ready()` calls `mgf.common.bootstrap()` exactly once per process via a module-level guard; `atexit` hook unwinds the bootstrap stack on shutdown. |
| `src/mgf/django/_middleware.py` | `MgfRequestIdMiddleware` + `MgfContextMiddleware` — sync-mode Django middleware. Shares the `mgf.common._request_id` contextvar with `mgf.fastapi.RequestIdMiddleware`. |
| `src/mgf/django/_logging.py` | `JsonFormatter` no-arg wrapper around `mgf.common.observability.JsonFormatter` for Django `LOGGING['formatters']`. |
| `src/mgf/django/_settings.py` | `DjangoSettingsBridge` — read-only `BaseAppSettings`-compatible snapshot of `django.conf.settings`. NEVER carries `SECRET_KEY` itself; exposes `secret_key_present` boolean only. |
| `PUBLIC_API.md` | Contract list — every public name with stability tier + description (per **AP-10**). |
| `CHANGELOG.md` | Per-release record (Keep a Changelog format). |
| `SECURITY.md` | Vulnerability-reporting policy (per **SC-12**). |
| `docs/standards/README.md` | Pointer-only stub — points at `mgf-standard/docs/standards/`. NOT a duplicate. |
| `docs/cutover/v0.1.0.md` | Maiden-voyage migration guide (the rename from `mgf.common.django.*` → `mgf.django.*`). |
| `docs/recipes/django.md` | Full Django-settings.py walkthrough. |

## Cross-cutting patterns

1. **Bootstrap exactly once.** `MgfCommonConfig.ready()` calls
   `mgf.common.bootstrap()` with a module-level
   `_BOOTSTRAP_DONE` guard. Multiple `ready()` calls (Django's
   `override_settings`, the autoreloader, the test runner) are
   no-ops. The `atexit` hook unwinds the bootstrap stack on
   shutdown.

2. **Request-id sharing.** `MgfRequestIdMiddleware` reads/sets
   the same `mgf.common._request_id` contextvar that
   `mgf.fastapi.RequestIdMiddleware` uses. A Django app that
   makes an internal RPC to a FastAPI service (or vice versa)
   propagates the same `X-Request-Id` end-to-end, ASSUMING the
   upstream call sets the header.

3. **Middleware install order.** `MgfRequestIdMiddleware` MUST
   come BEFORE `MgfContextMiddleware` so the request id is
   bound to the contextvar before the context middleware
   resolves the active `AppContext`.

4. **Django app label = `mgf_django`** (not `mgf.django`).
   Django labels can't contain dots; the package previously
   used `mgf_common` as a stable label, but at the v0.1
   sibling extraction the label moved to `mgf_django` to match
   the new module path. Any consumer config that hardcoded
   `apps.get_app_config("mgf_common")` MUST update to
   `"mgf_django"`.

5. **`DjangoSettingsBridge` snapshots at construction time.**
   Mutation of `django.conf.settings` after the bridge is
   constructed (rare in production, occasional in tests via
   `override_settings`) is NOT reflected — construct a fresh
   bridge.

## Build and release

The canonical sequence per
[`mgf-standard/docs/standards/RELEASING.md`](https://codeberg.org/magogi-admin/mgf-standard/src/branch/main/docs/standards/RELEASING.md):

1. Bump `version` in `pyproject.toml`.
2. Add the `[X.Y.Z] — YYYY-MM-DD` entry in `CHANGELOG.md` in
   the same commit.
3. Update `PUBLIC_API.md` if the public surface changed
   (validated by `tests/unit/test_public_api_doc.py` against
   `__all__`).
4. Run the full test suite locally (`pytest`).
5. Run `mypy --strict src/mgf/django/`.
6. Build: `uv build`.
7. `twine check dist/*` — both wheel and sdist MUST pass.
8. Commit (`chore: cut vX.Y.Z`).
9. Tag annotated: `git tag -a vX.Y.Z -m '...'`.
10. Push commit + tag: `git push origin main && git push origin vX.Y.Z`.
11. Upload: `twine upload dist/*`.
12. Post-publish smoke: `pip install --upgrade mgf-django==X.Y.Z`
    in a clean venv; import every public name.

## Common pitfalls

- **Forgetting to add `mgf.django` to `INSTALLED_APPS`.** The
  middleware works (the contextvar exists at import time) but
  `bootstrap()` never runs — `mgf-common` features that depend
  on it (OTel correlation, crash reporter, redactor) silently
  no-op. Symptom: log records have no `trace_id`/`span_id`.
- **Middleware order swapped.** `MgfContextMiddleware` BEFORE
  `MgfRequestIdMiddleware` → context resolves before the
  request id is bound → context's request-id field is `None`.
- **Bridge cached at module top.** A consumer that does
  `BRIDGE = DjangoSettingsBridge.from_django()` at module-load
  time captures `django.conf.settings` BEFORE Django's
  settings loader runs in some test arrangements. Construct
  per-request or per-test instead.
- **Async views.** All three middleware are sync-mode only.
  Mixed sync/async middleware in Django requires the
  `async_capable = True` flag, which `MgfRequestIdMiddleware`
  + `MgfContextMiddleware` do NOT set. Pin a future-async-shape
  upgrade behind a feature flag.

## Recently-touched areas

(Rolling list, last N changes. Update on every commit that
changes a load-bearing fact.)

- **v0.2.0 prep (2026-05-15)** — added v2.6/v2.7 compliance
  files (this CLAUDE.md + SECURITY.md + docs/standards/README.md
  pointer); bumped the mgf-common pin (in v0.1.0 prep
  commit `d07c20e`); v0.1.0 tag deleted in favour of v0.2.0
  as the maiden publish.
- **v0.1.0 extraction (2026-05-10)** — initial extraction
  from `mgf-common[django]` per the federation split plan.
  Five public names; 18 unit tests at parity with the
  pre-extraction shape.

---

*Last updated: 2026-05-15.*
