# 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.

2. **Input Context** — begins with the heading `# Input Context`. All blocks are wrapped in
   `<pblock>` tags. Two block types:
   - File blocks: `<pblock filename="<name>" role="<role>" guidance="...">` — optional
     `guidance` attribute carries context-specific instructions; content is in a fenced block.
   - Metadata/section blocks: `<pblock label="<label>" kind="<kind>">` — job parameters,
     rules, instructions, or group headers.

3. **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
- TARGET: CsvStat
- BUILD_DIRECTORY: /mnt/c/Users/barlo/projects/drydock/uat/CsvStat/runs/20261025.051314/build/CsvStat
- WORKING_DIRECTORY: /mnt/c/Users/barlo/projects/drydock/uat/CsvStat/runs/20261025.051314/build/CsvStat
- BUILD_BLOCK: Block 2 · Service (block-2)
- STORIES: Build the csvstat executable from the module root with a thin main over cli.Run. (executable), Read UTF-8 RFC 4180 CSV with the first record as header. (csv-reading), Trim leading and trailing spaces from every header name and value. (value-trimming), Recognise null spellings: empty, NA, N/A, NULL ignoring case. (null-values), Infer integer and number column types. (numeric-types), Infer date columns of real YYYY-MM-DD calendar dates. (date-type), Infer boolean, text, and empty column types. (boolean-text-types), Parse options and exactly one file argument, with options preceding the file. (args-parsing), Reject empty files, empty or repeated header names, and ragged records. (input-rejection)
- DATE: 2026-10-25
- BUILD_SCOPE: exactly one MANIFEST.md build block

</pblock>

<pblock label="Stories in this block" kind="section">
## Stories in this block
- Build the csvstat executable from the module root with a thin main over cli.Run. (executable) [story]
- Read UTF-8 RFC 4180 CSV with the first record as header. (csv-reading) [story]
- Trim leading and trailing spaces from every header name and value. (value-trimming) [story]
- Recognise null spellings: empty, NA, N/A, NULL ignoring case. (null-values) [story]
- Infer integer and number column types. (numeric-types) [story]
- Infer date columns of real YYYY-MM-DD calendar dates. (date-type) [story]
- Infer boolean, text, and empty column types. (boolean-text-types) [story]
- Parse options and exactly one file argument, with options preceding the file. (args-parsing) [story]
- Reject empty files, empty or repeated header names, and ragged records. (input-rejection) [story]

</pblock>

<pblock label="Files on disk" kind="section">
## Files on disk in the build directory
- sources/employees.csv
- sources/header_only.csv
- sources/orders.csv
- sources/ragged.csv
- sources/run.sh
- sources/sensors.csv

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/CsvStat/runs/20261025.051314/workspace/targets/CsvStat/COMPASS.md" guidance="Important: This is the core project intent, constraints, and guardrails. It should have presecedence in conflicts.">
```markdown
# COMPASS: CsvStat

## Compass

Build a command-line CSV column profiler, the Go executable `./cmd/csvstat`, as described in
`sources/INSTRUCTIONS.md`. It infers each column's type, reports counts, extremes, and for numeric
columns sum, mean, and median, and lists a column's most frequent values.

Correctness is measured by `sources/run.sh`: it builds the executable with `go build` and makes
22 checks of exit code and standard output against five supplied CSV files. The goal is every
check passing.

## Constraints

- Implement in Go 1.22 or newer with the standard library only. No third-party modules.
- The application root is a Go module; the executable's main package is `./cmd/csvstat`.
- Compute sums, means, and medians exactly (for example with `math/big`) and round once, half away
  from zero, when writing.
- 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 any supplied data file from application code, and do not
  hardcode a statistic, a type, or a value list. Every value comes from the file examined.

## 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/CsvStat/runs/20261025.051314/build/CsvStat`
- Authorized Target directory: `/mnt/c/Users/barlo/projects/drydock/uat/CsvStat/runs/20261025.051314/workspace/targets/CsvStat`
- 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/CsvStat/runs/20261025.051314/workspace/targets/CsvStat/blueprint/`
  - `/mnt/c/Users/barlo/projects/drydock/uat/CsvStat/runs/20261025.051314/workspace/targets/CsvStat/MANIFEST.md`
  - `/mnt/c/Users/barlo/projects/drydock/uat/CsvStat/runs/20261025.051314/workspace/targets/CsvStat/COMPASS.md`
  - `/mnt/c/Users/barlo/projects/drydock/uat/CsvStat/runs/20261025.051314/workspace/targets/CsvStat/QuarterDeck/`
  - `/mnt/c/Users/barlo/projects/drydock/uat/CsvStat/runs/20261025.051314/workspace/targets/CsvStat/evidence/`
<!-- drydock:build-write-guardrail:end -->
```
</pblock>


## STACK - Technology HOW

<pblock filename="go_compact.md" role="stack" path="/mnt/c/Users/barlo/projects/drydock/Rigging/languages/go/go_compact.md">
````
<!-- Compacted from Rigging/languages/go/go.md sha256=aa96c7155b26f091e4f2ee9b7a47ff2202fc7c162254f2b8676779198c7147da on 2026-10-18 by Rigging maintenance -->

## Foundation Contract

The published shape of this foundation. It is built before every other foundation: a web server,
a database, or a CLI is built *into* this tree, this environment, and this test runner. Carried
verbatim into `go_compact.md`.

- source_root: internal/
- test_command: go test ./...
- environment: the module declared in `go.mod`; no vendored toolchain
- dependencies: `go.mod`

```
project/
  go.mod                  # module path; the Go toolchain version
  cmd/                    # one directory per binary, each package main
  internal/               # application packages; not importable outside this module
  bin/                    # launchers; each runs the toolchain, never a vendored copy
```

Application foundations add packages under `internal/`. The generated persistence library is a
separate module at `persistence/`, linked by the root `go.mod`.

### Native application layouts and fixtures

Initialize the root `go.mod` in the language foundation before the DATABASE block.
Use `cmd/app/main.go` for process startup, `internal/cli` for CLI behavior, and
`internal/appserver` for HTTP behavior. The root application module requires
`drydock.local/persistence v0.0.0` with `replace drydock.local/persistence => ./persistence`;
the generated persistence directory owns its nested module. Run both module test suites.

For a CLI, expose `Run(args []string, stdout, stderr io.Writer) int`, use a local
`flag.FlagSet` with `flag.ContinueOnError`, and test with `bytes.Buffer`. Only main calls
`os.Exit`. For HTTP, expose `NewHandler(...) http.Handler` using `net/http.ServeMux`.
Use `httptest.NewRecorder` and `httptest.NewRequest` for handler tests, or
`httptest.NewServer` with `t.Cleanup(server.Close)` when testing a real HTTP client.
Keep business logic in application packages and persistence access in the shipped library.

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

