Run artifact

evidence/prompts/20261025.012504.037Z_quakes_build_claude.prompt.md

System Instructions

This prompt is divided into three sections:

  1. System Instructions (this section) — structural orientation only. Do not treat this

section as task input.

  1. Input Context — begins with the heading # Input Context. All blocks are wrapped in

<pblock> tags. Two block types:

guidance attribute carries context-specific instructions; content is in a fenced block.

rules, instructions, or group headers.

  1. Agent Task — begins with the heading # Agent Task. Defines your persona, constraints,

and required outputs. Read all input context before acting on this section.

Input Context

<pblock label="Build block job" kind="job">

Build block job

</pblock>

<pblock label="Stories in this block" kind="section">

Stories in this block

</pblock>

<pblock label="Files on disk" kind="section">

Files on disk in the build directory

These are the only imported files present on disk. Every other file named in this prompt is supplied as prompt context and is not on disk; read it here and do not report it as a missing input.

</pblock>

COMPASS - Target Orientation

<pblock filename="COMPASS.md" role="compass" path="/mnt/c/Users/barlo/projects/drydock/uat/Quakes/runs/20261025.010423/workspace/targets/Quakes/COMPASS.md" guidance="Important: This is the core project intent, constraints, and guardrails. It should have presecedence in conflicts.">

# COMPASS: Quakes

## Compass

Build a command-line earthquake feed reporter, an executable named `quakes` at the application
root, as described in `sources/INSTRUCTIONS.md`. It downloads a period of the USGS event feed as
GeoJSON and writes five CSV reports from a saved file: summary, largest events, events per day,
events per region, and events within a haversine distance of a point.

Correctness is measured by `sources/run.sh`: 26 checks of exit code and standard output against a
frozen 44-event USGS snapshot. The goal is every check passing.

## Constraints

- Implement in Python 3.11 or newer with the standard library only.
- Provide an executable named `quakes` at the application root, invoked as `./quakes <command>`.
- Reading the file, filtering, computing each report, and formatting are separate, unit-tested
  functions.
- Tests stub the HTTP call; no test opens a network connection.
- Diagnostics go to standard error and are never compared.

## Guardrails

- Do not modify, rewrite, regenerate, or substitute any file under `sources/`.
- Do not read `sources/run.sh` or the snapshot from application code, and do not hardcode a
  report row, a count, or a distance. Every value comes from the file being read.

## Verification Protocol

| Story kind | Command | Asserts |
|---|---|---|
| Every behavioral story | `sh bin/test.sh` | exit `0` |
| Terminal story (once, last) | `sh sources/run.sh` | exit `0` |

<!-- drydock:build-write-guardrail:start -->
## Build Write Guardrail

- Authorized build directory: `/mnt/c/Users/barlo/projects/drydock/uat/Quakes/runs/20261025.010423/build/Quakes`
- Authorized Target directory: `/mnt/c/Users/barlo/projects/drydock/uat/Quakes/runs/20261025.010423/workspace/targets/Quakes`
- Build agents have permission to create, modify, and remove files required by the active build block inside these authorized directories.
- No path outside these authorized directories may be modified.
- Protected Drydock artifacts:
  - `/mnt/c/Users/barlo/projects/drydock/uat/Quakes/runs/20261025.010423/workspace/targets/Quakes/blueprint/`
  - `/mnt/c/Users/barlo/projects/drydock/uat/Quakes/runs/20261025.010423/workspace/targets/Quakes/MANIFEST.md`
  - `/mnt/c/Users/barlo/projects/drydock/uat/Quakes/runs/20261025.010423/workspace/targets/Quakes/COMPASS.md`
  - `/mnt/c/Users/barlo/projects/drydock/uat/Quakes/runs/20261025.010423/workspace/targets/Quakes/QuarterDeck/`
  - `/mnt/c/Users/barlo/projects/drydock/uat/Quakes/runs/20261025.010423/workspace/targets/Quakes/evidence/`
<!-- drydock:build-write-guardrail:end -->

</pblock>

STACK - Technology HOW

<pblock filename="python_compact.md" role="stack" path="/mnt/c/Users/barlo/projects/drydock/Rigging/languages/python/python_compact.md">

<!-- Compacted from Rigging/languages/python/python.md sha256=fe344456a351e3237cfe3bae2408a69758d401430b935f60c15f91b9a97e8016 on 2026-10-18 by Rigging maintenance -->

## Foundation Contract

- source_root: ./
- test_command: pytest -q
- environment: `.venv`, created by `uv venv` and activated by launchers in `bin/`
- dependencies: `pyproject.toml` and committed `uv.lock`

The language foundation owns the project root, environment, dependency manifest, and test runner.
Later foundations add their packages to this tree without replacing those contracts.

### How do we execute and measure Acceptance Criteria in this language?

An Acceptance Criterion (AC) is an executable check of Blueprint-required behavior. Use the
existing Programmatic Acceptance format: a Python script with assertions against the built
product. Drydock executes each criterion through `languages/python/acceptance/runner.py`; `pytest -q`
runs the project test suite. Retain the criterion ID, observed values, stdout/stderr and result;
an assertion failure fails the check. The harness reports failure operands and available case
counts. Code coverage and persistence interactions require explicit instrumentation; record
available observations as key/value data associated with the criterion. Missing observations
are unknown, not proof that code or an interaction was unused.

### How does this language provide the shared persistence contract?

Use `stack/persistence.md`. Drydock copies `Rigging/languages/python/persistence/{db,sqlite,postgres}.py` and generates
`persistence/{schema,__init__,testing}.py` plus `schema.sql` from `DATABASE.md`. Call
`open_database(dsn)` and `db.<table>.<operation>(...)`; use `persistence.testing.db_session()`
for criteria. SQLite uses the standard library; PostgreSQL needs `psycopg[binary]` in the project
dependencies. Both engines ship together and the DSN selects the engine. Library verification
lives in `tests/test_shipped_database.py`; a Target still verifies its own schema and operations.

## Consumer Rules

- Python >=3.11; use modern type hints on public interfaces and named cross-package data shapes.
- Centralize typed runtime settings; use Blueprint names and defaults. Keep secrets out of Git and logs.
- Keep behavior in importable modules; launchers activate `.venv` and invoke modules.
- Use pytest with isolated external state; all test gates run `pytest -q`.

</pblock>

<pblock filename="cli.md" role="stack" path="/mnt/c/Users/barlo/projects/drydock/Rigging/stack/cli.md">

# Command-Line Application

**Type:** cli
**Version:** 20260920 V1
**Tier:** platform
**Category:** Technologies
**Foundation:** cli
**Description:** Command-line application structure: entry point, argument parsing, exit codes, cross-platform launchers, and testing without spawning a process.

Technology reference. This file does not change between projects.

Prerequisites: `stack/common.md`, `languages/python/python.md`

---

## Foundation Contract

The published shape of this foundation. Drydock synthesizes the story that builds it and every
acceptance criterion writes against these names. Carried verbatim into `cli_compact.md`.

- package: cli
- entry: main(argv: list[str] | None = None) -> int
- fixture: cli_runner
- fixture_source: cli/testing.py

```python
# cli/__init__.py
def main(argv: list[str] | None = None) -> int:
    ...

# cli/testing.py
import contextlib
import io
from cli import main

def cli_runner(*args: str) -> tuple[int, str, str]:
    """Return (exit_code, stdout, stderr) without spawning a process."""
    out, err = io.StringIO(), io.StringIO()
    with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
        code = main(list(args))
    return code, out.getvalue(), err.getvalue()

# conftest.py
import pytest
from cli import testing

@pytest.fixture
def cli_runner():
    return testing.cli_runner
```

A criterion imports `cli_runner` from `cli.testing`, calls `cli_runner("status", "--json")`, and
asserts on the returned tuple. It does not call `subprocess.run`, which measures the installed
console script and the shell rather than the code the story wrote.

---

## 1. Directory Layout

**Rule**: Command code lives in `cli/`. The root holds only packaging and infrastructure files.

```
project/
  pyproject.toml            # [project.scripts] declares the console script
  cli/
    __init__.py             # main() — the single entry point
    commands.py             # one function per command; no argument parsing
    parser.py               # argparse construction; no behavior
  bin/
    run.sh                  # bash launcher
    run.ps1                 # PowerShell launcher
  tests/
```

**Why**: Parsing, behavior, and launching are three contracts. Collapsing them produces a command
that cannot be tested without a shell.

---

## 2. Entry Point and Exit Codes

**Rule**: `main(argv=None) -> int` parses, dispatches, and returns an exit code. It never calls
`sys.exit` and never raises for an expected failure. The console script is the only caller that
translates the return value into a process exit.

```python
# cli/__init__.py
import sys
from cli.parser import build_parser
from cli import commands

def main(argv: list[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    try:
        return commands.dispatch(args)
    except OperationalError as exc:
        print(f"error: {exc}", file=sys.stderr)
        return 1
```

```toml
# pyproject.toml
[project.scripts]
mytool = "cli:main"
```

**Exit codes**: `0` success, `1` operational failure, `2` usage error. `argparse` already returns
`2` for a usage error; do not override it.

**Why**: A `main` that returns rather than exits is callable from a test in-process. A `main` that
calls `sys.exit` forces every criterion to spawn a subprocess and measure the shell.

---

## 3. Parsing Is Separate From Behavior

**Rule**: `parser.py` builds the `argparse` tree and returns it. `commands.py` holds one function
per command taking plain arguments, not a `Namespace`. Neither imports the other.

```python
# cli/parser.py
import argparse

def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(prog="mytool")
    sub = parser.add_subparsers(dest="command", required=True)
    status = sub.add_parser("status", help="Report current state")
    status.add_argument("--json", action="store_true")
    return parser
```

```python
# cli/commands.py
def status(*, as_json: bool) -> int:
    ...

def dispatch(args) -> int:
    if args.command == "status":
        return status(as_json=args.json)
    return 2
```

**Why**: Behavior tested through a `Namespace` is behavior tested through the parser. Separating
them lets a criterion call `status(as_json=True)` directly.

---

## 4. Cross-Platform Launchers

**Rule**: Ship both launchers. They locate the environment and invoke the package entry point;
they contain no business logic. A launcher that makes a decision is a second implementation of the
command.

```bash
#!/usr/bin/env bash
# bin/run.sh — locate the environment and hand off. No business logic.
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
if [ -d "$ROOT/.venv" ]; then
    source "$ROOT/.venv/bin/activate"
fi
exec python -m cli "$@"
```

