# Build an independent Media Discussions implementation

Target the documented alpha pilot interface served by this reference at version 0.1.0-alpha.1. Use this guide to build and verify an independent server in one implementation pass. Choose your own language, framework, layout, storage, and AT Protocol SDK. The current pilot fixture defines the HTTP examples below. Its software version follows SemVer, and pre-release interfaces may change. The schemas use Lexicon format `1`. [Public reference](https://media.experiments.verylittlegravitas.com/docs) · [Machine-readable Lexicons](https://media.experiments.verylittlegravitas.com/docs/lexicons) · [Conformance runner](https://media.experiments.verylittlegravitas.com/docs/conformance/run.py)

## 1. Load the contract and seed the pilot

1. Fetch the [Lexicon index](https://media.experiments.verylittlegravitas.com/docs/lexicons) and dereference every `href`. Pair each `id` with its downloaded schema. Use the seven schemas to build records under `com.danhon.atprotomedia.` Use an AT Protocol validator for field lengths, formats, and record keys.
2. Use the runner’s `EPISODES`, `BBC`, `IMDB`, `FANFARE`, and `REDDIT` constants as the data vectors. Seed *Doctor Who: 73 Yards* and the ten *Widow’s Bay* episodes, including their published watch destinations. Add public pre-episode, release-night, and post-episode links for *73 Yards*. Supply the original URL, source name, title, phase, and spoiler policy for each discussion.
3. Configure three local runs of the server: docs-only, app without a catalog identity, and app with a catalog DID. For the last local run, use the synthetic DID `did:plc:abcdefghijklmnopqrstuvwx` or another test fixture. For a real publishing deployment, configure the actual publisher DID. Keep credentials in the deployment environment, and use a configured canonical HTTPS origin for public links.

This step is done when the fixture catalog contains 2 series, 2 seasons, 11 episodes, and 23 mappings, and the schema version and software version are tracked independently. Downloading a schema from the project’s HTTP docs establishes the supplied schema version. Network Lexicon discovery is a separate namespace-owner publishing step. [AT Protocol Lexicon publication](https://atproto.com/guides/publishing-lexicons)

## 2. Implement the public read contract

| Request | Expected result |
| --- | --- |
| `GET /api/healthz` | `200` JSON with `status: "ok"` and `version`. Use that version in the docs and schema index. |
| `GET /docs`, `GET /llms.txt`, `GET /docs/agents.md` | `200` with HTML, plain text, and Markdown respectively. Link the human reference, agent guide, and schema index so a guest can discover the contract from the docs or `/llms.txt`. Redirect `/docs/` permanently to `/docs` with `308`. |
| `GET /docs/lexicons`, `GET /docs/lexicons/{nsid}.json` | `200` JSON with `{version, lexicons: [{id, href}]}` for the index and the schema object for a known ID. Return `404` for an unknown ID. |
| `GET /` | `303` to `/docs` in docs-only mode or to `/episodes/73-yards` in app mode. Docs-only returns `404` for app pages, read APIs, and OAuth metadata routes. |
| `GET /episodes/{slug}` | Initial guest-readable HTML with a canonical URL, original discussion links, and watch link where available. Include `og:title`, `og:type`, `og:url`, `og:description`, `og:image`, `og:image:alt`, and `twitter:card`. Use a public image and spoiler-safe copy and artwork. |
| `GET /api/episodes/{slug}` | `200` JSON with `{episode, series, season, mappings, discussions}`. Redirect known episode and API paths ending in `/` with `308`, preserving the query. Return `404` for an unknown episode. |
| `GET /api/resolve?url={percent-encoded URL}` | `200` with `{mapping, episode}` for one trusted, unambiguous match. Return `404` with `{"status":"unresolved"}` for an invalid or unrecognized input. Return `409` with `{"status":"ambiguous"}` when distinct eligible episode results remain. |
| `GET /api/catalog` | `200` with `{records: [{collection, rkey, record}]}` when configured, or `503` with `{"status":"catalog-identity-unconfigured"}`. Use the collection NSID in each record’s `$type`. |

Serve the docs and JSON read APIs (episodes, resolve, catalog) with `Access-Control-Allow-Origin: *` and without session cookies. Support `HEAD` with response headers and an empty body. The `/api/*` routes are the project’s HTTP interface. Use standard `/xrpc/{nsid}` operations when talking to a PDS. [AT Protocol XRPC](https://atproto.com/specs/xrpc) · [Open Graph protocol](https://ogp.me/)

### Identity and resolution

- Use `at://{publisher-did}/com.danhon.atprotomedia.episode/{rkey}` as the portable episode reference. Put the matching `seriesUri` and optional `seasonUri` on the episode; link the season back with `seriesUri`. Episode numbers and web paths are display and navigation data. A changed handle, title, or numbering leaves a published record key intact.
- For the fixture, derive the keys from the runner: `doctor-who-2024-73-yards` identifies *73 Yards*; the *Widow’s Bay* keys are their fixture slugs. Season keys append `-season-1` to the series key. Unconfigured catalogs use JSON `null` for AT URI fields and mapping publisher DID. Require a portable episode URI before any portable write.
- Keep the original URL and normalize by `(source, externalId)`. Recognize the pilot’s own origin and `/episodes/{slug}`, BBC PID from an exact BBC programme or iPlayer hostname/path, IMDb `tt…` ID from an exact IMDb hostname and episode title path, and Apple TV `umc.cmc.…` ID from `tv.apple.com/{locale}/episode/{title}/{id}`. Ignore query and fragment for identity. Accept HTTP(S) URLs without credentials. Reject nondefault ports for external providers, lookalike domains, trailing related paths, and URLs longer than 2,000 characters on the resolve API. Resolve from local or preloaded claims without fetching the submitted URL.
- In HTTP views, return `{source, externalId, url, episodeId, episodeUri, publisherDid}` for a mapping; return its original source URL for any accepted URL variant. In a published `mapping` record, use only the record fields in the Lexicon and determine authorship from the repository DID. Filter claims by the reader’s trusted publishers, deduplicate equivalent claims, and preserve conflicts for review without assigning an episode. For the pilot manifest, derive mapping rkeys from the source name, a hyphen, and the first 24 lowercase hex digits of the SHA-256 of the UTF-8 `externalId`; use the full canonical URL as the hash input for `episode-page` mappings. [AT URI scheme](https://atproto.com/specs/at-uri-scheme) · [Record key syntax](https://atproto.com/specs/record-key)

This step is done when all three local profiles pass the runner, episode references agree across routes, and source-link variants resolve to the same mapping.

## 3. Implement authenticated behavior with controlled fixtures

- **OAuth and native reactions.** Use an AT Protocol OAuth SDK for identity/PDS resolution, PKCE, DPoP, callback state, issuer and subject binding, and refresh. Use author-granted repository permission to write `com.danhon.atprotomedia.reply` through `com.atproto.repo.putRecord` in the author’s own repo. Write `$type`, `episode`, `text`, and `createdAt`. Verify the returned URI matches the author DID, collection, and chosen record key. Verify availability and visibility again before showing the reaction. Authenticate browser mutations, check the request origin and a session-bound CSRF token, and limit moderation to authorized moderators. Keep tokens and signing keys server-side. [AT Protocol OAuth](https://atproto.com/specs/oauth)
- **Bluesky links and curation.** Find links in real rich-text facets or external embeds, including inside a record-with-media embed. Resolve the actual link destination. Use a matching root post as the thread reference and a matching reply as that contribution in its original thread. Explicit submissions begin pending review. Recheck that listed material is available and public on every guest display path using a signed-out view; omit removed, deleted, gated, unavailable, or signed-out-restricted items entirely, including from snippets, counts, and metadata. Fail closed when eligibility cannot be verified. [Bluesky visibility preferences](https://bsky.network/docs/about-bluesky-content/visibility-preferences/) · [Blacksky-Only posts](https://docs.blacksky.community/using-blacksky/posts-and-feed/blacksky-only-posts)
- **Private watch history.** Open `com.danhon.atprotomedia.watchspace` with key `self` and the viewer DID as its authority. Request grants for the viewer’s own Space and `com.danhon.atprotomedia.watch` collection, covering needed read, create, update, delete, and Space creation actions. Derive the record key as lowercase SHA-256 hex of the exact UTF-8 episode AT URI. Use `{ $type, episode, watchedAt }` and delete it to clear the watched state. Distinguish an absent record from an authorization, resolution, or service failure. Keep private records, activity, and derived counts out of the public repo, directory, API, shares, and logs. [AT Protocol Spaces data](https://atproto.com/guides/spaces-data)

For a watch key unit test, SHA-256 of `at://did:plc:abcdefghijklmnopqrstuvwx/com.danhon.atprotomedia.episode/doctor-who-2024-73-yards` is `23db51417526345fb11e617b04d3b759be9787fecc2b8009df73f67fd7efccf0`.

This step is done locally when positive and negative fixtures cover the above rules. Include conflicting claims from two trusted publishers and a conflict from an untrusted one, root and reply discovery, moderator approval and removal, a once-listed post becoming restricted, unauthenticated and cross-session denial, private watch reads and writes across two owned test identities, and permission/service errors. Use stubs or controlled local services for these mutations.

## 4. Verify and report the evidence

Download the runner from this reference. Set each origin below to the corresponding local server address. The runner sends anonymous `GET` and `HEAD` requests only to the target and needs Python 3.8+ with its standard library.

```sh
curl -fsS 'https://media.experiments.verylittlegravitas.com/docs/conformance/run.py' -o run.py
python3 run.py --base-url "$DOCS_ORIGIN" --profile docs
python3 run.py --base-url "$DEMO_ORIGIN" --profile app --catalog demo
python3 run.py --base-url "$CATALOG_ORIGIN" --profile app --catalog live --json
```

The app profiles both check public episode pages, resolver vectors, docs, and schema discovery. `--catalog demo` checks null portable references and the 503 response. `--catalog live` checks a DID-based catalog manifest and graph and works with a synthetic local DID. When two trusted publishers claim different episodes for a separate test URL, add `--ambiguous-url "$FIXTURE_URL"` to check for the 409 response. Add `--oauth` on an HTTPS app origin to verify the confidential pilot’s published OAuth metadata and JWKS. Use `--expect-version` to pin the target’s advertised SemVer. Exit `0` means all selected checks passed, `1` means a check failed or could not reach the target, and `2` means invalid arguments. `--json` returns the selected profile, observed version, counts, and named checks.

After local checks pass, an authorized operator can verify the real publisher’s DID and PDS records with `com.atproto.repo.getRecord`, independently verify DNS Lexicon resolution, and run browser OAuth and author-repo writes on designated test accounts. For private watch portability, authorize a second client, read and update the same record, then migrate a dedicated test account and repeat. Test the stated Bluesky- and Blacksky-hosted account cases individually, including signed-out restrictions and the absence of Blacksky-Only content from every public display path. Inspect live share previews and test visibility changes with accounts and posts you control. Keep those checks open until observed. [Pilot acceptance guide](https://github.com/danhon/atproto-media/blob/9c2ae4d0edbde152ea46276cfa17937a924e298c/docs/PILOT.md) · [Account migration](https://atproto.com/guides/account-migration)

Report the implementation version, profiles and commands run, check counts, and local fixture results. Report each live check as passed, failed, or unrun using the evidence actually obtained. A passing public runner establishes only the selected alpha HTTP behavior. Use real PDS reads and explicitly authorized account tests for live interoperability claims. [Conformance research](https://media.experiments.verylittlegravitas.com/docs/conformance/research.md)
