Run artifact

evidence/prompts/20261025.054944.501Z_csvstat_build_claude.prompt.md

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.

  1. Input Context — begins with the heading # Input Context. All blocks are wrapped in

<pblock> tags. Two block types:

guidance attribute carries context-specific instructions; content is in a fenced block.

rules, instructions, or group headers.

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

</pblock>

<pblock label="Stories in this block" kind="section">

Stories in this block

</pblock>

<pblock label="Files on disk" kind="section">

Files on disk in the build directory

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

# 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-UsageErrors.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/CsvStat/runs/20261025.051314/workspace/targets/CsvStat/blueprint/FEATURE-UsageErrors.md" guidance="Feature Specification">

# FEATURE: Usage Errors

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | Reject malformed command-line arguments with exit status 2 and a single usage line on standard error. |
| Depends On  | FEATURE-Arguments.md |
| Provides    | exit code 2 |
| Consumes    | cli.ParseArgs |

## Purpose

Malformed invocations exit 2, write nothing to standard output, and write one diagnostic line to
standard error that shows the two command forms:

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

## Behavior

Exit 2 for each of:

- no file argument
- more than one file argument
- an unknown option
- an option given without its value
- `--top` that is not a positive integer (zero, negative, or non-numeric)
- `--top` without `--freq`
- `--column` together with `--freq`
- a repeated option

Usage errors are decided from the arguments alone, before the file is opened, and exit 2 even when
the file exists and is valid.

## Programmatic Acceptance

=== AC usage-errors-exit-two ===
Intent: Every malformed argument form exits 2 and writes nothing to standard output.
Requires: executable=go; scope=test

import csv
import os
import tempfile
from drydock_go import cli_runner

rows = [["qty", "sensor"], ["1", "east"], ["2", "west"]]
with tempfile.TemporaryDirectory() as d:
    path = os.path.join(d, "in.csv")
    other = os.path.join(d, "other.csv")
    for p in (path, other):
        with open(p, "w", newline="", encoding="utf-8") as f:
            csv.writer(f, lineterminator="\n").writerows(rows)
    cases = [
        [],
        [path, other],
        ["--frobnicate", path],
        ["--column"],
        ["--freq"],
        ["--freq", "sensor", "--top"],
        ["--freq", "sensor", "--top", "0", path],
        ["--freq", "sensor", "--top", "-1", path],
        ["--freq", "sensor", "--top", "abc", path],
        ["--top", "3", path],
        ["--column", "qty", "--freq", "qty", path],
    ]
    for args in cases:
        code, out, err = cli_runner(*args)
        print(args, code)
        print(err)
        assert code == 2, (args, code)
        assert out == "", (args, out)
=== END AC usage-errors-exit-two ===

=== AC usage-errors-single-stderr-line ===
Intent: A usage error writes exactly one non-blank diagnostic line to standard error.
Requires: executable=go; scope=test

from drydock_go import cli_runner

code, out, err = cli_runner()
print(err)
assert code == 2, code
assert out == ""
lines = [ln for ln in err.splitlines() if ln.strip()]
assert len(lines) == 1, lines
=== END AC usage-errors-single-stderr-line ===

=== AC usage-errors-before-file-open ===
Intent: A usage error is reported as 2 even when the named file does not exist.
Requires: executable=go; scope=test

import os
import tempfile
from drydock_go import cli_runner

with tempfile.TemporaryDirectory() as d:
    missing = os.path.join(d, "no-such-file.csv")
    code, out, err = cli_runner("--top", "3", missing)
print(err)
assert code == 2, code
assert out == ""
=== END AC usage-errors-before-file-open ===

=== AC usage-errors-valid-forms-accepted ===
Intent: Well-formed invocations are not rejected as usage errors.
Requires: executable=go; scope=test

import csv
import os
import tempfile
from drydock_go import cli_runner

rows = [["qty", "sensor"], ["1", "east"], ["2", "west"]]
with tempfile.TemporaryDirectory() as d:
    path = os.path.join(d, "in.csv")
    with open(path, "w", newline="", encoding="utf-8") as f:
        csv.writer(f, lineterminator="\n").writerows(rows)
    for args in ([path], ["--column", "qty", path], ["--freq", "sensor", path],
                 ["--freq", "sensor", "--top", "2", path]):
        code, out, err = cli_runner(*args)
        print(args, code)
        print(err)
        assert code == 0, (args, code)
=== END AC usage-errors-valid-forms-accepted ===

## User Acceptance