```powershell
# bin/run.ps1 — locate the environment and hand off. No business logic.
$ErrorActionPreference = "Stop"
$Root = Split-Path -Parent $PSScriptRoot
$Activate = Join-Path $Root ".venv\Scripts\Activate.ps1"
if (Test-Path $Activate) { & $Activate }
python -m cli @args
exit $LASTEXITCODE
```

```python
# cli/__main__.py — makes `python -m cli` work identically on both platforms
import sys
from cli import main

sys.exit(main())
```

**Why**: `python -m cli` is the one invocation both launchers share, so the two scripts cannot
drift in behavior — only in how they find the interpreter. `exit $LASTEXITCODE` is required in
PowerShell; without it the exit code is discarded and a failing command reports success.

---

## 5. Output and Streams

**Rule**: Results go to stdout, diagnostics to stderr. A `--json` mode prints one JSON document to
stdout and nothing else. Never interleave progress text into a machine-readable stream.

**Why**: A caller piping stdout to `jq` receives the progress lines too, and the command becomes
unusable in a pipeline.

---

## 6. Testing Without a Process

**Rule**: Test through `main(["status", "--json"])` or the `cli_runner` fixture. Reserve
`subprocess.run` for one packaging test asserting the installed console script exists and runs.

```python
def test_status_reports_json(cli_runner):
    code, out, err = cli_runner("status", "--json")
    assert code == 0
    assert json.loads(out)["state"] == "ready"
    assert err == ""
```

**Why**: In-process tests are fast, debuggable, and measure the code. Subprocess tests measure the
installed environment, which is a different and much smaller question.

---

## Checklist

- [ ] `cli/` package; `main(argv=None) -> int` that returns rather than exits
- [ ] `[project.scripts]` declares the console script
- [ ] `cli/__main__.py` so `python -m cli` works
- [ ] Both `bin/run.sh` and `bin/run.ps1`, neither holding logic; `.ps1` ends with `exit $LASTEXITCODE`
- [ ] Parsing in `parser.py`, behavior in `commands.py`, no import between them
- [ ] Exit codes `0` / `1` / `2` used consistently
- [ ] Results on stdout, diagnostics on stderr, `--json` emits nothing else
- [ ] Criteria use `cli_runner`; at most one subprocess test for packaging

</pblock>

CONTEXT - Read-Only Support

<pblock filename="ARCHITECTURE_compact.md" role="context" path="/mnt/c/Users/barlo/projects/drydock/uat/Quakes/runs/20261025.010423/workspace/targets/Quakes/blueprint/ARCHITECTURE_compact.md">

<!-- Compacted from ARCHITECTURE.md sha256=a4f0e3d35e74a3a608621cd364fd70b71c5a216cf0ef99264d9f012b2fdd0b87 on 2026-10-24 by drydock build agent -->

Project: quakes (Python >=3.11, stdlib only at runtime; pytest dev-only). Executable `quakes` at root -> `cli.main(argv=None)->int`.
Modules: cli/__init__.py (main, COMMANDS: dict[str, Callable[[Parsed], str]], exit mapping); cli/errors.py (UsageError exit 2, OperationalError exit 1); cli/options.py (parse_args(argv)->Parsed); cli/formatting.py (format_time, format_mag, format_mean, format_decimal, render_csv, write_csv); cli/feed.py (read_feed(path)->list[dict], extract_events(features)->list[Event], Event, filter_events(events,min_mag)); cli/reports.py (one pure fn per report, haversine_km); cli/fetch.py (build_url, http_get, fetch command); cli/testing.py (cli_runner(*args)->(exit_code, stdout, stderr)).
Parsed dataclass: command:str, min_mag:float|None, n:int (default 10), lat, lon, radius:float|None, start, end, out, file:str|None. min_mag default None for reports, 2.5 for fetch.
Commands: fetch, summary, top, daily, regions, near.
Exit codes: 0 success (incl. empty report); 1 OperationalError (unreadable file, not FeatureCollection, fetch network/HTTP/body failure); 2 UsageError. Failing command: empty stdout, one stderr line.
Pipeline: read_feed -> extract_events (drops null magnitude) -> filter_events -> report fn returns rows of preformatted strings -> write_csv. Handlers return full stdout text; main writes only after success.
Technical: half-up rounding via Decimal(repr(x)) ROUND_HALF_UP; string ordering by code point; UTF-8 output. Tests stub cli.fetch.http_get; no network in tests. No hardcoded rows/counts/distances.
Guardrails: never modify/read sources/ from app code. Tests never open network.
Project layout: pyproject.toml + uv.lock, .venv (uv venv), conftest.py (cli_runner fixture from cli.testing), tests/, bin/test.sh (runs pytest -q).

</pblock>

IMPLEMENTS - Authoritative Step Specifications

<pblock label="Implementation recency anchor" kind="section"> The files in this section are the load-bearing specifications for this build block. Build these files exactly. Treat earlier sections as constraints and context.

</pblock>

<pblock filename="FEATURE-Summary.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/Quakes/runs/20261025.010423/workspace/targets/Quakes/blueprint/FEATURE-Summary.md" guidance="Feature Specification">

# FEATURE: Summary Report

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | The summary command reports event count, time span, magnitude range, mean, and tsunami count. |
| Depends On  | FEATURE-MagFilter.md, FEATURE-Formatting.md, FEATURE-Options.md, FEATURE-ExitCodes.md |
| Provides    | quakes summary |
| Consumes    | read_feed, extract_events, filter_events, write_csv, parse_args |

## Purpose

`quakes summary [--min-mag <m>] <file>` reads a saved feed, applies the filter, and writes a
one-row CSV report to standard output.

## Behavior

- Header: `events,first,last,min_mag,max_mag,mean_mag,tsunami`.
- One data row computed over the filtered events:
  - `events`: the count.
  - `first` / `last`: the earliest and latest event times, formatted `YYYY-MM-DDTHH:MM:SSZ`.
  - `min_mag` / `max_mag`: one decimal place.
  - `mean_mag`: arithmetic mean, two decimals, rounded half up.
  - `tsunami`: the number of events whose `tsunami` equals `1`.
- With no events the row is `0,,,,,,0`.
- Only `--min-mag` is accepted; any other option is a usage error (exit 2).
- Success, including the empty report, exits `0`. An unreadable or invalid file exits `1` with
  nothing on standard output.

## Programmatic Acceptance

=== AC summary-values ===
Intent: The summary row carries count, time span, magnitude range, mean and tsunami count computed from the file.
Requires: executable=python3; scope=test

import csv
import datetime
import io
import json
import tempfile
from pathlib import Path

from cli.testing import cli_runner

BASE = 1735689600000


def feature(ident, mag, k, tsunami):
    return {"type": "Feature", "id": ident,
            "properties": {"mag": mag, "place": "10 km N of Town, Land",
                           "time": BASE + k * 3600000, "tsunami": tsunami},
            "geometry": {"type": "Point", "coordinates": [10.0, 20.0, 12.0]}}


specs = [("a", 5.0, 5, 0), ("b", 6.5, 1, 1), ("c", 5.5, 9, 1), ("d", 5.0, 3, 0)]
features = [feature(*s) for s in specs]
with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "feed.geojson"
    path.write_text(json.dumps({"type": "FeatureCollection", "features": features}), encoding="utf-8")
    code, out, err = cli_runner("summary", str(path))
print(out, err)
assert code == 0
rows = list(csv.reader(io.StringIO(out)))
assert len(rows) == 2
header, row = rows
assert header == ["events", "first", "last", "min_mag", "max_mag", "mean_mag", "tsunami"]
mags = [s[1] for s in specs]
times = [BASE + s[2] * 3600000 for s in specs]
record = dict(zip(header, row))
assert int(record["events"]) == len(specs)


def epoch(text):
    return int(datetime.datetime.fromisoformat(text).timestamp() * 1000)


assert record["first"].endswith("Z") and record["last"].endswith("Z")
assert epoch(record["first"]) == min(times)
assert epoch(record["last"]) == max(times)
assert float(record["min_mag"]) == min(mags)
assert float(record["max_mag"]) == max(mags)
assert abs(float(record["mean_mag"]) - sum(mags) / len(mags)) <= 0.005
assert int(record["tsunami"]) == sum(s[3] for s in specs)
=== END AC summary-values ===

=== AC summary-mean-half-up ===
Intent: A mean falling exactly on a half cent is rounded up, not to even.
Requires: executable=python3; scope=test

import csv
import io
import json
import tempfile
from pathlib import Path

from cli.testing import cli_runner

mags = [5.0] * 7 + [6.0]
features = [{"type": "Feature", "id": f"e{i}",
             "properties": {"mag": m, "place": "P", "time": 1735689600000 + i * 1000, "tsunami": 0},
             "geometry": {"type": "Point", "coordinates": [0.0, 0.0, 1.0]}} for i, m in enumerate(mags)]
with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "feed.geojson"
    path.write_text(json.dumps({"type": "FeatureCollection", "features": features}), encoding="utf-8")
    code, out, err = cli_runner("summary", str(path))
print(out, err)
assert code == 0
header, row = list(csv.reader(io.StringIO(out)))
mean_text = dict(zip(header, row))["mean_mag"]
# 41.0 / 8 is exactly 5.125, so half-up yields 5.13 (banker's rounding would give 5.12).
assert mean_text == "5.13"
=== END AC summary-mean-half-up ===

=== AC summary-min-mag-filter ===
Intent: --min-mag restricts the summary to events at or above the threshold.
Requires: executable=python3; scope=test

import csv
import io
import json
import tempfile
from pathlib import Path

from cli.testing import cli_runner

mags = [5.0, 5.4, 5.5, 6.0, 7.1]
features = [{"type": "Feature", "id": f"e{i}",
             "properties": {"mag": m, "place": "P", "time": 1735689600000 + i * 1000, "tsunami": 0},
             "geometry": {"type": "Point", "coordinates": [0.0, 0.0, 1.0]}} for i, m in enumerate(mags)]
threshold = 5.5
with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "feed.geojson"
    path.write_text(json.dumps({"type": "FeatureCollection", "features": features}), encoding="utf-8")
    code, out, err = cli_runner("summary", "--min-mag", str(threshold), str(path))
print(out, err)
assert code == 0
header, row = list(csv.reader(io.StringIO(out)))
record = dict(zip(header, row))
kept = [m for m in mags if m >= threshold]
assert int(record["events"]) == len(kept)
assert float(record["min_mag"]) == min(kept)
assert float(record["max_mag"]) == max(kept)
=== END AC summary-min-mag-filter ===

