Run artifact

evidence/prompt_outputs/20261025.010816.326Z_quakes_plan_claude.output.txt

=== BEGIN ARTIFACT FEATURE-FeedValidation.md ===
# FEATURE: Feed Validation

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | Read a saved GeoJSON file and confirm it is a USGS FeatureCollection. |
| Depends On  | ARCHITECTURE.md, FEATURE-ExitCodes.md |
| Provides    | read_feed |
| Consumes    | OperationalError |

## Questions

- None.

## Purpose

Every report command starts by reading a saved feed file. `read_feed` returns the raw `features` list
and rejects anything that is not a GeoJSON FeatureCollection as an operational failure (exit 1).

## Interface

- Module: `cli.feed`. Function: `read_feed(path) -> list`.
- `path` is a `str` or `pathlib.Path`. The file is read as UTF-8 and parsed with `json`.
- Returns the value of the `features` array unchanged (a `list` of feature objects).
- Raises `OperationalError` when:
  - the file cannot be read (missing, directory, permissions, undecodable bytes),
  - the content is not valid JSON,
  - the JSON value is not an object,
  - `"type"` is not the string `FeatureCollection`,
  - `features` is missing or not an array.
- An empty `features` array is valid and returns `[]`.
- The function writes nothing to standard output. The diagnostic line is produced by `main`.

## Programmatic Acceptance

=== AC feed-valid-collection ===
Intent: A FeatureCollection file returns its features list, including an empty one.
Requires: executable=python3; scope=test

import json
import tempfile
from pathlib import Path

from cli.feed import read_feed

with tempfile.TemporaryDirectory() as tmp:
    features = [{"type": "Feature", "id": "a", "properties": {"mag": 5.0}, "geometry": None},
                {"type": "Feature", "id": "b", "properties": {"mag": 6.0}, "geometry": None}]
    full = Path(tmp) / "full.geojson"
    full.write_text(json.dumps({"type": "FeatureCollection", "features": features}), encoding="utf-8")
    assert read_feed(full) == features
    assert read_feed(str(full)) == features

    empty = Path(tmp) / "empty.geojson"
    empty.write_text(json.dumps({"type": "FeatureCollection", "features": []}), encoding="utf-8")
    assert read_feed(empty) == []
=== END AC feed-valid-collection ===

=== AC feed-unreadable-file ===
Intent: A missing file and a directory both raise OperationalError.
Requires: executable=python3; scope=test

import tempfile
from pathlib import Path

from cli.feed import read_feed

with tempfile.TemporaryDirectory() as tmp:
    for target in (Path(tmp) / "no-such-file.geojson", Path(tmp)):
        raised = None
        try:
            read_feed(target)
        except Exception as exc:
            raised = exc
        assert raised is not None
        assert type(raised).__name__ == "OperationalError"
=== END AC feed-unreadable-file ===

=== AC feed-not-json ===
Intent: Content that is not JSON raises OperationalError.
Requires: executable=python3; scope=test

import tempfile
from pathlib import Path

from cli.feed import read_feed

with tempfile.TemporaryDirectory() as tmp:
    garbage = Path(tmp) / "garbage.json"
    garbage.write_text("this is not json\n", encoding="utf-8")
    raised = None
    try:
        read_feed(garbage)
    except Exception as exc:
        raised = exc
    assert raised is not None
    assert type(raised).__name__ == "OperationalError"
=== END AC feed-not-json ===

=== AC feed-wrong-shape ===
Intent: JSON that is not a FeatureCollection object with a features array raises OperationalError.
Requires: executable=python3; scope=test

import json
import tempfile
from pathlib import Path

from cli.feed import read_feed