An Acceptance Criterion (AC) is an executable check of Blueprint-required behavior. Native tests
use `testing` in `*_test.go`; the project gate is `go test ./...`. Within the existing Blueprint
Python AC container, execute a named test through the shipped helper:

```python
from drydock_go import run_test
result = run_test("./internal/orders", "TestCreateOrder")
assert result.passed, (result.status, result.stdout, result.stderr)
```

Drydock stages this helper beside the criterion. It runs `go test -json -count=1 -run` with an
exact test name, retains output and per-test outcomes, and rejects absent/skipped tests as proof.
The enclosing AC provides identity, timeout, result storage and repair state. Compilation errors
remain distinct from assertion failures in `result.status`. Coverage and persistence observations
require explicit instrumentation per criterion; unavailable observations are unknown.

A criterion that exercises the command line runs the built executable through the same helper,
never `go run`, which reports every non-zero program exit as 1:

```python
from drydock_go import cli_runner
code, out, err = cli_runner("--top", "0", "data.csv")
assert code == 2, (code, out, err)
```

`cli_runner` builds the single `./cmd/<name>` main package once with `go build` and returns
`(exit_code, stdout, stderr)`; pass `package="./cmd/<name>"` when there are several, and `input=`
for standard input. A failed build settles the criterion as `execution-error`.

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

Use the shipped module in `Rigging/languages/go/persistence/`. Drydock copies it to the Target's
`persistence/`, generates `schema.go`, `testing.go` and a schema command from `DATABASE.md`, and
links it into the existing root `go.mod` as `drydock.local/persistence`. Driver versions and sums
are shipped; SQLite uses `go-sqlite3` (a C compiler and CGO are required), PostgreSQL uses `lib/pq`.
Run `go mod download` during dependency provisioning; execution requires these modules available.

Call `persistence.OpenDatabase(ctx, dsn)`, then typed methods such as
`db.Tickets.List(ctx, persistence.TicketsListInput{Status: "open"})`. Methods return a value and
an error. Optional inputs use pointers; read results are generated structs. Undeclared operations
and unsupported field types fail explicitly. Use `OpenSession(ctx, dsn)` for native database criteria;
empty DSN selects the configured, provisioned application store. Defer its cleanup and check the
returned error: it rolls back on success and failure, never applies schema or deletes the store.
Pass the same Store to the feature. Other connections and external effects require committed,
idempotent criteria with owned records and supported cleanup. Both engines retain autocommit
outside explicit rollback scopes.

The Go library and generator are verified on SQLite and PostgreSQL. Keep application SQL inside
the library; agents write callers. The language foundation must create `go.mod` before the
DATABASE step. Python Blueprint AC containers invoke the native Go tests through `run_test`.

---

## Consumer Rules

- Use `gofmt`, explicit errors, small consumer-owned interfaces and owned goroutine lifetimes.
- Keep business logic in `internal/` and entry points in `cmd/`; commit `go.mod` and `go.sum`.
- Gate with `go vet ./...`, `go build ./...` and `go test -race ./...`.
````
</pblock>


## CONTEXT - Read-Only Support

<pblock filename="ARCHITECTURE_compact.md" role="context" path="/mnt/c/Users/barlo/projects/drydock/uat/CsvStat/runs/20261025.051314/workspace/targets/CsvStat/blueprint/ARCHITECTURE_compact.md">
```
<!-- Compacted from ARCHITECTURE.md sha256=e12f94e5c90e8e9b4581c3d4e02add14222bb76448d04c486ee6d71e88a43bf6 on 2026-10-25 by drydock build agent -->

Module: `csvstat`, `go 1.22`, no `require`.
Layout: `cmd/csvstat` (package main), `internal/cli`, `internal/csvdata`, `internal/profile`, `internal/freq`, `bin/test.sh` (vet then test).
Entry: `cli.Run(args []string, stdout, stderr io.Writer) int`; `args` excludes program name; only `cmd/csvstat/main.go` calls `os.Exit`.
Exit codes: 0 success; 1 operational (open/read failure); 2 usage; 3 rejected input.
Stdout written only on success; diagnostics to stderr only.
Rules: `sources/` read-only; no reading `sources/run.sh` or data files in app code; no embedded answers; stdlib only.
```
</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-Executable.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/CsvStat/runs/20261025.051314/workspace/targets/CsvStat/blueprint/FEATURE-Executable.md" guidance="Feature Specification">
```markdown
# FEATURE: Executable

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | Build the csvstat executable from the module root with a thin main package over cli.Run. |
| Depends On  | ARCHITECTURE.md |
| Provides    | csvstat command, cli.Run |
| Consumes    | None |

## Purpose

`go build ./cmd/csvstat` at the application root produces the `csvstat` executable using only the
standard library. This story delivers the entry point and a minimal `Run` that later stories extend.

## Behavior

- `cmd/csvstat/main.go` is `package main`. It calls `cli.Run(os.Args[1:], os.Stdout, os.Stderr)` and
  passes the returned code to `os.Exit`. It contains no other logic.
- `internal/cli` exports `Run(args []string, stdout, stderr io.Writer) int`. In this story it returns 0.
  Later stories add parsing, dispatch, and failure mapping.
- The import path of the cli package is `<module>/internal/cli`, where the module path is the one in
  `go.mod`.
- Every import in the module is either standard library or module-local.

## Tests For The Project Suite

The builder adds `internal/cli` tests that call `Run` with `bytes.Buffer` writers.

## Programmatic Acceptance

=== AC exe-builds ===
Intent: The csvstat executable builds with go build and runs to a defined exit code on a valid file.
Requires: executable=go; scope=test

import csv
import os
import tempfile
from drydock_go import cli_runner

with tempfile.TemporaryDirectory() as workdir:
    path = os.path.join(workdir, "data.csv")
    with open(path, "w", newline="", encoding="utf-8") as handle:
        writer = csv.writer(handle, lineterminator="\n")
        writer.writerow(["a", "b"])
        writer.writerow(["1", "2"])
    code, out, err = cli_runner(path)
    print(code, out, err)
    assert isinstance(code, int)
    assert 0 <= code <= 3
    assert isinstance(out, str)
=== END AC exe-builds ===

=== AC exe-stdlib-only ===
Intent: Every import in the module is standard library or module-local, with no third-party path.

import re
from pathlib import Path

files = list(Path("cmd").rglob("*.go")) + list(Path("internal").rglob("*.go"))
assert files
paths = []
for source in files:
    text = source.read_text(encoding="utf-8")
    blocks = re.findall(r"import\s*\((.*?)\)", text, re.S)
    blocks += re.findall(r"^import\s+(?:\w+\s+)?(\"[^\"]+\")", text, re.M)
    for block in blocks:
        paths += re.findall(r"\"([^\"]+)\"", block)
assert paths
for path in paths:
    first = path.split("/")[0]
    assert "." not in first, path
=== END AC exe-stdlib-only ===

=== AC exe-main-owns-exit ===
Intent: Only the main package calls os.Exit and main delegates to cli.Run.

from pathlib import Path

main_source = Path("cmd/csvstat/main.go").read_text(encoding="utf-8")
assert "package main" in main_source
assert "os.Exit(" in main_source
assert "cli.Run(" in main_source
for source in Path("internal").rglob("*.go"):
    assert "os.Exit(" not in source.read_text(encoding="utf-8"), source
=== END AC exe-main-owns-exit ===

=== AC exe-no-grader-read ===
Intent: Application code never references the supplied grader script.

from pathlib import Path

files = list(Path("cmd").rglob("*.go")) + list(Path("internal").rglob("*.go"))
for source in files:
    if source.name.endswith("_test.go"):
        continue
    assert "run.sh" not in source.read_text(encoding="utf-8"), source
=== END AC exe-no-grader-read ===

## User Acceptance

- None.

## Guardrails

- Standard library only; no third-party module.
- Application code never reads `sources/run.sh` or any supplied data file.
- Do not modify anything under `sources/`.
```
</pblock>