=== AC summary-null-mag-excluded ===
Intent: Features with a null magnitude are not counted.
Requires: executable=python3; scope=test

import csv
import io
import json
import tempfile
from pathlib import Path

from cli.testing import cli_runner

mags = [5.0, None, 6.0, None]
features = [{"type": "Feature", "id": f"e{i}",
             "properties": {"mag": m, "place": "P", "time": 1735689600000 + i * 1000, "tsunami": 0},
             "geometry": {"type": "Point", "coordinates": [0.0, 0.0, 1.0]}} for i, m in enumerate(mags)]
with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "feed.geojson"
    path.write_text(json.dumps({"type": "FeatureCollection", "features": features}), encoding="utf-8")
    code, out, err = cli_runner("summary", str(path))
print(out, err)
assert code == 0
header, row = list(csv.reader(io.StringIO(out)))
assert int(dict(zip(header, row))["events"]) == len([m for m in mags if m is not None])
=== END AC summary-null-mag-excluded ===

=== AC summary-empty ===
Intent: When nothing matches, the report is a single row with a zero count and empty fields.
Requires: executable=python3; scope=test

import csv
import io
import json
import tempfile
from pathlib import Path

from cli.testing import cli_runner

features = [{"type": "Feature", "id": "e0",
             "properties": {"mag": 5.0, "place": "P", "time": 1735689600000, "tsunami": 0},
             "geometry": {"type": "Point", "coordinates": [0.0, 0.0, 1.0]}}]
with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "feed.geojson"
    path.write_text(json.dumps({"type": "FeatureCollection", "features": features}), encoding="utf-8")
    code, out, err = cli_runner("summary", "--min-mag", "9", str(path))
print(out, err)
assert code == 0
rows = list(csv.reader(io.StringIO(out)))
assert len(rows) == 2
assert rows[1] == ["0", "", "", "", "", "", "0"]
=== END AC summary-empty ===

=== AC summary-failure-codes ===
Intent: An invalid file exits 1, an unlisted option or missing file exits 2, and stdout stays empty in both.
Requires: executable=python3; scope=test

import tempfile
from pathlib import Path

from cli.testing import cli_runner

with tempfile.TemporaryDirectory() as tmp:
    garbage = Path(tmp) / "garbage.json"
    garbage.write_text("this is not json\n", encoding="utf-8")
    missing = Path(tmp) / "no-such-file.geojson"

    code, out, err = cli_runner("summary", str(garbage))
    assert code == 1 and out == ""
    code, out, err = cli_runner("summary", str(missing))
    assert code == 1 and out == ""
    code, out, err = cli_runner("summary", "--n", "3", str(garbage))
    assert code == 2 and out == ""
    code, out, err = cli_runner("summary")
    assert code == 2 and out == ""
    code, out, err = cli_runner("summary", "--min-mag", "big", str(garbage))
    assert code == 2 and out == ""
=== END AC summary-failure-codes ===

## User Acceptance

- None.

## Guardrails

- No report row, count, or value is hardcoded; all values are computed from the file read.
- Application code never reads `sources/run.sh` or the frozen snapshot.
- Output is built completely before being written, so a failing command leaves standard output empty.

</pblock>

<pblock filename="FEATURE-Regions.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/Quakes/runs/20261025.010423/workspace/targets/Quakes/blueprint/FEATURE-Regions.md" guidance="Feature Specification">

# FEATURE: Regions

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | The `regions` report: event count and maximum magnitude per region derived from the place text. |
| Depends On  | FEATURE-MagFilter.md, FEATURE-Formatting.md, FEATURE-Options.md, FEATURE-ExitCodes.md |
| Provides    | quakes regions |
| Consumes    | read_feed, extract_events, filter_events, write_csv, format_mag, parse_args |

## Purpose

`quakes regions [--min-mag <m>] <file>` reports the most active regions in a saved USGS GeoJSON file.

## Trigger

Command line: `./quakes regions [--min-mag <m>] <file>`. Only `--min-mag` is accepted.

## Sequence

1. `read_feed`, `extract_events`, and `filter_events` produce the kept events.
2. `region_of(place)` is a pure function: the text after the last `", "` (comma, space) in `place`; the whole `place` when it has none; `"Unknown"` when `place` is `None`.
3. `compute_regions(events)` counts events and tracks the maximum magnitude per region.
4. Rows are ordered by events descending, then region ascending by byte value (plain code point order, so uppercase sorts before lowercase).
5. `write_csv` writes the complete report.

## Output

Header: `region,events,max_mag`. One row per region; `max_mag` has one decimal. With no events, the output is only the header, exit 0. A region containing a comma cannot occur (the last `", "` is split on), but quoting is always delegated to the `csv` module. Non-ASCII region names are written as UTF-8.

## Reads

The saved GeoJSON file named on the command line.

## Writes

Standard output only.

## Programmatic Acceptance

=== AC regions-extract-and-order ===
Intent: Region is the text after the last comma-space, counts and maxima are per region, ordered by events descending then region by byte value.
Suite: scoped
Requires: executable=python3; scope=test

import csv
import io
import json
import os
import tempfile

from cli.testing import cli_runner

# (region, mag) pairs supplied as input; the place text is built from the region.
pairs = [
    ("Zed", 5.0), ("Zed", 5.6),
    ("alpha", 5.1),
    ("Beta", 5.2), ("Beta", 5.0),
    ("Gamma", 5.3), ("Gamma", 5.9), ("Gamma", 5.1),
    ("Delta", 5.4),
]
features = []
for i, (region, mag) in enumerate(pairs):
    features.append({
        "type": "Feature",
        "properties": {"mag": mag, "place": "12 km N of Town " + str(i) + ", " + region,
                       "time": 1735706358208 + i, "tsunami": 0},
        "geometry": {"type": "Point", "coordinates": [1.0, 2.0, 3.0]},
        "id": "e" + str(i),
    })
doc = {"type": "FeatureCollection", "features": features}
expected = {}
for region, mag in pairs:
    entry = expected.setdefault(region, [0, mag])
    entry[0] += 1
    entry[1] = max(entry[1], mag)
order = sorted(expected, key=lambda r: (-expected[r][0], r))
with tempfile.TemporaryDirectory() as tmp:
    path = os.path.join(tmp, "q.geojson")
    with open(path, "w", encoding="utf-8") as fh:
        json.dump(doc, fh)
    code, out, err = cli_runner("regions", path)
print(out)
print(err)
assert code == 0
rows = list(csv.reader(io.StringIO(out)))
assert rows[0] == ["region", "events", "max_mag"]
assert [r[0] for r in rows[1:]] == order
for r in rows[1:]:
    assert int(r[1]) == expected[r[0]][0]
    assert float(r[2]) == expected[r[0]][1]
=== END AC regions-extract-and-order ===

=== AC regions-place-rules ===
Intent: A place with several commas splits on the last comma-space, a place without one is its own region, and a null place is Unknown.
Suite: scoped
Requires: executable=python3; scope=test

import csv
import io
import json
import os
import tempfile

from cli.testing import cli_runner

last_part = "Country"
multi_place = "Near Town, Province, " + last_part
plain_place = "Mid-Atlantic Ridge"
comma_no_space = "A,B"
places = [multi_place, plain_place, comma_no_space, None]
features = []
for i, place in enumerate(places):
    features.append({
        "type": "Feature",
        "properties": {"mag": 5.0, "place": place, "time": 1735706358208 + i, "tsunami": 0},
        "geometry": {"type": "Point", "coordinates": [1.0, 2.0, 3.0]},
        "id": "e" + str(i),
    })
doc = {"type": "FeatureCollection", "features": features}
with tempfile.TemporaryDirectory() as tmp:
    path = os.path.join(tmp, "q.geojson")
    with open(path, "w", encoding="utf-8") as fh:
        json.dump(doc, fh)
    code, out, err = cli_runner("regions", path)
print(out)
assert code == 0
rows = list(csv.reader(io.StringIO(out)))
names = {r[0] for r in rows[1:]}
assert names == {last_part, plain_place, comma_no_space, "Unknown"}
=== END AC regions-place-rules ===

=== AC regions-min-mag-and-empty ===
Intent: --min-mag restricts the regions counted, null magnitudes are excluded, and an empty result is only the header with exit 0.
Suite: scoped
Requires: executable=python3; scope=test

import csv
import io
import json
import os
import tempfile

from cli.testing import cli_runner

threshold = 5.4
pairs = [("Aland", 5.0), ("Aland", 5.4), ("Bland", 6.0), ("Cland", None), ("Dland", 5.3)]
features = []
for i, (region, mag) in enumerate(pairs):
    features.append({
        "type": "Feature",
        "properties": {"mag": mag, "place": "5 km S of T, " + region, "time": 1735706358208 + i, "tsunami": 0},
        "geometry": {"type": "Point", "coordinates": [1.0, 2.0, 3.0]},
        "id": "e" + str(i),
    })
doc = {"type": "FeatureCollection", "features": features}
kept = [(r, m) for r, m in pairs if m is not None and m >= threshold]
with tempfile.TemporaryDirectory() as tmp:
    path = os.path.join(tmp, "q.geojson")
    with open(path, "w", encoding="utf-8") as fh:
        json.dump(doc, fh)
    code, out, err = cli_runner("regions", "--min-mag", str(threshold), path)
    code_none, out_none, err_none = cli_runner("regions", "--min-mag", "9", path)
print(out)
assert code == 0 and code_none == 0
rows = list(csv.reader(io.StringIO(out)))
assert {r[0] for r in rows[1:]} == {r for r, _ in kept}
assert sum(int(r[1]) for r in rows[1:]) == len(kept)
assert list(csv.reader(io.StringIO(out_none))) == [["region", "events", "max_mag"]]
=== END AC regions-min-mag-and-empty ===

=== AC regions-failure-contract ===
Intent: A file that is not a FeatureCollection exits 1 and an unlisted option exits 2, each with empty standard output.
Suite: scoped
Requires: executable=python3; scope=test

import os
import tempfile

from cli.testing import cli_runner

with tempfile.TemporaryDirectory() as tmp:
    bad = os.path.join(tmp, "bad.json")
    with open(bad, "w", encoding="utf-8") as fh:
        fh.write("this is not json")
    code, out, err = cli_runner("regions", bad)
    assert code == 1
    assert out == ""
    code2, out2, err2 = cli_runner("regions", "--lat", "1", bad)
    assert code2 == 2
    assert out2 == ""
