# 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: A CSV Column Profiler

## Objective

Build a command-line tool that profiles a CSV file. For every column it infers a type and reports
row, null, and distinct counts, the minimum and maximum, and for numeric columns the sum, mean, and
median. It also lists the most frequent values of one column. It answers the first questions
anyone asks of an unfamiliar data file.

## Stack

Implement in Go 1.22 or newer using only the standard library. The application root is a Go
module, and its executable is the main package at `./cmd/csvstat`. Tests run under `go test`.

## 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 data files. `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 `go build -o <temporary path> ./cmd/csvstat` and then runs 22 checks. 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
CsvStat: NN passed, NN failed (of 22)
```

## 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/employees.csv` — 24 rows, 8 columns, including a quoted field that contains a comma
- `sources/sensors.csv` — 36 rows, 7 columns, including a column with no values
- `sources/orders.csv` — 30 rows, 8 columns, including padded text and an invalid date
- `sources/header_only.csv` — a header and no rows
- `sources/ragged.csv` — line 4 has one field too many

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

## Command

```text
csvstat [--column <name>] <file>
csvstat --freq <name> [--top <n>] <file>
```

Options precede the file. Exactly one file is required.

| Option | Meaning |
|---|---|
| `--column <name>` | Profile only the named column. |
| `--freq <name>` | List the most frequent values of the named column instead of profiling. |
| `--top <n>` | With `--freq`, list at most `<n>` values. A positive integer; default `5`. |

`--column` and `--freq` cannot be combined. `--top` is valid only with `--freq`.

## Reading the file

1. The file is UTF-8 CSV as RFC 4180 defines it, read with Go's `encoding/csv`. The first record
   is the header.
2. Every header name and every value is trimmed of leading and trailing spaces before any other
   rule applies.
3. The file is **rejected** when it is empty, when a header name is empty or repeated, or when any
   record has a different number of fields from the header.
4. **Null.** A value is null when it is empty, or when it equals `NA`, `N/A`, or `NULL` ignoring
   case. All other values are non-null.

## Types

A column's type is the first of these that every non-null value satisfies:

| Type | Every non-null value |
|---|---|
| `integer` | matches `-?[0-9]+` |
| `number` | matches `-?[0-9]+(\.[0-9]+)?` |
| `date` | matches `YYYY-MM-DD` and is a real calendar date (`2025-02-30` is not) |
| `boolean` | equals `true` or `false`, ignoring case |
| `text` | anything |

A column with no non-null values has type `empty`.

## Profile output

Header `column,type,rows,nulls,distinct,min,max,sum,mean,median`, then one row per column in file
order (or the one named by `--column`).

| Field | Value |
|---|---|
| `rows` | Number of data records. |
| `nulls` | Number of null values. |
| `distinct` | Number of different non-null values, compared as exact strings after trimming. |
| `min`, `max` | `integer`: the smallest and largest value as an integer. `number`: as a decimal. `date`: earliest and latest. `boolean`: `false` if any value is false, else `true`; `true` if any value is true, else `false`. `text`: smallest and largest by byte value. `empty`: empty. |
| `sum` | `integer`: the integer total. `number`: the decimal total. Otherwise empty. |
| `mean` | `integer` and `number`: total divided by non-null count. Otherwise empty. |
| `median` | `integer` and `number`: the middle value of the sorted non-null values, or the mean of the two middle values when the count is even. Otherwise empty. |

**Decimals.** Every `number` `min`, `max`, and `sum`, and every `mean` and `median`, is written with
exactly two decimal places, rounded half away from zero from the exact value, with a leading `-`
when negative and no thousands separator: `1012.50`, `-12.21`, `0.00`. Integer `min`, `max`, and
`sum` are written as plain integers.

## Frequency output

Header `value,count`, then one row per distinct non-null value of the column, ordered by count
descending, then value ascending by byte value, at most `--top` rows. Null values are not listed. A
column with no non-null values writes only the header.

## Output format