<pblock filename="FEATURE-CsvReading.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/CsvStat/runs/20261025.051314/workspace/targets/CsvStat/blueprint/FEATURE-CsvReading.md" guidance="Feature Specification">
```markdown
# FEATURE: CSV Reading

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | Read UTF-8 RFC 4180 CSV with the first record as the header, recording each record's source line. |
| Depends On  | ARCHITECTURE.md |
| Provides    | csvdata.Read |
| Consumes    | None |

## Purpose

`internal/csvdata` turns an input stream into a header and data records. Trimming, null recognition, and
rejection of malformed input are separate stories that build on this reader.

## Behavior

- `Read(r io.Reader) (*Table, error)` parses with `encoding/csv`, with `FieldsPerRecord = -1` so field
  counts are judged by the rejection story, and `LazyQuotes` off.
- `Table` has `Header []string` and `Records []Record`. `Record` has `Line int`, the 1-based source line
  on which the record starts, and `Fields []string`.
- The first record is the header; every later record is a data record. Values are returned as parsed
  with no trimming.
- A quoted field containing a comma is one value. A quoted field may contain doubled quotes and newlines.
- A line ending after the last record creates no extra record. Input with or without a final newline
  yields the same records.
- Input with no record at all (empty or only blank lines) returns a `Table` with a nil `Header` and no
  `Records` and no error; the input-rejection story turns that into a rejection.
- A syntax error reported by `encoding/csv` is returned wrapped so callers can recover the line number
  with `errors.As` and `*csv.ParseError`.
- `Read` does not open files; `cli` opens the file and passes the reader.

## Tests For The Project Suite

The builder writes these `internal/csvdata` tests, named exactly as listed:

- `TestReadHeaderAndRecords`: header is the first record; the rest are data records.
- `TestReadQuotedComma`: a quoted field with a comma is a single value.
- `TestReadTrailingNewline`: a final newline adds no record, matching the same input without one.
- `TestReadRecordLineNumbers`: each record carries the line on which it starts, including after a
  quoted field that spans lines.
- `TestReadHeaderOnly`: a header with no data yields zero records.
- `TestReadNoRecords`: empty input yields a nil header and no records.

## Programmatic Acceptance

=== AC read-header-and-records ===
Intent: The first record is the header and later records are data records.
Requires: executable=go; scope=test

import sys
from drydock_go import run_test

result = run_test("./internal/csvdata", "TestReadHeaderAndRecords")
print(result.stdout)
print(result.stderr, file=sys.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC read-header-and-records ===

=== AC read-quoted-comma ===
Intent: A quoted field containing a comma parses as one value.
Requires: executable=go; scope=test

import sys
from drydock_go import run_test

result = run_test("./internal/csvdata", "TestReadQuotedComma")
print(result.stdout)
print(result.stderr, file=sys.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC read-quoted-comma ===

=== AC read-trailing-newline ===
Intent: A line ending after the last record does not create an extra data record.
Requires: executable=go; scope=test

import sys
from drydock_go import run_test

result = run_test("./internal/csvdata", "TestReadTrailingNewline")
print(result.stdout)
print(result.stderr, file=sys.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC read-trailing-newline ===

=== AC read-line-numbers ===
Intent: Each record carries the source line on which it starts.
Requires: executable=go; scope=test

import sys
from drydock_go import run_test

result = run_test("./internal/csvdata", "TestReadRecordLineNumbers")
print(result.stdout)
print(result.stderr, file=sys.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC read-line-numbers ===

=== AC read-header-only-and-empty ===
Intent: A header-only input has zero records and an input with no record has no header.
Requires: executable=go; scope=test

import sys
from drydock_go import run_test

for name in ("TestReadHeaderOnly", "TestReadNoRecords"):
    result = run_test("./internal/csvdata", name)
    print(name, result.status)
    print(result.stdout)
    print(result.stderr, file=sys.stderr)
    assert result.passed, (name, result.status, result.stdout, result.stderr)
=== END AC read-header-only-and-empty ===

## User Acceptance

- None.

## Guardrails

- Read with Go's `encoding/csv`; do not write a custom CSV parser.
- The reader does not trim, classify, or reject values; those belong to later stories.
- Never read a supplied data file from application code; the file named on the command line is the only input.
```
</pblock>