- None.

## Guardrails

- A usage error never writes to standard output.
- Usage errors never depend on the contents of the file.

</pblock>

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

# FEATURE: Column Profile

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | Profile a single named column when --column is given. |
| Depends On  | FEATURE-ProfileOutput.md, FEATURE-UsageErrors.md |
| Provides    | csvstat --column |
| Consumes    | csvstat <file>, exit code 2 |

## Purpose

`csvstat --column <name> <file>` writes the profile header and only the row for the named column.

## Behavior

- The output has the same header and the same row content for that column as the full profile.
- The name is matched exactly and case-sensitively against the trimmed header.
- A name not present in the header exits 3 with empty standard output.
- Rejected input (ragged, empty, bad header) exits 3 with empty standard output.
- `--column` combined with `--freq` is a usage error (exit 2), owned by the usage-errors story.

## Programmatic Acceptance

=== AC column-profile-single-row ===
Intent: --column writes the profile header and exactly one row, equal to that column's row in the full profile.
Requires: executable=go; scope=test

import csv
import io
import os
import tempfile
from drydock_go import cli_runner

rows = [["id", "price", "label"], ["1", "1.50", "a"], ["2", "2.25", "b"], ["4", "3.00", "c"]]
with tempfile.TemporaryDirectory() as d:
    path = os.path.join(d, "in.csv")
    with open(path, "w", newline="", encoding="utf-8") as f:
        csv.writer(f, lineterminator="\n").writerows(rows)
    code_all, out_all, err_all = cli_runner(path)
    assert code_all == 0, code_all
    full = list(csv.reader(io.StringIO(out_all)))
    for name in rows[0]:
        code, out, err = cli_runner("--column", name, path)
        print(out)
        print(err)
        assert code == 0, code
        parsed = list(csv.reader(io.StringIO(out)))
        assert parsed[0] == full[0]
        assert len(parsed) == 2
        assert parsed[1][0] == name
        assert parsed[1] == [r for r in full[1:] if r[0] == name][0]
=== END AC column-profile-single-row ===

=== AC column-profile-trimmed-header ===
Intent: A padded header name is trimmed, so the trimmed name selects the column and is reported.
Requires: executable=go; scope=test

import csv
import io
import os
import tempfile
from drydock_go import cli_runner

padded = "  qty "
rows = [[padded, "other"], ["1", "x"], ["2", "y"]]
with tempfile.TemporaryDirectory() as d:
    path = os.path.join(d, "in.csv")
    with open(path, "w", newline="", encoding="utf-8") as f:
        csv.writer(f, lineterminator="\n").writerows(rows)
    code, out, err = cli_runner("--column", padded.strip(), path)
print(out)
print(err)
assert code == 0, code
parsed = list(csv.reader(io.StringIO(out)))
assert len(parsed) == 2
assert parsed[1][0] == padded.strip()
assert parsed[1][1] == "integer"
=== END AC column-profile-trimmed-header ===

=== AC column-profile-unknown-column ===
Intent: A column name absent from the header exits 3 with empty standard output.
Requires: executable=go; scope=test

import csv
import os
import tempfile
from drydock_go import cli_runner

rows = [["qty", "price"], ["1", "1.50"]]
with tempfile.TemporaryDirectory() as d:
    path = os.path.join(d, "in.csv")
    with open(path, "w", newline="", encoding="utf-8") as f:
        csv.writer(f, lineterminator="\n").writerows(rows)
    code, out, err = cli_runner("--column", "nosuch", path)
print(err)
assert code == 3, code
assert out == ""
=== END AC column-profile-unknown-column ===

=== AC column-profile-case-sensitive ===
Intent: Column names match case-sensitively, so a different case is an unknown column.
Requires: executable=go; scope=test

import csv
import os
import tempfile
from drydock_go import cli_runner

name = "qty"
rows = [[name, "price"], ["1", "1.50"]]
with tempfile.TemporaryDirectory() as d:
    path = os.path.join(d, "in.csv")
    with open(path, "w", newline="", encoding="utf-8") as f:
        csv.writer(f, lineterminator="\n").writerows(rows)
    code, out, err = cli_runner("--column", name.upper(), path)
print(err)
assert code == 3, code
assert out == ""
=== END AC column-profile-case-sensitive ===

=== AC column-profile-rejected-input ===
Intent: A ragged file with --column exits 3 and writes nothing to standard output.
Requires: executable=go; scope=test

import csv
import os
import tempfile
from drydock_go import cli_runner

