Run artifact

evidence/prompt_outputs/20261025.174154.969Z_dupfind_plan_claude.output.txt

=== BEGIN ARTIFACT ARCHITECTURE.md ===
# ARCHITECTURE: DupFind

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | Module layout, package boundaries, and pipeline of the dupfind command-line duplicate file finder. |
| Depends On  | None |
| Provides    | go.mod, internal/, cmd/dupfind, bin/ |

## Questions

- None.

## Overview

`dupfind` is a single-binary Go command-line tool. It finds regular files under a directory whose
contents are byte-for-byte identical, reports them as a CSV listing or a one-row CSV summary, and
never deletes, moves, or modifies any file.

Pipeline: parse arguments, validate the directory, walk, group by size, hash same-size groups with
SHA-256, order and number groups, emit CSV.

## Technology Stack

Derived from `TECHNOLOGY_STACK.md`; that file is the decision of record.

| Technology | Where it applies |
|---|---|
| Go 1.22 or newer, standard library only | All application code; `go.mod` declares no third-party requirement |
| go test and go vet | Test runner behind `bin/test.sh` |
| POSIX sh | `bin/test.sh` |

## Module Layout

| Path | Package | Responsibility |
|---|---|---|
| `go.mod` | module root | Module path and Go toolchain version; no `require` lines |
| `cmd/dupfind` | `main` | Calls `cli.Run(os.Args[1:], os.Stdout, os.Stderr)` and passes the result to `os.Exit`; the only caller of `os.Exit` |
| `internal/cli` | `cli` | `Run(args []string, stdout, stderr io.Writer) int`: argument parsing, directory validation, pipeline orchestration, exit codes |
| `internal/walk` | `walk` | Recursive directory walk yielding eligible regular files |
| `internal/dupes` | `dupes` | Size grouping, SHA-256 digest grouping, reclaimable bytes, ordering and numbering |
| `internal/report` | `report` | CSV listing and summary writers using `encoding/csv` |
| `bin/test.sh` | POSIX sh | Runs `go vet ./...` then `go test ./...` from the application root |

## Boundaries

- Only `main` calls `os.Exit`. `cli.Run` returns the exit code: 0 success, 1 operational failure, 2 usage error.
- Standard output carries only CSV. A failing command writes nothing to standard output and one diagnostic line to standard error.
- Warnings (unreadable file or subdirectory) go to standard error only and never change the exit code.
- File contents are read only by `dupes`, and only for files that share a size with another file.
- Files under the examined directory are opened read-only. Nothing is written, moved, or deleted there.
- Application code never reads `sources/run.sh` and never embeds a digest, path, or total.

## Module Ownership

| Boundary | Owning module | Allowed low-level APIs |
|---|---|---|
| Directory traversal and file metadata | `internal/walk` | `os.Lstat`, `os.ReadDir`, `io/fs` |
| File content reading and hashing | `internal/dupes` | `os.Open`, `crypto/sha256`, `io.Copy` |
| CSV output | `internal/report` | `encoding/csv` |
| Process arguments and exit codes | `internal/cli` and `cmd/dupfind` | `flag`, `os.Args`, `os.Exit` (main only) |
| Persistence, configuration files, external services | None; the tool has no persistent state | None |

## Foundation Scope

The foundation story creates `go.mod`, the package tree above, a `cmd/dupfind/main.go` that
delegates to `cli.Run`, and a minimal compiling placeholder in each internal package, so that
`go build ./cmd/dupfind`, `go vet ./...`, and `go test ./...` succeed before feature stories land.
The placeholder `Run` returns 0. `bin/` exists; `bin/test.sh` itself is delivered by the test-gate story.

## Programmatic Acceptance

=== AC arch-module-no-third-party ===
Intent: The application root is a Go module that declares no third-party requirement.

import pathlib

text = pathlib.Path("go.mod").read_text()
lines = [ln.strip() for ln in text.splitlines()]
module_lines = [ln for ln in lines if ln.startswith("module ")]
go_lines = [ln for ln in lines if ln.startswith("go ")]
assert len(module_lines) == 1, text
assert len(go_lines) == 1, text
assert "require" not in text, text
=== END AC arch-module-no-third-party ===

