# `atproto-devtool test labeler` design

## Summary

The implementation is organized as a **layered four-stage pipeline** (identity → HTTP → subscription → crypto) driving a single `LabelerReport`. Each stage is an async function with a typed input and a typed output (`Outcome<T>`), so the Rust type system enforces the dependency graph at compile time: the crypto stage literally cannot be called without the `IdentityFacts` and label slice produced by earlier stages. The pipeline driver is non-fail-fast — it runs every stage whose inputs are available regardless of prior failures — so a single invocation always produces a complete diagnostic picture rather than stopping at the first problem.

Diagnostics are first-class throughout. Every non-passing result carries a `miette::Diagnostic` whose `NamedSource` attaches the offending raw bytes (JSON document, CBOR frame, serialized record) and whose `#[label]` spans highlight the exact field that caused the violation — making the tool useful for debugging rather than merely detecting. The subscription stage uses a two-connection strategy with a configurable time budget, inferring backfill completion from an idle gap heuristic. The crypto stage is designed around the reality of key rotation: it verifies label signatures against the currently declared key first, then falls back lazily to the PLC operation audit log to accept labels signed by a legitimately rotated-out key, attaching an `Advisory` rather than a `Fail` in that case. Stages are coded against narrow async traits (`DidResolver`, `HttpClient`, `WebSocketClient`, `PlcLogFetcher`) so unit tests can replay recorded fixtures from real labelers without any network access; rendered output is locked down with `insta` snapshots to catch diagnostic drift automatically.

## Definition of Done

**Primary deliverable:** A Rust binary `atproto-devtool` with a modular subcommand architecture (single crate, clap-derived, async/tokio), designed so new feature modules can be added with minimal ceremony.

**First feature:** `atproto-devtool test labeler <handle | endpoint> [--did <did>]` that runs a conformance suite across four layers:

- **Identity:** DID document contains an `atproto_labeler` service entry of type `AtprotoLabeler` and a `#atproto_label` signing key; the labeler's PDS holds a valid `app.bsky.labeler.service/self` record with policies.
- **HTTP:** `com.atproto.label.queryLabels` responds with well-formed labels and handles pagination/schema correctly.
- **Subscription:** `com.atproto.label.subscribeLabels` WebSocket firehose emits valid frames and supports `cursor=0` backfill.
- **Crypto:** Label signatures verify against the declared `#atproto_label` key.

Skipped checks are clearly reported when inputs don't unlock them (e.g., endpoint-only invocation without `--did` skips identity/crypto checks).

**Output:** Rich human-readable diagnostics via `miette`; non-zero exit on any check failure.

**Out of scope (initial):** JSON output, Ozone (`tools.ozone.*`) moderation endpoints, authenticated check flows, additional subcommands beyond `test labeler`.

## Acceptance Criteria

### test-labeler.AC1: CLI skeleton and invocation modes

- **test-labeler.AC1.1 Success:** `atproto-devtool test labeler <handle>` accepts an atproto handle, resolves it to a DID, and runs all four stages.
- **test-labeler.AC1.2 Success:** `atproto-devtool test labeler <did>` accepts a DID directly (did:plc or did:web) and runs all four stages without a prior handle resolution.
- **test-labeler.AC1.3 Success:** `atproto-devtool test labeler <https-url>` accepts a raw endpoint URL and runs the HTTP and subscription stages while marking identity and crypto checks `Skipped` with a clear reason.
- **test-labeler.AC1.4 Success:** `atproto-devtool test labeler <https-url> --did <did>` unlocks identity checks (and therefore the crypto stage) against an endpoint URL, and also cross-checks that the DID's declared labeler service endpoint matches the provided URL — reporting a `SpecViolation` on mismatch.
- **test-labeler.AC1.5 Failure:** A target argument that is neither a valid handle, DID, nor URL produces a clap parsing error with a helpful message and exit code `2`.
- **test-labeler.AC1.6 Edge:** `atproto-devtool test labeler --help` renders the subcommand's help text including all stage-related flags (`--subscribe-timeout`, `--did`, `--verbose`, `--no-color`).

### test-labeler.AC2: Identity-layer checks