rows = [["a", "b"], ["1", "2"], ["3", "4", "5"]]
with tempfile.TemporaryDirectory() as d:
    path = os.path.join(d, "ragged.csv")
    with open(path, "w", newline="", encoding="utf-8") as f:
        csv.writer(f, lineterminator="\n").writerows(rows)
    code, out, err = cli_runner("--column", "a", path)
print(err)
assert code == 3, code
assert out == ""
=== END AC column-profile-rejected-input ===

## User Acceptance

- None.

## Guardrails

- Standard output stays empty whenever the command fails.
- Column names are never matched case-insensitively.

</pblock>

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

# FEATURE: Failure Diagnostics

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | Ensures every failing csvstat command writes nothing to standard output and exactly one diagnostic line to standard error. |
| Depends On  | FEATURE-InputRejection.md, FEATURE-UsageErrors.md, FEATURE-ProfileOutput.md |
| Provides    | stderr diagnostics, exit code 3 |
| Consumes    | csvdata.ErrRejected, cli.Run |

## Purpose

A command that fails reports the failure on standard error as one line and leaves standard output empty. Rejected input exits 3. The diagnostic names the file and, for a rejected record, its line number. Standard error is never compared by the grader, so its wording is free; its shape (one line, nothing on standard output) is the contract.

## Behavior

- Rejected input (empty file, file containing only blank lines, empty header name, repeated header name, ragged record) exits 3.
- Standard output is written only after the whole result is built, so no partial output precedes a failure.
- Exactly one non-blank line is written to standard error per failure.
- A ragged record's diagnostic includes the line number of the offending record.
- Exit code 1 (unreadable file) and exit code 2 (usage) share the same stdout-empty, one-line-stderr rule and are owned by their own stories.

## Programmatic Acceptance

=== AC diag-ragged-fixture ===
Intent: The supplied ragged fixture exits 3, writes nothing to standard output, and writes one diagnostic line.
Requires: executable=go; scope=test

from drydock_go import cli_runner

code, out, err = cli_runner("sources/ragged.csv")
print(out)
print(err)
assert code == 3, code
assert out == "", out
lines = [ln for ln in err.splitlines() if ln.strip()]
assert len(lines) == 1, lines
=== END AC diag-ragged-fixture ===

=== AC diag-ragged-line-number ===
Intent: The diagnostic for a ragged record carries the number of the line holding that record.
Requires: executable=go; scope=test

import csv
import os
import re
import tempfile
from drydock_go import cli_runner

rows = [["a", "b"], ["1", "2"], ["3", "4"], ["5", "6", "7"], ["8", "9"]]
bad_line = 4
with tempfile.TemporaryDirectory() as tmp:
    path = os.path.join(tmp, "ragged_case.csv")
    with open(path, "w", newline="", encoding="utf-8") as fh:
        csv.writer(fh, lineterminator="\n").writerows(rows)
    code, out, err = cli_runner(path)
print(out)
print(err)
assert code == 3, code
assert out == "", out
assert str(bad_line) in re.findall(r"\d+", err), err
=== END AC diag-ragged-line-number ===

=== AC diag-empty-file ===
Intent: An empty file is rejected with exit 3 and nothing on standard output.
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", encoding="utf-8") as fh:
        fh.write("")
    code, out, err = cli_runner(path)
print(out)
print(err)
assert code == 3, code
assert out == "", out
lines = [ln for ln in err.splitlines() if ln.strip()]
assert len(lines) == 1, lines
=== END AC diag-empty-file ===

=== AC diag-blank-lines-only ===
Intent: A file containing only blank lines is rejected as empty with exit 3.
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", encoding="utf-8", newline="") as fh:
        fh.write("\n\n\n")
    code, out, err = cli_runner(path)
print(out)
print(err)
assert code == 3, code
assert out == "", out
=== END AC diag-blank-lines-only ===

=== AC diag-empty-header-name ===
Intent: An empty header name is rejected with exit 3 and nothing on standard output.
Requires: executable=go; scope=test

import csv
import os
import tempfile
from drydock_go import cli_runner

rows = [["a", "", "c"], ["1", "2", "3"]]
with tempfile.TemporaryDirectory() as tmp:
    path = os.path.join(tmp, "emptyname.csv")
    with open(path, "w", newline="", encoding="utf-8") as fh:
        csv.writer(fh, lineterminator="\n").writerows(rows)
    code, out, err = cli_runner(path)