<pblock filename="FEATURE-Trimming.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/CsvStat/runs/20261025.051314/workspace/targets/CsvStat/blueprint/FEATURE-Trimming.md" guidance="Feature Specification">
```markdown
# FEATURE: Trimming

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | Trim leading and trailing spaces from every header name and every value before any other rule applies. |
| Depends On  | FEATURE-CsvReading.md |
| Provides    | csvdata.Trim |
| Consumes    | csvdata.Read |

## Purpose

Every header name and every value is trimmed of leading and trailing spaces before null recognition,
typing, counting, or comparison. Padded text such as `  Globex  ` and `Acme Corp ` therefore count as
`Globex` and `Acme Corp`.

## Behavior

- `Trim(t *Table)` replaces, in place, each header name and each record field with the same string
  stripped of leading and trailing space characters (U+0020).
- Only U+0020 is trimmed. Tabs and other whitespace are preserved. Interior spaces are preserved.
- Trimming applies after CSV parsing, so spaces inside a quoted field are also trimmed.
- Record line numbers and field counts are unchanged.
- The cli pipeline calls `Read` then `Trim` before any other rule; the profile-output and
  frequency-mode stories wire that call.

## Tests For The Project Suite

The builder writes these `internal/csvdata` tests, named exactly as listed:

- `TestTrimHeaderNames`: padded header names are trimmed.
- `TestTrimValues`: padded values are trimmed on both sides.
- `TestTrimQuotedPadding`: spaces inside a quoted field are trimmed, and the comma inside the quotes is kept.
- `TestTrimOnlySpaces`: tabs are preserved and interior spaces are kept.
- `TestTrimKeepsLines`: line numbers and field counts are unchanged.

## Programmatic Acceptance

=== AC trim-header-names ===
Intent: Leading and trailing spaces are removed from header names.
Requires: executable=go; scope=test

import sys
from drydock_go import run_test

result = run_test("./internal/csvdata", "TestTrimHeaderNames")
print(result.stdout)
print(result.stderr, file=sys.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC trim-header-names ===

=== AC trim-values ===
Intent: Leading and trailing spaces are removed from every value.
Requires: executable=go; scope=test

import sys
from drydock_go import run_test

result = run_test("./internal/csvdata", "TestTrimValues")
print(result.stdout)
print(result.stderr, file=sys.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC trim-values ===

=== AC trim-quoted-padding ===
Intent: Padding inside a quoted field is trimmed while the quoted comma is kept.
Requires: executable=go; scope=test

import sys
from drydock_go import run_test

result = run_test("./internal/csvdata", "TestTrimQuotedPadding")
print(result.stdout)
print(result.stderr, file=sys.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC trim-quoted-padding ===

=== AC trim-scope ===
Intent: Only spaces are trimmed, interior spaces remain, and line numbers and field counts are unchanged.
Requires: executable=go; scope=test

import sys
from drydock_go import run_test

for name in ("TestTrimOnlySpaces", "TestTrimKeepsLines"):
    result = run_test("./internal/csvdata", name)
    print(name, result.status)
    print(result.stdout)
    print(result.stderr, file=sys.stderr)
    assert result.passed, (name, result.status, result.stdout, result.stderr)
=== END AC trim-scope ===

## User Acceptance

- None.

## Guardrails

- Trimming happens before null recognition, typing, counting, and comparison.
- Trim leading and trailing spaces only; do not alter interior content.
- Distinctness is compared as exact strings after trimming.
```
</pblock>

<pblock filename="FEATURE-NullValues.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/CsvStat/runs/20261025.051314/workspace/targets/CsvStat/blueprint/FEATURE-NullValues.md" guidance="Feature Specification">
```markdown
# FEATURE: Null Values

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | Recognise null spellings (empty, NA, N/A, NULL ignoring case) on trimmed values. |
| Depends On  | FEATURE-Trimming.md, FEATURE-CsvReading.md |
| Provides    | csvdata.IsNull |
| Consumes    | csvdata.Read |

## Purpose

Statistics, type inference and frequency counting all need one shared definition of "null". This
feature provides it as a function in `internal/csvdata` so no other package re-implements it.

## Behavior

- `func IsNull(value string) bool` in package `csvdata` receives a value that has already been
  trimmed of leading and trailing spaces.
- A value is null when it is the empty string, or equals `NA`, `N/A`, or `NULL` ignoring case
  (`na`, `n/a`, `Null` and `null` are null).
- Every other value is non-null, including `0`, `false`, `NAN`, `N/B`, `NULLS` and `NA ` is not
  an input (trimming precedes this rule), so only exact spellings match.
- A quoted empty field (`""`) is read by `encoding/csv` as an empty string, so it is null.
- A field made only of spaces is empty after trimming and is therefore null.
- `IsNull` is pure: it never reads files and never allocates state.

## Tests the build must write

The project's own suite in `internal/csvdata` contains these test functions (names are fixed so
acceptance can run them):

- `TestIsNullEmpty`
- `TestIsNullSpellings`
- `TestIsNullNonNullValues`
- `TestQuotedEmptyFieldIsNull`
- `TestSpacesOnlyFieldIsNull`

## Programmatic Acceptance

=== AC null-empty ===
Intent: The empty string is reported null by csvdata.IsNull.
Requires: executable=go; scope=test

from drydock_go import run_test

result = run_test("./internal/csvdata", "TestIsNullEmpty")
print(result.stdout)
print(result.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC null-empty ===

=== AC null-spellings ===
Intent: NA, N/A and NULL are null in any letter case.
Requires: executable=go; scope=test

from drydock_go import run_test

result = run_test("./internal/csvdata", "TestIsNullSpellings")
print(result.stdout)
print(result.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC null-spellings ===

=== AC null-non-null-values ===
Intent: Ordinary values such as 0, false and near-miss spellings are not null.
Requires: executable=go; scope=test

from drydock_go import run_test

result = run_test("./internal/csvdata", "TestIsNullNonNullValues")
print(result.stdout)
print(result.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC null-non-null-values ===

=== AC null-quoted-empty ===
Intent: A quoted empty field read from a CSV file is null.
Requires: executable=go; scope=test

from drydock_go import run_test

result = run_test("./internal/csvdata", "TestQuotedEmptyFieldIsNull")
print(result.stdout)
print(result.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC null-quoted-empty ===

=== AC null-spaces-only ===
Intent: A field of only spaces is null once trimmed.
Requires: executable=go; scope=test

from drydock_go import run_test

result = run_test("./internal/csvdata", "TestSpacesOnlyFieldIsNull")
print(result.stdout)
print(result.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC null-spaces-only ===

## User Acceptance

- None.

## Guardrails

- `IsNull` never reads `sources/run.sh` or any supplied data file and embeds no answer.
- Only the standard library is used.
- Null spellings are exactly those named in the source; no other token is treated as null.
```
</pblock>