- **test-labeler.AC2.1 Success:** A DID document containing a `#atproto_labeler` service entry of type `AtprotoLabeler` with a valid `serviceEndpoint`, plus a signing-key verification method parseable as k256 or p256, passes all identity checks.
- **test-labeler.AC2.2 Success:** A `app.bsky.labeler.service/self` record with a non-empty `policies.labelValues` list passes the labeler-record checks.
- **test-labeler.AC2.3 Failure:** A DID document missing the `atproto_labeler` service entry produces a `SpecViolation` `CheckResult` whose diagnostic's `NamedSource` is the DID-document JSON and whose `#[label]` span highlights the `service` array.
- **test-labeler.AC2.4 Failure:** A DID document missing the labeler signing key produces a `SpecViolation` whose diagnostic highlights the `verificationMethod` array.
- **test-labeler.AC2.5 Failure:** A labeler `serviceEndpoint` that is not a valid HTTPS URL produces a `SpecViolation` with the offending endpoint value highlighted in the DID doc.
- **test-labeler.AC2.6 Failure:** A missing `app.bsky.labeler.service/self` record (PDS returns 404) produces a `SpecViolation` distinct from a PDS transport failure.
- **test-labeler.AC2.7 Failure:** An `app.bsky.labeler.service/self` record with an empty `policies.labelValues` list produces a `SpecViolation` whose diagnostic highlights the `policies` field in the re-serialized record.
- **test-labeler.AC2.8 NetworkError:** A DNS failure resolving a handle, an unreachable `plc.directory`, or an unreachable PDS produces a `NetworkError` result that is called out separately in the summary and does not by itself fail the run.

### test-labeler.AC3: HTTP-layer checks (`queryLabels`)

- **test-labeler.AC3.1 Success:** A labeler endpoint that responds to `com.atproto.label.queryLabels` with a well-formed lexicon response decodes into typed labels and passes the schema check.
- **test-labeler.AC3.2 Success:** A labeler that honors the `cursor` parameter — returning a distinct page when called with a cursor from the first page — passes the pagination round-trip check.
- **test-labeler.AC3.3 Success:** A labeler that returns an empty labels array passes the schema and pagination checks and contributes a distinct `Advisory` ("labeler has no published labels") to inform downstream stages.
- **test-labeler.AC3.4 Failure:** A `queryLabels` response that omits required fields or otherwise fails lexicon decoding produces a `SpecViolation` whose diagnostic carries the response JSON as its `NamedSource`.
- **test-labeler.AC3.5 Failure:** A labeler that ignores the `cursor` parameter (returns the first page again) produces a `SpecViolation` on the pagination check.
- **test-labeler.AC3.6 NetworkError:** An unreachable or TLS-failing labeler endpoint produces a `NetworkError` that does not cascade into `queryLabels` schema failures.

### test-labeler.AC4: Subscription-layer checks (`subscribeLabels`)

- **test-labeler.AC4.1 Success (backfill completes within budget):** A labeler whose backfill flushes within `--subscribe-timeout` followed by a ≥500ms idle gap produces a `Pass` backfill check and an implicit `Pass` live-tail check ("live tail observed after backfill completed").
- **test-labeler.AC4.2 Success (backfill exceeds budget):** A labeler whose backfill is still producing frames at the end of the budget produces an `Advisory` backfill check and triggers a second connection for the live-tail check. A clean live-tail connection (any frames decoded, or connection held open with no decode errors) produces a `Pass` live-tail check.
- **test-labeler.AC4.3 Success (empty labeler):** A labeler producing no frames at all during the budget produces an `Advisory` backfill check ("labeler has no published labels") and a `Skipped` live-tail check with the same reason.
- **test-labeler.AC4.4 Failure:** A frame that fails the two-CBOR-block decode, or a `#labels` payload that fails lexicon decoding, produces a `SpecViolation` `CheckResult` independent of the backfill/live-tail pass/fail dimension. The diagnostic carries the offending frame bytes as `NamedSource`.
- **test-labeler.AC4.5 Failure:** A WebSocket handshake that succeeds but whose first frame has `op: -1` (error) with a malformed `#info` payload produces a `SpecViolation` on decode.
- **test-labeler.AC4.6 NetworkError:** An unreachable WebSocket endpoint or a handshake TLS failure produces a `NetworkError` rather than a subscription `Fail`.
- **test-labeler.AC4.7 Edge:** Passing `--subscribe-timeout 0` (or another invalid duration) produces a clap parse error; values below a reasonable floor (e.g., 1s) are rejected with a helpful message.

### test-labeler.AC5: Crypto-layer checks (signature verification with key rotation)