=== AC arch-package-tree ===
Intent: The package directories named by the architecture exist in the build tree.

import pathlib

for rel in ["cmd/dupfind", "internal/cli", "internal/walk", "internal/dupes", "internal/report", "bin"]:
    assert pathlib.Path(rel).is_dir(), rel
assert pathlib.Path("cmd/dupfind/main.go").is_file()
=== END AC arch-package-tree ===

=== AC arch-vet-and-build ===
Intent: The foundation compiles and passes go vet across every package.

import subprocess
import sys

for cmd in (["go", "vet", "./..."], ["go", "build", "./..."]):
    result = subprocess.run(cmd, capture_output=True, text=True)
    print(result.stdout)
    print(result.stderr, file=sys.stderr)
    assert result.returncode == 0, cmd
=== END AC arch-vet-and-build ===

## User Acceptance

- None.

## Guardrails

- Standard library only; no third-party modules.
- Never delete, move, or write a file under the directory examined.
- Do not modify, rewrite, regenerate, or substitute `sources/run.sh`, and never read it from application code.
- Do not hardcode a digest, a path, or a total; every value is computed from the directory examined.
- Read a file's contents only when another file has the same size.
=== END ARTIFACT ===
=== BEGIN ARTIFACT FEATURE-ArgParsing.md ===
# FEATURE: Arg Parsing

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | Parse --summary, --min-size, and exactly one directory argument, rejecting malformed usage with exit 2. |
| Depends On  | ARCHITECTURE.md |
| Provides    | cli.Run, cli.Config |

## Questions

- None.

## Purpose

`cli.Run(args []string, stdout, stderr io.Writer) int` in `internal/cli` interprets the command
line `dupfind [--summary] [--min-size <bytes>] <directory>` and produces a parsed configuration for
later stories.

## Behavior

- Parsing uses a local `flag.FlagSet` with `flag.ContinueOnError` and its own output discarded.
- `cli.Config` carries `Summary bool`, `MinSize int64`, and `Dir string`. `MinSize` defaults to 1.
- Options precede the directory. Exactly one directory argument is required.
- Usage errors return exit code 2, write nothing to stdout, and write exactly one diagnostic line to stderr. Usage errors are:
  - no arguments, or an option with no directory;
  - more than one positional argument, or an option placed after the directory (it counts as an extra argument);
  - an unknown option, including `-h` and `--help`;
  - `--min-size` with a missing value, or a value that is not a positive decimal integer.
- A `--min-size` value is accepted only when it consists solely of ASCII decimal digits, is at least 1, and fits in an `int64`. Signs (`+5`, `-5`), zero, hexadecimal, exponent forms, and overflow are usage errors.
- Argument errors take precedence over directory validation.

## Reads

None.

## Writes

Standard error only, on usage errors.

## Programmatic Acceptance

=== AC argparse-usage-errors-exit-2 ===
Intent: Every malformed command line exits 2 with empty standard output.

import os
import tempfile
from drydock_go import cli_runner

with tempfile.TemporaryDirectory() as d:
    other = os.path.join(d, "other")
    os.mkdir(other)
    bad = [
        [],
        ["--summary"],
        ["--min-size", "5"],
        [d, other],
        ["--frobnicate", d],
        ["-h", d],
        ["--min-size", "abc", d],
        ["--min-size", "0", d],
        ["--min-size", "-5", d],
        ["--min-size", "+5", d],
        ["--min-size", "0x10", d],
        ["--min-size", "1e3", d],
        ["--min-size", "99999999999999999999999", d],
        ["--min-size", d],
        [d, "--summary"],
    ]
    for args in bad:
        code, out, err = cli_runner(*args)
        print(args, code, repr(out), repr(err))
        assert code == 2, args
        assert out == "", args
=== END AC argparse-usage-errors-exit-2 ===

=== AC argparse-diagnostic-on-stderr ===
Intent: A usage error writes exactly one diagnostic line to standard error.

from drydock_go import cli_runner

