# Attribute Stories to Source Requirements

You are the lineage attribution agent. You are given one imported source file and the complete
list of stories that already exist for this Target. Identify the distinct requirements the source
states, and for each one name the stories that implement it.

This is a matching task against a closed set. Every story you may name is listed in `<stories>`.
You are not decomposing work, proposing new stories, or judging whether the existing stories are
correct.

## Method

1. Read the source and identify each distinct requirement it states. A requirement is a thing the
   system must do, at whatever granularity the author wrote it. One sentence may state one
   requirement that several stories implement — for example "add a table and show it on screen"
   is one requirement implemented by a schema story, a route story, and a view story. Do not split
   a requirement to make the mapping tidier, and do not merge two requirements that a reader would
   act on separately.
2. Give each requirement a short kebab-case name that describes it. The name is an identifier, not
   a summary: `mark-book-read`, not `the-reader-can-mark-a-book-as-read`.
3. For each requirement, list every story that implements any part of it. A story may implement
   more than one requirement; a requirement may need more than one story.
4. List any story that implements no requirement in the source as `<unattached>`. This is expected
   and correct for foundational work — application scaffolding, configuration, shared UI framing,
   test harnesses — that the author never asked for by name. Do not force such a story onto an
   unrelated requirement.

## Rules

- Use only story ids that appear in `<stories>`. Never invent one.
- Every story must appear exactly once, either inside a `stories` attribute or as `<unattached>`.
- Quote the requirement text verbatim from the source in the tag body. Do not paraphrase it.
- Emit nothing but the tags below. No preamble, no commentary, no explanation.

## Output

```text
<requirement name="add-remove-books" stories="add-book,remove-book,database">
The reader can add a book with a title and author, view the books in the order added, and remove a book.
</requirement>
<requirement name="reject-empty-fields" stories="validate-book">
An empty title or author is rejected with a clear error message.
</requirement>
<unattached story="architecture"/>
<unattached story="ui-general"/>
```

# Attribution job

<source name="INSTRUCTIONS.md">
# Build Instructions: An Earthquake Feed Reporter

## Objective

Build a command-line tool that downloads earthquake data from the United States Geological Survey
(USGS) and reports on it. `quakes fetch` saves a period of the USGS event feed as a GeoJSON file.
Five report commands then read a saved file and answer common questions: how many events and how
strong, the largest events, events per day, the most active regions, and the events within a
distance of a point.

## Stack

Implement in Python 3.11 or newer using only the standard library (`urllib.request` for HTTP).
Tests run under pytest. The product is an executable named `quakes` at the application root.

## Run Harness

`sources/run.sh` is the scoring entry point. It is supplied, not authored, and is staged verbatim
into the application root with the snapshot. `drydock uat` runs `sh sources/run.sh` from the
completed application root and takes its exit code and output as the score.

The harness runs 26 checks of the report commands against the frozen snapshot. It never runs
`fetch` and uses no network. Each check compares one command's exit code and standard output with
a known answer. Standard error is never compared. The harness prints `PASS` or `FAIL` per check
and ends with:

```text
Quakes: NN passed, NN failed (of 26)
```

## Read-only scoring assets

These files are the exam. Do not modify, rewrite, regenerate, or substitute them:

- `sources/run.sh` — the scoring entry point and its known answers
- `sources/quakes_2025-01-01_07.geojson` — a frozen USGS snapshot: the 44 events of magnitude 5.0
  or greater from 2025-01-01 through 2025-01-07 UTC, one feature per line

Application code never reads `sources/run.sh` and never embeds a report answer. Every value is
computed from the file it is given.

## Commands

```text
quakes fetch --start <YYYY-MM-DD> --end <YYYY-MM-DD> [--min-mag <m>] --out <file>
quakes summary [--min-mag <m>] <file>
quakes top [--min-mag <m>] [--n <count>] <file>
quakes daily [--min-mag <m>] <file>
quakes regions [--min-mag <m>] <file>
quakes near --lat <deg> --lon <deg> --radius <km> [--min-mag <m>] <file>
```

The command comes first, options follow it in any order, and the file is last. An option that the
command does not list is a usage error. `<m>`, `<deg>`, and `<km>` are decimals matching
`-?[0-9]+(\.[0-9]+)?`. `<count>` is a positive integer, default `10`.

### fetch

`fetch` requests
`https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=<start>&endtime=<end>&minmagnitude=<m>&orderby=time-asc`
(`--min-mag` defaults to `2.5`) and writes the response body unchanged to `<file>`. It writes
`fetched,<count>` to standard output, where `<count>` is the number of features. A network error,
an HTTP status other than 200, or a body that is not a GeoJSON FeatureCollection is an operational
failure, and no file is written. Tests of `fetch` replace the HTTP call with a stub; they never use
the network.

## Reading a file

1. The file is a GeoJSON `FeatureCollection` as the USGS feed returns it. A file that cannot be
   read, is not JSON, or is not an object with `"type": "FeatureCollection"` and a `features`
   array is an operational failure.