<pblock filename="FEATURE-NumericTypes.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/CsvStat/runs/20261025.051314/workspace/targets/CsvStat/blueprint/FEATURE-NumericTypes.md" guidance="Feature Specification">
```markdown
# FEATURE: Numeric Types

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | Infer integer and number column types from the non-null values of a column. |
| Depends On  | FEATURE-NullValues.md |
| Provides    | profile.InferType (integer, number) |
| Consumes    | csvdata.IsNull |

## Purpose

Column typing decides which statistics apply. This feature starts `profile.InferType` in
`internal/profile` with the two numeric types. Later features extend the same function with
`date`, `boolean`, `text`, and `empty`.

## Behavior

- `func InferType(values []string) string` in package `profile` receives the trimmed values of one
  column and returns the type name.
- Null values (per `csvdata.IsNull`) are ignored.
- A column is `integer` when every non-null value matches `-?[0-9]+`.
- Otherwise it is `number` when every non-null value matches `-?[0-9]+(\.[0-9]+)?`.
- Integer is tested before number, so a column of whole numbers is `integer`; a single decimal
  value makes the column `number`.
- Matching is anchored over the whole value and uses no float parsing. Values such as `+1`, `1.`,
  `.5`, `1e3`, `1,5`, `0x10`, and `-` are not numeric.
- When a column has at least one non-null value that is not numeric, this feature returns the
  fallback `text` until later features add the remaining types.
- A column whose non-null values are all null returns `empty`.

## Tests the build must write

In `internal/profile`:

- `TestInferIntegerColumn`
- `TestInferNumberColumn`
- `TestIntegerPreferredOverNumber`
- `TestNullsIgnoredWhenInferringNumeric`
- `TestMalformedNumericsAreNotNumeric`

## Programmatic Acceptance

=== AC numeric-integer ===
Intent: A column of integer-shaped values, including negatives, is typed integer.
Requires: executable=go; scope=test

from drydock_go import run_test

result = run_test("./internal/profile", "TestInferIntegerColumn")
print(result.stdout)
print(result.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC numeric-integer ===

=== AC numeric-number ===
Intent: A column with a decimal value among integers is typed number.
Requires: executable=go; scope=test

from drydock_go import run_test

result = run_test("./internal/profile", "TestInferNumberColumn")
print(result.stdout)
print(result.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC numeric-number ===

=== AC numeric-integer-preferred ===
Intent: Integer is chosen over number when both patterns match every value.
Requires: executable=go; scope=test

from drydock_go import run_test

result = run_test("./internal/profile", "TestIntegerPreferredOverNumber")
print(result.stdout)
print(result.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC numeric-integer-preferred ===

=== AC numeric-nulls-ignored ===
Intent: Null spellings among numeric values do not change the inferred type.
Requires: executable=go; scope=test

from drydock_go import run_test

result = run_test("./internal/profile", "TestNullsIgnoredWhenInferringNumeric")
print(result.stdout)
print(result.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC numeric-nulls-ignored ===

=== AC numeric-malformed ===
Intent: Values such as +1, 1., .5, 1e3 and 1,5 are not numeric.
Requires: executable=go; scope=test

from drydock_go import run_test

result = run_test("./internal/profile", "TestMalformedNumericsAreNotNumeric")
print(result.stdout)
print(result.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC numeric-malformed ===

## User Acceptance

- None.

## Guardrails

- Classification never uses float parsing; values stay exact strings for later exact arithmetic.
- No type is hardcoded for any column or file; every type comes from the values examined.
- Only the standard library is used.
```
</pblock>

<pblock filename="FEATURE-DateType.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/CsvStat/runs/20261025.051314/workspace/targets/CsvStat/blueprint/FEATURE-DateType.md" guidance="Feature Specification">
```markdown
# FEATURE: Date Type

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | Infer date columns whose non-null values are real YYYY-MM-DD calendar dates. |
| Depends On  | FEATURE-NumericTypes.md |
| Provides    | profile.InferType (date) |
| Consumes    | csvdata.IsNull, profile.InferType |

## Purpose

Extend `profile.InferType` so date columns are recognised and sort chronologically in later
statistics.

## Behavior

- After integer and number are ruled out, a column is `date` when every non-null value has the
  shape `YYYY-MM-DD` (four digits, hyphen, two digits, hyphen, two digits) and is a real calendar
  date.
- Real-date validation uses `time.Parse` with layout `2006-01-02` in addition to the digit-shape
  check, so `2025-02-30`, `2025-13-01`, and `2025-02-29` are not dates while `2024-02-29` is.
- Shapes such as `2025-2-3`, `2025/02/03`, `20250203`, and `2025-02-03T10:00` are not dates.
- Null values are ignored.
- One non-date value makes the column fall through to later types (`boolean`, then `text`).
  Integer and number take precedence, but no YYYY-MM-DD value can match them.

## Tests the build must write

In `internal/profile`:

- `TestInferDateColumn`
- `TestInvalidCalendarDateIsNotDate`
- `TestLeapDayHandling`
- `TestDateShapeIsStrict`
- `TestNullsIgnoredWhenInferringDate`

## Programmatic Acceptance

=== AC date-column ===
Intent: A column of valid YYYY-MM-DD values is typed date.
Requires: executable=go; scope=test

from drydock_go import run_test

result = run_test("./internal/profile", "TestInferDateColumn")
print(result.stdout)
print(result.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC date-column ===

=== AC date-invalid-calendar ===
Intent: A column containing an impossible date such as 2025-02-30 is not typed date.
Requires: executable=go; scope=test

from drydock_go import run_test

result = run_test("./internal/profile", "TestInvalidCalendarDateIsNotDate")
print(result.stdout)
print(result.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC date-invalid-calendar ===

=== AC date-leap-day ===
Intent: A leap-year February 29 is a date and a non-leap-year February 29 is not.
Requires: executable=go; scope=test

from drydock_go import run_test

result = run_test("./internal/profile", "TestLeapDayHandling")
print(result.stdout)
print(result.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC date-leap-day ===

=== AC date-shape-strict ===
Intent: Values with the wrong shape (unpadded, slashes, timestamps) are not dates.
Requires: executable=go; scope=test

from drydock_go import run_test

result = run_test("./internal/profile", "TestDateShapeIsStrict")
print(result.stdout)
print(result.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC date-shape-strict ===

=== AC date-nulls-ignored ===
Intent: Null spellings among dates do not change the inferred date type.
Requires: executable=go; scope=test

from drydock_go import run_test

result = run_test("./internal/profile", "TestNullsIgnoredWhenInferringDate")
print(result.stdout)
print(result.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC date-nulls-ignored ===

## User Acceptance

- None.

## Guardrails

- Date validity is computed from the value, never from a list of known dates.
- Only the standard library (`time`, `regexp`) is used.
- The numeric rules from FEATURE-NumericTypes.md are not altered.
```
</pblock>