code, out, err = cli_runner("--min-size", "0", ".")
print(code, repr(out), repr(err))
assert code == 2
assert out == ""
assert len(err.splitlines()) == 1
=== END AC argparse-diagnostic-on-stderr ===

=== AC argparse-valid-forms-not-usage-errors ===
Intent: Well-formed command lines are not rejected as usage errors.

import tempfile
from drydock_go import cli_runner

with tempfile.TemporaryDirectory() as d:
    valid = [
        [d],
        ["--summary", d],
        ["--min-size", "5", d],
        ["--summary", "--min-size", "5", d],
        ["--min-size", "5", "--summary", d],
    ]
    for args in valid:
        code, out, err = cli_runner(*args)
        print(args, code, repr(out), repr(err))
        assert code != 2, args
=== END AC argparse-valid-forms-not-usage-errors ===

## User Acceptance

- None.

## Guardrails

- Standard library only; parsing uses `flag` with `flag.ContinueOnError`.
- Only `main` calls `os.Exit`; `Run` returns the code.
- A failing command writes nothing to standard output.
- Never touch any file under the directory examined.
=== END ARTIFACT ===
=== BEGIN ARTIFACT FEATURE-ModuleBuild.md ===
# FEATURE: Module Build

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | The cmd/dupfind main package builds with go build using only the standard library and delegates to cli.Run. |
| Depends On  | ARCHITECTURE.md, FEATURE-ArgParsing.md |
| Provides    | cmd/dupfind |
| Consumes    | cli.Run |

## Questions

- None.

## Purpose

The application root is a Go module whose executable is the main package at `./cmd/dupfind`.
`go build ./cmd/dupfind` must succeed using only the standard library.

## Behavior

- `cmd/dupfind/main.go` is `package main`. `main` calls `cli.Run(os.Args[1:], os.Stdout, os.Stderr)` and passes the returned code to `os.Exit`.
- `main` contains no other logic and is the only caller of `os.Exit`.
- Every package in the build's dependency graph is either in the standard library or inside this module.

## Reads

Process arguments, standard output, standard error.

## Writes

None.

## Programmatic Acceptance

=== AC modbuild-go-build ===
Intent: go build ./cmd/dupfind succeeds and produces an executable.

import os
import subprocess
import sys
import tempfile

with tempfile.TemporaryDirectory() as d:
    out_path = os.path.join(d, "dupfind")
    result = subprocess.run(["go", "build", "-o", out_path, "./cmd/dupfind"], capture_output=True, text=True)
    print(result.stdout)
    print(result.stderr, file=sys.stderr)
    assert result.returncode == 0
    assert os.path.isfile(out_path)
=== END AC modbuild-go-build ===

=== AC modbuild-standard-library-only ===
Intent: The executable's dependency graph contains only standard library and in-module packages.

import pathlib
import subprocess
import sys

mod = ""
for line in pathlib.Path("go.mod").read_text().splitlines():
    if line.startswith("module "):
        mod = line.split()[1]
assert mod
result = subprocess.run(
    ["go", "list", "-deps", "-f", "{{if not .Standard}}{{.ImportPath}}{{end}}", "./cmd/dupfind"],
    capture_output=True, text=True,
)
print(result.stdout)
print(result.stderr, file=sys.stderr)
assert result.returncode == 0
for pkg in result.stdout.split():
    assert pkg == mod or pkg.startswith(mod + "/"), pkg
=== END AC modbuild-standard-library-only ===

=== AC modbuild-executable-runs ===
Intent: The built executable runs and rejects an empty command line with exit 2.

from drydock_go import cli_runner

code, out, err = cli_runner()
print(code, repr(out), repr(err))
assert code == 2
assert out == ""
=== END AC modbuild-executable-runs ===

## User Acceptance

- None.

## Guardrails

- Standard library only; no third-party modules.
- `main` never reads `sources/run.sh` and embeds no digest, path, or total.
- Only `main` calls `os.Exit`.
=== END ARTIFACT ===
=== BEGIN ARTIFACT FEATURE-DirectoryValidation.md ===
# FEATURE: Directory Validation

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | Exit 1 with empty standard output when the directory argument is missing or is not a directory. |
| Depends On  | ARCHITECTURE.md, FEATURE-ArgParsing.md |
| Provides    | cli.validateDirectory |
| Consumes    | cli.Config |