bad_values = [
    {"type": "Feature", "properties": {}, "geometry": None},
    {"type": "FeatureCollection"},
    {"type": "FeatureCollection", "features": {"a": 1}},
    {"type": "FeatureCollection", "features": None},
    {"features": []},
    [],
    "FeatureCollection",
    None,
]
with tempfile.TemporaryDirectory() as tmp:
    for n, value in enumerate(bad_values):
        path = Path(tmp) / f"bad{n}.json"
        path.write_text(json.dumps(value), encoding="utf-8")
        raised = None
        try:
            read_feed(path)
        except Exception as exc:
            raised = exc
        assert raised is not None, value
        assert type(raised).__name__ == "OperationalError", value
=== END AC feed-wrong-shape ===

## User Acceptance

- None.

## Guardrails

- Application code never reads `sources/run.sh` or the frozen snapshot.
- `read_feed` never writes to standard output; failures surface only through `OperationalError`.
- Standard library only.
=== END ARTIFACT ===
=== BEGIN ARTIFACT FEATURE-EventExtraction.md ===
# FEATURE: Event Extraction

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | Turn GeoJSON features into event records and drop events with a null magnitude. |
| Depends On  | FEATURE-FeedValidation.md |
| Provides    | extract_events, Event |
| Consumes    | read_feed |

## Questions

- None.

## Purpose

Reports operate on `Event` records, not raw features. Extraction reads only the fields the reports
need and excludes every feature whose magnitude is `null`.

## Interface

- Module: `cli.feed`. Function: `extract_events(features) -> list[Event]`, preserving feed order.
- `Event` is an immutable dataclass with fields:
  - `id` (str), `mag` (float), `place` (str or `None`),
  - `time_ms` (int, milliseconds since the Unix epoch), `tsunami` (int),
  - `lon` (float), `lat` (float), `depth_km` (float).
- Source fields: `id`, `properties.mag`, `properties.place`, `properties.time`,
  `properties.tsunami`, and `geometry.coordinates` as `[longitude, latitude, depth_km]`.
  Every other field is ignored.
- A feature whose `properties.mag` is `null` is dropped. A magnitude of `0` is kept.
- A `null` place stays `None`; the regions report maps it to `Unknown`.
- A missing `tsunami` is read as `0`.

## Programmatic Acceptance

=== AC extract-fields ===
Intent: Every needed field is read from the feature into the matching Event attribute.
Requires: executable=python3; scope=test

from cli.feed import extract_events

feature = {
    "type": "Feature",
    "id": "ev1",
    "properties": {"mag": 5.4, "place": "10 km N of Town, Land", "time": 1735706358208,
                   "tsunami": 1, "ignored": {"deep": [1, 2, 3]}},
    "geometry": {"type": "Point", "coordinates": [169.5, -20.25, 22]},
}
events = extract_events([feature])
assert len(events) == 1
event = events[0]
assert event.id == feature["id"]
assert event.mag == feature["properties"]["mag"]
assert event.place == feature["properties"]["place"]
assert event.time_ms == feature["properties"]["time"]
assert event.tsunami == feature["properties"]["tsunami"]
lon, lat, depth = feature["geometry"]["coordinates"]
assert event.lon == lon
assert event.lat == lat
assert event.depth_km == depth
=== END AC extract-fields ===

=== AC extract-null-mag-excluded ===
Intent: Features with a null magnitude are absent from the result and the rest keep feed order.
Requires: executable=python3; scope=test

from cli.feed import extract_events


def feature(ident, mag):
    return {"type": "Feature", "id": ident,
            "properties": {"mag": mag, "place": "P", "time": 1735706358000, "tsunami": 0},
            "geometry": {"type": "Point", "coordinates": [1.0, 2.0, 3.0]}}


features = [feature("a", 5.0), feature("b", None), feature("c", 0), feature("d", 6.1), feature("e", None)]
events = extract_events(features)
kept_ids = [f["id"] for f in features if f["properties"]["mag"] is not None]
assert [e.id for e in events] == kept_ids
assert len(events) == len(kept_ids)
=== END AC extract-null-mag-excluded ===

=== AC extract-null-place-and-empty ===
Intent: A null place is preserved as None and an empty feature list yields no events.
Requires: executable=python3; scope=test

from cli.feed import extract_events

assert extract_events([]) == []