- **test-labeler.AC5.1 Success:** Every label in `HttpFacts::first_page` whose signature verifies against the current declared signing key produces a `Pass` on the crypto rollup with no historic-key fetch performed.
- **test-labeler.AC5.2 Success (rotated-out key, did:plc):** When at least one label fails against the current key, the crypto stage fetches the PLC audit log and retries verification against each historic verification-method entry for the labeler's signing-key slot. Labels that verify against a historic key are accepted, the rollup is `Pass`, and an `Advisory` is attached listing the count and key ids involved.
- **test-labeler.AC5.3 Success (empty labeler):** A labeler with zero published labels results in the crypto stage being `Skipped("labeler published no labels; nothing to verify")` and does not affect the exit code.
- **test-labeler.AC5.4 Failure (current-key mismatch, no history):** A did:web labeler whose labels do not verify against the current key produces a `Fail` rollup with a diagnostic listing the current key id and stating that did:web provides no rotation history.
- **test-labeler.AC5.5 Failure (current and historic mismatch, did:plc):** A did:plc labeler whose labels verify against neither the current nor any historic key produces a `Fail` rollup with a diagnostic listing every key id that was tried.
- **test-labeler.AC5.6 Failure (canonicalization mismatch surfaced):** A label whose serialized-for-signing bytes cannot be produced (e.g., invalid CBOR in the fetched record) produces a per-label `Fail` with a distinct diagnostic code from signature mismatch, so misbehaviour of the canonicalizer is distinguishable from a genuine signature problem.
- **test-labeler.AC5.7 NetworkError:** A failure to fetch the PLC audit log (`plc.directory` unreachable) during the historic-key path produces a `NetworkError` result and prevents the stage from issuing a false `Fail`; the labels that failed against the current key are reported as `Fail` only if history could not be consulted.

### test-labeler.AC6: Cross-cutting reporting and exit semantics

- **test-labeler.AC6.1 Success:** A labeler that passes every stage produces a `LabelerReport` whose rendered output shows each stage with `[OK]` glyphs, a header listing the target and resolved DID/PDS, a summary with all-zero failure/advisory counts, and exits `0`.
- **test-labeler.AC6.2 Success:** A run containing at least one `SpecViolation` exits `1`, and the summary footer shows the count broken down by severity.
- **test-labeler.AC6.3 Success:** A run containing only `NetworkError` results (no `SpecViolation`s) exits `0`, with the network-error count called out separately in the summary.
- **test-labeler.AC6.4 Success:** A run containing only `Advisory` results exits `0`.
- **test-labeler.AC6.5 Success:** `Skipped` checks are rendered with a reason string taken from the stage's `Outcome::Skipped` variant, so users can see why a check was not run (missing DID, upstream failure, empty labeler, not-yet-implemented).
- **test-labeler.AC6.6 Success:** Setting `NO_COLOR=1` suppresses ANSI color codes in the rendered output while keeping ASCII glyphs (`[OK]`/`[FAIL]`/`[SKIP]`/`[WARN]`) and miette diagnostic layout intact.
- **test-labeler.AC6.7 Success:** `--verbose` raises the tracing filter, causing stage IO (HTTP requests, WebSocket frames, PLC log fetch) to be logged at DEBUG to stderr without affecting the rendered report or exit code.
- **test-labeler.AC6.8 Edge:** The tool's own unrecoverable bootstrap failures (invalid CLI args, panics caught by the miette handler, tokio runtime failure) exit `2` — distinct from a `SpecViolation`-driven `1`.

## Glossary