## Questions

- None.

## Purpose

After successful argument parsing, `cli.Run` checks that `Config.Dir` names an existing directory
before any walking or output.

## Behavior

- A nonexistent path, or a path that exists but is not a directory (for example a regular file), returns exit code 1.
- A failure writes nothing to stdout and exactly one diagnostic line to stderr.
- Validation runs after argument parsing and before the walk, so a usage error (exit 2) takes precedence over an operational failure (exit 1).
- An existing directory, empty or not, proceeds and the run succeeds with exit 0.
- The check uses `os.Stat`, so a symbolic link given as the directory argument that resolves to a directory is accepted.

## Reads

File metadata of the directory argument.

## Writes

Standard error only, on failure.

## Programmatic Acceptance

=== AC dirval-missing-directory ===
Intent: A nonexistent directory exits 1 with empty standard output and one stderr line.

import os
import tempfile
from drydock_go import cli_runner

with tempfile.TemporaryDirectory() as d:
    missing = os.path.join(d, "no-such-directory")
    for args in ([missing], ["--summary", missing], ["--min-size", "3", missing]):
        code, out, err = cli_runner(*args)
        print(args, code, repr(out), repr(err))
        assert code == 1, args
        assert out == "", args
        assert len(err.splitlines()) == 1, args
=== END AC dirval-missing-directory ===

=== AC dirval-not-a-directory ===
Intent: A regular file given as the directory exits 1 with empty standard output.

import os
import tempfile
from drydock_go import cli_runner

with tempfile.TemporaryDirectory() as d:
    path = os.path.join(d, "plain.txt")
    with open(path, "w") as fh:
        fh.write("content")
    for args in ([path], ["--summary", path]):
        code, out, err = cli_runner(*args)
        print(args, code, repr(out), repr(err))
        assert code == 1, args
        assert out == "", args
=== END AC dirval-not-a-directory ===

=== AC dirval-usage-precedes-validation ===
Intent: A usage error on a nonexistent directory still exits 2, not 1.

import os
import tempfile
from drydock_go import cli_runner

with tempfile.TemporaryDirectory() as d:
    missing = os.path.join(d, "no-such-directory")
    code, out, err = cli_runner("--min-size", "0", missing)
    print(code, repr(out), repr(err))
    assert code == 2
    assert out == ""
=== END AC dirval-usage-precedes-validation ===

=== AC dirval-existing-directory-succeeds ===
Intent: An existing empty directory is accepted and the run exits 0.

import tempfile
from drydock_go import cli_runner

with tempfile.TemporaryDirectory() as d:
    code, out, err = cli_runner(d)
    print(code, repr(out), repr(err))
    assert code == 0
=== END AC dirval-existing-directory-succeeds ===

## User Acceptance

- None.

## Guardrails

- A failing command writes nothing to standard output.
- Validation never creates, modifies, or removes anything on disk.
=== END ARTIFACT ===
=== BEGIN ARTIFACT FEATURE-Walk.md ===
# FEATURE: Walk

| Field       | Value |
|-------------|-------|
| Version     | 20261025 V1 |
| Description | Walk the directory recursively and yield eligible regular files at or above the minimum size. |
| Depends On  | ARCHITECTURE.md, FEATURE-DirectoryValidation.md |
| Provides    | walk.Files |
| Consumes    | cli.Config |

## Questions

- None.

## Purpose

`internal/walk` enumerates the files that may be considered for duplicate detection. It never opens
file contents.

## Interface

```go
package walk

type Entry struct {
	Path string // relative to root, "/" separated, no leading "./"
	Size int64
}

func Files(root string, minSize int64, warn io.Writer) ([]Entry, error)
```

## Behavior