=== END AC regions-failure-contract ===

## User Acceptance

- None.

## Guardrails

- Region splitting uses the last `", "` only; `","` without a following space does not split.
- Ties in event count are broken by region name in byte order, not locale or case-insensitive order.
- No region row is hardcoded; all values come from the file read.

</pblock>

<pblock filename="FEATURE-Daily.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/Quakes/runs/20261025.010423/workspace/targets/Quakes/blueprint/FEATURE-Daily.md" guidance="Feature Specification">

# FEATURE: Daily

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | The `daily` report: event count and maximum magnitude per UTC date, followed by a TOTAL row. |
| Depends On  | FEATURE-MagFilter.md, FEATURE-Formatting.md, FEATURE-Options.md, FEATURE-ExitCodes.md |
| Provides    | quakes daily |
| Consumes    | read_feed, extract_events, filter_events, write_csv, format_time, format_mag, parse_args |

## Purpose

`quakes daily [--min-mag <m>] <file>` reads a saved USGS GeoJSON file and reports how many events occurred on each UTC date and the strongest magnitude on that date.

## Trigger

Command line: `./quakes daily [--min-mag <m>] <file>`. The command accepts only `--min-mag`; any other option is a usage error handled by `parse_args`.

## Sequence

1. `read_feed(file)` validates and returns the features (`OperationalError`, exit 1, on failure).
2. `extract_events` drops null-magnitude features.
3. `filter_events(events, min_mag)` applies `--min-mag`.
4. `compute_daily(events)` groups events by date, where date is the first 10 characters of `format_time(event.time)`.
5. Rows are ordered by date ascending (byte order), followed by one `TOTAL` row.
6. `write_csv` writes the whole report to standard output in one step, after it is fully computed.

`compute_daily(events)` is a pure function returning `(rows, total_row)` with no I/O; formatting is performed by the `format_daily` step that uses `format_mag` and `write_csv`.

## Output

Header: `date,events,max_mag`.

- One row per date that has at least one event, ascending.
- `events` is the integer count; `max_mag` is the maximum magnitude with one decimal.
- Final row: `TOTAL,<events>,<max_mag>` where both values are over all kept events.
- With no events the output is the header followed by `TOTAL,0,` (empty max).
- Exit code 0, including the empty case.

## Reads

The saved GeoJSON file named on the command line. No other input.

## Writes

Standard output only. Nothing is written to any file.

## Programmatic Acceptance

=== AC daily-groups-by-utc-date ===
Intent: Events are grouped per UTC date with counts and maximum magnitude, ascending, followed by a TOTAL row.
Suite: scoped
Requires: executable=python3; scope=test

import csv
import io
import json
import os
import tempfile
from datetime import datetime, timezone

from cli.testing import cli_runner


def ms(day, hour, minute=0, second=0, milli=0):
    moment = datetime(2025, 1, day, hour, minute, second, tzinfo=timezone.utc)
    return int(moment.timestamp()) * 1000 + milli


def feat(i, mag, t):
    return {
        "type": "Feature",
        "properties": {"mag": mag, "place": "10 km N of Town, Land", "time": t, "tsunami": 0},
        "geometry": {"type": "Point", "coordinates": [10.0, 20.0, 5.0]},
        "id": "e" + str(i),
    }


