# 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

- Copy story ids byte-for-byte from `<stories>`, preserving underscores, hyphens, and case; never invent or normalize one.
- Every story appears in one or more requirement `stories` attributes, or once as `<unattached>`, never both.
- 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="run.sh">
#!/bin/sh
# run.sh — FxRates grader. Do not filter, skip, or reinterpret.
#
# Runs ./fxrates against a fresh database: loads the supplied ECB files from the command line,
# starts `./fxrates serve` on a free local port, and compares every command's exit code and
# standard output, and every HTTP response's status and JSON body, with the known answer below.
# JSON bodies are compared as values, so key order and whitespace do not matter. Standard error
# and error-response bodies are never compared. No network beyond 127.0.0.1 is used.
#
#   sh sources/run.sh               from the application root (how `drydock uat` runs it)
#   sh uat/FxRates/bin/run.sh APP   from anywhere, grading the application root APP
#
# Exit 0 only when every check passes.
set -u

HERE=$(cd "$(dirname "$0")" && pwd)
APP=$(cd "${1:-.}" && pwd)
if [ -f "$HERE/eurofxref-hist_2025-01.csv" ]; then DATA=$HERE; else DATA=$(cd "$HERE/../sources" && pwd); fi
WORK=$(mktemp -d)
BIN="$APP/fxrates"
DATABASE_URL="$WORK/fxrates.db"
export DATABASE_URL
SERVER=""
PORT=$(python3 -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])')
BASE="http://127.0.0.1:$PORT"

stop_server() {
    if [ -n "$SERVER" ]; then
        pkill -TERM -P "$SERVER" 2>/dev/null
        kill -TERM "$SERVER" 2>/dev/null
        wait "$SERVER" 2>/dev/null
        SERVER=""
    fi
}
trap 'stop_server; rm -rf "$WORK"' EXIT
trap 'exit 1' INT TERM

if [ ! -x "$BIN" ]; then
    echo "error: no executable ./fxrates at the application root $APP." >&2
    echo "The deliverable is an executable named fxrates at the application root." >&2
    exit 1
fi

PASSED=0
FAILED=0

pass() { PASSED=$((PASSED + 1)); echo "PASS $1"; }
fail() { FAILED=$((FAILED + 1)); echo "FAIL $1"; }

# check <id> <expected exit> <fxrates args...>  — expected standard output on stdin.
check() {
    id=$1
    want_rc=$2
    shift 2
    cat > "$WORK/want"
    (cd "$APP" && "$BIN" "$@") > "$WORK/got" 2> "$WORK/err" < /dev/null
    rc=$?
    if [ "$rc" -eq "$want_rc" ] && cmp -s "$WORK/want" "$WORK/got"; then
        pass "$id: fxrates $*"
    else
        fail "$id: fxrates $*"
        echo "  exit: expected $want_rc, got $rc"
        diff "$WORK/want" "$WORK/got" | sed 's/^/  /'
        sed 's/^/  stderr: /' "$WORK/err"
    fi
}

# http <id> <expected status> <path>  — expected JSON body on stdin (compared only for 200).
http() {
    id=$1
    want_status=$2
    path=$3
    cat > "$WORK/want"
    if python3 - "$BASE$path" "$want_status" "$WORK/want" > "$WORK/got" 2>&1 <<'PY'
import json, sys, urllib.error, urllib.request
url, want, want_file = sys.argv[1], int(sys.argv[2]), sys.argv[3]
try:
    with urllib.request.urlopen(url, timeout=15) as r:
        status, body = r.status, r.read()
except urllib.error.HTTPError as e:
    status, body = e.code, e.read()
except Exception as e:
    print(f"request failed: {e}")
    sys.exit(1)
if status != want:
    print(f"status: expected {want}, got {status}")
    print(body.decode("utf-8", "replace")[:400])
    sys.exit(1)
if want != 200:
    sys.exit(0)
try:
    got = json.loads(body)
except ValueError:
    print("body is not JSON:", body.decode("utf-8", "replace")[:400])
    sys.exit(1)
expected = json.loads(open(want_file, encoding="utf-8").read())
if got != expected:
    print("expected:", json.dumps(expected, sort_keys=True))
    print("got:     ", json.dumps(got, sort_keys=True))
    sys.exit(1)
PY
    then
        pass "$id: GET $path"
    else
        fail "$id: GET $path"
        sed 's/^/  /' "$WORK/got"
    fi
}