CSV on standard output with `\n` line endings. A field that contains a comma, a double quote, or a
newline is quoted as RFC 4180 specifies; Go's `encoding/csv` writer produces this format. A
failing command writes nothing to standard output and one diagnostic line to standard error naming
the file and, for a rejected record, its line number.

## Exit codes

| Code | Meaning |
|---|---|
| `0` | Success. |
| `1` | Operational failure: the file cannot be opened or read. |
| `2` | Usage error: missing or extra file, unknown option, missing option value, `--top` not a positive integer, `--top` without `--freq`, `--column` with `--freq`. |
| `3` | Rejected: empty file, empty or repeated header name, ragged record, or a column name that is not in the header. |

## Tests

The completed application provides a POSIX-compatible `bin/test.sh` that runs `go vet ./...` and
`go test ./...` from the application root and exits zero only when both pass. The suite covers
each type, each statistic, null handling, rounding, each output form, and each exit code using
files written by the tests.
</source>

<stories>
  <story id="foundation" implements="ARCHITECTURE.md">Stand up the Go module, directory layout, and architecture for csvstat.</story>
  <story id="executable" implements="FEATURE-Executable.md">Build the csvstat executable from the module root with a thin main over cli.Run.</story>
  <story id="csv-reading" implements="FEATURE-CsvReading.md">Read UTF-8 RFC 4180 CSV with the first record as header.</story>
  <story id="value-trimming" implements="FEATURE-Trimming.md">Trim leading and trailing spaces from every header name and value.</story>
  <story id="null-values" implements="FEATURE-NullValues.md">Recognise null spellings: empty, NA, N/A, NULL ignoring case.</story>
  <story id="numeric-types" implements="FEATURE-NumericTypes.md">Infer integer and number column types.</story>
  <story id="date-type" implements="FEATURE-DateType.md">Infer date columns of real YYYY-MM-DD calendar dates.</story>
  <story id="boolean-text-types" implements="FEATURE-BooleanTextTypes.md">Infer boolean, text, and empty column types.</story>
  <story id="args-parsing" implements="FEATURE-Arguments.md">Parse options and exactly one file argument, with options preceding the file.</story>
  <story id="input-rejection" implements="FEATURE-InputRejection.md">Reject empty files, empty or repeated header names, and ragged records.</story>
  <story id="row-counts" implements="FEATURE-RowCounts.md">Report rows, nulls, and distinct counts per column.</story>
  <story id="sum-mean" implements="FEATURE-SumMean.md">Compute exact sum and mean for integer and number columns.</story>
  <story id="median" implements="FEATURE-Median.md">Compute the median for integer and number columns.</story>
  <story id="min-max" implements="FEATURE-MinMax.md">Compute min and max by column type.</story>
  <story id="decimal-format" implements="FEATURE-DecimalFormat.md">Format decimal results to two places, rounded half away from zero once.</story>
  <story id="freq-count" implements="FEATURE-FreqCount.md">Count and order distinct non-null values of a column.</story>
  <story id="freq-limit" implements="FEATURE-FreqLimit.md">Limit frequency rows with --top, default 5.</story>
  <story id="profile-output" implements="FEATURE-ProfileOutput.md">Write the column profile as RFC 4180 CSV for the default invocation.</story>
  <story id="usage-errors" implements="FEATURE-UsageErrors.md">Reject malformed arguments with exit 2 and a usage line on standard error.</story>
  <story id="column-profile" implements="FEATURE-ColumnProfile.md">Profile a single named column with --column.</story>
  <story id="failure-diagnostics" implements="FEATURE-FailureDiagnostics.md">Write one stderr diagnostic line and nothing on stdout when a command fails.</story>
  <story id="unreadable-file" implements="FEATURE-UnreadableFile.md">Exit 1 when the file cannot be opened or read.</story>
  <story id="freq-mode" implements="FEATURE-FreqMode.md">Select frequency mode with --freq.</story>
  <story id="test-gate" implements="FEATURE-TestGate.md">Provide bin/test.sh running go vet and go test and the project test suite.</story>
  <story id="release-verification" implements="VERIFICATION.md">Pass the supplied grader sources/run.sh with all 22 checks.</story>
</stories>