print(out)
print(err)
assert code == 3, code
assert out == "", out
=== END AC diag-empty-header-name ===

=== AC diag-repeated-header-name ===
Intent: A repeated header name, including one repeated only after trimming, is rejected with exit 3.
Requires: executable=go; scope=test

import csv
import os
import tempfile
from drydock_go import cli_runner

name = "dup"
rows = [[name, "x", "  " + name + "  "], ["1", "2", "3"]]
with tempfile.TemporaryDirectory() as tmp:
    path = os.path.join(tmp, "repeated.csv")
    with open(path, "w", newline="", encoding="utf-8") as fh:
        csv.writer(fh, lineterminator="\n").writerows(rows)
    code, out, err = cli_runner(path)
print(out)
print(err)
assert code == 3, code
assert out == "", out
=== END AC diag-repeated-header-name ===

=== AC diag-failure-with-column-option ===
Intent: A rejected file under --column still exits 3 with nothing on standard output.
Requires: executable=go; scope=test

from drydock_go import cli_runner

code, out, err = cli_runner("--column", "sku", "sources/ragged.csv")
print(out)
print(err)
assert code == 3, code
assert out == "", out
=== END AC diag-failure-with-column-option ===

## User Acceptance

- None.

## Guardrails

- A failing command never writes a partial profile or frequency listing to standard output.
- Diagnostics go to standard error only and are never compared by the grader.
- Rejected files are never modified.

</pblock>

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

# FEATURE: Unreadable File

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | Exits 1 with an empty standard output when the named file cannot be opened or read. |
| Depends On  | FEATURE-FailureDiagnostics.md |
| Provides    | exit code 1 |
| Consumes    | cli.Run, csvdata.Read |

## Purpose

Exit code 1 is the operational-failure code. It is used when the file named on the command line does not exist, is not permitted to be read, or fails while being read. It is distinct from exit 3, which means the file was read but its content was rejected.

## Behavior

- An open or read error from the operating system maps to exit 1, not exit 3.
- Standard output stays empty.
- One diagnostic line naming the file is written to standard error.
- This applies to every invocation form: profile, `--column`, and `--freq`.
- Usage errors (exit 2) take precedence over file access, because argument parsing completes before the file is opened.

## Programmatic Acceptance

=== AC unreadable-missing-file ===
Intent: A path that does not exist exits 1 and writes nothing to standard output.
Requires: executable=go; scope=test

import os
import tempfile
from drydock_go import cli_runner

with tempfile.TemporaryDirectory() as tmp:
    missing = os.path.join(tmp, "no-such-file.csv")
    assert not os.path.exists(missing)
    code, out, err = cli_runner(missing)
print(out)
print(err)
assert code == 1, code
assert out == "", out
lines = [ln for ln in err.splitlines() if ln.strip()]
assert len(lines) == 1, lines
=== END AC unreadable-missing-file ===

=== AC unreadable-missing-file-freq ===
Intent: A missing file under --freq also exits 1 with nothing on standard output.
Requires: executable=go; scope=test

import os
import tempfile
from drydock_go import cli_runner

with tempfile.TemporaryDirectory() as tmp:
    missing = os.path.join(tmp, "absent.csv")
    code, out, err = cli_runner("--freq", "anything", missing)
print(out)
print(err)
assert code == 1, code
assert out == "", out
=== END AC unreadable-missing-file-freq ===

=== AC unreadable-missing-file-column ===
Intent: A missing file under --column also exits 1 with nothing on standard output.
Requires: executable=go; scope=test

import os
import tempfile
from drydock_go import cli_runner

with tempfile.TemporaryDirectory() as tmp:
    missing = os.path.join(tmp, "absent.csv")
    code, out, err = cli_runner("--column", "anything", missing)
print(out)
print(err)
assert code == 1, code
assert out == "", out
=== END AC unreadable-missing-file-column ===

=== AC unreadable-directory-as-file ===
Intent: A directory named as the file cannot be read and exits 1 with nothing on standard output.
Requires: executable=go; scope=test

import tempfile
from drydock_go import cli_runner

with tempfile.TemporaryDirectory() as tmp:
    code, out, err = cli_runner(tmp)
print(out)
print(err)
assert code == 1, code
assert out == "", out
=== END AC unreadable-directory-as-file ===

=== AC unreadable-readable-file-still-succeeds ===
Intent: A readable fixture is not treated as unreadable and exits 0.
Requires: executable=go; scope=test

from drydock_go import cli_runner