# start_server — run `fxrates serve` in the background and wait up to 30 s for /health.
start_server() {
    (cd "$APP" && exec "$BIN" serve --port "$PORT") > "$WORK/server.log" 2>&1 < /dev/null &
    SERVER=$!
    tries=0
    until python3 -c "import urllib.request, sys; urllib.request.urlopen(sys.argv[1], timeout=2)" \
            "$BASE/health" 2>/dev/null; do
        tries=$((tries + 1))
        if [ "$tries" -ge 30 ] || ! kill -0 "$SERVER" 2>/dev/null; then
            echo "FAIL S1: fxrates serve --port $PORT did not answer GET /health within 30 s"
            sed 's/^/  server: /' "$WORK/server.log"
            echo "FxRates: $PASSED passed, unscored HTTP checks (server did not start)"
            exit 1
        fi
        sleep 1
    done
}

# ── A. Command line: initialize and load ───────────────────────────────────────────────
check A1 0 init < /dev/null
check A2 0 load "$DATA/eurofxref-hist_2025-01.csv" <<'EOF'
dates,rates
22,176
EOF
check A3 0 load "$DATA/eurofxref-hist_2025-01.csv" <<'EOF'
dates,rates
22,176
EOF
check A4 3 load "$DATA/eurofxref-hist_bad.csv" < /dev/null
check A5 1 load "$WORK/no-such-file.csv" < /dev/null

# ── U. Command-line usage errors ─────────────────────────────────────────────────────────
check U1 2 < /dev/null
check U2 2 frobnicate < /dev/null
check U3 2 load < /dev/null
check U4 2 serve --port notaport < /dev/null

start_server
# ── H. HTTP over January 2025 ────────────────────────────────────────────────────────────
http H1 200 '/health' <<'EOF'
{"status":"ok"}
EOF
http H2 200 '/stats' <<'EOF'
{"dates":22,"rates":176,"first":"2025-01-02","last":"2025-01-31"}
EOF
http H3 200 '/currencies' <<'EOF'
{"base":"EUR","currencies":["AUD","CAD","CHF","CNY","GBP","JPY","SEK","USD"]}
EOF
http H4 200 '/rates/2025-01-17' <<'EOF'
{"date":"2025-01-17","requested":"2025-01-17","base":"EUR","rates":{"AUD":"1.6646","CAD":"1.4864","CHF":"0.9394","CNY":"7.5474","GBP":"0.84453","JPY":"160.23","SEK":"11.506","USD":"1.0298"}}
EOF
http H5 200 '/rates/2025-01-18' <<'EOF'
{"date":"2025-01-17","requested":"2025-01-18","base":"EUR","rates":{"AUD":"1.6646","CAD":"1.4864","CHF":"0.9394","CNY":"7.5474","GBP":"0.84453","JPY":"160.23","SEK":"11.506","USD":"1.0298"}}
EOF
http H6 404 '/rates/2024-12-31' < /dev/null
http H7 422 '/rates/2025-13-01' < /dev/null
http H8 200 '/rates/latest' <<'EOF'
{"date":"2025-01-31","requested":"latest","base":"EUR","rates":{"AUD":"1.6702","CAD":"1.5035","CHF":"0.9449","CNY":"7.5363","GBP":"0.83608","JPY":"160.99","SEK":"11.474","USD":"1.0393"}}
EOF
http H9 200 '/convert?from=USD&to=GBP&amount=100&date=2025-01-17' <<'EOF'
{"date":"2025-01-17","from":"USD","to":"GBP","amount":"100","rate":"0.820091","result":"82.01"}
EOF
http H10 200 '/convert?from=EUR&to=JPY&amount=250.25&date=2025-01-05' <<'EOF'
{"date":"2025-01-03","from":"EUR","to":"JPY","amount":"250.25","rate":"161.770000","result":"40482.94"}
EOF
http H11 200 '/convert?from=GBP&to=EUR&amount=1000' <<'EOF'
{"date":"2025-01-31","from":"GBP","to":"EUR","amount":"1000","rate":"1.196058","result":"1196.06"}
EOF
http H12 200 '/convert?from=SEK&to=CNY&amount=12345.67&date=2025-01-20' <<'EOF'
{"date":"2025-01-20","from":"SEK","to":"CNY","amount":"12345.67","rate":"0.656236","result":"8101.67"}
EOF
http H13 404 '/convert?from=USD&to=XXX&amount=1' < /dev/null
http H14 422 '/convert?from=USD&to=GBP' < /dev/null
http H15 422 '/convert?from=USD&to=GBP&amount=abc' < /dev/null
http H16 404 '/convert?from=USD&to=GBP&amount=10&date=2024-12-01' < /dev/null
http H17 200 '/history/USD?start=2025-01-20&end=2025-01-24' <<'EOF'
{"currency":"USD","base":"EUR","count":5,"min":"1.0316","max":"1.0472","mean":"1.039840","points":[{"date":"2025-01-20","rate":"1.0316"},{"date":"2025-01-21","rate":"1.0357"},{"date":"2025-01-22","rate":"1.0443"},{"date":"2025-01-23","rate":"1.0404"},{"date":"2025-01-24","rate":"1.0472"}]}
EOF
http H18 200 '/history/CHF?start=2025-01-27' <<'EOF'
{"currency":"CHF","base":"EUR","count":5,"min":"0.943","max":"0.9453","mean":"0.944280","points":[{"date":"2025-01-27","rate":"0.9453"},{"date":"2025-01-28","rate":"0.9441"},{"date":"2025-01-29","rate":"0.943"},{"date":"2025-01-30","rate":"0.9441"},{"date":"2025-01-31","rate":"0.9449"}]}
EOF
http H19 404 '/history/HRK' < /dev/null
http H20 200 '/history/USD?start=2025-02-01' <<'EOF'
{"currency":"USD","base":"EUR","count":0,"min":null,"max":null,"mean":null,"points":[]}
EOF
http H21 422 '/history/GBP?start=2025-01-31-x' < /dev/null

