| Expected commit from audit plan | `151c536cb91ebedb6039270b752bae219dfe33d0` (`Add comparison diagnostics to the future roadmap`) |
| Baseline difference | The audit uses the current `main`, one commit ahead of the expected commit. The intervening commit adds the audit workflow plan used to conduct this audit. |
| Branch | `main` |
| Initial worktree | Clean; `git status --porcelain=v1` produced no entries before the audit ledger was created. |
| Go toolchain | `go version go1.26.5 linux/amd64`; `go env GOVERSION` reported `go1.26.5`. |
| Graph refresh | Refreshed from the baseline checkout in `moderate` mode without a persisted artifact: 2,674 nodes and 11,572 edges. The indexer excluded `docs`, `examples`, embedded-asset directories, and test-data directories, so their inventories below come from tracked files rather than the graph. |
| Baseline exclusions | None. There were no pre-existing worktree changes. |
| Environmental limitations | None encountered. Validation was deterministic and offline. |
## Scope And Inventory
Stage 1 inventories the checked-out repository without judging subsystem
correctness or test sufficiency. The repository has 219 tracked files. Its Go
inventory contains 24 packages, 83 non-test source files, and 50 test files.
`docs/integrations/promptkit.md`, `docs/integrations/weatherapi.md`, and the
three documents under `docs/integrations/distributor/`;
- internal documents: all 17 tracked documents under `docs/internal/`; and
- release notes: the four tracked documents under `docs/releases/`.
The maintained examples are `examples/config.yml`,
`examples/minimal-config.yml`, and
`examples/weather-light-local-profile.yml`. Roadmaps are coordination records,
not canonical current-state documents; the four pre-existing roadmap files are
therefore outside the canonical count.
## Baseline Validation
| Command | Result | Evidence |
| --- | --- | --- |
| `go test ./...` | Pass | Exit 0. All 24 packages were evaluated; 22 package test suites passed and `cmd/weatherreporter` plus `internal/buildinfo` reported no test files. |
| `go run ./cmd/weatherreporter --help` | Pass | Exit 0. Help printed usage for help, version, four report generators, two batch commands, and comparison. |
| `git diff --check` | Pass | Exit 0 with no output on the clean pre-ledger baseline. |
| `go vet ./...` | Pass | Exit 0 with no diagnostics. |
Supplementary baseline commands were `git rev-parse HEAD`,
| Architecture and dependency direction | Assembled app and CLI tests; graph traces | 2 | Sufficient at the architectural boundary: direct imports are acyclic, external dependency types remain adapter-local, and representative workflow ordering and publication boundaries have focused tests. `AUD-001` records unused persistence APIs that do not participate in normal execution. |
| Report identity, periods, dates, and timezones | `internal/report`, `internal/timeutil`, plus focused `internal/app` and `internal/forecast` callers | 3 | Partly insufficient. Registry identities, alias policies, batch membership, civil-day boundaries, and elapsed six-hour periods are coherent and exercised. `AUD-002` records incorrect wall-clock windows on daylight-saving transition days, and `AUD-003` records the missing regression test for Daily run-ID uniqueness across dates. |
| Generated-text validation | `internal/generatedtext` | 12 | Partly insufficient. The four current registry definitions dispatch to typed validators with coherent required-field and normalization behavior, and schema bytes are independently copied. `AUD-036` through `AUD-039` record report-independent catalog matching, case-insensitive Go field aliases, unbounded prose/diagnostics, and duplicated or misplaced contract tests. |
| Single-report publication and preservation | `internal/app`, `internal/fileutil` | 15 | Partly insufficient. Destination precedence, regular-file publication, same-directory temporary replacement, prior-output preservation, temporary cleanup, restrictive modes, truthful committed paths, and notification-after-publication have focused owners. `AUD-045` through `AUD-047` record destructive non-regular target handling, late failure for valid long basenames, and cancellation not checked at the rename boundary. |
| Batch partial success and notification | `internal/app`, `internal/adapters/distributor` | 16 | Partly insufficient. Collect-once planning, complete output preflight, deterministic sequential execution, independent partial success, report-only counters, published-source selection, and one all-success batch notification are coherent. `AUD-048` through `AUD-052` record late Distributor endpoint rejection, unsafe and unbounded response diagnostics, cancellation flattened into report failure, and the missing production HTTP adapter test boundary. |
| Comparison concurrency and CLI behavior | `internal/app`, `internal/cli` | 18 | Partly insufficient. Explicit profiles are preflighted sequentially, one immutable prepared package feeds concurrent profile-local executions, goroutines join, slice positions lock durable/CLI order, partial bundles publish coherently, and safe summaries preserve committed paths and fail the action on any error. `AUD-058` records a missing mixed failure/cancellation case and the resulting overwrite of an already completed profile failure. |
module, prompt, rendering, comparison, and notification correctness remains
assigned to Stages 3-18. Cross-cutting complexity, deduplication, and full
documentation coherence remain assigned to Stages 22-24.
#### Boundary Accounting
| Normative boundary or invariant | Implementation owner and evidence | Disposition |
| --- | --- | --- |
| Binary entry and CLI ownership | `cmd/weatherreporter.main` calls `cli.Run`; `internal/cli` owns action parsing, config loading, executor construction, and bounded result output. Graph traces place app calls below action resolution. | Matches policy. |
| Configuration ownership | `internal/config` owns defaults, YAML loading, normalization, secrets, and validation. CLI loads config and passes effective values down; app does not parse config files. | Matches policy; the config-to-briefing validation edge is routed to Stages 4, 8, and 23. |
| Application orchestration | `GenerateDetailed`, `RunBatchDetailed`, and `compareDetailed` sequence preflight, collection, preparation, execution, publication, and notification through repository-owned values and interfaces. No lower package imports app. | Matches policy; retained as `RET-001`. |
| Report and domain ownership | `report`, `timeutil`, `weatherdata`, `forecast`, `facts`, `module`, `briefing`, `promptinput`, `generatedtext`, and `reporttemplate` form one-way deterministic dependencies below app. | Matches policy at package level; local rules remain for Stages 3 and 7-13. |
| Prompt execution boundary | `promptexec.Executor` is dependency-neutral. CLI constructs the Promptkit adapter once per action, app consumes only `promptexec` requests/results, and the prepared-report data flow supplies curated serialized module packages. | Matches policy; retained as `RET-002`. |
| Weather API boundary | App calls its `Collector` interface; the production implementation delegates through `collect.Run` to `adapters/weatherapi.FetchBundle`, which returns normalized `weatherdata.Bundle`. Production HTTP imports occur only in external adapters. | Matches policy; retained as `RET-004`. |
| Distributor boundary | App owns notification timing and repository request/result types; `distributorNotifier` translates them to adapter-local types and the adapter alone imports the Distributor dependency. Comparison exposes no notifier path. | Matches policy. |
| Prompt preflight and curated inputs | Generate inspects the exact prompt/profile before `collectWeather`; batch inspects all candidates before its one collection; comparison inspects prompt and all profiles before collection, then calls `prepareReport` once. Data-flow traces reach `promptinput.Build` and `MarshalYAML`, not raw bundle serialization into Promptkit. | Matches policy at workflow level; detailed checks remain for Stages 10, 11, 14, and 18. |
| Single output and notification order | `publishPromptReport` checks context, calls `fileutil.WriteFileAtomic`, records the path, and only then calls `notifyReport`. Focused tests cover pre-publication preservation and notification ordering. | Matches policy; publication split retained as `RET-003`. |
| Batch output and notification order | `RunBatchDetailed` validates every planned path before sequential execution, suppresses item notification, continues across item failures, and calls `notifyBatch` only after the loop. Focused tests cover preflight, partial failure, and notification-after-publication. | Matches policy at workflow level; detailed review remains for Stage 16. |
| Comparison publication | App preflights before external work and again before publication. `internal/comparison` owns bundle validation, guarded replacement, staging, commit, restoration, and cleanup results. The comparison request has no notifier and the trace does not reach Distributor. | Matches policy at workflow level; detailed review remains for Stages 17-18. |
| Stateless execution | Normal traces retain preparation and execution values in memory. Production filesystem writes are limited to selected Markdown publication, selected comparison bundles, explicit prompt-debug capture, and the unreachable helpers in `AUD-001`; no cache, workspace, history, receipt, or resume owner appears in the package graph. | Matches normal-runtime policy; `AUD-001` records the unused persistence surface. |
| Dependency cycles and direction | The compiler-derived direct-import inventory is acyclic. Entry packages point inward, adapters do not import app/CLI, domain packages do not import orchestration, and no external dependency type appears outside its production adapter. | Matches policy. |
#### Commands And Evidence
- Refreshed graph project `home-eric-Workspace-weatherreporter` in moderate
mode. The graph's branch identity remains production baseline `e7c7262`;
Stage 1's intervening commit changes only this excluded audit document.
- Used graph architecture views for structure, dependencies, entry points,
hotspots, boundaries, layers, and clusters; queried the graph schema and
direct import edges.
- Used graph search, snippets, inbound/outbound call traces, and data-flow
traces for `main`, `cli.Run`, `GenerateDetailed`, `RunBatchDetailed`,
### Stage 3: Audit Report Identity And Time Foundations
- Status: Complete.
- Scope reviewed: all production and focused-test code in `internal/report`
and `internal/timeutil`; report and timezone contracts in `docs/cli.md`,
`docs/config.md`, and `docs/internal/report-registry.md`; and the focused
`internal/app` and `internal/forecast` callers that consume batch membership,
run IDs, civil periods, clock windows, and hourly coverage.
- Exclusions: Effective configuration validation and CLI date parsing remain
assigned to Stages 4-5. Forecast derivation beyond the time boundary remains
assigned to Stage 7. Module, prompt, schema, and template compatibility
remains assigned to Stages 8 and 10-13. Batch notification and Distributor
idempotency behavior remains assigned to Stage 16, and documentation-wide
coherence remains assigned to Stage 24.
#### Contract Accounting
| Contract or risk | Implementation and caller evidence | Disposition |
| --- | --- | --- |
| Stable report identities | The default registry contains exactly Daily, Today, Tomorrow, and Hourly. Each definition carries the documented prompt `2.0.0`, matching template/schema identity, modules, output name, and Distributor paths; focused registry tests assert the retained surface. | Matches the registry contract; explicit definitions retained as `RET-005`. Asset compatibility remains for later owner stages. |
| Alias resolution | Command lookup accepts exact current command names. Config lookup separately normalizes whitespace, case, and hyphens. Both reject retired aliases in focused tests. | Matches the distinct boundary contracts; separation retained as `RET-006`. |
| Batch membership and ordering | Morning explicitly plans Today then Tomorrow before eligible Daily dates; Evening explicitly plans Tomorrow before eligible Daily dates. Focused app tests cover ordering, flags, multiple Daily dates, and no eligible dates. | Matches CLI and registry contracts. Detailed partial-success and notification semantics remain for Stage 16. |
| Report period policy | Daily requires an explicit date; Today uses an explicit date or current local date; Tomorrow selects the next local civil day; Hourly spans six elapsed hours from the injected clock. `Resolve` defaults a missing location to UTC and a zero clock to the system clock. | Matches documented selection policy; calendar and elapsed policies retained separately as `RET-007`. |
| Civil-day and hourly DST behavior | `CivilDay` uses local midnight plus one calendar day, and batch hourly coverage walks actual instants, correctly accommodating 23-hour and 25-hour dates. Focused batch tests exercise DST civil days. | Sufficient for the reviewed policy. |
| Configured clock windows | `ClockWindow` adds elapsed clock durations to local midnight. The only production path reaches `forecast.ResolveDayparts`, daily summaries, and facts. Fixed-zone tests do not exercise either DST transition. | Incorrect on DST dates; recorded as `AUD-002`. |
| Date and timezone parsing | `ParseLocalDate` uses strict `YYYY-MM-DD` parsing in the selected location. `LoadLocation` covers IANA names, `America/` fallback, documented aliases, fixed US abbreviations, and signed offsets, returning contextual errors for invalid input. | Implementation is coherent for Stage 3. Effective config validation and CLI error presentation remain for Stages 4-5. |
| Clock control | All report resolvers accept an injected `Now`; only zero-valued input falls back to `time.Now`. Focused report and batch tests use fixed clocks. | Sufficient for deterministic period selection. |
| Daily output and run identity | Daily output names derive from the resolved valid-start date, and Daily run IDs append that date so same-clock multi-date products remain distinct. The downstream batch-notification map rejects duplicate IDs. | Implementation is coherent, but the identity invariant lacks a focused behavior test; recorded as `AUD-003`. |
| Half-open period operations | `Period.Valid`, `Contains`, `Overlaps`, and `Intersection` consistently use `[start,end)` semantics, and focused tests protect overlap boundaries. | Matches the internal period contract. |
#### Commands And Evidence
- Used graph search, source snippets, and inbound/outbound traces for the four
report definitions, registry construction and lookup, command/config mapping,
batch mapping and planning, `Resolve`, every period resolver, `CivilDay`,
`ClockWindow`, `ParseLocalDate`, `LoadLocation`, period overlap operations,
### Stage 4: Audit Configuration, Secrets, And Validation
- Status: Complete.
- Scope reviewed: all production and focused-test code in `internal/config`;
the configuration-to-executor mapping in `internal/cli`; Promptkit adapter
configuration and focused tests; all three maintained examples;
`docs/config.md`; and configuration-related architecture, operations,
documentation, and testing rules.
- Exclusions: CLI parsing and action-specific diagnostics remain assigned to
Stage 5. Weather API transport behavior remains assigned to Stage 6.
Promptkit source loading and sensitive execution diagnostics remain assigned
to Stage 11. Output publication preflight remains assigned to Stages 15 and
17, Distributor delivery remains assigned to Stage 16, and repository-wide
documentation coherence remains assigned to Stage 24.
#### Precedence And Validation Map
| Contract or risk | Implementation and consumer evidence | Disposition |
| --- | --- | --- |
| Discovery and precedence | `Load` starts with `Defaults`, merges the explicit or default YAML path, tolerates only an absent implicit default file, applies nonempty units/timezone overrides, normalizes report modules, loads configured secrets, and validates. Representative CLI coverage proves explicit units/timezone beat file values while unrelated file values remain. | Matches the documented defaults → file → CLI order. Environment variables do not override config fields. |
| YAML schema and migrations | `mergeFile` uses `KnownFields(true)`; custom notification, report, Distributor-path, and module decoders reject their own unknown fields. Retired `scriptorium`, recent-change, and workspace keys have focused migration/rejection tests. | Sufficient for known struct fields and retired top-level contracts. Unsupported keys inside the semantic missing-source map are `AUD-004`. |
| Defaults and partial merges | Exact documented defaults are built once in `Defaults`; YAML decoding merges partial nested structs over them, and focused tests cover default literals, omitted optional sections, batch partial configuration, and both maintained config examples. | Matches the canonical reference. Exact-default assertions protect user-visible contracts rather than private constants. |
| Output directory | Config accepts empty, relative, and absolute values, preserves them byte-for-byte, and rejects only nonempty whitespace. Graph traces place path resolution, inspection, creation, and publication below app/filesystem owners. | Matches policy; retained as `RET-008`. |
| Weather and daypart validation | Config checks absolute base URLs when present, positive timeout, nonnegative precision, nonempty units/timezone, resolvable timezone, JSON format, nonempty dayparts, names, and parseable clocks. Collection separately requires a base URL for collection actions. | Matches the documented split. The Stage 3 DST defect remains `AUD-002`. |
| Missing-source policy | Policy values and nonblank keys are validated, and the adapter consumes source-specific values by source name with a default fallback. Required hourly failures bypass optional-source policy. | Unsupported and ineffective keys pass silently; `AUD-004`. |
| Report/module overrides | Loaded aliases, duplicate normalized reports, module identities/order, compatibility, duplicate modules/stanzas, typed options, explicit empty lists, and Distributor path templates are validated through report/module registries. | Loaded YAML behavior is well covered. Exported constructed values cannot establish private presence state; `AUD-006`. Detailed module semantics remain for Stages 8-9. |
| Promptkit settings | Config validates mutually exclusive profile sources, positive timeout, optional absolute local endpoint, and nonnegative concurrency. CLI maps a dormant endpoint-less limit to the adapter zero value; adapter construction owns file/directory loading, backend registration, fallbacks, and safe error classification. | Matches the documented inactive/active split; retained as `RET-009` and `RET-010`. |
| Secret directory | Empty disables loading. A configured directory accepts only directly contained regular files with environment-variable basenames, rejects symlinks/directories/nonregular/unreadable entries, removes one LF or CRLF, overwrites the named environment value, and reports only directory/file names and operation context. | Values are absent from tested diagnostics, but failure application is not atomic; `AUD-007`. |
| Distributor configuration | Disabled notification skips active-field checks. Enabled notification validates endpoint, token variable name, timeout, failure policy, allowed template variables, batch activation, and report path safety/uniqueness. Templates render from repository-owned metadata rather than environment values. | Mostly sufficient. Two single-report rendered identities omit the nonblank invariant; `AUD-005`. |
| Filesystem and URL timing | Config validates intrinsic string/URL shape. Output destinations are inspected by app/publication owners, Promptkit sources by its adapter, and secret entries by the config loader. No audit command contacted an external service. | Matches ownership boundaries for Stage 4; transport-specific scheme support is routed to later stages. |
| Constructed configuration | `Validate`, report override accessors, and focused tests attempt to provide loaded/constructed consistency without mutating caller-owned option values. | General scalar validation is consistent, but report override presence is not externally constructible; `AUD-006`. |
| Maintained examples | Both YAML configuration examples load through the strict config suite. The endpoint-only `weather-light` profile is inspected through the real Promptkit adapter with embedded assets and no network or credential. All examples contain synthetic endpoints and no secrets. | Matches documentation and testing policy. |
#### Commands And Evidence
- Used graph search, source snippets, call traces, and graph-augmented test
searches for defaults, `Load`, YAML merging and migration rejection,
and comparison execution correctness remain assigned to Stages 6-18.
Cross-cutting parser deduplication, test portfolio durability, documentation
coherence, and dynamic robustness remain assigned to Stages 21 and 23-25.
#### Command And Exit Accounting
| Command or risk | Parsing, result, and exit evidence | Disposition |
| --- | --- | --- |
| Root help and version | No arguments, `-h`, and `--help` print static help without config/provider setup. Exact `--version` prints the injected or build version; extra version arguments fail. Main prints any returned error to stderr and exits `1`; nil returns normally. | Matches the documented root contract. Help wording drift is routed to Stage 24. |
| Generate dispatch | Requires one of four exact report names. Command-specific flag sets accept only documented flags; Daily requires a date, Today defaults or parses one, and Tomorrow/Hourly reject `--date`. Config and explicit output/working-directory values map into one app request and one executor. | Functional mapping matches, but date validation occurs after executor construction; `AUD-009`. Assembled result/exit coverage is `AUD-010`. |
| Run dispatch | Requires exact Morning or Evening batch identity, accepts `--out-dir` rather than `--out`, resolves only explicit relative overrides against the absolute invocation directory, preserves configured fallback, and constructs one executor/request. | Matches the parser/wiring contract. Representative assembled result coverage is incomplete in `AUD-010`; detailed batch behavior remains Stage 16. |
| Compare dispatch | Requires a valid report and two distinct nonblank ordered profiles before config/executor work; applies the same report date eligibility; clears the configured default profile; maps exact bundle destination/replace/debug options; constructs one executor. | Matches the CLI contract. Focused tests cover parser, construction frequency, pre-execution failure, success/partial/cleanup summaries, quiet behavior, and safe errors. Detailed execution remains Stage 18. |
| Common flags and ownership | `addCommonFlags` registers config, units, timezone, and prompt debug only. Each action separately registers its output, quiet, date, profile, and replacement flags. Report and batch name lookup delegates to `internal/report`; config precedence delegates to `internal/config`. | Intentional explicitness retained as `RET-011`; repeated date policy is routed to Stage 23. |
| Validation ordering | Unknown commands/reports, unsupported flags, extra args, and comparison profile shape fail before configuration or executor creation. Generate performs Daily presence and Daily/Today parsing after config and executor creation. | Partly incorrect; `AUD-009`. |
| Output paths | CLI captures/validates one absolute working directory, preserves configured fallbacks, and resolves only nonempty relative explicit output overrides against that directory. App owns default naming and publication. | Matches CLI/config documentation and architecture ownership. |
| Stdout, stderr, and quiet | Result-bearing actions emit indented JSON to stdout. Run emits compact ordered item/notification/batch lines to stderr first. Quiet returns before both routine channels but the returned error still reaches main stderr. Pre-result failures emit no structured output. | Matches the documented separation; summary design retained as `RET-012`. Broken status-writer behavior is routed to Stage 25. |
| Generate summaries | Selected report, prompt, time, profile/model, warnings, validation, output, debug, notification, and error fields are copied; status is failed exactly when a result accompanies an error. | Shape matches documentation, but only the constructor is tested; assembled behavior is `AUD-010`. Producer redaction remains for Stages 6, 11, and 16. |
| Batch summaries and exit | Report counters remain independent of notification failure. Any failed report or failed notification makes summary status/error failed, emits status lines unless quiet, and returns typed `BatchError` so main exits nonzero. | Mapping is coherent and notification failure is assembled-tested. Broader representative translation coverage is `AUD-010`. |
| Comparison summaries | Field order is fixed by the explicit DTO; profile order is retained; unpublished artifact fields are omitted; errors are mapped to bounded aggregate, cancellation, deadline, Promptkit, destination, cleanup, or application categories. | Matches the documented safe CLI contract with strong focused coverage. |
| Cancellation | `Runner.Run` forwards its context to every app action, and app tests protect cancellation behavior. Production main supplies an uncancelable background context and has no signal bridge. | Programmatic propagation is correct; executable cancellation is `AUD-008`. |
| Test ownership | Parser/resolver tests own flag acceptance, paths, configuration mapping, and one-executor construction; summary tests own selected fields; comparison command tests own assembled translation. | Comparison is sufficient. Non-comparison assembled coverage is insufficient in `AUD-010`; lower workflow details correctly remain in app tests. |
#### Commands And Evidence
- Used graph inventory, source snippets, inbound/outbound traces, and
graph-augmented searches for root dispatch, every action parser/resolver,
common flag registration, working/output path resolution, executor mapping,
derivation, and aliasing policy remain assigned to Stage 7. Prompt-facing
curation remains assigned to Stages 8-10, app orchestration to Stages 14-16,
cross-cutting cleanup to Stage 23, documentation reconciliation to Stage 24,
and adversarial dynamic checks to Stage 25.
#### Source And Failure Accounting
| Source or transport risk | Required, empty, malformed, and provenance behavior | Disposition |
| --- | --- | --- |
| Warmup | Calls `/conditions/current` first with format, units, and precision; requires a readable 2xx body; closes it; and stops before source requests on failure. Context cancels requests and retry waits. | Endpoint and cancellation behavior match. Permanent statuses are retried contrary to the shared policy in `AUD-015`; body safety/limits are `AUD-012` and `AUD-013`. |
| Observations | Optional. Missing/null and malformed data use configured policy. A successful value records observation timestamp as issue time plus endpoint, query, fetch time, and compact-data hash. | Matches the source contract. |
| Current conditions | Optional. Missing/null and malformed data use configured policy; successful normalized fields and provenance are retained. | Matches the source contract. |
| Hourly forecast | Required regardless of optional-source policy. Missing/null, decode failure, and an empty period list fail collection; format, units, precision, and timezone are sent. | Availability mapping matches, but periods with zero/reversed time bounds pass; `AUD-014`. |
| Narrative forecast | Optional. Missing/null and malformed data use configured policy; issue/update timestamps and forecast periods are normalized. An empty period list remains checked data. | Matches the documented source contract. Semantic forecast use remains Stage 7. |
| Active alerts | Optional. An absent member is missing, explicit `null` is checked empty data with a hash and no warning, and malformed non-null data uses configured policy. Alert items remain raw payloads at this boundary. | Matches the explicit alerts exception. Full duplicate raw payload is routed to Stage 23. |
| Forecast discussion | Optional. Missing/null and malformed data use configured policy; issue/update times, key messages, and short/long sections are normalized. | Matches the source contract. |
| Weather story | Optional. Uses format only; missing/null and malformed data use configured policy; start/update provenance is retained when available. | Matches the source contract. |
| SPC convective outlooks | Optional. Uses format/timezone without units; missing/null uses configured policy; non-null empty outlook/discussion lists are checked data; issue time prefers `issuedAt` and falls back to `asOf`; GeoJSON remains raw. | Matches the explicit SPC empty-data and provenance contract. |
| Optional-source policy | `error` aborts with no partial bundle, `warn` records the same stable warning in source and bundle, and `none` records a missing source without a warning. Transport/status/envelope failures remain direct request errors. | Matches the documented division. Unsupported policy keys remain the Stage 4 finding `AUD-004`. |
| Endpoint construction | Joins every fixed endpoint to a base path prefix and applies only the required format/units/precision/timezone matrix. | Query/path behavior matches for HTTP(S); unsupported absolute schemes survive until runtime in `AUD-011`. Base URL query/user-info shape is routed to Stage 24. |
| HTTP attempt lifecycle | Requests carry context and configured client timeout; response bodies close after bounded reads; source attempts retry transport/read failures and only the documented transient statuses. | Mostly coherent. Unsafe response text and silent truncation are `AUD-012`/`AUD-013`; warmup classification divergence is `AUD-015`. |
| Normalization and collection ownership | `weatherdata` contains no HTTP/config/filesystem behavior. The adapter translates wire envelopes into project types. `collect.Run` constructs one adapter, forwards context, and distinguishes setup from fetch errors. | Matches architecture; the narrow collection seam remains retained under `RET-004`. Source-specific normalization remains explicit under `RET-013`. |
| Test assets and ownership | Adapter tests use `httptest.Server` for HTTP/query/status/retry/cancellation/policy behavior and eight small checked-in JSON fixtures for translation. `weatherdata` owns a focused GeoJSON round trip; `collect` owns three real local composition/error cases. Fixtures are synthetic, credential-free, and total under 5 KiB. | Ownership is distinct and offline. Missing high-risk cases are attached to `AUD-011` through `AUD-015`, not inferred from coverage alone. |
#### Commands And Evidence
- Used graph architecture, symbol search, source snippets, inbound traces, and
graph-augmented use searches for adapter construction, all eight source
methods, HTTP attempts and retries, body lifecycle, endpoint/query assembly,
missing/malformed policy, hashes and timestamps, normalized source consumers,
`collect.Run`, and propagation toward app/CLI boundaries.
- Scope reviewed: all production code and focused tests in
`internal/forecast` and `internal/facts`; the forecast derivation and facts
internal documents; normalized forecast types; and immediate briefing/app
consumers needed to determine unit meaning, mutation ownership, and whether
derived facts participate in normal workflows.
- Exclusions: Detailed source-facing, derived, planning, formatting, and SPC
briefing behavior remains assigned to Stages 8-9. Cross-cutting test
portfolio and cleanup remain assigned to Stages 19-23, documentation
reconciliation to Stage 24, and adversarial dynamic checks to Stage 25.
#### Derivation Rule And Edge-Case Accounting
| Derivation rule or risk | Boundary, ordering, and test evidence | Disposition |
| --- | --- | --- |
| Valid-period selection | Hourly, narrative, and daily runs use half-open overlap, retain complete source periods, and stable-sort by start time. Nil runs return no facts. Focused tests cover unsorted input, partial overlap, and exact-boundary exclusion. | Matches the source-period contract; complete-period selection is retained as `RET-014`. Structurally invalid required periods remain `AUD-014`. |
| Civil-day summaries and dayparts | Daily summaries require hourly data, resolve configured local windows, and select each daypart independently. Empty dayparts remain explicit summaries; overnight hourly selection crosses midnight. | Ordinary and empty behavior matches. DST window construction remains `AUD-002`; after-midnight alert selection is incorrect in `AUD-017`. |
| Temperature and wind aggregation | Min/max and peak selection is deterministic for populated values; numeric heat/cold thresholds distinguish Fahrenheit and Celsius. Wind and all unitless summary fields fall back between explicit unit fields without conversion. | Incorrect for metric fallback values; `AUD-016`. Paired unit-system regressions are absent. |
| Condition indicators | Text matching is case-insensitive; numerical heat, cold, and wind signals merge monotonically across periods. Dominant-condition ties resolve lexically and notable conditions sort. | Deterministic, but common “icy” text is missed; `AUD-019`. Broader briefing interpretation remains Stage 9. |
| Precipitation timing | Input is copied and stable-sorted. Exact threshold inclusion, dry input, gaps, maxima, text aggregation, thunder mentions, and intentionally open final windows have focused tests. | Window mechanics match. The percentage domain is unenforced in `AUD-018`; the open final window is an intentional horizon signal. |
| Alert parsing and overlap | Supported time-field fallbacks, malformed omission, instruction whitespace, half-open clipping, ordering, and direct boundary cases have focused tests. | Direct behavior matches. Daily prefiltering loses alerts in wrapping dayparts; `AUD-017`. |
| Collected facts and mutation | Collection projects every normalized product and copies top-level sources/warnings. Bundle reconstruction repeats those top-level copies; derivation reads shared nested values without mutation. | Fits immutable workflow ownership and is retained as `RET-015`; no speculative deep-copy requirement was added. |
| Report-family derived facts | Every report selects valid-period hourly, narrative, daily, alert, precipitation, and SPC facts. Daily/Today/Tomorrow additionally build one daily/daypart summary; Hourly does not; unknown reports and invalid periods fail. | Matches the implemented report-family contract with focused cases. The stale multi-day documentation name is routed to Stage 24. |
| SPC outlooks and discussions | Only valid overlapping outlook periods are selected. Output ordering uses day, type, severity rank, validity, label, and ID; discussions are retained only for selected days and sorted deterministically. Nil and checked-empty runs remain empty facts. | Matches documented checked-empty and deterministic ordering behavior with focused tests. Detailed briefing meaning remains Stage 9. |
| Repeated work and realistic size | One derived build performs several linear selections, then each configured daypart scans the hourly run and its alert candidates; selected precipitation and SPC slices are sorted. With the normal four dayparts and service-sized runs of a few hundred periods, this is only low-thousands of simple overlap checks. | No Stage 7 performance finding. Reassess in Stage 22 only if horizons, daypart counts, or alert volumes become materially larger or derivation is repeated per module. |
| Test ownership | `forecast` owns selection, summaries, thresholds, precipitation, parsing, overlap, ordering, and fixture integration. `facts` owns projection, report-family derivation, SPC filtering/order, and failure cases. `timeutil` owns the underlying period rules. | Ownership is coherent. Missing high-risk unit, overnight-alert, percentage-domain, and icy-text cases are attached to `AUD-016` through `AUD-019`, not inferred from coverage alone. |
#### Commands And Evidence
- Used graph architecture, symbol search, source snippets, call traces, and
graph queries for every scoped derivation function, report-family consumers,
unit-bearing normalized fields, comparison helpers, loops, sorting, and
immediate unit interpretations. Text search was limited to documents,
literals, fixtures, and focused assertions where graph discovery was not
applicable.
- Compared implementation and tests with
`docs/internal/forecast-derivation.md`, `docs/internal/facts.md`, and the
architecture, documentation, and testing policies. Existing Stage 3 and
Stage 6 findings were treated as dependencies rather than duplicated.
- Ran
`go test -coverprofile=/tmp/weatherreporter-stage7-cover.out ./internal/forecast ./internal/facts ./internal/timeutil`;
all focused packages passed. Statement coverage was 89.7% for forecast,
73.4% for facts, and 54.5% for timeutil; coverage guided branch inspection
but was not itself a finding.
- Findings: `AUD-016`, `AUD-017`, `AUD-018`, and `AUD-019`.
- Retained decisions: `RET-014` and `RET-015`.
- Open questions: the three leads recorded above are routed to their assigned
formatting, and SPC builders remain assigned to Stage 9. Complete prompt
serialization and asset contracts remain Stage 10, application preparation
remains Stage 14, cross-cutting cleanup remains Stage 23, and documentation
coherence remains Stage 24.
#### Registry And Source-Module Accounting
| Contract or module | Registry, transformation, and test evidence | Disposition |
| --- | --- | --- |
| Neutral module envelope | Stable IDs and fact/option vocabulary live in `internal/module`; snapshots preserve caller order, omit runtime prompt values from JSON, reject missing identities and duplicates, and support typed rich-stanza lookup. | Separation is retained as `RET-016`. Exact version compatibility is not enforced; `AUD-022`. |
| Registry initialization | Default definitions have unique IDs/stanzas, builders, supported reports, typed defaults, missing-data behavior, requirements, and prompt-export policy. Constructor tests cover duplicates, absent builders, and unsupported `warn`; default report compositions validate. | Default metadata is coherent. Unknown custom missing-data values fail only at build time; low-impact constructor hardening is left for Stage 23 unless the registry becomes extensible. |
| Configuration and options | Configuration normalizes raw YAML into registry-declared option types, validates compositions through the same registry, and preserves report order. Only AFD has nonempty default selections and consumes a section list. | IDs/defaults/order agree. Accepted pointer/value option shapes diverge at the AFD builder; `AUD-020`. |
| BuildModule policy | Lookup, report support, option shape, fact availability, omit/error/empty behavior, output identity, and prompt export execute in one boundary. Exporter failures receive module/stanza context and outputs are identity-checked before export. | Coherent for defaults. The branching is policy-driven rather than per-module switch testing; builders are exercised through public registry behavior. |
| Metadata | Emits report identity, variant, prompt, generation/period context, configured units/timezone/location, and bounded source-warning summaries without endpoint/hash provenance or alert duplication. It remains available with empty source metadata. | Matches the documented prompt-safe module contract with focused field/omission tests. Parallel non-module metadata construction is routed to Stage 23. |
| Current conditions | Optional source; rounds explicit unit fields, retains day/condition/humidity, derives compass labels, omits a wholly empty value, and uses a curated prompt projection without lowercase/display helpers. | Matches source and prompt-export contracts with focused rich/prompt tests. |
| Narrative forecast | Daily/Today/Tomorrow only; requires both source presence and selected derived periods, maps only valid-period values, copies unit-bearing fields, and produces local friendly bounds and compass wind labels. Missing or empty selections omit the module. | Matches support, selection, transformation, and omission contracts with focused tests. Invalid normalized percentages remain `AUD-018`. |
| Hourly forecast | All reports; requires source presence and selected periods, maps the complete selected weather fields, derives labels/compass direction, and marks precipitation at the exact 20-percent threshold. Its prompt export omits rich-only labels and mention helpers. | Matches support, boundary, rich-value, and curated-export contracts with focused tests. Invalid period/percentage inputs remain `AUD-014`/`AUD-018`. |
| Alert digest | All reports with explicit empty behavior; distinguishes checked-empty and source-missing states, counts raw active and relevant overlaps separately, preserves derived order, and formats full alert periods with guidance. | Matches availability and value contracts; distinction retained as `RET-018`. Overnight relevance remains the upstream `AUD-017`. |
| Area forecast discussion | Optional for all reports; empty section lists mean all sections, report defaults select long-term for Daily and key messages/short-term for Hourly, unsupported names fail, and selected slices are copied. | Section policy and defaults agree, but pointer-shaped accepted options fail construction; `AUD-020`. |
| Weather story | Optional for all reports; copies story content, flags, URL, update time, and friendly valid-period labels. | Populated and missing behavior is tested. Structurally empty data is incorrectly emitted as available; `AUD-021`. Complete prompt curation remains Stage 10. |
| Mutation and ordering | Snapshot outputs copy the outer slice; source modules copy scalar pointers and AFD key-message slices. Prepared-report construction later deep-copies complete inputs. Registry and report order flow unchanged into snapshots. | No shared-mutation finding under immutable preparation ownership. Rich/prompt separation is retained as `RET-017`. |
| Complexity drivers | `BuildModule` centralizes validation/missing/export branching; fact availability uses parallel requirement switches; default definitions form a long policy table; current/hourly prompt projections copy many fields. Builders otherwise perform small linear maps over service-sized periods/alerts. | No Stage 8 performance finding. Table/switch drift, parallel metadata, and projection duplication are routed to Stage 23 with concrete owners. |
| Test ownership | Module tests own snapshot structure/order and rich-versus-prompt selection. Briefing registry tests own default composition, support, options, missing behavior, output/export validation, and assembled snapshots. Source-module tests own observable transformations and omissions; config tests own YAML normalization. | Mostly sufficient and behavioral. Missing pointer-consumption, empty-story, and unsupported-schema cases are attached to `AUD-020` through `AUD-022`. |
#### Commands And Evidence
- Used graph architecture, symbol search, source snippets, inbound traces, and
graph queries for snapshot consumers, registry/config validation, all scoped
builders and exporters, source fields, default report compositions, tests,
shared-state copying, and complexity drivers. Text inspection was limited to
scoped documentation and targeted source/test bodies.
- Compared implementation and focused tests with `docs/internal/module.md`,
relevant portions of `docs/internal/briefing.md` and
`docs/internal/prompt-input.md`, and the architecture, documentation, and
testing policies.
- Ran
`go test -coverprofile=/tmp/weatherreporter-stage8-cover.out ./internal/module ./internal/briefing ./internal/config ./internal/report`;
all focused packages passed. Statement coverage was 86.5% for module, 82.5%
for briefing, 86.1% for config, and 48.8% for report; coverage guided risk
inspection but was not itself a finding.
- Findings: `AUD-020`, `AUD-021`, and `AUD-022`.
- Retained decisions: `RET-016`, `RET-017`, and `RET-018`.
- Open questions: the four leads recorded above are routed to their assigned
Stage 24; and adversarial dynamic checks remain Stage 25.
#### Derived And Planning Rule Accounting
| Module or risk | Threshold, ordering, missing-data, and test evidence | Disposition |
| --- | --- | --- |
| Daily summary | Selects narrative high/low and daily precipitation when present, falls back to daypart aggregates, preserves deterministic conditions/hazards, and emits timing/gust facts. | Ordinary and fallback selection are exercised. Apparent temperature is incorrectly relabeled as heat index in `AUD-023`; unit fallback remains upstream `AUD-016`. |
| Daypart summaries | Emit local periods, ranges, condition/hazard flags, precipitation and gust maxima, temperature phrases/trends, and configured normalized keys; date prefixes prevent ordinary multi-day collisions. | Field and positive-temperature behavior is exercised. Canonical key collisions are `AUD-024`, subzero wording is `AUD-027`, and unit interpretation remains `AUD-016`. |
| Precipitation timing | Maps dry and rainy windows, open-ended periods, expectation thresholds, type phrases, thunder mentions, and local labels without mutating derived order. | Matches the reviewed briefing contract with focused rainy, dry, threshold, phrase, and missing-daypart cases. Percentage-domain defects remain `AUD-018`. |
| Outdoor windows | Scores precipitation, gusts, alerts, heat, and cold; preserves deterministic input-order ties and exposes best/worst periods and reasons to Today planning. | Incomplete hazard policy: snow, ice, and fog can score as quiet; `AUD-026`. |
| Planning variants | Daily and Tomorrow share morning, workday, and overnight sections; Today intentionally adds outdoor and late-day sections. Empty daily summaries produce empty modules or defined fallback prose according to builder context. | Report variation is intentional and retained as `RET-019`. Configurable name classification is inconsistent in `AUD-025`; upstream unit/alert/text defects are not duplicated. |
| User-facing formatting | Time/date labels use the requested location with UTC fallback, wind compass boundaries are focused-tested, strings are deduplicated in stable order, and sentence casing is Unicode-aware. | Ordinary formatting is coherent. Signed temperature bands are incorrect in `AUD-027`; byte-oriented title casing is routed to Stage 23 after the identity defects. |
| SPC outlooks | Preserve selected overlapping records and checked/missing status, attach definitions only for recognized normalized keys, and compute a location-specific categorical risk digest at severity rank 3 or higher. | Selection, ordering, threshold equality, type, location, overlap, unknown definitions, and empty/missing states have focused tests; separation retained as `RET-020`. Official categorical descriptions have drifted in `AUD-028`. |
| SPC discussion | Includes selected discussions only for days with an overlapping categorical outlook meeting the rank threshold; ignores high-rank noncategorical products and nonoverlapping outlooks. | Matches the explicit regional discussion policy with focused threshold, day, type, overlap, missing-text, and missing-source cases. |
| Complexity and repetition | Scoped builders perform small linear maps over configured dayparts, precipitation windows, outlooks, and discussions. The highest production cognitive scores are in planning, precipitation type selection, and outdoor scoring, with no material service-sized cost. | No Stage 9 performance finding. Repeated daypart role/display logic is routed to Stage 23 with concrete evidence. |
| Test ownership | One derived-module suite owns daily/daypart/precipitation/planning behavior, format-helper tests own compass mapping, and dedicated SPC suites own risk/discussion/definition behavior. | Mostly behavioral. Missing semantic regressions are attached to `AUD-023` through `AUD-028`, not inferred from coverage alone. |
#### Commands And Evidence
- Used graph symbol and augmented-code search, source snippets, inbound traces,
and complexity queries for every remaining builder/helper, configured
daypart identities, apparent-temperature flow, outdoor hazard inputs, signed
temperature bands, SPC selection/definition lookup, and their focused tests.
Bounded text inspection was used for scoped documents, configuration
examples, and the embedded JSON asset.
- Compared SPC vocabulary and externally attributed definitions with NOAA/NWS
Storm Prediction Center's current convective-outlook reference and the
Stage 14; cross-cutting API cleanup and documentation coherence remain Stages
23-24; and adversarial repository-wide checks remain Stage 25.
#### Prompt Boundary And Execution Accounting
| Contract or risk | Serialization, asset, caller, and test evidence | Disposition |
| --- | --- | --- |
| Curated work-package construction | Application preparation reaches `promptinput.Build` and `MarshalYAML` from ordered module `DataPackageValue` exports, not normalized bundle serialization. Report identity, local date, period, and module categories are explicit. | Module values follow the curated path, but the top-level raw warning copy violates it in `AUD-029`. |
| Category order and normalization | One fixed table groups known stanzas as metadata, applicable risk, derived, narrative, and raw data; module order is retained within groups. Values normalize through JSON before YAML, and repeated marshals are byte-identical in focused tests. | Coherent and retained as `RET-021`; missing failure-branch coverage is `AUD-033`. |
| Package validation and loading | Current schema, report/run metadata, ordered stanza presence, duplicate order entries, known category membership, and misplaced stanzas are rejected. A temporary table-driven probe exercised additional malformed shapes. | Incomplete for required metadata, orphan values, unknown struct fields, and trailing documents; `AUD-032`. |
| Embedded prompt identities | Exactly four report definitions bind the registry's prompt ID/version, embedded profile, `weatherreporter.data_package.v4` input schema, and matching generated-text output schema. Real offline Promptkit inspection succeeds for each. | Identity is coherent; common prose references nonexistent serialized paths in `AUD-030`. |
| Safety-sensitive prompt semantics | The shared prompt prioritizes risk, forbids invention, and asks regional discussion limitations to be preserved. | Its blanket assertion that all retained products are location matched contradicts SPC module semantics; `AUD-031`. |
| Embedded profiles and schemas | Exactly three profiles carry the intended backend/model/timeouts/reasoning/tier settings; tests reject unsafe/incidental profile settings and retired runtime strings. Embedded schema bytes are independently copied. | Matches the scoped identity and immutability contracts. Output-schema field meaning remains Stage 12. |
| Inspection and execution lifecycle | Dependency-neutral requests carry context and exact prompt/profile identity. Execution runs validation callbacks before provider work and distinguishes completed validation rejection from operational failure without a result. | Coherent and retained as `RET-022`; adapter realization remains Stage 11. |
| Safe errors, debug, and result isolation | All stable error categories are covered; safe errors preserve causes while omitting cause text; messages and invalid UTF-8 diagnostics are bounded; debug is opt-in; returned output/debug bytes and maps are copied. | Sufficient at the neutral contract boundary. Dependency diagnostics remain Stage 11. |
| Complexity and realistic input size | The highest scoped production path is stanza YAML marshaling, with two shallow loops over five fixed categories and the report's service-sized module list. Asset lookup and neutral result construction are constant or small linear work. | No Stage 10 performance finding; explicit grouping remains cheaper to reason about than generic reflection. |
| Test ownership | Prompt-input tests own construction, validation, grouping, ordering, category placement, and YAML round trips; prompt-assets tests own embedded inventories/identities and real inspection; prompt-exec tests own lifecycle, category, error, debug, bound, and copy semantics. | Mostly behavioral and nonduplicated. Missing provider-boundary warning/path/locality and serialization/load cases are attached to `AUD-029` through `AUD-033`. |
#### Commands And Evidence
- Used graph architecture, symbol and augmented-code search, snippets,
inbound/outbound traces, data-flow traces, and complexity queries for
and broader adversarial diagnostics remain Stage 25.
#### Adapter And Debug-Security Accounting
| Contract or risk | Adapter, filesystem, caller, and test evidence | Disposition |
| --- | --- | --- |
| Dependency containment and configuration | Promptkit production imports occur only in its adapter. CLI-owned settings map to profile directory/file, local endpoint/capacity, and timeout; mutually exclusive sources and inactive local capacity fail construction. | Matches the architecture boundary. Profile resolution remains dependency-owned under `RET-023`. |
| Profile source precedence | Explicit in-memory definitions, configured file/directory, embedded fallback, and built-ins provide complete definitions in the documented order. Absence falls through; a malformed matching configured definition fails. | Coherent with offline focused tests and retained as part of `RET-023`. |
| Exact inspection and credential preflight | Prompt inspection returns exact ID/version/hash, one input, and output contract. Profile inspection returns only logical ID, backend/model, direct-key requirement, and environment-variable name; app checks direct keys and nonblank environment values before collection. | Safe values and missing-credential categories match. Environment names are identifiers, not secret values. |
| Prepared inline execution | The adapter copies the YAML bytes into one inline artifact, prepares once, invokes the callback before generation, and runs the same opaque one-use handle. Callback failure prevents the provider call and deferred discard clears unused private state. | Matches the integration contract with exact-provenance and callback tests. |
| Cancellation and concurrency | Preparation and execution receive caller context independently; canceled/deadline causes map before generic generation errors. Promptkit documents `Engine` as concurrency-safe with capacity owned per engine, and comparison uses one adapter concurrently without wrapper state. | Coherent; race-enabled adapter/app tests pass. No redundant application-wide limit or adapter mutex is warranted. |
| Error classification and normal redaction | Promptkit configuration, prompt/profile, credential, artifact/render, capacity, generation, validation, request, cancellation, and deadline errors map to bounded repository categories. Underlying causes remain discoverable but their content does not enter `Error()`, summaries, or logs. | Sufficient at this boundary; focused marker and category tests protect normal output. |
| Debug authorization and isolation | Empty root disables all filesystem access; an enabled root must be absolute and not `/`. Report/date/run segments reject separators and traversal, comparison derives distinct deterministic run segments, and content-rich values appear only when capture is requested. | Matches explicit opt-in and per-run isolation. Separate ownership retained as `RET-024`. |
| Debug credential projection | User information, fragments, known secret query keys, and known nested parameter keys are removed or redacted before preparation JSON is written. | The denylist misses common aliases, signed/path credentials, and arbitrary provider vocabulary; `AUD-034`. |
| Directory and symlink containment | Static symlinks in the root or any visible descendant component are rejected; directory modes are tightened to `0700`, and unsafe references fail before a file write. | Path checks are separated from later name-based creation/replacement and can be raced; `AUD-035`. |
| File collision, modes, and partial writes | JSON is marshaled before creation; same-name artifacts use a mode-`0600` temporary in the final directory and atomic rename; non-regular existing targets are rejected; distinct concurrent run directories and shared missing ancestors are tested. | Coherent for non-adversarial paths. A failed requested callback stops generation, and a failed execution write stops publication. |
| Complexity and test ownership | Adapter mapping/classification is straight-line or small linear copying. Debug recursion follows bounded JSON-compatible parameter trees; directory traversal is linear in path components; realistic artifact sizes are dominated by intentionally captured prompt/output content. Adapter tests own dependency translation; debug tests own filesystem/security behavior; app tests own callback consequences. | No Stage 11 efficiency or duplication finding. Redaction and race gaps are attached to their narrow owners rather than inferred from coverage. |
#### Commands And Evidence
- Used graph architecture, symbol and augmented-code search, snippets,
inbound/data-flow traces, and hotspot inspection for adapter construction,
durability and refactoring remain Stages 19-23 except for duplication
explicitly assigned to this stage; documentation-wide coherence remains
Stage 24; and repository-wide adversarial checks remain Stage 25.
#### Generated-Text Contract Accounting
| Contract or risk | Schema, decoder, catalog, caller, and test evidence | Disposition |
| --- | --- | --- |
| Raw output to typed value | Promptkit validates raw provider JSON against the report definition's embedded schema and reports passed/failed status. After a pass, app dispatches the same raw bytes through the prepared handler; the report validator strictly decodes shape, trims prose, removes blank day-style paragraphs, applies semantic required-field rules, and returns a typed value plus canonical JSON before context construction. | The path and ownership are explicit. Retain both validation layers under `RET-026`; their exact-name disagreement is `AUD-037`. |
| Required and empty fields | Every schema requires summary, forecast discussion, and precipitation timing and rejects additional properties. Go requires nonblank trimmed summary/discussion; day-style discussion retains one or more nonblank paragraphs; precipitation timing must be present and string-valued but may normalize to empty. Null and wrong structural types fail. | Coherent aside from case-insensitive aliases. The schema intentionally permits lexical blanks that repository semantic validation rejects. |
| JSON document strictness | Typed decoding rejects malformed JSON, unknown canonical additions, wrong field types, and multiple top-level values. It accepts surrounding whitespace. Duplicate names follow Go/parsed-JSON last-value semantics because no stronger canonical rule exists. | Sufficient for documented document shape, with exact-key enforcement missing in `AUD-037`. Duplicate policy is routed to Stage 25 remediation validation rather than declared retroactively. |
| Array and size behavior | Day-style arrays require one schema item and one nonblank normalized paragraph but have no item-count or aggregate bound. No schema or Go string/total-output bound exists, and decoder unknown-field errors quote arbitrary names. | Unbounded accepted prose and diagnostics are `AUD-038`. |
| Report-specific types and shared mechanics | Daily, Today, and Tomorrow are distinct types and validators over one private field projection and validation helper; Hourly deliberately uses a single discussion string. Typed context builders can therefore distinguish reports even when day-style fields match. | Appropriate separation retained as `RET-025`; tests duplicate rather than merely protect that choice in `AUD-039`. |
| Catalog compatibility | Four entries bind schema/template pairs to validators and builders; current registry iteration resolves all entries, schema/template lookup returns nonempty assets, and unknown IDs or mismatched known pairs fail. | Entries omit report identity, so a complete known pair can be assigned to the wrong report; `AUD-036`. |
| Asset ownership and immutability | `promptassets` embeds and returns independent copies of all four schema byte slices. `generatedtext.Handler.Schema` adds report context; `reporttemplate` production code owns templates and does not own schemas. | Production ownership and copy isolation are coherent. Schema tests placed in `reporttemplate` duplicate the asset owner's assertions; `AUD-039`. |
| Error safety | Semantic required-field errors and catalog errors contain stable report/schema/template identifiers. JSON library errors are wrapped with report kind and preserve causes. | Arbitrary unknown-field names are emitted without a diagnostic bound and can be wrapped into normal application errors; part of `AUD-038`. No raw value is otherwise deliberately included. |
| Complexity and realistic cost | Scoped validators are straight-line except for one pass over discussion paragraphs; catalog lookup scans four fixed entries. Normal work is linear in provider output and paragraph count. | Algorithms are proportionate, but absent input/array limits make their allocation and normalization cost attacker/provider-controlled; `AUD-038`. |
| Test ownership and durability | Focused tests cover all four dispatches, canonical normalization, malformed/type/multiple-value cases, required semantics, retired fields, catalog lookup, schema inventory/identity, and independent schema bytes. | Exact report pairing, schema/Go agreement, and bounds are unprotected. Day-style semantics and schema shapes are redundantly asserted across packages; `AUD-036` through `AUD-039`. |
#### Commands And Evidence
- Used graph architecture, symbol and augmented-code search, inbound/data-flow
tracing, snippets, and complexity queries for catalog lookup, schema access,
typed decoding/normalization, report validators, application execution, and
their production/test callers. Bounded text inspection covered the four JSON
schemas, scoped tests, generated-text/Promptkit documentation, and policy.
- Compared each schema's exact required fields and property shapes with Daily,
Today, Tomorrow, and Hourly structs and semantic validators. Traced schema
validation status through Promptkit adaptation into app's handler dispatch
and verified schema byte-copy isolation and fixed catalog scan cost.
- Ran temporary offline probes showing that a Daily definition accepts the
known Hourly pair, Go accepts case-varied summary/discussion keys while real
embedded-schema validation rejects them, both layers accept a two-MiB valid
summary, and a 64-KiB synthetic unknown key appears in full in the decoder
error. The probes were removed without retaining source or test changes.
- Ran
`go test -coverprofile=/tmp/weatherreporter-stage12-cover.out ./internal/generatedtext ./internal/promptassets ./internal/reporttemplate`;
all packages passed with 81.3%, 73.7%, and 86.2% statement coverage
respectively. Coverage guided branch inspection but was not itself treated
as a finding. Ran `go test ./...`, `go vet ./...`, and `git diff --check`;
all passed.
- Findings: `AUD-036`, `AUD-037`, `AUD-038`, and `AUD-039`.
- Retained decisions: `RET-025` and `RET-026`.
- Open questions: the three leads recorded above are routed to their assigned
### Stage 13: Audit Render Contexts, Templates, And Markdown Rendering
- Status: Complete.
- Scope reviewed: `internal/generatedtext/render_context.go` and all focused
context tests; all production code, tests, four top-level templates, and four
partials in `internal/reporttemplate`; the generated-text and report-template
internal documents; the complete maintainer template guide; and the narrow
catalog/application caller path needed to establish report identity,
template pairing, and in-memory render behavior.
- Exclusions: Generated-text JSON decoding and schema semantics remain Stage
12 except where their validated strings enter Markdown; application
preparation, immutable copies, and execution ordering remain Stage 14;
publication and notification consequences remain Stages 15-18; portfolio-
wide test and complexity work remains Stages 19-23; documentation-wide
coherence remains Stage 24; and broader adversarial rendering remains Stage
25.
#### Context And Markdown Accounting
| Contract or risk | Context, template, partial, caller, and test evidence | Disposition |
| --- | --- | --- |
| Report metadata and identity | Hourly builds location and rolling-period labels; day-style reports derive civil-date/day-name labels and preserve distinct titles. Timezones, generated times, and periods are validated before construction. | Builders do not validate the report ID or reconcile the separately decoded metadata stanza; `AUD-040`. Error branches for invalid time metadata also lack focused tests, to be covered with the identity remediation rather than as a second finding. |
| Module-to-context mapping | Snapshot stanzas are selected by canonical stanza name, JSON-normalized through `module.StanzaValue`, and projected into typed optional pointers. Common day-style extraction is followed by report-specific Daily, Today, or Tomorrow planning fields; Hourly has its own surface. Extraction errors name the failing module. | Coherent under valid snapshots and retained as `RET-027`. Snapshot schema-version permissiveness remains the upstream `AUD-022`; duplicate stanzas are rejected by `module.NewSnapshot`. |
| Deterministic daypart ordering | Typed row slices follow `DerivedFacts.DaypartSummaries`, try canonical and date-qualified keys, suppress already selected keys, then append remaining module keys lexically. Templates range only the ordered slices, not the source map. | Byte-stable and semantically protected for configured and remaining rows. Upstream key collisions remain `AUD-024`; no new ordering defect. |
| Generated prose slots | Summary and forecast discussion occupy explicit top-level prose positions. Precipitation prose renders only when deterministic precipitation windows exist, preventing that slot from creating a dry-period timing section by itself. | Slot selection is coherent, but raw Markdown lets any prose slot create unauthorized report structure; `AUD-041`. Unbounded prose remains `AUD-038`. |
| Deterministic sections | Alert/SPC, current conditions, hourly/daypart forecast, precipitation windows, and their numeric values come from typed module fields. Alert instructions/descriptions and unused planning/narrative modules do not silently enter current output. Enhanced-or-higher SPC policy is centralized in helpers. | Current field ownership is explicit. Dynamic module strings share the Markdown-escaping defect in `AUD-041`; Today's all-filtered daypart case is `AUD-042`. |
| Missing values and report variation | Optional module pointers are guarded. Hourly provides explicit current/hourly fallbacks; day-style reports provide daypart fallbacks; Today alone includes current conditions and deliberately suppresses conditionless rows. Daily/Tomorrow share one richer daypart partial. | Intentional variation is preserved, except Today's row filter can leave a bare heading; `AUD-042`. |
| Template and partial lookup | Four fixed IDs resolve independent embedded source strings. `Render` applies `missingkey=error`, parses the chosen top-level asset and every shared partial, and attributes lookup, top-level parse, partial read/parse, and execution failures. All partials being parsed for every report makes a broken shared asset fail closed. | Coherent and retained as `RET-028`. Schema ownership remains in `promptassets`; catalog report pairing remains `AUD-036` and misplaced schema tests remain `AUD-039`. |
| Escaping and formatting | Repository literals define headings, bullets, ordering, and spacing. Templates use `text/template`; dynamic strings are not recursively evaluated as template actions. | There is no Markdown/HTML structural escaping for provider or source-derived strings; `AUD-041`. |
| Output determinism | Embedded assets, typed slices, fixed partial order, and absence of current map iteration make repeated rendering of an unchanged context byte-identical. A temporary repeat-render probe confirmed identical output. | Sufficient. Context aliasing/immutability before rendering belongs to Stage 14. |
| Test review value | Tests cover real context construction for all reports, rich/omitted modules, module decoding errors, ordering, partial thresholds, conditional sections, fallback rows, open-ended precipitation, missing context, actionable unknown IDs, and semantically important output order. They use focused fragments rather than full-output goldens. | Good semantic review value under `RET-028`. Identity mismatch, Markdown structure, and all-filtered Today rows are missing and attach directly to `AUD-040` through `AUD-042`; cross-suite fixture cost remains Stages 20-21. |
| Complexity and cost | Builders are straight-line projections plus linear stanza/daypart passes; remaining daypart keys sort deterministically. Template helpers scan small alert/SPC slices, and rendering parses eight embedded assets per call. | Proportionate at current service-sized inputs. Output-size amplification remains `AUD-038`; cross-cutting render performance remains Stage 22. |
#### Commands And Evidence
- Used graph architecture, symbol and augmented-code search, snippets,
inbound traces, and complexity queries for all context builders, module
extraction, daypart ordering, template lookup/rendering, partial helpers, and
application callers. Text inspection covered every scoped Go file, template,
partial, focused test, and canonical template/internal document.
- Cross-checked every current template field against its typed context
producer, confirmed no template ranges over a map, inventoried optional
guards and fallbacks, compared the Today/Daily/Tomorrow variations, and
traced normalized snapshot values and validated generated prose into
repository-owned Markdown.
- Ran temporary offline probes showing that a Daily builder accepts outer
Hourly metadata alongside a Daily metadata stanza, a schema-valid generated
summary can inject an Alert Digest heading and fabricated warning bullet,
repeated rendering is byte-identical, and an all-filtered Today daypart slice
produces a bare heading. The probes were removed without retaining source or
test changes.
- Ran focused coverage for `./internal/generatedtext` and
`./internal/reporttemplate`; both passed with 81.3% and 86.2% statement
`prompt_generate.go`, and `profile_execution.go`; the narrow ordinary,
batch, and comparison callers needed to establish collection order,
preparation count, cancellation, and partial-result consequences; and the
prepared-report and application-orchestration internal contracts.
- Exclusions: Single-report destination resolution and atomic publication
remain Stage 15; batch continuation and notification remain Stage 16;
comparison identity/publication and scheduling remain Stages 17-18;
portfolio-wide test consolidation and application refactoring remain Stages
20-23; documentation-wide reconciliation remains Stage 24; and broader
adversarial execution remains Stage 25.
#### Preparation And Execution Accounting
| Contract or risk | Ordering, copy, execution, and test evidence | Disposition |
| --- | --- | --- |
| Pre-collection validation | Ordinary and comparison flows resolve report and destination before optional debug initialization, then inspect prompt/profile and credentials before `collectWeather`; batch inspects all needed prompt/profile pairs before its one collection. Exact prompt ID/version, one required YAML input, JSON Schema output path, selected profile ID, and environment credential availability fail before collection. | The generated-text template/catalog binding is absent from this preflight and is checked late; `AUD-043`. Output publication preflight remains with the assigned later stages. |
| Prompt/profile inspection | Inspection is side-effect-free, caches one effective batch profile, preserves explicit comparison order, and returns a successfully inspected comparison prefix on profile failure. Unclassified dependency failures become content-safe configuration errors. | Coherent and retained as `RET-030`, except that safe provenance can be incomplete and is not later reconciled; `AUD-044`. |
| Post-collection preparation | Preparation requires a bundle, builds facts once, builds one ordered module snapshot and metadata value, constructs and deterministically serializes the curated package, resolves a generated-text handler, and wraps every failure with its operation. No model or normal publication occurs on a preparation error. | The construction boundary is explicit. Catalog lookup order is `AUD-043`; missing serialization/no-executor regression remains `AUD-033`. |
| Immutable prepared state | Facts, snapshots, metadata, source warnings, resolved slice-bearing fields, and YAML bytes are copied before retention. Executor requests receive byte copies and rendering receives fresh typed clones. Focused tests mutate the source bundle and returned render values; concurrent comparison tests observe equal package bytes for every profile. | Demonstrably isolated for current types and retained as `RET-029`. The manual future option-shape risk is routed to Stage 23, not treated as a current alias defect. |
| Single-build reuse | Ordinary generation prepares once for its one selected profile. Comparison collects and prepares once, then passes the same immutable logical package through independent copies to every profile; it does not recompute facts or modules per provider. | Matches the prepared-report contract and avoids cross-profile derivation drift. |
| Executor request and cancellation | Execution receives the inspected prompt ID/version, selected profile ID, caller context, independent YAML bytes, and debug capture only when explicitly enabled. Classified provider errors retain their category; otherwise they become generation errors. The reusable executor/render core performs no durable writes. | Request shape and context propagation are coherent. Missing provenance checks are `AUD-044`; post-render publication cancellation and comparison aggregation remain Stages 15 and 18. |
| Debug callbacks | Preparation debug is written only through the explicit writer. A requested callback write failure is marked local and returned directly, preventing provider work under the executor contract; execution-debug failures stop before rendering/publication. Normal results retain only safe identities and an artifact path. | Matches Stage 11's secure-debug ownership. Callback invocation and identity are nevertheless trusted rather than verified; part of `AUD-044`. |
| Generated text and rendering | Only completed `passed` validation proceeds; `failed` becomes validation rejection and incomplete states become operational validation errors. The prepared handler independently validates raw JSON, clones render inputs, builds a typed context, and renders in memory. | Correct layer order under coherent provenance. Schema/mode and execution identity are not tied to the inspected contract; `AUD-044`. Existing schema, size, context, and Markdown findings remain `AUD-036` through `AUD-042`. |
| Errors and partial results | Preparation and execution wrappers preserve actionable operation names. Ordinary generation copies source warnings after preparation and records resolved profile identity, validation status, and debug path before returning execution errors. Comparison outcomes independently retain ordered safe execution status. | Coherent for reachable callers. Durable-path truthfulness and aggregation policy remain explicitly assigned to Stages 15-18. |
| Complexity and test ownership | The preparation path is a guarded straight-line pipeline over service-sized typed values; its dominant cost is deliberate deep copy and serialization. Execution is another guarded pipeline with no loop. Focused suites own inspection, mutation isolation, debug callbacks, validation states, rendering without publication, and concurrent shared-package reuse. | No Stage 14 performance finding. Missing invalid-catalog ordering, provenance mismatch, and serialization consequence tests attach directly to `AUD-043`, `AUD-044`, and `AUD-033`. |
#### Commands And Evidence
- Used graph symbol and augmented-code search, exact source snippets,
inbound/data-flow traces, and scoped complexity metadata for preparation,
inspection, ordinary generation, profile execution, collection, and
comparison reuse. Bounded text inspection covered the four scoped production
files, focused tests, task-specific internal documents, audit plan, and all
repository policies.
- Enumerated every pre-collection failure (report/output/debug setup, executor,
exact prompt shape, profile selection, and credentials), post-collection
| Contract or risk | Destination, filesystem, result, and test evidence | Disposition |
| --- | --- | --- |
| Stage order and destination precedence | Report resolution precedes output resolution; an explicit file wins over the configured directory, which wins over the captured absolute working directory. Existing configured non-directories fail before prompt inspection or collection, while missing directories are deferred until publication. | Coherent for ordinary paths. Catalog preflight remains `AUD-043`; CLI executor-before-date ordering remains `AUD-009`. |
| Path normalization and target type | Relative paths are anchored to the captured working directory, absolute paths are cleaned, roots and directories are rejected, and result paths are absolute. Final validation otherwise accepts every non-directory object and follows symlinks. | Destructive special-file and ambiguous symlink behavior is `AUD-045`. |
| Atomic write and linearization | The writer creates a temporary file in the destination directory, writes and closes complete bytes, then uses same-directory `os.Rename`. Successful rename is the single visibility/commit point. Existing regular output is untouched on all earlier application failures and writer failures before rename. | Mechanism retained as `RET-031`. Temporary naming can reject a valid final component in `AUD-046`; crash durability is not claimed. |
| File and directory modes | `os.CreateTemp` creates new report files as mode `0600`; `MkdirAll` requests `0755` for missing operator-selected parents and leaves existing modes unchanged. Replacement takes the temporary file's restrictive mode. | Safe for report content. Focused tests do not assert the final mode, but the standard-library primitive directly defines it and no conflicting user contract exists; no coverage-only finding. |
| Temporary and failure cleanup | A deferred remove covers write, close, and rename failures after temporary creation; the rename-error test proves no matching temp remains. Parent directories created before a later create/write failure are not rolled back. | Temp cleanup is coherent. The valid-long-name failure and directory residue are `AUD-046`; broad directory rollback would need concurrency-safe ownership. |
| Cancellation | Cancellation/deadline before publication entry returns the stable category, leaves `OutputPath` empty, preserves previous bytes, and skips notification; focused app tests cover both. | The check precedes all temporary I/O rather than the rename boundary, so later-observable cancellation can still commit; `AUD-047`. |
| Pre-publication preservation | Prompt inspection, collection, generation, schema/typed validation, render, debug-write, destination, cancellation, and atomic-write failures occur before `OutputPath` is set. Tests preserve an existing file across generation, render, cancellation, deadline, and directory-collision failures; fileutil tests cover rename error and temp cleanup. | Sufficient for regular files aside from the final cancellation gap. Stage 14 owns preparation/execution provenance and Stage 16 owns multi-output consequences. |
| Post-publication semantics | Immediately after rename, the result records the absolute path. Optional notification is then built from and sent with that exact file. Notification failure returns a failed action while retaining the committed path and Markdown; disabled notification returns success without a notification object. | Coherent and retained as `RET-032`. Single-report identity rendering gaps remain `AUD-005`; Distributor adapter/batch policy remain Stage 16. |
| Errors and CLI result truth | Cancellation is wrapped with report/run/operation context and preserves its category. Filesystem errors carry the exact affected directory, temp operation, or final path; notification errors carry report/run/output context. CLI projection copies active safe fields, committed path, notification, and returned error, marking any result-bearing error failed. | Actionable and truthful at the reviewed boundary. Assembled non-comparison CLI status/exit tests remain the existing `AUD-010`. |
| Complexity and test ownership | Resolution and publication are short guarded pipelines; file publication is constant-pass work over rendered bytes and has no service-sized loop beyond the write itself. App tests own workflow preservation/result ordering; fileutil tests own atomic replacement and temporary cleanup. | No Stage 15 complexity finding. Missing special-target, long-name, and final cancellation cases attach directly to `AUD-045` through `AUD-047`. |
#### Commands And Evidence
- Used graph symbol and augmented-code search, exact snippets, inbound/outbound
traces, and scoped complexity/coverage data for `GenerateDetailed`, output
resolution and validation, publication/cancellation, atomic writing,
notification, and CLI result projection. Bounded text inspection covered all
scoped production/tests, task-specific documents, policies, and the exact
Stage 15 boundary.
- Traced every consequential result through the CLI projection: pre-result
resolution failure, resolved but unpublished destination/preflight,
races remain Stage 25; and finding remediation remains outside this audit
stage.
#### Batch Outcome And Delivery Accounting
| Contract or risk | Planning, publication, delivery, result, and test evidence | Disposition |
| --- | --- | --- |
| Pre-collection validation | The application resolves the selected batch, output directory, debug writer, and one representative of every possible prompt/profile identity before collection. The Daily candidate uses the first possible post-Tomorrow date; later Daily reports share its definition and execution profile. | Coherent. Generated-text catalog timing remains `AUD-043`; unsupported Distributor endpoint forms are not included in this gate and are `AUD-048`. |
| Collect-once and data-dependent plan | One collected result is retained for every item. Morning plans Today then Tomorrow; Evening plans Tomorrow; both append only complete post-Tomorrow local civil days in ascending order. DST transition days are checked by instant coverage rather than assuming 24 rows. | Coherent and retained as `RET-033`. Daypart clock semantics remain the separate `AUD-002`. |
| Complete output preflight | After collection determines membership, every final absolute report path is resolved and validated before any executor call. A later invalid destination prevents all report replacement; an existing earlier file remains untouched. | Coherent for the fixed distinct registry outputs. Each final path retains the single-file limitations in `AUD-045` through `AUD-047`. |
| Sequential execution and partial success | Reports execute one at a time in plan order through the shared generation/publication core. Per-report notification is suppressed. An independent item failure is recorded and later items continue; successful files and their output paths remain. Counters match appended report statuses. | Coherent and retained as `RET-034`. Shared cancellation is incorrectly treated as repeatable independent failure in `AUD-051`. |
| Notification gate and request membership | Disabled integration yields no notification object. Any report failure yields one skipped result and no notifier call. All-success execution builds one request after all sources exist, matches results to unique planned run IDs, rejects duplicate bundle paths, and maps only each report's committed output path in report/template order. | Coherent and retained as `RET-035`. Dynamic single-report identity emptiness remains `AUD-005`; active endpoint admission remains `AUD-048`. |
| Exactly-once ownership and retries | The application invokes the batch notifier once; the adapter constructs one client, calls `UploadFiles` once at its boundary, then performs status lookup/polling. The pinned dependency alone owns replay-safe retries and reuses the supplied idempotency key. Status failures retain accepted-upload diagnostics; terminal run failure fails notification. | Ownership is coherent. Local tests do not traverse the production HTTP path (`AUD-052`), and remote response safety/bounds are `AUD-049` and `AUD-050`. |
| Report versus notification accounting | Report totals count only report items. A skipped notification follows a report failure; a failed notification leaves every report succeeded and every committed path intact but makes `RunBatch`, the CLI summary, and exit status fail with notification-specific wording. Accepted-but-unconfirmed status remains separate diagnostic state. | Coherent and retained as `RET-035`. Normal remote error text is not safe merely because it is notification-specific (`AUD-049`). |
| Cancellation and timeout | Context reaches inspection, collection, every prompt execution/publication, Distributor upload, retry delay, status request, and polling timer. Adapter timeout returns the latest accepted/run status plus a diagnostic when confirmation does not finish. | Adapter propagation is coherent. The batch loop continues after shared cancellation and loses cause identity in aggregate/CLI errors (`AUD-051`); final report rename timing remains `AUD-047`. |
| Response lifecycle and resource safety | The pinned HTTP client closes upload and status bodies and the adapter copies returned JSON so results do not alias dependency buffers. Conflict type identity and exact bearer-token replacement survive local wrapping. | Body closure and typed conflict handling are sound. Remote body text reaches normal output (`AUD-049`) and all response classes are unbounded (`AUD-050`). |
| Test ownership and cost | App tests own preflight, ordering, partial files, all-output-before-notify, one notifier call, counters, and notification-failure exit semantics. Adapter fakes cover mapping, polling, conflicts, and token replacement without importing app policy. Planning is linear over the forecast horizon and report/file mappings. | App ownership is appropriate. Adapter tests substitute below the production HTTP translation and need a narrow realistic local boundary under `AUD-052`; broader duplication/cost review remains Stages 20-22. |
#### Commands And Evidence
- Used graph symbol and augmented-code search, exact snippets, and caller/callee
traces for batch execution, planning, destination preparation, notification
request construction, Distributor upload/status translation, and CLI result
projection. Bounded text inspection covered every scoped production/test
file, all assigned canonical documents, policies, and the exact Stage 16
boundary.
- Traced every consequential batch outcome: setup/preflight failure before a
result; independent report failure before or after a peer publication; full
report success with notification disabled, skipped, accepted/unconfirmed,
terminally succeeded, or failed; request-construction failure; upload
conflict; status error; timeout; and shared cancellation. Cross-checked
report paths, counters, notification state, summary wording, and exit status.
- Inspected the pinned Distributor `v0.5.0` client and bundle contracts to
distinguish repository wiring from dependency-owned retries, idempotency,
archive construction, endpoint grammar, body closure, and response parsing.
This showed the production-only endpoint mismatch and unbounded/raw response
paths without treating upstream unit tests as local adapter coverage.
- Ran focused race/coverage checks for `./internal/app` and
`./internal/adapters/distributor`; both passed with 76.0% and 70.5% statement
coverage respectively. Coverage guided missing cancellation and production
boundary inspection but was not itself treated as a finding. Ran
`go test ./...`, `go vet ./...`, `go run ./cmd/weatherreporter --help`, and
`git diff --check`; all passed.
- Findings: `AUD-048` through `AUD-052`.
- Retained decisions: `RET-033` through `RET-035`.
- Open questions: the three leads recorded above are routed to their assigned
result construction, and CLI integration remain Stage 18; repository-wide
test, efficiency, and refactoring review remain Stages 19-23;
documentation-wide reconciliation remains Stage 24; adversarial pathname and
crash robustness remain Stage 25; and remediation remains outside this audit
stage.
#### Durable Bundle And Filesystem Transaction Accounting
| Contract or risk | Model, destination, mutation, recovery, and test evidence | Disposition |
| --- | --- | --- |
| Logical identity and names | Profile IDs require at least two exact distinct nonblank values. Comparison IDs derive from report run IDs; directory names derive from report output names; profile slugs retain the documented ASCII set and byte bound; ordinal width expands at 100 and higher. | Pure helpers are deterministic and focused tests cover boundaries. Manifest validation does not connect successful paths back to `ReportFilename`; `AUD-054`. |
| Manifest schema and encoding | One current version validates nonzero ordered timestamps, valid period, identity/hashes, at least two contiguous distinct profile results, exact counters, success/failure shapes, bounded UTF-8 messages, and unique safe report basenames. Encoding is two-space indented in declaration order with one newline. | Core shape is coherent and retained as `RET-036`. Recognition accepts duplicate/case-variant JSON fields (`AUD-053`) and arbitrary safe report names (`AUD-054`). |
| Logical payload agreement | `LogicalBundle.Validate` hashes the exact data-package bytes, requires one report for each and only each successful manifest result, and reconciles report order, positions, and paths before any filesystem mutation. Failed results carry no Markdown. | Coherent aside from the shared canonical-name gap in `AUD-054`. Report-content hashes are deliberately not part of the current schema. |
| Recognition and compatibility | Recognition requires a real directory containing exactly the declared manifest, data package, and successful reports as regular non-symlink files; rejects unknown fields, trailing JSON, unsupported versions, unsafe paths, extra/missing entries, and a data digest mismatch. | Exact file/type/digest protection is strong. Decoder ambiguity is `AUD-053`; full report reads are routed to Stage 22. |
| Read-only destination authorization | Planning requires clean absolute working/target paths, rejects roots, the exact working directory, final symlinks, non-directories, unreadable states, and nonempty content without explicit recognized replacement; missing-parent inspection creates nothing. Empty targets remain usable without `--replace`. | Coherent and retained as `RET-037`. Existing parent symlinks and adversarial path changes are routed to Stage 25. |
| Staging mutations | After bundle validation and replanning, publication creates missing parents, a mode-`0700` sibling staging directory, and mode-`0600` data/report/manifest files with exclusive creation; manifest is written last and deferred cleanup removes uncommitted staging. | Restrictive complete staging is coherent. Derived staging/backup components reject valid long targets and can leave new parents; `AUD-057`. Mid-write failure seams are simple and remain pre-target. |
| Initial commit | Immediately before installing an absent target, publication replans, exposes a deterministic final test hook, checks context, and uses one sibling rename as the visibility linearization point. Rename failure retains no target and deferred staging cleanup runs. | Coherent for ordinary filesystem state and retained in `RET-038`. Syscall races remain Stage 25. |
| Replacement authorization and rollback | Replacement moves the current empty or recognized target to a unique sibling, re-runs destination/recognition policy against the moved entry, and restores it if authorization or staging installation fails. A reappeared target is not overwritten during restoration; the error retains the backup path. | Strong ordinary-state defense, retained as `RET-037` and `RET-038`. Cancellation after the first rename is not rechecked before install; `AUD-055`. |
| Committed state and backup cleanup | Once staging is renamed to target, the new bundle remains authoritative. Successful backup removal returns clean commit; removal failure returns `Committed: true`, a typed error, and a sibling path rather than rolling back the new bundle. | Correct commit truth is retained as `RET-038`. Recursive cleanup may already have damaged or removed the old bundle, so the reported retained-backup state is overstated in `AUD-056`. |
| Safe and recovery errors | Destination kinds and `ErrUnrecognizedBundle` are inspectable; pre-commit restoration errors join the triggering cause with target/backup recovery context; post-commit cleanup errors unwrap the filesystem cause. Manifest failures remain bounded through `SafeError`. | Error identity is actionable. `AUD-056` requires surviving cleanup state to be classified truthfully; Stage 18 owns safe CLI projection of these package errors. |
| Test ownership and transaction cost | Model tests own naming, invariants, encoding, hashing, and logical reconciliation. Real `t.TempDir` tests own layout, modes, recognition, destination states, commit, restore, reauthorization, retained paths, and cancellation; injected rename/remove operations deterministically reach recovery states. Work is linear in profiles and artifact bytes. | Good package-boundary ownership. Missing strict decoding, canonical-name, post-backup cancellation, partial-cleanup, and long-name cases attach directly to `AUD-053` through `AUD-057`; broader cost and suite maintenance remain Stages 20-22. |
#### Commands And Evidence
- Used the codebase graph architecture view, symbol search, exact snippets, and
caller/callee metadata for manifest validation/encoding, identity helpers,
destination planning, recognition, publication, restoration, and cleanup.
Bounded text inspection covered all four scoped Go files, every focused test,
the exact Stage 17 boundary, and all assigned canonical documents/policies.
- Traced every filesystem mutation from parent creation through staging files,
bundle-model and filesystem-transaction defects; Stage 14 owns prepared
execution provenance.
#### Comparison Execution And Result Accounting
| Contract or risk | Execution, publication, CLI, and test evidence | Disposition |
| --- | --- | --- |
| Ordered explicit selection and sequential preflight | CLI parsing preserves repeated profile order and validates exact distinct IDs before config/executor work. Application inspection resolves the prompt once, then profiles sequentially in supplied order, stopping at the first failure before collection. Resolved prompt identity survives later preflight failures in the partial result. | Coherent. Generated-text catalog timing and provenance reconciliation remain `AUD-043` and `AUD-044`. |
| Collect/prepare once and identical immutable input | After destination, debug, prompt, profile, and credential preflight, comparison calls weather collection and `prepareReport` once. Every execution receives an independent byte copy of the same serialized YAML plus cloned prepared values, so provider mutation cannot affect peers. Focused concurrent tests compare the captured package bytes. | Coherent and retained as `RET-039`. |
| One executor, concurrency, and backend capacity | CLI constructs one Promptkit adapter and passes it into one comparison request. Application starts one goroutine per selected profile; the backend owns configured provider capacity rather than an application semaphore. Production execution creates a private prepared handle per call. | Ownership matches the contract. Extreme profile-count cost is routed to Stage 22, and the interface comment gap to Stage 24. |
| Goroutine lifecycle and shared state | Each goroutine captures its own loop index/profile, writes only that preallocated slice element, and decrements one wait group. The caller waits for every started goroutine before reading outcomes or returning. Immutable prepared state and concurrency-safe executor/debug boundaries are shared; the scoped race suites pass. | Joined and race-clean for covered production boundaries; retained as `RET-039`. |
| Profile isolation and cancellation | Generation, validation, render, and debug failures stay in their own safe bounded outcome while peers continue. Context reaches every execution, prevents later starts when observed, joins started work, and prevents publication. The post-join sweep nevertheless overwrites an independent completed failure when any peer makes cancellation observable. | Mixed failure identity is incorrect in `AUD-058`; all-canceled joining and failure-without-cancellation have focused tests. |
| Deterministic result and debug identity | Results are initialized and stored by caller position, copied to the application result in that order, encoded into the manifest in that order, and projected by CLI without sorting. Filenames use position/count/profile identity; debug run IDs include comparison identity, ordinal width, and profile slug. Inverse completion and distinct-debug tests cover both properties. | Completion order cannot change durable or CLI order; retained as `RET-039`. Canonical filename validation remains `AUD-054`. |
| Partial and all-failed publication | After all noncanceled work joins, one logical bundle contains the exact shared package and only successful Markdown reports. Independent failures do not suppress publication; both partial-success and all-failed manifests commit, then the application returns a comparison aggregate error. Paths become visible only after commit. | Coherent and retained as `RET-040`. Execution provenance remains `AUD-044`. |
| Publication and post-commit cleanup failures | Pre-commit destination/publication errors leave manifest, data-package, and report paths empty. A committed bundle followed by backup-cleanup failure retains authoritative target paths and profile report paths while returning a typed failure. CLI maps destination and cleanup errors to stable content-safe categories. | End-to-end projection is truthful for the currently reported package state. Underlying cancellation/partial-cleanup defects remain `AUD-055` and `AUD-056`. |
| Never-notify policy | `ComparisonRequest`, comparison orchestration, and CLI comparison wiring expose no notifier. The complete call path ends at bundle publication and aggregate result construction, never Distributor delivery. | Matches policy and retained in `RET-040`. |
| Safe summaries and exit behavior | Result-bearing outcomes emit one ordered JSON summary unless quiet. Per-profile errors are already bounded `SafeError` values; top-level aggregate, prompt, destination, cleanup, cancellation, and deadline errors map to fixed safe categories/messages. Success requires all profiles plus committed manifest/data paths; partial, all-failed, publication, cleanup, and cancellation paths return an error and failed status. | Coherent and retained as `RET-041`. Pre-result input/config failures deliberately remain ordinary CLI diagnostics. |
| Test ownership and cost | Application tests own order under concurrent completion, equal input bytes, capacity observation, failure isolation, cancellation joining, debug identities, collect/prepare/publish ordering, partial/all-failed bundles, destination changes, preservation, and cleanup paths. CLI tests own parsing/wiring, one executor, safe structured outcomes, quiet mode, committed cleanup, and status. | Focused ownership is strong except for the mixed cancellation overlap in `AUD-058`; broader suite and cost review remain Stages 19-22. |
#### Commands And Evidence
- Used codebase graph symbol and augmented-code search, exact snippets, and
caller/data-flow inspection for comparison orchestration, profile execution,