code, out, err = cli_runner("sources/header_only.csv")
print(out)
print(err)
assert code == 0, code
assert out != ""
=== END AC unreadable-readable-file-still-succeeds ===

## User Acceptance

- None.

## Guardrails

- Exit 1 is reserved for files that cannot be opened or read; rejected content is exit 3.
- A failing command writes nothing to standard output.

</pblock>

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

# FEATURE: Frequency Mode

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | Dispatches `csvstat --freq <name> [--top <n>] <file>` to the frequency listing instead of the profile. |
| Depends On  | FEATURE-FreqLimit.md, FEATURE-UsageErrors.md |
| Provides    | csvstat --freq, csvstat --freq --top |
| Consumes    | freq.Count, freq.Top, cli.ParseArgs |

## Purpose

When `--freq <name>` is given, `cli.Run` writes the frequency listing for that column and never the profile. `--top <n>` limits the rows and defaults to 5. The listing is CSV with header `value,count`, rows ordered by count descending and then value ascending by byte value, using trimmed non-null values only.

## Behavior

- The column name is matched exactly and case-sensitively against the trimmed header.
- A column name absent from the header exits 3 with nothing on standard output and one diagnostic line on standard error.
- Combinations that are usage errors (`--column` with `--freq`, `--top` without `--freq`, a non-positive `--top`) are rejected with exit 2 by the usage-errors story before this dispatch runs.
- Output is built in memory and written to standard output only on success, so a failing command writes nothing to standard output.
- A column with no non-null values writes only the header.

## Programmatic Acceptance

=== AC freq-default-matches-fixture ===
Intent: The default frequency listing for a named column equals the top five counts computed independently from the fixture.
Requires: executable=go; scope=test

import csv
import io
from collections import Counter
from drydock_go import cli_runner

path = "sources/employees.csv"
column = "department"
with open(path, newline="", encoding="utf-8") as fh:
    records = list(csv.reader(fh))
header = [h.strip() for h in records[0]]
idx = header.index(column)
values = [r[idx].strip() for r in records[1:] if r[idx].strip() != ""]
counts = Counter(values)
ordered = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0].encode("utf-8")))
expected = [[v, str(c)] for v, c in ordered][:5]

code, out, err = cli_runner("--freq", column, path)
print(out)
print(err)
assert code == 0, code
rows = list(csv.reader(io.StringIO(out)))
assert rows[0] == ["value", "count"], rows[0]
assert rows[1:] == expected, (rows[1:], expected)
=== END AC freq-default-matches-fixture ===

=== AC freq-top-limits-rows ===
Intent: With --top 2 exactly the first two ordered rows are listed.
Requires: executable=go; scope=test

import csv
import io
from collections import Counter
from drydock_go import cli_runner

path = "sources/sensors.csv"
column = "sensor"
top = 2
with open(path, newline="", encoding="utf-8") as fh:
    records = list(csv.reader(fh))
header = [h.strip() for h in records[0]]
idx = header.index(column)
values = [r[idx].strip() for r in records[1:] if r[idx].strip() != ""]
counts = Counter(values)
ordered = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0].encode("utf-8")))
expected = [[v, str(c)] for v, c in ordered][:top]

code, out, err = cli_runner("--freq", column, "--top", str(top), path)
print(out)
print(err)
assert code == 0, code
rows = list(csv.reader(io.StringIO(out)))
assert len(rows) - 1 == top, rows
assert rows[1:] == expected, (rows[1:], expected)
=== END AC freq-top-limits-rows ===

=== AC freq-omits-null-spellings ===
Intent: Null values (empty, NA, N/A, NULL in any case) are not listed in a frequency listing.
Requires: executable=go; scope=test

import csv
import io
from collections import Counter
from drydock_go import cli_runner

path = "sources/employees.csv"
column = "manager_id"
top = 3
nulls = {"", "na", "n/a", "null"}
with open(path, newline="", encoding="utf-8") as fh:
    records = list(csv.reader(fh))
header = [h.strip() for h in records[0]]
idx = header.index(column)
values = [r[idx].strip() for r in records[1:] if r[idx].strip().lower() not in nulls]
counts = Counter(values)
ordered = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0].encode("utf-8")))
expected = [[v, str(c)] for v, c in ordered][:top]

code, out, err = cli_runner("--freq", column, "--top", str(top), path)
print(out)
print(err)
assert code == 0, code
rows = list(csv.reader(io.StringIO(out)))
listed = {r[0].lower() for r in rows[1:]}
assert listed.isdisjoint(nulls), listed
assert rows[1:] == expected, (rows[1:], expected)
=== END AC freq-omits-null-spellings ===