- **atproto (AT Protocol)**: The open, federated social-network protocol developed by Bluesky. It defines the identity, data, and communication standards that this tool validates against.
- **labeler**: An atproto service that publishes moderation labels — structured judgments that clients use to filter or annotate content. A labeler is identified by its DID and exposes two XRPC endpoints for querying and streaming its labels.
- **DID (Decentralized Identifier)**: A W3C standard for self-sovereign identity. In atproto, every account and service is identified by a DID; the DID resolves to a DID document that declares the entity's public keys and service endpoints.
- **did:plc**: An atproto-specific DID method maintained by a centralized-but-auditable directory (`plc.directory`). Key rotations and endpoint changes are recorded as a signed operation log, which this tool consults to accept labels signed by rotated-out keys.
- **did:web**: A DID method that derives identity from a domain's HTTPS server (e.g., `did:web:example.com` resolves via `https://example.com/.well-known/did.json`). Unlike did:plc, did:web provides no rotation history, so historic-key fallback is unavailable.
- **PLC audit log**: The append-only sequence of signed operations at `https://plc.directory/{did}/log/audit` recording every key rotation and service change for a did:plc identity. The crypto stage walks this log newest-to-oldest to find historic signing keys.
- **handle**: A human-readable atproto username (e.g., `alice.bsky.social`). Handles are resolved to DIDs via a DNS TXT record or an HTTPS `.well-known` path before any protocol checks can proceed.
- **PDS (Personal Data Server)**: The server that hosts a user's or labeler's repository of records. The identity stage fetches the `app.bsky.labeler.service/self` record from the labeler's declared PDS endpoint.
- **XRPC**: The HTTP-based RPC layer used by atproto. Procedure names like `com.atproto.label.queryLabels` are lexicon-defined endpoints served under the `/xrpc/` path prefix.
- **`com.atproto.label.queryLabels`**: The XRPC HTTP endpoint that returns a paginated list of labels published by a labeler. The HTTP stage calls this endpoint to fetch labels and verify schema conformance and pagination behavior.
- **`com.atproto.label.subscribeLabels`**: The XRPC WebSocket endpoint that streams label events as they are published, and replays historical labels when called with `cursor=0`. The subscription stage tests both the backfill replay and the live-tail behavior.
- **`app.bsky.labeler.service/self`**: The well-known record in a labeler's PDS repository that declares the labeler's policy configuration, including the set of label values it may apply. Absence of this record or an empty `labelValues` list is a spec violation.
- **`#atproto_labeler` service entry**: The entry in a DID document's `service` array with the fragment `#atproto_labeler` and type `AtprotoLabeler`, declaring the labeler's XRPC endpoint URL. The identity stage checks that this entry is present and well-formed.
- **DRISL-CBOR**: The deterministic CBOR serialization required by atproto for data that is cryptographically signed. It mandates strict map key ordering, minimal integer encoding, and no floats or indefinite-length items. The crypto stage canonicalizes each label to this format before hashing and verifying its signature.
- **multikey**: The atproto encoding for public keys in DID documents — a multibase-prefixed byte string that encodes both the curve identifier and the raw key bytes. This tool decodes multikeys to obtain `k256` (secp256k1) or `p256` (NIST P-256) verifying keys.
- **miette**: A Rust diagnostics library that provides rich, human-readable error reporting with source code spans, labels, and help text. This tool uses it to attach the offending JSON or CBOR bytes to every check failure, so users see exactly which field caused a violation.
- **`NamedSource` / `#[label]` spans**: The miette types that attach a named source document (e.g., a DID document's raw JSON) and highlight specific byte ranges within it in the rendered output. Each `CheckResult` failure uses these to point to the offending field.
- **`insta` snapshot testing**: A Rust testing library that records the text output of a function on first run and then asserts it matches on subsequent runs. Used here to lock down rendered `LabelerReport` output so any change in diagnostic formatting is caught automatically.
- **clap**: The standard Rust CLI argument-parsing library, used in derive mode here to generate the subcommand tree and argument validation declaratively.

## Architecture

### High-level shape

`atproto-devtool` is a single-crate async Rust binary. The top-level CLI is a tree of clap-derived subcommands: the root `Command` enum has one initial variant `Test`, which itself is an enum whose initial variant `Labeler` holds the `test labeler` arguments. Adding a new feature is a two-line enum edit plus a new sibling module — the same pattern used by `zcash-devtool`.

The first feature, `test labeler`, is a **layered pipeline** of four typed stages (identity → HTTP → subscription → crypto). Each stage is an async function whose signature consumes the outputs the stage actually needs, so the type system enforces the dependency graph: crypto verification cannot be called without a resolved signing key and a set of labels to verify. The pipeline driver runs every stage whose inputs are available — no fail-fast — so a single invocation produces a complete diagnostic picture.

Each stage emits one or more `CheckResult`s tagged with a named check ID, a status (`Pass | Fail | Skipped | Advisory`), and — for non-`Pass` results — a `miette::Diagnostic` with source spans pointing into the JSON/CBOR document that caused the violation. The collected `LabelerReport` is rendered through `miette`'s `GraphicalReportHandler` at the end of the run.

### Crate layout

Sibling-file module pattern throughout (no `mod.rs`):

```text
atproto-devtool/
├── Cargo.toml
├── src/
│   ├── main.rs                         # tokio bootstrap
│   ├── cli.rs                          # root clap Parser + error reporting
│   ├── commands.rs                     # top-level Command enum
│   ├── commands/
│   │   ├── test.rs                     # Test subcommand enum { Labeler(..) }
│   │   └── test/
│   │       ├── labeler.rs              # clap Args + pipeline entry point
│   │       └── labeler/
│   │           ├── pipeline.rs         # drives the four stages, assembles Report
│   │           ├── identity.rs         # stage 1: DID doc + labeler record
│   │           ├── http.rs             # stage 2: queryLabels
│   │           ├── subscription.rs     # stage 3: subscribeLabels WS
│   │           ├── crypto.rs           # stage 4: signature verification
│   │           └── report.rs           # LabelerReport + miette rendering
│   ├── common.rs                       # cross-feature primitives
│   └── common/
│       ├── identity.rs                 # handle→DID, DID doc fetch, service lookup
│       └── diagnostics.rs              # miette helpers shared by all features
```

### Pipeline contracts

The pipeline operates on two input shapes that reflect the two invocation modes:

```rust
pub enum LabelerTarget {
    Identified { identifier: AtIdentifier },        // handle or DID
    Endpoint   { url: Url, did: Option<Did> },      // raw endpoint, optional DID
}
```

Each stage returns an `Outcome<T>`:

```rust
pub enum Outcome<T> {
    Pass(T),
    Fail(Diagnostic),
    Skipped(&'static str),
}
```

Stage signatures:

```rust
identity::run(&LabelerTarget, &IdentityOptions)
    -> Outcome<IdentityFacts>;

http::run(&Url /* labeler endpoint */, &HttpOptions)
    -> Outcome<HttpFacts>;

subscription::run(&Url, &SubscriptionOptions)
    -> Outcome<SubscriptionFacts>;

crypto::run(&IdentityFacts, &[Label])
    -> Outcome<CryptoFacts>;

pub struct IdentityFacts {
    pub did: Did,
    pub did_doc: DidDocument,                // carries source bytes for span-tagging
    pub labeler_endpoint: Url,
    pub pds_endpoint: Url,
    pub signing_key: VerifyingKey,           // k256 or p256, parsed from multikey
    pub service_record: LabelerServiceRecord,
}

pub struct HttpFacts {
    pub first_page: Vec<Label>,              // fed into crypto stage
    pub pagination_ok: bool,
}

pub struct SubscriptionFacts {
    pub backfill_outcome: BackfillOutcome,
    pub live_tail_outcome: Option<LiveTailOutcome>,
    pub decode_errors: Vec<FrameDecodeError>,
}

pub struct CryptoFacts {
    pub verified_with_current: usize,
    pub verified_with_historic: Vec<HistoricKeyHit>, // (key_id, label_count)
    pub unverified: usize,
}
```

The `LabelerReport` aggregator exposes `record_<stage>` methods that collect per-stage `Vec<CheckResult>` values into the final rendered output.

### Error classification

Every `CheckResult` carries one of three severities for exit-code purposes:

- **`SpecViolation`** — the check ran successfully and the labeler does not conform. Non-zero exit.
- **`NetworkError`** — the check could not run because transport/DNS/TLS failed. Reported but does not fail the run by itself (exit 0); they are called out separately in the summary.
- **`Advisory`** — informational (e.g., empty labeler, rotated-out key used). Does not affect exit code.

The top-level exit codes are: `0` clean, `1` at least one `SpecViolation`, `2` usage error or unrecoverable bootstrap failure.

### Subscription strategy

The subscription stage runs a sequence of up to two WebSocket connections sharing the same time budget (`--subscribe-timeout`, default 5s each):

1. **Backfill check.** Connects with `cursor=0`. During the budget window:
   - If an idle gap (≥500ms without new frames) is observed after frames have been flowing, backfill is judged to have completed and the remaining time is implicitly the live tail. The live-tail check is marked `Pass` ("live tail observed after backfill completed") and the stage ends.
   - If the budget is exhausted while frames are still arriving, backfill is marked `Advisory` ("backfill exceeded budget — could not confirm full replay") and the live-tail check runs as a second connection.
   - If no frames arrive at all, the backfill check is marked `Advisory` ("labeler has no published labels") and the live-tail check is `Skipped` for the same reason.
2. **Live-tail check** (only if not already satisfied). Opens a fresh connection using the current high-water sequence number (live-only). Runs for the same timeout. Passes if the connection holds open cleanly and any frames that arrive decode correctly; zero frames in the window is acceptable.

Both checks reuse the same two-CBOR-block frame parser. Decode errors always surface as their own `Fail` diagnostics regardless of which check captured them.

### Crypto strategy with key rotation

Each label from `HttpFacts::first_page` is verified independently:

1. Canonicalize the label record to DRISL-CBOR (strict CBOR subset, `sig` field removed), SHA-256 the bytes.
2. Verify against the **currently declared** labeler signing key (`VerifyingKey` from `IdentityFacts`). If it verifies, the label is accepted.
3. If verification fails and the DID is `did:plc`, fetch the PLC operation log from `https://plc.directory/{did}/log/audit` **lazily** (only when at least one label fails against the current key). Walk operations newest-to-oldest, extract each historic `verificationMethod` entry for the labeler's signing-key slot, and retry verification. A label that verifies against a historic key is accepted with an `Advisory` attached to the rollup: "N label(s) signed by a rotated-out key — expected for labels older than the most recent rotation; confirm rotations were intentional."
4. If verification fails against the current key AND all historic keys (or history is unavailable — `did:web` or the PLC log fetch fails), the label is `Fail` with a diagnostic listing which keys were tried.

Rollup: `CryptoFacts` is `Pass` iff every label verified against some key (current or historic); otherwise `Fail`. Empty-label labelers result in `Skipped("labeler published no labels; nothing to verify")` and do not fail the stage.

### Diagnostics and rendering

Diagnostics use `miette`'s `Diagnostic` derive with `code`, `help`, and — where a source document exists — `source_code` (`NamedSource`) plus `#[label]` spans. Examples of source-carrying diagnostics:

- `labeler::identity::signing_key_missing` highlights the `verificationMethod` array in the DID document where the labeler's signing key would live.
- `labeler::identity::record_policies_empty` highlights the empty `policies` field in the re-serialized `app.bsky.labeler.service/self` record.
- `labeler::crypto::signature_mismatch` highlights the `sig` field in the offending label record.

`LabelerReport::render` prints, in order: a header (target, resolved DID and PDS if known, wall-clock duration), each stage as a section with ASCII status glyphs (`[OK]`, `[FAIL]`, `[SKIP]`, `[WARN]`), every non-`Pass` `CheckResult`'s full miette diagnostic via `GraphicalReportHandler` (respecting `NO_COLOR`/`CLICOLOR`), and a summary footer with counts per status and the separate network-error count.

### Testing surface

Stages are written against narrow async traits for their IO surface (`DidResolver`, `HttpClient`, `WebSocketClient`, `PlcLogFetcher`). Unit tests supply fakes that replay recorded fixtures captured from real labelers (e.g., `moderation.bsky.app`). Rendered `LabelerReport` output is locked down with `insta` snapshots for the golden path and one snapshot per named failure case, so any drift in diagnostics is caught automatically.

## Existing Patterns

Investigation of the repository found only an empty binary crate (`src/main.rs` stub, single top-level `Cargo.toml`) with no prior conventions to follow. The design therefore introduces new patterns rather than extending existing code:

- **Subcommand module shape** modeled directly on [`zcash-devtool`](https://github.com/zcash/zcash-devtool): a single binary crate, clap derive parsing, nested subcommand enums per feature area, and each command struct exposing an async `run()` method invoked from `main`.
- **Sibling-file module layout** (`foo.rs` + `foo/` rather than `foo/mod.rs`) per the user's global Rust conventions.
- **Typed-stage pipeline with accumulating report** is new to this codebase and becomes the default pattern for future "test" subcommands where multiple dependent checks need to be run against a single target.

No existing `atproto-devtool`-style tool in the Rust ecosystem was found. The closest prior art is [`atproto-labeler-diagnostics`](https://github.com/FlippingBinary/atproto-labeler-diagnostics), a small TypeScript proof-of-concept whose check surface is substantially narrower than this design.

## Implementation Phases

<!-- START_PHASE_1 -->
### Phase 1: Crate skeleton and CLI bootstrap

**Goal:** Get the binary crate compiling with a clap-derived subcommand tree, working async runtime, miette-installed error handling, and a stub `test labeler` command that parses its arguments and prints a "not yet implemented" message.

**Components:**
- `Cargo.toml` — single-crate (no workspace) `[dependencies]` section with `clap` (derive), `tokio` (`rt`, `macros`, `time`, `net`), `miette` (`fancy`), `thiserror`, `tracing`, `tracing-subscriber`, `url`.
- `src/main.rs` — `#[tokio::main(flavor = "current_thread")]` bootstrap that installs the miette panic handler and hands off to `cli::run`.
- `src/cli.rs` — root `Cli` struct with global flags (`--verbose`, `--no-color`), `Command` dispatch, and `miette::Result` return type.
- `src/commands.rs` + `src/commands/test.rs` + `src/commands/test/labeler.rs` — the nested subcommand enums and stub `LabelerCmd::run` that prints its parsed args.
- `src/common.rs` + `src/common/diagnostics.rs` — shared miette helpers (report handler installation, `NamedSource` constructors from byte slices, JSON-pointer-to-span helpers).

**Dependencies:** None (first phase).

**Done when:** `cargo build` succeeds; `cargo run -- test labeler --help` prints the subcommand help; `cargo run -- test labeler example.bsky.social` prints a parsed-args placeholder message and exits 0. Infrastructure phase — operational verification only, no acceptance criteria tests.
<!-- END_PHASE_1 -->

<!-- START_PHASE_2 -->
### Phase 2: Shared identity primitives

**Goal:** A reusable `common::identity` module covering handle resolution, DID-document fetch, service-entry lookup, and multikey parsing — the primitives that every future `test` subcommand will need.

**Components:**
- `src/common/identity.rs` with:
  - `resolve_handle(&str) -> Result<Did>` — DNS TXT lookup at `_atproto.<handle>` via `hickory-resolver`, HTTPS fallback to `https://<handle>/.well-known/atproto-did`.
  - `resolve_did(&Did) -> Result<DidDocument>` — `did:plc:*` via `https://plc.directory/{did}`, `did:web:*` via `https://<host>/.well-known/did.json` (including path-form targets). Returns both the parsed document and the raw bytes as a `NamedSource`.
  - `find_service(&DidDocument, id_fragment, service_type) -> Option<&Service>` — spec-correct matching.
  - `parse_multikey(&str) -> Result<VerifyingKey>` — multibase decode with curve-tag dispatch to `k256` or `p256`.
- New dependencies: `reqwest` (`rustls-tls`, `json`), `hickory-resolver`, `multibase`, `k256` (`ecdsa`), `p256` (`ecdsa`), `serde`, `serde_json`.
- Unit tests over recorded fixtures (real handles and DID documents from well-known Bluesky accounts and labelers) for each resolution path and each multikey curve.

**Dependencies:** Phase 1.

**Done when:** All identity resolution unit tests pass against recorded fixtures. Infrastructure/library phase — tests verify primitive correctness but do not yet cover acceptance criteria (those arrive once wired into the labeler pipeline in Phase 3).
<!-- END_PHASE_2 -->

<!-- START_PHASE_3 -->
### Phase 3: Identity stage and report scaffolding

**Goal:** The first end-to-end labeler check path: run the pipeline driver with only the identity stage implemented, render a `LabelerReport` with real diagnostics. The tool becomes genuinely useful for debugging DID/record misconfigurations at the end of this phase.

**Components:**
- `src/commands/test/labeler/report.rs` — `LabelerReport`, `CheckResult`, `CheckStatus`, severity classification, ASCII glyph renderer, `render(&self, &mut impl ReportHandler)`.
- `src/commands/test/labeler/pipeline.rs` — `LabelerTarget`, `LabelerOptions`, pipeline driver function (identity stage only for now; remaining stages return `Skipped("not yet implemented")`).
- `src/commands/test/labeler/identity.rs` — the identity stage. Emits named `CheckResult`s for: DID resolves, DID doc carries `atproto_labeler` service entry of correct type, labeler endpoint URL is valid, signing key present and parseable, PDS entry present and reachable, `app.bsky.labeler.service/self` record fetchable, record schema valid, record `policies.labelValues` non-empty.
- `src/commands/test/labeler.rs` — wire the clap args to the pipeline and render the report.
- New dependencies: `atrium-api`, `atrium-xrpc-client` (for the `com.atproto.repo.getRecord` call against the PDS).
- `insta` snapshot tests (dev-dependency) covering: golden-path labeler, missing DID, DID doc missing labeler service, DID doc missing signing key, PDS unreachable, missing/empty labeler record.

**Dependencies:** Phase 2.

**Acceptance criteria covered:** `test-labeler.AC1.*`, `test-labeler.AC2.*`.

**Done when:** Every listed identity `CheckResult` is emitted correctly for its fixture, the `LabelerReport` renders as expected (snapshot-locked), and running the binary against a real healthy labeler exits 0 with an identity section of all `[OK]`s.
<!-- END_PHASE_3 -->

<!-- START_PHASE_4 -->
### Phase 4: HTTP stage (`queryLabels`)

**Goal:** The HTTP stage hits `com.atproto.label.queryLabels` on the labeler endpoint, verifies schema conformance, exercises pagination once, and publishes its collected labels into `HttpFacts::first_page` for the crypto stage to consume.

**Components:**
- `src/commands/test/labeler/http.rs` — HTTP stage using the typed `atrium-api` client against the labeler endpoint. Emits `CheckResult`s for: endpoint reachable (TCP+TLS), `queryLabels` returns a well-formed lexicon response, optional `cursor` round-trip is honored (one second page requested with a cursor from the first), returned labels decode into typed records.
- Pipeline driver update to thread `HttpFacts` into the accumulating report.
- Dev fixtures: recorded `queryLabels` responses from a real labeler plus synthetic malformed responses for each failure case; tests run against a fake in-process XRPC server that replays them.

**Dependencies:** Phase 3.

**Acceptance criteria covered:** `test-labeler.AC3.*`.

**Done when:** Running against a real labeler shows a populated HTTP section in the report with pass/fail classification matching fixtures, and snapshot tests are locked for each named failure case.
<!-- END_PHASE_4 -->

<!-- START_PHASE_5 -->
### Phase 5: Subscription stage (`subscribeLabels`)

**Goal:** Add the two-check subscription stage — backfill check and conditional live-tail check — each time-bounded by `--subscribe-timeout` (default 5s).

**Components:**
- `src/commands/test/labeler/subscription.rs` with:
  - Two-CBOR-block frame parser for `subscribeLabels` frames (header + payload), using `ciborium` in strict mode. Validates header `op`/`t` fields, routes `#labels` / `#info` message types.
  - Backfill check: connects with `cursor=0`, consumes frames up to the budget, detects backfill completion via ≥500ms idle gap after frames started flowing, handles "no frames at all" as an `Advisory` distinct from the decode-error path.
  - Live-tail check: fresh connection with cursor set to current high-water sequence, runs the same budget, passes on clean hold or any correctly-decoded frame. Skipped when backfill already implied a live-tail observation.
  - `BackfillOutcome` / `LiveTailOutcome` enums feeding into `SubscriptionFacts`.
- New dependencies: `tokio-tungstenite` (`rustls-tls-native-roots`), `ciborium`.
- Dev fixtures: recorded frame sequences plus synthetic malformed frames; tests run against a fake WebSocket server.

**Dependencies:** Phase 4.

**Acceptance criteria covered:** `test-labeler.AC4.*`.

**Done when:** Snapshot tests pass for each named subscription outcome (backfill-complete-within-budget, backfill-exceeds-budget, empty-stream, decode-error). Running against a real labeler shows a populated subscription section.
<!-- END_PHASE_5 -->

<!-- START_PHASE_6 -->
### Phase 6: Crypto stage and end-to-end polish

**Goal:** The final stage — verify the signatures of labels collected by the HTTP stage, with did:plc key-history fallback for rotated-out keys. Ship docs and end-to-end tests for the full pipeline.

**Components:**
- `src/common/identity.rs` extended with a `plc_history` helper that lazily fetches `https://plc.directory/{did}/log/audit` and extracts historic verification methods by fragment. Tests over recorded audit logs.
- `src/commands/test/labeler/crypto.rs`:
  - DRISL-CBOR canonicalizer wrapper over `ciborium` (strict map key ordering, minimal integer encoding, no floats). Test vectors generated from a real labeler's labels plus the reference spec.
  - SHA-256 prehash → `k256`/`p256` `verify_prehash` dispatch based on the `IdentityFacts::signing_key` variant.
  - Current-key-first verification; on any failure, lazy PLC history fetch (did:plc only) and retry against each historic key.
  - Empty-labeler path → `Skipped`, not `Fail`. Rotated-out-key hits → `Advisory` attached to the rollup.
- End-to-end `insta` snapshot tests covering: all-pass labeler, identity-only failure, HTTP decode failure, subscription decode error, current-key signature failure that resolves against history, unresolvable signature failure (mixed-failure run) — each fixture runs the full pipeline.
- `README.md` with install instructions, `--help` excerpt, and one example invocation per mode (handle, endpoint-only, endpoint + `--did`).
- New dependency: `sha2`.

**Dependencies:** Phase 5.

**Acceptance criteria covered:** `test-labeler.AC5.*`, `test-labeler.AC6.*`.

**Done when:** Full-pipeline snapshot tests pass, `cargo test` is green, running the binary against a real healthy labeler produces an all-`[OK]` report and exits 0, running against a fixture labeler with a rotated-out signing key produces an `Advisory` rollup and still exits 0, and running against a fixture labeler with an actual signature mismatch produces a `Fail` and exits 1.
<!-- END_PHASE_6 -->

## Additional Considerations

**Error classification discipline.** The distinction between `SpecViolation`, `NetworkError`, and `Advisory` is the single most important thing to get right for this tool's usefulness. A user debugging their own labeler needs network failures called out separately so they can re-run with connectivity fixed; a user checking another team's labeler needs advisories (empty labels, rotated keys) visibly separated from real violations. Every new check added to the suite must explicitly pick a severity — there is no default.

**Canonicalization risk.** DRISL-CBOR label canonicalization is subtle (strict map key ordering, minimal integer encoding, no floats/indefinite-length items). Phase 6 should validate the canonicalizer against labels fetched from a known-good production labeler (e.g., `moderation.bsky.app`) before declaring the crypto stage done, to avoid false-positive `Fail` results caused by canonicalization drift rather than real signature problems.

**Future extensibility (not in scope for this design):** The layered-pipeline pattern is intentionally feature-local. If future `test` subcommands (`test pds`, `test feed-generator`) share checks with `test labeler` — most plausibly DID/PDS resolution — they will extract into `common::identity` rather than growing a general-purpose check registry. A shared registry is explicitly YAGNI territory until a second feature demands it.

**Fixtures as a versioned asset.** Phase 3 onwards depends on recorded fixtures (DID docs, repo records, queryLabels responses, WebSocket frames, PLC audit logs). Store these under `tests/fixtures/<stage>/<case>.{json,cbor,bin}` with a short README per fixture describing its source and the case it exercises, so regressions can be triaged by reading one file rather than re-running network probes.