<pblock filename="FEATURE-BooleanTextTypes.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/CsvStat/runs/20261025.051314/workspace/targets/CsvStat/blueprint/FEATURE-BooleanTextTypes.md" guidance="Feature Specification">
```markdown
# FEATURE: Boolean and Text Types

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | Infer boolean, text, and empty column types, completing the type order. |
| Depends On  | FEATURE-DateType.md |
| Provides    | profile.InferType (boolean, text, empty) |
| Consumes    | csvdata.IsNull, profile.InferType |

## Purpose

Complete `profile.InferType` so every column receives exactly one type: the first of `integer`,
`number`, `date`, `boolean`, `text` that every non-null value satisfies, or `empty` when there is
no non-null value.

## Behavior

- A column is `boolean` when every non-null value equals `true` or `false` ignoring case
  (`True`, `TRUE`, `false`, `False`). Values such as `yes`, `1`, `0`, and `t` are not boolean.
- `text` is the fallback for any column that satisfies none of the earlier types.
- A column with no non-null value (every value null, or zero data rows) is `empty`.
- The order of evaluation is: empty check, integer, number, date, boolean, text.
- A column of `0` and `1` is `integer`, not boolean.
- Original value case is preserved for distinct counting; only classification ignores case. The
  min and max statistics later render booleans as lowercase `true` or `false` regardless of input
  case; that rendering belongs to the min/max feature.
- Null values are ignored during classification.

## Tests the build must write

In `internal/profile`:

- `TestInferBooleanColumnMixedCase`
- `TestInferTextFallback`
- `TestInferEmptyWhenAllNull`
- `TestInferEmptyWhenNoRows`
- `TestBooleanLookalikesAreText`
- `TestTypeOrderPrecedence`

## Programmatic Acceptance

=== AC type-boolean-mixed-case ===
Intent: Values true and false in any letter case form a boolean column.
Requires: executable=go; scope=test

from drydock_go import run_test

result = run_test("./internal/profile", "TestInferBooleanColumnMixedCase")
print(result.stdout)
print(result.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC type-boolean-mixed-case ===

=== AC type-text-fallback ===
Intent: A column matching no earlier type is text.
Requires: executable=go; scope=test

from drydock_go import run_test

result = run_test("./internal/profile", "TestInferTextFallback")
print(result.stdout)
print(result.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC type-text-fallback ===

=== AC type-empty-all-null ===
Intent: A column whose values are all null spellings is typed empty.
Requires: executable=go; scope=test

from drydock_go import run_test

result = run_test("./internal/profile", "TestInferEmptyWhenAllNull")
print(result.stdout)
print(result.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC type-empty-all-null ===

=== AC type-empty-no-rows ===
Intent: A column with zero data rows is typed empty.
Requires: executable=go; scope=test

from drydock_go import run_test

result = run_test("./internal/profile", "TestInferEmptyWhenNoRows")
print(result.stdout)
print(result.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC type-empty-no-rows ===

=== AC type-boolean-lookalikes ===
Intent: Values such as yes, 1 or t do not make a boolean column.
Requires: executable=go; scope=test

from drydock_go import run_test

result = run_test("./internal/profile", "TestBooleanLookalikesAreText")
print(result.stdout)
print(result.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC type-boolean-lookalikes ===

=== AC type-order-precedence ===
Intent: Earlier types win over later ones when several would match.
Requires: executable=go; scope=test

from drydock_go import run_test

result = run_test("./internal/profile", "TestTypeOrderPrecedence")
print(result.stdout)
print(result.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC type-order-precedence ===

## User Acceptance

- None.

## Guardrails

- No column name, file name, or value list is hardcoded to decide a type.
- Booleans are classified case-insensitively but the stored value is never rewritten here.
- Only the standard library is used.
```
</pblock>

<pblock filename="FEATURE-Arguments.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/CsvStat/runs/20261025.051314/workspace/targets/CsvStat/blueprint/FEATURE-Arguments.md" guidance="Feature Specification">
````markdown
# FEATURE: Arguments

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | Parse csvstat options and exactly one file argument, with options preceding the file. |
| Depends On  | FEATURE-Executable.md |
| Provides    | cli.ParseArgs |
| Consumes    | cli.Run |

## Purpose

csvstat accepts two command forms:

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

Options precede the file and exactly one file is required. This story delivers the parser and its
wiring into `Run`. Cross-option validation (`--top` without `--freq`, `--column` with `--freq`,
non-positive `--top`) belongs to the usage-errors story.

## Behavior

- `internal/cli` exports `ParseArgs(args []string) (Options, error)`.
- `Options` has fields `Column string`, `Freq string`, `Top int`, `TopSet bool`, `File string`, and
  flags are recorded as set or not set (a presence flag for `--column` and `--freq`, so an empty value
  is distinguishable from an absent option).
- Parsing uses a local `flag.FlagSet` created with `flag.ContinueOnError` and its output discarded.
  Options take a separate value (`--top 3`); a repeated option is a parse error.
- Parsing stops at the first non-option argument. That argument is the file. Any argument after it,
  including a later option, is an extra argument and a parse error. Options after the file are
  therefore rejected.
- A missing file, an extra argument, an unknown option, and an option with no value each return an
  error. `--top` is parsed as a decimal integer; a non-integer value is a parse error.
- `Run` calls `ParseArgs`. When it returns an error, `Run` writes one line to `stderr`, writes nothing
  to `stdout`, and returns 2.

## Tests For The Project Suite

The builder writes these `internal/cli` tests, named exactly as listed, using the named inputs:

- `TestParseArgsFileOnly`: `[file]` yields File set and no options.
- `TestParseArgsColumn`: `[--column name file]` yields Column and File.
- `TestParseArgsFreqTop`: `[--freq name --top 3 file]` yields Freq, Top 3, TopSet, and File.
- `TestParseArgsMissingFile`: `[--column name]` is an error.
- `TestParseArgsExtraFile`: two files is an error.
- `TestParseArgsUnknownOption`: `[--frobnicate file]` is an error.
- `TestParseArgsMissingValue`: `[file-less --top]` forms with no value are an error.
- `TestParseArgsOptionsAfterFile`: `[file --column name]` is an error.

## Programmatic Acceptance

=== AC args-file-only ===
Intent: A lone file argument parses.
Requires: executable=go; scope=test

import sys
from drydock_go import run_test