# ── L. A load while the server runs is visible to the next request ───────────────────────
check L1 0 load "$DATA/eurofxref-hist_2025-02-03_04.csv" <<'EOF'
dates,rates
2,16
EOF
http L2 200 '/stats' <<'EOF'
{"dates":24,"rates":192,"first":"2025-01-02","last":"2025-02-04"}
EOF
http L3 200 '/rates/latest' <<'EOF'
{"date":"2025-02-04","requested":"latest","base":"EUR","rates":{"AUD":"1.6629","CAD":"1.4894","CHF":"0.9396","CNY":"7.4943","GBP":"0.83188","JPY":"160.52","SEK":"11.418","USD":"1.0335"}}
EOF
http L4 200 '/rates/2025-02-01' <<'EOF'
{"date":"2025-01-31","requested":"2025-02-01","base":"EUR","rates":{"AUD":"1.6702","CAD":"1.5035","CHF":"0.9449","CNY":"7.5363","GBP":"0.83608","JPY":"160.99","SEK":"11.474","USD":"1.0393"}}
EOF
http L5 200 '/history/AUD?start=2025-01-30' <<'EOF'
{"currency":"AUD","base":"EUR","count":4,"min":"1.6629","max":"1.6705","mean":"1.667675","points":[{"date":"2025-01-30","rate":"1.6705"},{"date":"2025-01-31","rate":"1.6702"},{"date":"2025-02-03","rate":"1.6671"},{"date":"2025-02-04","rate":"1.6629"}]}
EOF

stop_server
TOTAL=$((PASSED + FAILED))
echo "FxRates: $PASSED passed, $FAILED failed (of $TOTAL)"
[ "$FAILED" -eq 0 ]
</source>

<stories>
  <story id="architecture" implements="ARCHITECTURE.md">Define application modules and their ownership boundaries.</story>
  <story id="database" implements="DATABASE.md">Declare the rates schema and generated repository contract.</story>
  <story id="app_server" implements="FEATURE-AppServer.md">Establish the FastAPI application and test client.</story>
  <story id="cli" implements="FEATURE-CLI.md">Establish the fxrates executable and CLI entry point.</story>
  <story id="load" implements="FEATURE-Load.md">Validate and load ECB CSV history files atomically.</story>
  <story id="init" implements="FEATURE-Init.md">Initialize an empty rates store.</story>
  <story id="api_currencies" implements="FEATURE-Currencies.md">List currencies that have stored rates.</story>
  <story id="api_latest" implements="FEATURE-LatestRates.md">Retrieve rates from the latest publication.</story>
  <story id="api_stats" implements="FEATURE-Stats.md">Report stored rate statistics.</story>
  <story id="api_rates" implements="FEATURE-Rates.md">Retrieve rates by effective date.</story>
  <story id="history" implements="FEATURE-History.md">Retrieve currency history and summary statistics.</story>
  <story id="convert" implements="FEATURE-Convert.md">Convert amounts between currencies.</story>
  <story id="api_health" implements="FEATURE-Health.md">Serve the health endpoint.</story>
  <story id="cli_errors" implements="FEATURE-CLI-Errors.md">Report CLI usage and operational errors.</story>
  <story id="fetch" implements="FEATURE-Fetch.md">Download and load the ECB history archive.</story>
  <story id="tests" implements="FEATURE-Tests.md">Provide the offline pytest suite and test launcher.</story>
  <story id="grader" implements="FEATURE-Grader.md">Verify complete supplied grader conformance.</story>
</stories>