2. Each feature is one event. The tool reads `id`, `properties.mag`, `properties.place`,
   `properties.time` (milliseconds since the Unix epoch), `properties.tsunami` (`1` or `0`), and
   `geometry.coordinates` (`[longitude, latitude, depth_km]`). Every other field is ignored.
3. A feature whose `mag` is `null` is excluded from every report.
4. `--min-mag <m>` keeps only events with `mag >= m`. It applies to every report.
5. **Time** is written in UTC as `YYYY-MM-DDTHH:MM:SSZ`, truncated to whole seconds. An event's
   date is the first 10 characters.
6. **Region** is the text after the last `, ` (comma, space) in `place`, or the whole of `place`
   when it has none. A `null` place is `Unknown`, which is also its region.

## Formatting

- Magnitudes are written with one decimal place: `5.0`, `7.1`.
- `mean_mag` is written with two decimal places, rounded half up.
- `depth_km` and `distance_km` are written with one decimal place, rounded half up.
- Text is compared by byte value.
- Output is CSV on standard output with `\n` line endings, written with Python's `csv` module, so
  a place containing a comma is quoted. Place names contain non-ASCII characters and are written
  as UTF-8.

## Reports

| Command | Header | Rows |
|---|---|---|
| `summary` | `events,first,last,min_mag,max_mag,mean_mag,tsunami` | One row. `first` and `last` are the earliest and latest event times. `tsunami` counts events with `tsunami` equal to `1`. With no events: `0,,,,,,0`. |
| `top` | `time,mag,depth_km,place,id` | The `--n` largest events, by `mag` descending, then time ascending. |
| `daily` | `date,events,max_mag` | One row per date that has events, ascending, then `TOTAL,<events>,<max_mag>`. With no events, the max is empty: `TOTAL,0,`. |
| `regions` | `region,events,max_mag` | One row per region, by events descending, then region ascending. |
| `near` | `distance_km,time,mag,place,id` | Events whose distance from (`--lat`, `--lon`) is at most `--radius` km, by distance ascending, then time ascending. |

**Distance** is the haversine great-circle distance on a sphere of radius 6371.0 km:

```text
h = sin²((lat2 − lat1) / 2) + cos(lat1) · cos(lat2) · sin²((lon2 − lon1) / 2)
d = 2 · 6371.0 · asin(√h)          (angles in radians)
```

A failing command writes nothing to standard output and one diagnostic line to standard error.

## Exit codes

| Code | Meaning |
|---|---|
| `0` | Success, including a report with no matching events. |
| `1` | Operational failure: file unreadable or not a FeatureCollection; `fetch` network or HTTP failure. |
| `2` | Usage error: unknown command or option, an option the command does not take, missing or malformed value, `--lat` outside −90 to 90, `--lon` outside −180 to 180, `--radius` not positive, `near` without all three of `--lat`, `--lon`, and `--radius`, missing or extra file. |

## Tests

The completed application provides a POSIX-compatible `bin/test.sh` that runs its own pytest suite
from the application root and exits zero only when every test passes. The suite covers each report,
each option, the region and distance rules, `fetch` against a stubbed HTTP response, and each exit
code, using files written by the tests.
</source>

<stories>
  <story id="architecture" implements="ARCHITECTURE.md">Stand up the Python project tree, environment, dependency manifest, and pytest runner.</story>
  <story id="cli-foundation" implements="FEATURE-CliFoundation.md">Publish the cli package, main entry point, cli_runner test helper, and the quakes launcher.</story>
  <story id="options" implements="FEATURE-Options.md">Parse and validate the command, options, and file argument, with usage errors exiting 2.</story>
  <story id="exit-codes" implements="FEATURE-ExitCodes.md">Map usage and operational failures to exit codes 2 and 1 with silent stdout and one stderr line.</story>
  <story id="formatting" implements="FEATURE-Formatting.md">Format times, magnitudes, depths, distances, and CSV output.</story>
  <story id="feed-validation" implements="FEATURE-FeedValidation.md">Read a saved GeoJSON file and validate that it is a FeatureCollection.</story>
  <story id="event-extraction" implements="FEATURE-EventExtraction.md">Extract event fields from features and exclude null-magnitude events.</story>
  <story id="mag-filter" implements="FEATURE-MagFilter.md">Apply the --min-mag filter to events.</story>
  <story id="test-suite" implements="FEATURE-TestSuite.md">Provide bin/test.sh running the pytest suite.</story>
  <story id="summary" implements="FEATURE-Summary.md">The summary report.</story>
  <story id="regions" implements="FEATURE-Regions.md">The regions report of events per region.</story>
  <story id="daily" implements="FEATURE-Daily.md">The daily report of events per UTC date.</story>
  <story id="top" implements="FEATURE-Top.md">The top report listing the largest events.</story>
  <story id="fetch" implements="FEATURE-Fetch.md">The fetch command that downloads a USGS date range to a file.</story>
  <story id="fetch-failure" implements="FEATURE-FetchFailure.md">Fetch fails without writing a file on network, HTTP, or body errors.</story>
  <story id="near" implements="FEATURE-Near.md">The near report using haversine distance.</story>
  <story id="verification" implements="VERIFICATION.md">Terminal gate running the supplied grader against the finished application.</story>
</stories>