specs = [
    (5.0, ms(3, 1)),
    (6.1, ms(1, 2)),
    (5.4, ms(1, 23, 59, 59, 999)),
    (5.5, ms(3, 12)),
    (5.2, ms(7, 0)),
]
expected = {}
for mag, t in specs:
    label = datetime.fromtimestamp(t // 1000, timezone.utc).strftime("%Y-%m-%d")
    entry = expected.setdefault(label, [0, mag])
    entry[0] += 1
    entry[1] = max(entry[1], mag)

doc = {"type": "FeatureCollection", "features": [feat(i, m, t) for i, (m, t) in enumerate(specs)]}
with tempfile.TemporaryDirectory() as tmp:
    path = os.path.join(tmp, "q.geojson")
    with open(path, "w", encoding="utf-8") as fh:
        json.dump(doc, fh)
    code, out, err = cli_runner("daily", path)
print(out)
print(err)
assert code == 0
rows = list(csv.reader(io.StringIO(out)))
assert rows[0] == ["date", "events", "max_mag"]
body = rows[1:-1]
assert [r[0] for r in body] == sorted(expected)
for r in body:
    assert int(r[1]) == expected[r[0]][0]
    assert float(r[2]) == expected[r[0]][1]
total = rows[-1]
assert total[0] == "TOTAL"
assert int(total[1]) == len(specs)
assert float(total[2]) == max(m for m, _ in specs)
=== END AC daily-groups-by-utc-date ===

=== AC daily-empty-report ===
Intent: With no matching events the report is the header and a TOTAL row with zero events and an empty maximum, exit 0.
Suite: scoped
Requires: executable=python3; scope=test

import csv
import io
import json
import os
import tempfile

from cli.testing import cli_runner

feature = {
    "type": "Feature",
    "properties": {"mag": 5.0, "place": "X, Y", "time": 1735706358208, "tsunami": 0},
    "geometry": {"type": "Point", "coordinates": [1.0, 2.0, 3.0]},
    "id": "only",
}
doc = {"type": "FeatureCollection", "features": [feature]}
threshold = 9
with tempfile.TemporaryDirectory() as tmp:
    path = os.path.join(tmp, "q.geojson")
    with open(path, "w", encoding="utf-8") as fh:
        json.dump(doc, fh)
    code, out, err = cli_runner("daily", "--min-mag", str(threshold), path)
    empty_doc = {"type": "FeatureCollection", "features": []}
    path2 = os.path.join(tmp, "empty.geojson")
    with open(path2, "w", encoding="utf-8") as fh:
        json.dump(empty_doc, fh)
    code2, out2, err2 = cli_runner("daily", path2)
print(out, out2)
assert code == 0 and code2 == 0
for text in (out, out2):
    rows = list(csv.reader(io.StringIO(text)))
    assert rows == [["date", "events", "max_mag"], ["TOTAL", "0", ""]]
=== END AC daily-empty-report ===

=== AC daily-min-mag-and-null-mag ===
Intent: --min-mag keeps only events with mag at or above it, and null-magnitude events are absent from rows and TOTAL.
Suite: scoped
Requires: executable=python3; scope=test

import csv
import io
import json
import os
import tempfile
from datetime import datetime, timezone

from cli.testing import cli_runner


def ms(day, hour):
    return int(datetime(2025, 1, day, hour, tzinfo=timezone.utc).timestamp()) * 1000


def feat(i, mag, t):
    return {
        "type": "Feature",
        "properties": {"mag": mag, "place": "P", "time": t, "tsunami": 0},
        "geometry": {"type": "Point", "coordinates": [0.0, 0.0, 1.0]},
        "id": "e" + str(i),
    }


threshold = 5.4
specs = [(5.0, ms(1, 1)), (5.4, ms(1, 2)), (6.0, ms(2, 3)), (None, ms(2, 4)), (5.3, ms(4, 5))]
kept = [(m, t) for m, t in specs if m is not None and m >= threshold]
doc = {"type": "FeatureCollection", "features": [feat(i, m, t) for i, (m, t) in enumerate(specs)]}
with tempfile.TemporaryDirectory() as tmp:
    path = os.path.join(tmp, "q.geojson")
    with open(path, "w", encoding="utf-8") as fh:
        json.dump(doc, fh)
    code, out, err = cli_runner("daily", "--min-mag", str(threshold), path)
    code_all, out_all, err_all = cli_runner("daily", path)
print(out)
print(out_all)
assert code == 0 and code_all == 0
rows = list(csv.reader(io.StringIO(out)))
assert int(rows[-1][1]) == len(kept)
assert float(rows[-1][2]) == max(m for m, _ in kept)
assert len(rows) - 2 == len({datetime.fromtimestamp(t // 1000, timezone.utc).date() for _, t in kept})
rows_all = list(csv.reader(io.StringIO(out_all)))
assert int(rows_all[-1][1]) == len([1 for m, _ in specs if m is not None])
=== END AC daily-min-mag-and-null-mag ===

=== AC daily-failure-contract ===
Intent: An unreadable file exits 1 and an option daily does not take exits 2, both with empty standard output.
Suite: scoped
Requires: executable=python3; scope=test

import os
import tempfile

from cli.testing import cli_runner

with tempfile.TemporaryDirectory() as tmp:
    missing = os.path.join(tmp, "absent.geojson")
    code, out, err = cli_runner("daily", missing)
    assert code == 1
    assert out == ""
    present = os.path.join(tmp, "x.geojson")
    with open(present, "w", encoding="utf-8") as fh:
        fh.write("{}")
    code2, out2, err2 = cli_runner("daily", "--n", "3", present)
    assert code2 == 2
    assert out2 == ""
=== END AC daily-failure-contract ===

## User Acceptance

- None.

## Guardrails

- The date is the first 10 characters of the formatted UTC time; local time zones are never used.
- No report row, count, or date is hardcoded; every value is computed from the file read.
- Standard output is written only after the report is fully computed, so a failure leaves it empty.
- `daily` accepts no option other than `--min-mag`.

</pblock>

<pblock filename="FEATURE-Top.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/Quakes/runs/20261025.010423/workspace/targets/Quakes/blueprint/FEATURE-Top.md" guidance="Feature Specification">

# FEATURE: Top Report

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | The top command lists the largest events by magnitude. |
| Depends On  | FEATURE-MagFilter.md, FEATURE-Formatting.md, FEATURE-Options.md, FEATURE-ExitCodes.md |
| Provides    | quakes top |
| Consumes    | read_feed, extract_events, filter_events, write_csv, parse_args |

## Purpose

`quakes top [--min-mag <m>] [--n <count>] <file>` writes the `--n` largest events as CSV.

## Behavior

- Header: `time,mag,depth_km,place,id`.
- Events are filtered by `--min-mag` first, then sorted by magnitude descending, then time ascending
  (ties beyond that keep feed order), then the first `--n` are written.
- `--n` is a positive integer and defaults to `10`. `--n 0` or a non-integer is a usage error (exit 2).
- `time` is `YYYY-MM-DDTHH:MM:SSZ`; `mag` and `depth_km` have one decimal place.
- A place containing a comma is quoted by the `csv` module.
- Only `--min-mag` and `--n` are accepted. No matching events yields the header alone with exit `0`.

## Programmatic Acceptance

=== AC top-order-and-default-n ===
Intent: Rows are sorted by magnitude descending then time ascending, and the default count is ten.
Requires: executable=python3; scope=test

import csv
import datetime
import io
import json
import tempfile
from pathlib import Path

from cli.testing import cli_runner

BASE = 1735689600000
# (id, mag, minutes offset); two pairs tie on magnitude with different times.
specs = [("a", 5.0, 50), ("b", 6.0, 40), ("c", 6.0, 10), ("d", 5.5, 30), ("e", 5.1, 20),
         ("f", 7.0, 60), ("g", 5.2, 70), ("h", 5.3, 80), ("i", 5.4, 90), ("j", 5.6, 15),
         ("k", 5.7, 25), ("l", 5.8, 35)]
features = [{"type": "Feature", "id": s[0],
             "properties": {"mag": s[1], "place": "P", "time": BASE + s[2] * 60000, "tsunami": 0},
             "geometry": {"type": "Point", "coordinates": [0.0, 0.0, 12.0]}} for s in specs]
with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "feed.geojson"
    path.write_text(json.dumps({"type": "FeatureCollection", "features": features}), encoding="utf-8")
    code, out, err = cli_runner("top", str(path))
print(out, err)
assert code == 0
rows = list(csv.reader(io.StringIO(out)))
header, body = rows[0], rows[1:]
assert header == ["time", "mag", "depth_km", "place", "id"]
ranked = sorted(specs, key=lambda s: (-s[1], s[2]))
default_n = 10
assert len(specs) > default_n
assert [r[4] for r in body] == [s[0] for s in ranked[:default_n]]
first = dict(zip(header, body[0]))
assert float(first["mag"]) == ranked[0][1]
assert float(first["depth_km"]) == 12.0
parsed = datetime.datetime.fromisoformat(first["time"])
assert int(parsed.timestamp() * 1000) == BASE + ranked[0][2] * 60000
=== END AC top-order-and-default-n ===

=== AC top-n-option ===
Intent: --n limits the number of rows written.
Requires: executable=python3; scope=test

import csv
import io
import json
import tempfile
from pathlib import Path

from cli.testing import cli_runner

specs = [("a", 5.0), ("b", 6.0), ("c", 7.1), ("d", 5.5), ("e", 6.2)]
features = [{"type": "Feature", "id": s[0],
             "properties": {"mag": s[1], "place": "P", "time": 1735689600000 + i * 1000, "tsunami": 0},
             "geometry": {"type": "Point", "coordinates": [0.0, 0.0, 5.0]}} for i, s in enumerate(specs)]
count = 3
with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "feed.geojson"
    path.write_text(json.dumps({"type": "FeatureCollection", "features": features}), encoding="utf-8")
    code, out, err = cli_runner("top", "--n", str(count), str(path))
print(out, err)
assert code == 0
body = list(csv.reader(io.StringIO(out)))[1:]
assert [r[4] for r in body] == [s[0] for s in sorted(specs, key=lambda s: -s[1])[:count]]
=== END AC top-n-option ===

=== AC top-min-mag-before-cut ===
Intent: --min-mag filters before --n cuts the list.
Requires: executable=python3; scope=test

import csv
import io
import json
import tempfile
from pathlib import Path

from cli.testing import cli_runner

specs = [("a", 5.0), ("b", 5.1), ("c", 5.2), ("d", 6.0), ("e", 7.0)]
features = [{"type": "Feature", "id": s[0],
             "properties": {"mag": s[1], "place": "P", "time": 1735689600000 + i * 1000, "tsunami": 0},
             "geometry": {"type": "Point", "coordinates": [0.0, 0.0, 5.0]}} for i, s in enumerate(specs)]
threshold = 5.1
count = 4
with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "feed.geojson"
    path.write_text(json.dumps({"type": "FeatureCollection", "features": features}), encoding="utf-8")
    code, out, err = cli_runner("top", "--min-mag", str(threshold), "--n", str(count), str(path))
print(out, err)
assert code == 0
body = list(csv.reader(io.StringIO(out)))[1:]
kept = sorted([s for s in specs if s[1] >= threshold], key=lambda s: -s[1])
assert [r[4] for r in body] == [s[0] for s in kept[:count]]
assert all(float(r[1]) >= threshold for r in body)
=== END AC top-min-mag-before-cut ===

=== AC top-place-with-comma ===
Intent: A place containing a comma round-trips through CSV quoting.
Requires: executable=python3; scope=test

import csv
import io
import json
import tempfile
from pathlib import Path

from cli.testing import cli_runner

place = "56 km SSE of Some Town, Some Country"
features = [{"type": "Feature", "id": "c1",
             "properties": {"mag": 6.2, "place": place, "time": 1735689600000, "tsunami": 0},
             "geometry": {"type": "Point", "coordinates": [0.0, 0.0, 46.0]}}]
with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "feed.geojson"
    path.write_text(json.dumps({"type": "FeatureCollection", "features": features}), encoding="utf-8")
    code, out, err = cli_runner("top", str(path))
print(out, err)
assert code == 0
body = list(csv.reader(io.StringIO(out)))[1:]
assert len(body) == 1
assert body[0][3] == place
assert body[0][4] == "c1"
=== END AC top-place-with-comma ===

=== AC top-empty-result ===
Intent: When no event matches, only the header is written and the exit status is 0.
Requires: executable=python3; scope=test

import csv
import io
import json
import tempfile
from pathlib import Path

from cli.testing import cli_runner

features = [{"type": "Feature", "id": "e0",
             "properties": {"mag": 5.0, "place": "P", "time": 1735689600000, "tsunami": 0},
             "geometry": {"type": "Point", "coordinates": [0.0, 0.0, 1.0]}}]
with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "feed.geojson"
    path.write_text(json.dumps({"type": "FeatureCollection", "features": features}), encoding="utf-8")
    code, out, err = cli_runner("top", "--min-mag", "9", str(path))
print(out, err)
assert code == 0
rows = list(csv.reader(io.StringIO(out)))
assert rows == [["time", "mag", "depth_km", "place", "id"]]
=== END AC top-empty-result ===

=== AC top-usage-errors ===
Intent: A non-positive or malformed --n, an unlisted option, and a missing file all exit 2 with empty stdout.
Requires: executable=python3; scope=test

import json
import tempfile
from pathlib import Path

from cli.testing import cli_runner

features = [{"type": "Feature", "id": "e0",
             "properties": {"mag": 5.0, "place": "P", "time": 1735689600000, "tsunami": 0},
             "geometry": {"type": "Point", "coordinates": [0.0, 0.0, 1.0]}}]
with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "feed.geojson"
    path.write_text(json.dumps({"type": "FeatureCollection", "features": features}), encoding="utf-8")
    for args in (("top", "--n", "0", str(path)),
                 ("top", "--n", "-2", str(path)),
                 ("top", "--n", "many", str(path)),
                 ("top", "--lat", "1", str(path)),
                 ("top",)):
        code, out, err = cli_runner(*args)
        assert code == 2, args
        assert out == "", args
=== END AC top-usage-errors ===

## User Acceptance

- None.

## Guardrails

- No report row is hardcoded; every row is computed from the file read.
- Application code never reads `sources/run.sh` or the frozen snapshot.
- Output is built completely before being written, so a failing command leaves standard output empty.

</pblock>

<pblock filename="FEATURE-Fetch.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/Quakes/runs/20261025.010423/workspace/targets/Quakes/blueprint/FEATURE-Fetch.md" guidance="Feature Specification">

# FEATURE: Fetch

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | The `fetch` command: download a USGS date range as GeoJSON and save the response unchanged to a file. |
| Depends On  | FEATURE-Options.md, FEATURE-ExitCodes.md, FEATURE-FeedValidation.md |
| Provides    | quakes fetch, build_url, http_get |
| Consumes    | parse_args, read_feed |

## Purpose

`quakes fetch --start <YYYY-MM-DD> --end <YYYY-MM-DD> [--min-mag <m>] --out <file>` saves a period of the USGS event feed so the report commands can read it.

## Trigger

Command line. `--start`, `--end`, and `--out` are required; `--min-mag` defaults to `2.5`. A missing required option, an unlisted option, or any positional argument is a usage error (exit 2) and no HTTP call is made.

## Module layout

Code lives in `cli/fetch.py`:

- `build_url(start, end, min_mag) -> str` returns `https://earthquake.usgs.gov/fdsnws/event/1/query` with query parameters `format=geojson`, `starttime=<start>`, `endtime=<end>`, `minmagnitude=<min_mag>`, `orderby=time-asc`. `min_mag` is the text given on the command line (or `2.5`).
- `http_get(url) -> tuple[int, bytes]` is the single replaceable network function. It calls `urllib.request.urlopen` through attribute access on the `urllib.request` module (so a test can patch `urllib.request.urlopen`), returns the HTTP status and body bytes, and is the only function in the product that opens a connection.
- The command handler calls `http_get` through the module global (`cli.fetch.http_get`) so tests can replace it.

## Sequence

1. Build the URL and call `http_get(url)`.
2. Validate: status 200, body parses as JSON, and is an object with `"type": "FeatureCollection"` and a list `features` (reusing the `read_feed` validation rules on the body).
3. Only after validation, write the body bytes unchanged (binary write) to `--out`.
4. Write `fetched,<count>` to standard output, where `<count>` is the number of features.

Failure handling is specified in FEATURE-FetchFailure.md.

## Output

Standard output is exactly one CSV line `fetched,<count>`; exit 0. The saved file is byte-for-byte the response body.

## Reads

The USGS FDSN event web service over HTTPS.

## Writes

The file named by `--out`, and standard output.

## Programmatic Acceptance

=== AC fetch-saves-body-unchanged ===
Intent: fetch writes the response body byte for byte to --out and prints fetched with the feature count; the HTTP call is stubbed.
Suite: scoped
Requires: executable=python3; scope=test

import csv
import io
import json
import os
import tempfile
from unittest import mock

from cli.testing import cli_runner

features = [
    {"type": "Feature", "properties": {"mag": 5.1, "place": "Awash, Ethiopia", "time": 1735706358208, "tsunami": 0},
     "geometry": {"type": "Point", "coordinates": [40.0, 9.0, 10]}, "id": "a" + str(i)}
    for i in range(3)
]
body = json.dumps({"type": "FeatureCollection", "features": features}, indent=3, ensure_ascii=False).encode("utf-8") + b"\n\n"
with tempfile.TemporaryDirectory() as tmp:
    out_path = os.path.join(tmp, "saved.geojson")
    with mock.patch("cli.fetch.http_get", return_value=(200, body)) as stub:
        code, out, err = cli_runner("fetch", "--start", "2025-01-01", "--end", "2025-01-08", "--out", out_path)
    print(out)
    print(err)
    assert code == 0
    assert stub.call_count == 1
    with open(out_path, "rb") as fh:
        assert fh.read() == body
rows = list(csv.reader(io.StringIO(out)))
assert rows == [["fetched", str(len(features))]]
=== END AC fetch-saves-body-unchanged ===

=== AC fetch-request-url ===
Intent: The request goes to the USGS FDSN query endpoint with the GeoJSON format, the given dates, the default minimum magnitude, and time ascending order.
Suite: scoped
Requires: executable=python3; scope=test

import json
import os
import tempfile
import urllib.parse
from unittest import mock

from cli.testing import cli_runner

start = "2025-01-01"
end = "2025-01-08"
body = json.dumps({"type": "FeatureCollection", "features": []}).encode("utf-8")
with tempfile.TemporaryDirectory() as tmp:
    out_path = os.path.join(tmp, "saved.geojson")
    with mock.patch("cli.fetch.http_get", return_value=(200, body)) as stub:
        code, out, err = cli_runner("fetch", "--start", start, "--end", end, "--out", out_path)
    assert code == 0
    url = stub.call_args[0][0]
parts = urllib.parse.urlsplit(url)
query = urllib.parse.parse_qs(parts.query)
assert parts.scheme == "https"
assert parts.netloc == "earthquake.usgs.gov"
assert parts.path == "/fdsnws/event/1/query"
assert query["format"] == ["geojson"]
assert query["starttime"] == [start]
assert query["endtime"] == [end]
assert query["minmagnitude"] == ["2.5"]
assert query["orderby"] == ["time-asc"]
=== END AC fetch-request-url ===

=== AC fetch-min-mag-passthrough ===
Intent: An explicit --min-mag value is sent as minmagnitude, and build_url builds the same query directly.
Suite: scoped
Requires: executable=python3; scope=test

import json
import os
import tempfile
import urllib.parse
from unittest import mock

from cli.fetch import build_url
from cli.testing import cli_runner

start = "2025-02-01"
end = "2025-02-03"
min_mag = "4.5"
body = json.dumps({"type": "FeatureCollection", "features": []}).encode("utf-8")
with tempfile.TemporaryDirectory() as tmp:
    out_path = os.path.join(tmp, "saved.geojson")
    with mock.patch("cli.fetch.http_get", return_value=(200, body)) as stub:
        code, out, err = cli_runner(
            "fetch", "--min-mag", min_mag, "--end", end, "--start", start, "--out", out_path
        )
    assert code == 0
    url = stub.call_args[0][0]
query = urllib.parse.parse_qs(urllib.parse.urlsplit(url).query)
assert query["minmagnitude"] == [min_mag]
assert query["starttime"] == [start]
assert query["endtime"] == [end]
direct = urllib.parse.parse_qs(urllib.parse.urlsplit(build_url(start, end, min_mag)).query)
assert direct == query
=== END AC fetch-min-mag-passthrough ===

=== AC fetch-usage-errors ===
Intent: Missing required options, an unlisted option, or an extra positional argument exit 2, make no HTTP call, and write no file.
Suite: scoped
Requires: executable=python3; scope=test

import os
import tempfile
from unittest import mock

from cli.testing import cli_runner

with tempfile.TemporaryDirectory() as tmp:
    out_path = os.path.join(tmp, "saved.geojson")
    cases = [
        ("fetch", "--end", "2025-01-08", "--out", out_path),
        ("fetch", "--start", "2025-01-01", "--out", out_path),
        ("fetch", "--start", "2025-01-01", "--end", "2025-01-08"),
        ("fetch", "--start", "2025-01-01", "--end", "2025-01-08", "--out", out_path, "extra"),
        ("fetch", "--start", "2025-01-01", "--end", "2025-01-08", "--out", out_path, "--n", "3"),
        ("fetch", "--start", "2025-01-01", "--end", "2025-01-08", "--min-mag", "big", "--out", out_path),
    ]
    with mock.patch("cli.fetch.http_get", return_value=(200, b"{}")) as stub:
        for args in cases:
            code, out, err = cli_runner(*args)
            assert code == 2, args
            assert out == "", args
        assert stub.call_count == 0
    assert not os.path.exists(out_path)
=== END AC fetch-usage-errors ===

=== AC fetch-http-get-uses-urllib ===
Intent: http_get returns the status and body from urllib.request.urlopen, which is stubbed so no network connection is opened.
Suite: scoped
Requires: executable=python3; scope=test

from unittest import mock

from cli.fetch import http_get

payload = b"payload bytes"
status = 200


class FakeResponse:
    def __init__(self, code, data):
        self.status = code
        self._data = data

    def read(self):
        return self._data

    def getcode(self):
        return self.status

    def __enter__(self):
        return self

    def __exit__(self, *exc):
        return False


with mock.patch("urllib.request.urlopen", return_value=FakeResponse(status, payload)) as opener:
    got_status, got_body = http_get("https://example.invalid/query")
assert opener.call_count == 1
assert got_status == status
assert got_body == payload
=== END AC fetch-http-get-uses-urllib ===

## User Acceptance

- None.

## Guardrails

- Tests never open a network connection; every fetch test replaces `cli.fetch.http_get` or `urllib.request.urlopen`.
- The saved file is the response body unchanged: no re-serialization, re-encoding, or newline translation.
- The output file is written only after the response is validated.
- Only the `fetch` command touches the network; report commands never do.

</pblock>

<pblock filename="FEATURE-FetchFailure.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/Quakes/runs/20261025.010423/workspace/targets/Quakes/blueprint/FEATURE-FetchFailure.md" guidance="Feature Specification">

# FEATURE: Fetch Failure

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | Failure behavior of `fetch`: network, HTTP, and body errors exit 1 and never write or alter a file. |
| Depends On  | FEATURE-Fetch.md, FEATURE-ExitCodes.md |
| Provides    | fetch failure handling |
| Consumes    | http_get |

## Purpose

When the download cannot produce a valid GeoJSON FeatureCollection, `fetch` reports an operational failure and leaves the filesystem exactly as it found it.

## Trigger

Any of the following during `quakes fetch` (after arguments parse successfully):

- a network error (any `urllib.error.URLError`, `OSError`, or timeout from the HTTP layer);
- an HTTP status other than 200;
- a 200 body that is not JSON, or is JSON but not an object with `"type": "FeatureCollection"` and a list `features`.

## Behavior

- `http_get` returns `(status, body)` for every HTTP response, including non-200 statuses (an `HTTPError` is converted to its code and body), and raises `OperationalError` for `URLError`, `OSError`, and timeouts.
- The `fetch` handler also converts any `OSError` raised by a replaced `http_get` into `OperationalError`.
- A non-200 status or an invalid body raises `OperationalError`.
- All checks complete before `--out` is opened, so no file is created and a pre-existing file at `--out` keeps its exact bytes.
- The command exits 1, writes nothing to standard output, and writes one diagnostic line to standard error.

## Reads

The HTTP response only.

## Writes

Standard error only; never the output file on failure.

## Programmatic Acceptance

=== AC fetch-failure-http-status ===
Intent: A non-200 status exits 1 with empty standard output, one stderr line, and no file written.
Suite: scoped
Requires: executable=python3; scope=test

import json
import os
import tempfile
from unittest import mock

from cli.testing import cli_runner

valid = json.dumps({"type": "FeatureCollection", "features": []}).encode("utf-8")
bad_status = 500
with tempfile.TemporaryDirectory() as tmp:
    out_path = os.path.join(tmp, "saved.geojson")
    with mock.patch("cli.fetch.http_get", return_value=(bad_status, valid)):
        code, out, err = cli_runner("fetch", "--start", "2025-01-01", "--end", "2025-01-02", "--out", out_path)
    print(err)
    assert code == 1
    assert out == ""
    assert len(err.strip().splitlines()) == 1
    assert not os.path.exists(out_path)
=== END AC fetch-failure-http-status ===

=== AC fetch-failure-bad-body ===
Intent: A body that is not JSON, or JSON that is not a FeatureCollection, exits 1 and writes no file.
Suite: scoped
Requires: executable=python3; scope=test

import json
import os
import tempfile
from unittest import mock

from cli.testing import cli_runner

bodies = [
    b"this is not json",
    json.dumps({"type": "Feature", "properties": {}, "geometry": None}).encode("utf-8"),
    json.dumps({"type": "FeatureCollection"}).encode("utf-8"),
    json.dumps({"type": "FeatureCollection", "features": "nope"}).encode("utf-8"),
    json.dumps([1, 2, 3]).encode("utf-8"),
]
with tempfile.TemporaryDirectory() as tmp:
    for n, body in enumerate(bodies):
        out_path = os.path.join(tmp, "saved" + str(n) + ".geojson")
        with mock.patch("cli.fetch.http_get", return_value=(200, body)):
            code, out, err = cli_runner("fetch", "--start", "2025-01-01", "--end", "2025-01-02", "--out", out_path)
        assert code == 1, n
        assert out == "", n
        assert not os.path.exists(out_path), n
=== END AC fetch-failure-bad-body ===

=== AC fetch-failure-network-error ===
Intent: A network error from a stubbed http_get, and a URLError from a patched urlopen, both exit 1 with no file written.
Suite: scoped
Requires: executable=python3; scope=test

import os
import tempfile
import urllib.error
from unittest import mock

from cli.testing import cli_runner

with tempfile.TemporaryDirectory() as tmp:
    first = os.path.join(tmp, "first.geojson")
    with mock.patch("cli.fetch.http_get", side_effect=OSError("unreachable")):
        code, out, err = cli_runner("fetch", "--start", "2025-01-01", "--end", "2025-01-02", "--out", first)
    assert code == 1
    assert out == ""
    assert not os.path.exists(first)

    second = os.path.join(tmp, "second.geojson")
    with mock.patch("urllib.request.urlopen", side_effect=urllib.error.URLError("no route")) as opener:
        code2, out2, err2 = cli_runner("fetch", "--start", "2025-01-01", "--end", "2025-01-02", "--out", second)
    assert opener.call_count == 1
    assert code2 == 1
    assert out2 == ""
    assert not os.path.exists(second)
=== END AC fetch-failure-network-error ===

=== AC fetch-failure-http-error-status ===
Intent: An HTTPError raised by urlopen is treated as a non-200 status, exits 1, and writes no file.
Suite: scoped
Requires: executable=python3; scope=test

import io
import os
import tempfile
import urllib.error
from unittest import mock

from cli.testing import cli_runner

error = urllib.error.HTTPError("https://example.invalid", 503, "unavailable", {}, io.BytesIO(b"down"))
with tempfile.TemporaryDirectory() as tmp:
    out_path = os.path.join(tmp, "saved.geojson")
    with mock.patch("urllib.request.urlopen", side_effect=error):
        code, out, err = cli_runner("fetch", "--start", "2025-01-01", "--end", "2025-01-02", "--out", out_path)
    assert code == 1
    assert out == ""
    assert not os.path.exists(out_path)
=== END AC fetch-failure-http-error-status ===

=== AC fetch-failure-preserves-existing-file ===
Intent: A failed fetch leaves a pre-existing output file byte-for-byte untouched.
Suite: scoped
Requires: executable=python3; scope=test

import os
import tempfile
from unittest import mock

from cli.testing import cli_runner

original = b"previous contents, not JSON\n"
with tempfile.TemporaryDirectory() as tmp:
    out_path = os.path.join(tmp, "saved.geojson")
    with open(out_path, "wb") as fh:
        fh.write(original)
    with mock.patch("cli.fetch.http_get", return_value=(404, b"missing")):
        code, out, err = cli_runner("fetch", "--start", "2025-01-01", "--end", "2025-01-02", "--out", out_path)
    assert code == 1
    with open(out_path, "rb") as fh:
        assert fh.read() == original
    with mock.patch("cli.fetch.http_get", return_value=(200, b"not json")):
        code2, out2, err2 = cli_runner("fetch", "--start", "2025-01-01", "--end", "2025-01-02", "--out", out_path)
    assert code2 == 1
    with open(out_path, "rb") as fh:
        assert fh.read() == original
=== END AC fetch-failure-preserves-existing-file ===

## User Acceptance

- None.

## Guardrails

- A failing `fetch` never creates, truncates, or modifies the output file.
- A failing command writes nothing to standard output and exactly one diagnostic line to standard error; standard error text is never part of a contract.
- Tests exercise failure only through stubbed HTTP; no test opens a network connection.

</pblock>

<pblock filename="FEATURE-Near.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/Quakes/runs/20261025.010423/workspace/targets/Quakes/blueprint/FEATURE-Near.md" guidance="Feature Specification">

# FEATURE: Near

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | The `near` report: events within a haversine great-circle distance of a point, nearest first. |
| Depends On  | FEATURE-MagFilter.md, FEATURE-Formatting.md, FEATURE-Options.md, FEATURE-ExitCodes.md |
| Provides    | quakes near, haversine_km |
| Consumes    | read_feed, extract_events, filter_events, write_csv, format_time, format_mag, format_decimal, parse_args |

## Purpose

`quakes near --lat <deg> --lon <deg> --radius <km> [--min-mag <m>] <file>` lists the events whose distance from a point is at most the radius.

## Trigger

Command line. `--lat`, `--lon`, and `--radius` are all required. `parse_args` enforces `--lat` in -90..90, `--lon` in -180..180, and `--radius` greater than zero; any violation or omission is a usage error (exit 2).

## Sequence

1. `read_feed`, `extract_events`, and `filter_events` produce the kept events.
2. `haversine_km(lat1, lon1, lat2, lon2)` is a pure function on a sphere of radius 6371.0 km, with angles in radians:
   `h = sin^2((lat2 - lat1) / 2) + cos(lat1) * cos(lat2) * sin^2((lon2 - lon1) / 2)` and `d = 2 * 6371.0 * asin(sqrt(h))`. Event coordinates are `[longitude, latitude, depth_km]`.
3. `compute_near(events, lat, lon, radius)` keeps events whose unrounded distance is `<= radius` and orders them by unrounded distance ascending, then by event time ascending.
4. `write_csv` writes the report, with `distance_km` rounded half up to one decimal.

## Output

Header: `distance_km,time,mag,place,id`. One row per matching event: distance with one decimal, UTC time, magnitude with one decimal, place, id. An event at exactly the radius is included. No matches yields only the header with exit 0. Places containing commas are quoted by the `csv` module; non-ASCII places are UTF-8.

## Reads

The saved GeoJSON file named on the command line.

## Writes

Standard output only.

## Programmatic Acceptance

=== AC near-haversine-distance-and-radius ===
Intent: Reported distances match an independent haversine on a 6371.0 km sphere, and only events within the radius are listed, nearest first.
Suite: scoped
Requires: executable=python3; scope=test

import csv
import io
import json
import math
import os
import tempfile

from cli.testing import cli_runner


def hav(lat1, lon1, lat2, lon2):
    p1, p2 = math.radians(lat1), math.radians(lat2)
    dphi = p2 - p1
    dlam = math.radians(lon2 - lon1)
    h = math.sin(dphi / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dlam / 2) ** 2
    return 2 * 6371.0 * math.asin(math.sqrt(h))


origin = (27.72, 85.32)
points = [
    ("far", 35.68, 139.69),
    ("mid", 28.60, 87.37),
    ("near1", 28.80, 87.13),
    ("near2", 28.50, 87.35),
]
features = []
for i, (name, lat, lon) in enumerate(points):
    features.append({
        "type": "Feature",
        "properties": {"mag": 5.0 + i / 10, "place": "Place " + name, "time": 1736200000000 + i * 1000, "tsunami": 0},
        "geometry": {"type": "Point", "coordinates": [lon, lat, 10.0]},
        "id": name,
    })
doc = {"type": "FeatureCollection", "features": features}
dist = {name: hav(origin[0], origin[1], lat, lon) for name, lat, lon in points}
radius = round(sorted(dist.values())[2] + 1.0, 1)
inside = sorted([n for n in dist if dist[n] <= radius], key=lambda n: dist[n])
assert 0 < len(inside) < len(points)
with tempfile.TemporaryDirectory() as tmp:
    path = os.path.join(tmp, "q.geojson")
    with open(path, "w", encoding="utf-8") as fh:
        json.dump(doc, fh)
    code, out, err = cli_runner(
        "near", "--lat", str(origin[0]), "--lon", str(origin[1]), "--radius", str(radius), path
    )
print(out)
print(err)
assert code == 0
rows = list(csv.reader(io.StringIO(out)))
assert rows[0] == ["distance_km", "time", "mag", "place", "id"]
assert [r[4] for r in rows[1:]] == inside
for r in rows[1:]:
    assert abs(float(r[0]) - dist[r[4]]) <= 0.051
=== END AC near-haversine-distance-and-radius ===

=== AC near-ordering-ties-and-quoting ===
Intent: Events at equal distance are ordered by time ascending, and a place containing a comma round-trips through CSV quoting.
Suite: scoped
Requires: executable=python3; scope=test

import csv
import io
import json
import os
import tempfile

from cli.testing import cli_runner

place = "10 km N of Somewhere, Country"
times = [1736200003000, 1736200001000, 1736200002000]
features = []
for i, t in enumerate(times):
    features.append({
        "type": "Feature",
        "properties": {"mag": 5.0, "place": place, "time": t, "tsunami": 0},
        "geometry": {"type": "Point", "coordinates": [10.0, 10.0, 5.0]},
        "id": "t" + str(i),
    })
doc = {"type": "FeatureCollection", "features": features}
expected_ids = ["t" + str(i) for i in sorted(range(len(times)), key=lambda i: times[i])]
with tempfile.TemporaryDirectory() as tmp:
    path = os.path.join(tmp, "q.geojson")
    with open(path, "w", encoding="utf-8") as fh:
        json.dump(doc, fh)
    code, out, err = cli_runner("near", "--lat", "10", "--lon", "10.5", "--radius", "500", path)
print(out)
assert code == 0
rows = list(csv.reader(io.StringIO(out)))
assert [r[4] for r in rows[1:]] == expected_ids
assert all(r[3] == place for r in rows[1:])
=== END AC near-ordering-ties-and-quoting ===

=== AC near-min-mag-null-mag-and-empty ===
Intent: --min-mag filters near results, null magnitudes never appear, and no match yields only the header with exit 0.
Suite: scoped
Requires: executable=python3; scope=test

import csv
import io
import json
import os
import tempfile

from cli.testing import cli_runner

threshold = 5.3
mags = [5.0, 5.3, 6.0, None]
features = []
for i, mag in enumerate(mags):
    features.append({
        "type": "Feature",
        "properties": {"mag": mag, "place": "P" + str(i), "time": 1736200000000 + i, "tsunami": 0},
        "geometry": {"type": "Point", "coordinates": [20.0, 20.0, 5.0]},
        "id": "m" + str(i),
    })
doc = {"type": "FeatureCollection", "features": features}
kept = ["m" + str(i) for i, m in enumerate(mags) if m is not None and m >= threshold]
with tempfile.TemporaryDirectory() as tmp:
    path = os.path.join(tmp, "q.geojson")
    with open(path, "w", encoding="utf-8") as fh:
        json.dump(doc, fh)
    code, out, err = cli_runner(
        "near", "--lat", "20", "--lon", "20", "--radius", "50", "--min-mag", str(threshold), path
    )
    code_e, out_e, err_e = cli_runner("near", "--lat", "0", "--lon", "0", "--radius", "100", path)
print(out)
assert code == 0 and code_e == 0
rows = list(csv.reader(io.StringIO(out)))
assert sorted(r[4] for r in rows[1:]) == sorted(kept)
assert list(csv.reader(io.StringIO(out_e))) == [["distance_km", "time", "mag", "place", "id"]]
=== END AC near-min-mag-null-mag-and-empty ===

=== AC near-usage-errors ===
Intent: Missing required options and out-of-range values exit 2 with empty standard output.
Suite: scoped
Requires: executable=python3; scope=test

import json
import os
import tempfile

from cli.testing import cli_runner

doc = {"type": "FeatureCollection", "features": []}
with tempfile.TemporaryDirectory() as tmp:
    path = os.path.join(tmp, "q.geojson")
    with open(path, "w", encoding="utf-8") as fh:
        json.dump(doc, fh)
    cases = [
        ("near", "--lat", "10", "--lon", "10", path),
        ("near", "--lat", "10", "--radius", "5", path),
        ("near", "--lon", "10", "--radius", "5", path),
        ("near", "--lat", "95", "--lon", "0", "--radius", "10", path),
        ("near", "--lat", "0", "--lon", "181", "--radius", "10", path),
        ("near", "--lat", "0", "--lon", "0", "--radius", "0", path),
        ("near", "--lat", "x", "--lon", "0", "--radius", "5", path),
        ("near", "--lat", "0", "--lon", "0", "--radius", "5", "--n", "2", path),
    ]
    for args in cases:
        code, out, err = cli_runner(*args)
        assert code == 2, args
        assert out == "", args
=== END AC near-usage-errors ===

=== AC near-unreadable-file ===
Intent: An unreadable file is an operational failure: exit 1 with empty standard output.
Suite: scoped
Requires: executable=python3; scope=test

import os
import tempfile

from cli.testing import cli_runner

with tempfile.TemporaryDirectory() as tmp:
    missing = os.path.join(tmp, "absent.geojson")
    code, out, err = cli_runner("near", "--lat", "1", "--lon", "1", "--radius", "5", missing)
assert code == 1
assert out == ""
=== END AC near-unreadable-file ===

## User Acceptance

- None.

## Guardrails

- The earth radius is exactly 6371.0 km; no other radius or formula is used.
- The radius test compares the unrounded distance; only the printed value is rounded.
- An event at exactly the radius is included (`<=`).
- No distance or row is hardcoded; all values are computed from the file and the arguments.

</pblock>

<pblock label="Build instructions" kind="instructions">

Build instructions for this block

The summary report. (summary)

Header events,first,last,min_mag,max_mag,mean_mag,tsunami. One row; first and last are the earliest and latest times; tsunami counts events equal to 1. No events yields 0,,,,,,0.

The regions report of events per region. (regions)

Header region,events,max_mag. Region is the text after the last ", " in place, else the whole place; null place is Unknown. Order by events descending then region ascending by byte value.

The daily report of events per UTC date. (daily)

Header date,events,max_mag. One row per date with events, ascending, then TOTAL,<events>,<max>. Date is the first 10 characters of the formatted time. No events yields TOTAL,0,.

The top report listing the largest events. (top)

Header time,mag,depth_km,place,id. Sort by mag descending then time ascending, take --n (default 10). Filter applies before the cut.

The fetch command that downloads a USGS date range to a file. (fetch)

Request https://earthquake.usgs.gov/fdsnws/event/1/query with format=geojson, starttime, endtime, minmagnitude (default 2.5), orderby=time-asc, using urllib.request via a single replaceable function http_get(url) returning (status, body bytes). Write the body unchanged to --out and print fetched,<count>. Tests stub http_get and never open a network connection.

Fetch fails without writing a file on network, HTTP, or body errors. (fetch-failure)

A network error, status other than 200, or body that is not a FeatureCollection raises OperationalError (exit 1) before any file is created. A pre-existing output file is left untouched.

The near report using haversine distance. (near)

Header distance_km,time,mag,place,id. Haversine on a 6371.0 km sphere. Include events with distance <= --radius (compare unrounded distance), ordered by distance ascending then time ascending. Distance is written with one decimal, rounded half up.

</pblock>

Agent Task

You are a Drydock build agent implementing exactly one build step of a larger plan. The build job block below names the target, the build working directory, and the step. Everything you need is stacked into this prompt under role headings:

authoritative; implement them exactly.

Operating contract:

  1. Follow the write authorization and protected paths in the stacked COMPASS.md exactly.

That persisted guardrail is the sole authority for paths this build may modify.

  1. Start by inspecting the build working directory. Preserve existing application

files unless this step's specifications require a change. Its sources/ subdirectory holds staged build assets — imported test corpora, conformance harnesses, and fixtures — placed there for you. They are read-only inputs: run them, import them, and write code against them, but never create, rewrite, trim, regenerate, or substitute one, even to make a check pass. A step that modifies a staged asset fails and the asset is restored. If an asset you expect is absent, report that; do not author a replacement.

  1. Implement only this step. Use context, stack, and rules as constraints,

not as additional work to perform.

  1. Follow the stack and rules for languages, structure, naming, and branding.
  2. The programmatic acceptance assertions in the implements specifications are

this step's Definition of Done — human-owned, declared before the build, and fixed. Build the story and, in this same step, write the deterministic tests that prove each declared assertion, as a TDD master would; add finer tests for coverage. Every test you write follows the same rule the acceptance assertions do: act on the system, read the state back, compare to expected. The oracle is a return value, parsed JSON, a status code, a stored row, file contents read back, or an exit status — never a substring of captured stdout or stderr, a test-runner tally, or a log line. Write tests in the project's own language using that language's libraries; an in-language HTTP client yields a status code and a parsed body, where curl yields text to scrape. Round-trip anything that stores state: act, then read back through the public interface. Assert declared failure signals on negative paths, never message wording. You may add tests but must never remove, soften, or weaken a declared acceptance assertion. A Suite: full conformance check gates on the entire imported test suite: the step is done only when it passes in full, never on a representative subset — reproduce the standard exactly rather than wrapping a third-party library that approximates it. For a suite, the runner's exit status is the verdict and the whole verdict: print its captured output for diagnosis, never assert on the text of its summary. When an assertion is a static or filesystem scan (import boundary, "X never appears outside Y," grep/AST gate), honor the scope the specification states and never widen it: scan production source only, exclude .venv/, site-packages, and vendored or generated code, and do not flag test doubles or fixtures that use the guarded dependency. Run every declared acceptance assertion before returning. For a conformance suite, use its section or example filters to diagnose coherent root-cause clusters, but rerun the full declared scope before reporting the result. Treat failing examples as a work queue for fixing general behavior; never add example-specific exceptions.

  1. Grow the project's own test suite as you write the code, and treat it as the project's

real coverage. The acceptance assertions in implements are gates: few, fixed, and written before any code existed, so every expectation in them is a prediction. The tests you write are written beside the finished code, so their expected values are observed rather than predicted — which is why exhaustive coverage belongs here and not there. Extend the suite in the project's established location and runner, keep it runnable by the project's declared test command, and leave it green when you return. Cover, at minimum: every public entry point and every verb it declares, including declared error paths; the boundaries — empty, exactly one, many, absent optional fields, declared maxima; declared idempotence, applied twice; one behavior per test, named for the behavior; and isolation — database criteria use the provisioned application store and the shipped rollback fixture, passing its connection into the feature. Other connections and durability tests use criterion-owned records, idempotent setup and checked cleanup through supported interfaces. Never replace the configured store, reapply schema, or delete unrelated business records. Where a staged authoritative suite already covers a surface, that suite is the coverage: run it, and do not restate its cases. Run it only through the invocation this step's acceptance criteria declare. A criterion marked Suite: scoped names the whole of this step's obligation to that suite; running the suite's unscoped entry point instead is not extra rigor, it is a different step's gate executed early. A partial capability fails most of an authoritative corpus by construction and its unimplemented cases exhaust the runner's per-case timeout rather than returning, so the unscoped run costs the most where it teaches the least, and interrupting it forfeits the step. If no criterion in this step invokes the staged suite, do not invoke it. Report the pass/fail counts of the invocations you did run in your SUMMARY so a reader can see coverage moving across steps.

  1. Treat User Acceptance entries as review evidence requirements. Implement

the supporting behavior, but do not claim to have performed human judgment.

  1. The implements section is authoritative and intentionally stacked late in

the prompt as the recency anchor. Build that WHAT exactly; do not substitute generic framework defaults.

  1. Before adding or installing Python dependencies, verify each package name

against the declared registry. Do not invent package names. If a needed package cannot be verified or appears newly published, fail explicitly instead of installing it.

  1. Use the stack's required package manager workflow for dependency changes.

When the stack requires uv, update manifests through uv conventions rather than bare pip install.

  1. Do not claim success unless you actually created or modified project files in

the build working directory. If you cannot write files or cannot complete the step, report failure explicitly.

  1. Do not run git add, git commit, create branches, create tags, rewrite

history, or otherwise mutate Git history. Drydock checkpoints application changes and Target evidence after each execution and completed step. File lineage comes from Git and the Manifest's implements: entries; no additional attribution response is required.

  1. End your response with this exact closing structure:
RESULT: SUCCESS | FAILED

FILES CHANGED:
- relative/path

SUMMARY:
<brief reviewable summary>

BLOCKERS:
- <only if any>

Before RESULT, you may emit one optional JSON payload when implementation required a bounded choice not already settled by the owning specification. This records what you did; it does not ask permission, create a questionnaire, or excuse incomplete work:

<blueprint-decisions>
[{"spec":"FEATURE-Example.md","severity":"Material","subject":"Chosen behavior","decision":"Options A and B were available. I implemented B because ... Is that acceptable, or should this change on replan?"}]
</blueprint-decisions>

Name only a specification implemented by this build block. Use Low or Material; Build never emits a Blocking decision. Omit the payload when no implementation decision was necessary.

  1. FILES CHANGED must list only files actually written in the build working

directory. When the existing implementation already satisfies this step, report RESULT: SUCCESS, list no changed files, and state the checks performed and their results. A verification-only step requires no application changes. Drydock runs the declared deterministic checks and decides the outcome independently of this report.

  1. On RESULT: FAILED, append two additional lines so the failure is actionable

without opening logs. FAILURE_SUMMARY is one line naming the cause; FAILURE_DETAIL states what happened, why, and what to change before a rerun. Name concrete conditions when they apply: token or context limit exceeded, could not execute commands in this environment, a required input was missing, or a specific tool or command failed.

FAILURE_SUMMARY: <one line naming the cause>
FAILURE_DETAIL: <what happened, why, and what to change before rerunning>
  1. When a declared acceptance criterion cannot pass no matter how the code is written,

say so with this exact token. You may not edit the criterion — it is staged and restored before grading:

AC_BROKEN: <check-id>[, <check-id>]

This is a report, not a verdict, and it stops nothing. A criterion reaches you only when its expected value is one its author could not have invented — a status code, a staged suite's exit status, a value the criterion itself supplied as input — so your claim that the criterion rather than the code is at fault is the less likely explanation, and the budget is spent as it would be for any other failure. A criterion whose expectation was hand-typed already settles DISPUTED on its own, without you naming it. Emit the token only after running the criterion and confirming the underlying command succeeded while the assertion still failed. Name the affected check ids, emit it alongside your normal RESULT line, state the reasoning in FAILURE_DETAIL, and emit it even when RESULT: SUCCESS. Do not use it for a criterion you merely failed to satisfy.