=== AC freq-values-are-trimmed ===
Intent: Padded values are trimmed before counting, so padded and unpadded spellings count together.
Requires: executable=go; scope=test

import csv
import io
from collections import Counter
from drydock_go import cli_runner

path = "sources/orders.csv"
column = "customer"
with open(path, newline="", encoding="utf-8") as fh:
    records = list(csv.reader(fh))
header = [h.strip() for h in records[0]]
idx = header.index(column)
values = [r[idx].strip() for r in records[1:] if r[idx].strip() != ""]
counts = Counter(values)
ordered = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0].encode("utf-8")))
expected = [[v, str(c)] for v, c in ordered][:5]

code, out, err = cli_runner("--freq", column, path)
print(out)
print(err)
assert code == 0, code
rows = list(csv.reader(io.StringIO(out)))
assert rows[1:] == expected, (rows[1:], expected)
=== END AC freq-values-are-trimmed ===

=== AC freq-all-null-column-header-only ===
Intent: A column with no non-null values lists only the header.
Requires: executable=go; scope=test

import csv
import io
from drydock_go import cli_runner

code, out, err = cli_runner("--freq", "battery", "sources/sensors.csv")
print(out)
print(err)
assert code == 0, code
rows = list(csv.reader(io.StringIO(out)))
assert rows == [["value", "count"]], rows
=== END AC freq-all-null-column-header-only ===

=== AC freq-unknown-column-rejected ===
Intent: A column name absent from the header exits 3 and writes nothing to standard output.
Requires: executable=go; scope=test

from drydock_go import cli_runner

code, out, err = cli_runner("--freq", "nosuch", "sources/orders.csv")
print(out)
print(err)
assert code == 3, code
assert out == "", out
=== END AC freq-unknown-column-rejected ===

=== AC freq-name-is-case-sensitive ===
Intent: A column name differing only in case from a header name is not found and exits 3.
Requires: executable=go; scope=test

import csv
from drydock_go import cli_runner

path = "sources/employees.csv"
with open(path, newline="", encoding="utf-8") as fh:
    header = [h.strip() for h in next(csv.reader(fh))]
name = header[2]
swapped = name.upper() if name != name.upper() else name.lower()
assert swapped not in header

code, out, err = cli_runner("--freq", swapped, path)
print(out)
print(err)
assert code == 3, code
assert out == "", out
=== END AC freq-name-is-case-sensitive ===

## User Acceptance

- None.

## Guardrails

- Frequency mode never writes the profile header or any profile row.
- Application code never reads `sources/run.sh` or embeds a count or value list; every row comes from the file examined.
- A failing command writes nothing to standard output.

</pblock>

<pblock label="Build instructions" kind="instructions">

Build instructions for this block

Reject malformed arguments with exit 2 and a usage line on standard error. (usage-errors)

Exit 2, with nothing on stdout, for: missing file, extra file, unknown option, missing option value, --top not a positive integer, --top without --freq, and --column with --freq. Write one stderr line showing both command forms.

Profile a single named column with --column. (column-profile)

Write the profile header and only the named column's row. A column name absent from the trimmed header exits 3 with nothing on stdout. Match names exactly and case-sensitively.

Write one stderr diagnostic line and nothing on stdout when a command fails. (failure-diagnostics)

Failures write one stderr line naming the file and, for a ragged record, its line number. Stdout stays empty on every failure. Exit 3 for rejected input.

Exit 1 when the file cannot be opened or read. (unreadable-file)

A missing or unreadable file exits 1 with nothing on stdout and one stderr line naming the file.

Select frequency mode with --freq. (freq-mode)

Dispatch to the frequency listing when --freq is given, honouring --top. A column name absent from the header exits 3 with nothing on stdout.

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

authoritative; implement them exactly.

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.

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

  1. Implement only this step. Use context, stack, and rules as constraints,

not as additional work to perform.

  1. Follow the stack and rules for languages, structure, naming, and branding.
  2. 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.

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

  1. Treat User Acceptance entries as review evidence requirements. Implement

the supporting behavior, but do not claim to have performed human judgment.

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

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

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

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

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

  1. End your response with this exact closing structure:
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:

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

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

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

FAILURE_SUMMARY: <one line naming the cause>
FAILURE_DETAIL: <what happened, why, and what to change before rerunning>
  1. 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:

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.