result = run_test("./internal/cli", "TestParseArgsFileOnly")
print(result.stdout)
print(result.stderr, file=sys.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC args-file-only ===

=== AC args-column ===
Intent: The --column option and its value parse before the file.
Requires: executable=go; scope=test

import sys
from drydock_go import run_test

result = run_test("./internal/cli", "TestParseArgsColumn")
print(result.stdout)
print(result.stderr, file=sys.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC args-column ===

=== AC args-freq-top ===
Intent: The --freq and --top options and their values parse before the file.
Requires: executable=go; scope=test

import sys
from drydock_go import run_test

result = run_test("./internal/cli", "TestParseArgsFreqTop")
print(result.stdout)
print(result.stderr, file=sys.stderr)
assert result.passed, (result.status, result.stdout, result.stderr)
=== END AC args-freq-top ===

=== AC args-structural-errors ===
Intent: Missing file, extra file, unknown option, missing value, and options after the file are parse errors.
Requires: executable=go; scope=test

import sys
from drydock_go import run_test

names = [
    "TestParseArgsMissingFile",
    "TestParseArgsExtraFile",
    "TestParseArgsUnknownOption",
    "TestParseArgsMissingValue",
    "TestParseArgsOptionsAfterFile",
]
for name in names:
    result = run_test("./internal/cli", name)
    print(name, result.status)
    print(result.stdout)
    print(result.stderr, file=sys.stderr)
    assert result.passed, (name, result.status, result.stdout, result.stderr)
=== END AC args-structural-errors ===

=== AC args-valid-forms-not-usage-errors ===
Intent: The valid command forms are accepted by the executable and never exit with the usage-error code.
Requires: executable=go; scope=test

import csv
import os
import tempfile
from drydock_go import cli_runner

usage_exit = 2
with tempfile.TemporaryDirectory() as workdir:
    path = os.path.join(workdir, "data.csv")
    with open(path, "w", newline="", encoding="utf-8") as handle:
        writer = csv.writer(handle, lineterminator="\n")
        writer.writerow(["a", "b"])
        writer.writerow(["1", "2"])
    forms = [
        [path],
        ["--column", "a", path],
        ["--freq", "a", path],
        ["--freq", "a", "--top", "3", path],
    ]
    for form in forms:
        code, out, err = cli_runner(*form)
        print(form, code, out, err)
        assert code != usage_exit, form
=== END AC args-valid-forms-not-usage-errors ===

=== AC args-options-after-file-exit ===
Intent: An option placed after the file is rejected by the executable with the usage-error exit status and no standard output.

import csv
import os
import tempfile
from drydock_go import cli_runner

with tempfile.TemporaryDirectory() as workdir:
    path = os.path.join(workdir, "data.csv")
    with open(path, "w", newline="", encoding="utf-8") as handle:
        writer = csv.writer(handle, lineterminator="\n")
        writer.writerow(["a", "b"])
        writer.writerow(["1", "2"])
    code, out, err = cli_runner(path, "--column", "a")
    print(code, out, err)
    assert code == 2
    assert out == ""
=== END AC args-options-after-file-exit ===

## User Acceptance

- None.

## Guardrails

- Options precede the file; exactly one file is required.
- A parse failure writes nothing to standard output.
- Use a local `flag.FlagSet` with `flag.ContinueOnError`; never the global flag set.
````
</pblock>

<pblock filename="FEATURE-InputRejection.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/CsvStat/runs/20261025.051314/workspace/targets/CsvStat/blueprint/FEATURE-InputRejection.md" guidance="Feature Specification">
```markdown
# FEATURE: Input Rejection

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | Reject empty files, blank-only files, empty or repeated header names, and ragged records with exit 3. |
| Depends On  | FEATURE-Trimming.md, FEATURE-CsvReading.md, FEATURE-Arguments.md |
| Provides    | csvdata.ErrRejected |
| Consumes    | csvdata.Read, cli.ParseArgs |

## Purpose

Malformed input must never produce partial output. Rejection is detected in `internal/csvdata`
and mapped to exit code 3 by `internal/cli`.

## Behavior

- `csvdata` exposes a rejection error type (sentinel or typed error matched with `errors.Is` /
  `errors.As`) named `ErrRejected`. For a ragged record it carries the 1-based line number.
- The file is rejected when:
  - it is empty (zero bytes);
  - it contains only blank lines;
  - any header name is empty after trimming;
  - any header name repeats (compared exactly after trimming);
  - any record has a different number of fields from the header.
- A header-only file is valid and yields zero data records.
- A trailing line ending after the last record creates no extra record.
- `cli.Run` reads the file named by the parsed arguments. On a rejection error it writes nothing
  to standard output, writes one diagnostic line to standard error naming the file (and the line
  number for a ragged record), and returns exit code 3.
- A CSV syntax error from `encoding/csv` (for example a bare quote) is also a rejection, exit 3.

## Tests the build must write

In `internal/csvdata`:

- `TestRejectEmptyFile`
- `TestRejectBlankLinesOnly`
- `TestRejectEmptyHeaderName`
- `TestRejectRepeatedHeaderName`
- `TestRejectRaggedRecord`
- `TestHeaderOnlyFileAccepted`
- `TestTrailingNewlineAddsNoRecord`

## Programmatic Acceptance

=== AC reject-unit-empty-and-blank ===
Intent: Empty files and files of only blank lines are rejected by the reader.
Requires: executable=go; scope=test

from drydock_go import run_test

for name in ("TestRejectEmptyFile", "TestRejectBlankLinesOnly"):
    result = run_test("./internal/csvdata", name)
    print(result.stdout)
    print(result.stderr)
    assert result.passed, (name, result.status, result.stdout, result.stderr)
=== END AC reject-unit-empty-and-blank ===

=== AC reject-unit-headers ===
Intent: Empty and repeated header names are rejected by the reader.
Requires: executable=go; scope=test

from drydock_go import run_test

for name in ("TestRejectEmptyHeaderName", "TestRejectRepeatedHeaderName"):
    result = run_test("./internal/csvdata", name)
    print(result.stdout)
    print(result.stderr)
    assert result.passed, (name, result.status, result.stdout, result.stderr)
=== END AC reject-unit-headers ===

=== AC reject-unit-ragged-and-valid ===
Intent: Ragged records are rejected while header-only and newline-terminated files are accepted.
Requires: executable=go; scope=test

from drydock_go import run_test

for name in (
    "TestRejectRaggedRecord",
    "TestHeaderOnlyFileAccepted",
    "TestTrailingNewlineAddsNoRecord",
):
    result = run_test("./internal/csvdata", name)
    print(result.stdout)
    print(result.stderr)
    assert result.passed, (name, result.status, result.stdout, result.stderr)
=== END AC reject-unit-ragged-and-valid ===

=== AC reject-cli-ragged ===
Intent: The executable exits 3 with empty standard output for a ragged record.
Requires: executable=go; scope=test

import os
import tempfile

from drydock_go import cli_runner

with tempfile.TemporaryDirectory() as tmp:
    path = os.path.join(tmp, "ragged.csv")
    with open(path, "w", newline="") as handle:
        handle.write("a,b\n1,2\n3,4,5\n6,7\n")
    code, out, err = cli_runner(path)
print(out)
print(err)
assert code == 3, (code, out, err)
assert out == "", out
=== END AC reject-cli-ragged ===

=== AC reject-cli-empty-file ===
Intent: The executable exits 3 with empty standard output for a zero-byte file.
Requires: executable=go; scope=test

import os
import tempfile

from drydock_go import cli_runner

with tempfile.TemporaryDirectory() as tmp:
    path = os.path.join(tmp, "empty.csv")
    with open(path, "w", newline="") as handle:
        handle.write("")
    code, out, err = cli_runner(path)
print(out)
print(err)
assert code == 3, (code, out, err)
assert out == "", out
=== END AC reject-cli-empty-file ===

=== AC reject-cli-blank-lines-only ===
Intent: The executable exits 3 with empty standard output for a file holding only blank lines.
Requires: executable=go; scope=test

import os
import tempfile

from drydock_go import cli_runner

with tempfile.TemporaryDirectory() as tmp:
    path = os.path.join(tmp, "blank.csv")
    with open(path, "w", newline="") as handle:
        handle.write("\n\n\n")
    code, out, err = cli_runner(path)
print(out)
print(err)
assert code == 3, (code, out, err)
assert out == "", out
=== END AC reject-cli-blank-lines-only ===

=== AC reject-cli-repeated-header ===
Intent: The executable exits 3 with empty standard output when a header name repeats.
Requires: executable=go; scope=test

import csv
import os
import tempfile

from drydock_go import cli_runner

with tempfile.TemporaryDirectory() as tmp:
    path = os.path.join(tmp, "dup.csv")
    with open(path, "w", newline="") as handle:
        writer = csv.writer(handle, lineterminator="\n")
        writer.writerow(["id", "name", "id"])
        writer.writerow(["1", "x", "2"])
    code, out, err = cli_runner(path)
print(out)
print(err)
assert code == 3, (code, out, err)
assert out == "", out
=== END AC reject-cli-repeated-header ===

=== AC reject-cli-empty-header-name ===
Intent: The executable exits 3 with empty standard output when a header name is empty.
Requires: executable=go; scope=test

import csv
import os
import tempfile

from drydock_go import cli_runner

with tempfile.TemporaryDirectory() as tmp:
    path = os.path.join(tmp, "emptyname.csv")
    with open(path, "w", newline="") as handle:
        writer = csv.writer(handle, lineterminator="\n")
        writer.writerow(["id", "", "name"])
        writer.writerow(["1", "x", "y"])
    code, out, err = cli_runner(path)
print(out)
print(err)
assert code == 3, (code, out, err)
assert out == "", out
=== END AC reject-cli-empty-header-name ===

## User Acceptance

- None.

## Guardrails

- A rejected command never writes anything to standard output.
- The diagnostic goes to standard error only and is never part of any contract.
- Rejection logic lives in `internal/csvdata`; `internal/cli` only maps it to exit 3.
- Only the standard library is used; supplied files under `sources/` are never modified.
```
</pblock>

<pblock label="Build instructions" kind="instructions">
### Build instructions for this block

#### Build the csvstat executable from the module root with a thin main over cli.Run. (executable)
Implement cmd/csvstat/main.go, which calls cli.Run(os.Args[1:], os.Stdout, os.Stderr) and passes
the result to os.Exit. Implement a minimal internal/cli.Run that returns 0 so the module builds
with go build ./cmd/csvstat using only the standard library.

#### Read UTF-8 RFC 4180 CSV with the first record as header. (csv-reading)
In internal/csvdata, read a file with encoding/csv (FieldsPerRecord = -1 so raggedness is judged
by this package, LazyQuotes off). Return header and data records. A quoted field containing a
comma is one value. A line ending after the last record creates no extra record. Record the source
line number of each record for diagnostics.

#### Trim leading and trailing spaces from every header name and value. (value-trimming)
After reading, trim spaces from every header name and every value before any other rule applies.
Trim spaces only (not other whitespace classes beyond what the source states).

#### Recognise null spellings: empty, NA, N/A, NULL ignoring case. (null-values)
Implement IsNull on a trimmed value. A quoted empty field is empty and null. A value of only
spaces becomes empty after trimming and is null.

#### Infer integer and number column types. (numeric-types)
In internal/profile, a column is integer when every non-null value matches -?[0-9]+, and number
when every non-null value matches -?[0-9]+(\.[0-9]+)?. Integer is tested first. Use anchored
regular expressions or hand-written scanners; no float parsing for classification.

#### Infer date columns of real YYYY-MM-DD calendar dates. (date-type)
A column is date when every non-null value matches YYYY-MM-DD and is a real calendar date
(2025-02-30 is not). Validate with time.Parse using layout 2006-01-02 plus a digit-shape check.

#### Infer boolean, text, and empty column types. (boolean-text-types)
Boolean when every non-null value equals true or false ignoring case. Text is the fallback. A
column with no non-null value is empty. The full order is integer, number, date, boolean, text.

#### Parse options and exactly one file argument, with options preceding the file. (args-parsing)
In internal/cli, parse args with a local flag.FlagSet using flag.ContinueOnError and output
discarded. Recognise --column <name>, --freq <name>, --top <n>, then exactly one positional file.
Return a typed Options value (Column, Freq, Top, TopSet, File) or a usage error. Validation of
combinations belongs to the usage-errors story.

#### Reject empty files, empty or repeated header names, and ragged records. (input-rejection)
Return a rejection error (carrying the line number for a ragged record) for: an empty file, a
file with only blank lines, an empty header name, a repeated header name, or any record whose
field count differs from the header. A header-only file is valid and has zero rows. The cli layer
maps this error to exit 3.

</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:

- `compass` — the Target's COMPASS.md orientation.
- `implements` — the Typed Specification files this step builds. These are
  authoritative; implement them exactly.
- `context` — read-only support specifications. Do not reimplement them.
- `stack` — enterprise stack and technology rules. Honor them.
- `rules` — governance and branding rules. Honor them.

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.
2. 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.
3. Implement only this step. Use `context`, `stack`, and `rules` as constraints,
   not as additional work to perform.
4. Follow the stack and rules for languages, structure, naming, and branding.
5. 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.
6. 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.
7. Treat `User Acceptance` entries as review evidence requirements. Implement
   the supporting behavior, but do not claim to have performed human judgment.
8. 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.
9. 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.
10. 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`.
11. 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.
12. 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.
13. End your response with this exact closing structure:

```text
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:

```text
<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.

14. `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.
15. 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.

```text
FAILURE_SUMMARY: <one line naming the cause>
FAILURE_DETAIL: <what happened, why, and what to change before rerunning>
```

16. 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:

```text
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.