feature = {"type": "Feature", "id": "np",
           "properties": {"mag": 5.1, "place": None, "time": 1735706358000, "tsunami": 0},
           "geometry": {"type": "Point", "coordinates": [1.0, 2.0, 3.0]}}
events = extract_events([feature])
assert len(events) == 1
assert events[0].place is None
=== END AC extract-null-place-and-empty ===

## User Acceptance

- None.

## Guardrails

- Fields other than those listed are never read into an `Event`.
- No event value is hardcoded; every value comes from the feature given.
- Standard library only.
=== END ARTIFACT ===
=== BEGIN ARTIFACT FEATURE-MagFilter.md ===
# FEATURE: Magnitude Filter

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | Keep only events whose magnitude is at least the --min-mag value. |
| Depends On  | FEATURE-EventExtraction.md |
| Provides    | filter_events |
| Consumes    | extract_events |

## Questions

- None.

## Purpose

`--min-mag <m>` applies to every report. `filter_events` is the single shared implementation, so
all reports share one inclusive rule: `mag >= m`.

## Interface

- Module: `cli.feed`. Function: `filter_events(events, min_mag) -> list[Event]`.
- `min_mag` is a `float` or `None`. `None` keeps every event.
- An event whose magnitude equals `min_mag` is kept.
- Feed order is preserved. The input list is not mutated.

## Programmatic Acceptance

=== AC filter-threshold-inclusive ===
Intent: Events at or above the threshold are kept, including those exactly at it, and order is preserved.
Requires: executable=python3; scope=test

from cli.feed import extract_events, filter_events


def feature(ident, mag):
    return {"type": "Feature", "id": ident,
            "properties": {"mag": mag, "place": "P", "time": 1735706358000, "tsunami": 0},
            "geometry": {"type": "Point", "coordinates": [1.0, 2.0, 3.0]}}


mags = [5.0, 5.4, 5.5, 5.6, 7.1, 5.49]
features = [feature(f"e{i}", m) for i, m in enumerate(mags)]
events = extract_events(features)
threshold = 5.5
kept = filter_events(events, threshold)
expected_ids = [f"e{i}" for i, m in enumerate(mags) if m >= threshold]
assert [e.id for e in kept] == expected_ids
assert any(e.mag == threshold for e in kept)
=== END AC filter-threshold-inclusive ===

=== AC filter-none-keeps-all ===
Intent: A None threshold keeps every event and does not mutate the input.
Requires: executable=python3; scope=test

from cli.feed import extract_events, filter_events

features = [{"type": "Feature", "id": f"e{i}",
             "properties": {"mag": 5.0 + i, "place": "P", "time": 1735706358000, "tsunami": 0},
             "geometry": {"type": "Point", "coordinates": [1.0, 2.0, 3.0]}} for i in range(4)]
events = extract_events(features)
before = list(events)
kept = filter_events(events, None)
assert [e.id for e in kept] == [e.id for e in before]
assert events == before
=== END AC filter-none-keeps-all ===

=== AC filter-nothing-matches ===
Intent: A threshold above every magnitude yields an empty list rather than an error.
Requires: executable=python3; scope=test

from cli.feed import extract_events, filter_events

features = [{"type": "Feature", "id": "only",
             "properties": {"mag": 5.2, "place": "P", "time": 1735706358000, "tsunami": 0},
             "geometry": {"type": "Point", "coordinates": [1.0, 2.0, 3.0]}}]
events = extract_events(features)
assert filter_events(events, 9.0) == []
=== END AC filter-nothing-matches ===

## User Acceptance

- None.

## Guardrails

- The comparison is `mag >= min_mag`, never `>`.
- Standard library only.
=== END ARTIFACT ===
=== BEGIN ARTIFACT FEATURE-Summary.md ===
# 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 |

## Questions

- None.

## 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.
=== END ARTIFACT ===
=== BEGIN ARTIFACT FEATURE-Top.md ===
# 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 |

## Questions

- None.

## 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.
=== END ARTIFACT ===