- Traversal is recursive and includes hidden files and directories (names beginning `.`).
- Only regular files are returned. Entries are classified without following links (`os.Lstat` or the `fs.DirEntry` type).
- Symbolic links are neither followed nor reported, whether they point at files or directories. A directory reachable only through a symbolic link is not traversed.
- Files whose size is below `minSize` are ignored. Zero-byte files are never returned, even if `minSize` is below 1.
- Paths use `/` as the separator and no leading `./`.
- A subdirectory that cannot be read yields one warning line on `warn`, is skipped, and the walk continues. This does not change the exit code.
- Return order is unspecified; ordering is the responsibility of later stories.

## Reads

Directory listings and file metadata under the root.

## Writes

Warning lines on the `warn` writer only.

## Programmatic Acceptance

=== AC walk-rules ===
Intent: Walk returns hidden and nested regular files, omits symbolic links and zero-byte files, and honors the minimum size.

import os
import pathlib
import subprocess
import sys

mod = ""
for line in pathlib.Path("go.mod").read_text().splitlines():
    if line.startswith("module "):
        mod = line.split()[1]
assert mod

GO_TEST = """package walk_test

import (
	"io"
	"os"
	"path/filepath"
	"sort"
	"testing"

	"MODPATH/internal/walk"
)

func build(t *testing.T, files map[string]string) string {
	root := t.TempDir()
	for name, body := range files {
		p := filepath.Join(root, filepath.FromSlash(name))
		if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
			t.Fatal(err)
		}
		if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
			t.Fatal(err)
		}
	}
	return root
}

func check(t *testing.T, root string, files map[string]string, min int) {
	got, err := walk.Files(root, int64(min), io.Discard)
	if err != nil {
		t.Fatal(err)
	}
	var gotPaths []string
	for _, e := range got {
		gotPaths = append(gotPaths, e.Path)
		if int(e.Size) != len(files[e.Path]) {
			t.Errorf("size of %s = %d", e.Path, e.Size)
		}
	}
	var want []string
	for name, body := range files {
		if len(body) >= min && len(body) > 0 {
			want = append(want, name)
		}
	}
	sort.Strings(gotPaths)
	sort.Strings(want)
	if len(gotPaths) != len(want) {
		t.Fatalf("got %v want %v", gotPaths, want)
	}
	for i := range want {
		if gotPaths[i] != want[i] {
			t.Fatalf("got %v want %v", gotPaths, want)
		}
	}
}

func TestAcceptanceWalkEligibility(t *testing.T) {
	files := map[string]string{"a.txt": "abc", ".hid/.x": "hidden", "sub/deep/f": "ff", "empty": "", "b": "z"}
	root := build(t, files)
	if err := os.Symlink("a.txt", filepath.Join(root, "link")); err != nil {
		t.Fatal(err)
	}
	if err := os.Symlink("sub", filepath.Join(root, "dirlink")); err != nil {
		t.Fatal(err)
	}
	check(t, root, files, 1)
}

func TestAcceptanceWalkMinSize(t *testing.T) {
	files := map[string]string{"one": "a", "two": "ab", "three": "abc", "d/four": "abcd"}
	root := build(t, files)
	check(t, root, files, 3)
	check(t, root, files, 1)
}
""".replace("MODPATH", mod)

target = pathlib.Path("internal/walk/zz_acceptance_test.go")
target.write_text(GO_TEST)
try:
    result = subprocess.run(
        ["go", "test", "./internal/walk", "-run", "TestAcceptanceWalk", "-count=1", "-v"],
        capture_output=True, text=True,
    )
    print(result.stdout)
    print(result.stderr, file=sys.stderr)
    assert result.returncode == 0
finally:
    if target.exists():
        os.remove(target)
=== END AC walk-rules ===

=== AC walk-vet ===
Intent: The walk package compiles and passes go vet.

import subprocess
import sys

result = subprocess.run(["go", "vet", "./internal/walk"], capture_output=True, text=True)
print(result.stdout)
print(result.stderr, file=sys.stderr)
assert result.returncode == 0
=== END AC walk-vet ===

## User Acceptance

- None.

## Guardrails

- Never follow or report a symbolic link, and never traverse a directory reached only through one.
- Never open file contents in the walk.
- Never delete, move, or write any file under the directory examined.
- Zero-byte files are never reported.
=== END ARTIFACT ===