# Offline NWS normalization preview

`normalize-nws.mjs` converts **already saved, hash-verified** property/evidence JSON into proposed `hazard_record` and `measurement` rows. It supports two adapters: `nws-observation` (registry ID `nws-observations`) and `nws-alerts`. It makes no requests and opens no database. This is a review artifact, not an executable migration or a claim that the source reflects current conditions.

Use Node 20 or newer. Keep `normalize-nws.mjs`, `import-bundle.mjs` and `api-registry.json` from the same release together. Download all three from the website's data-foundation section or use this directory in the repository.

```powershell
# Use a previously exported packet; no browser fetch is needed:
node normalize-nws.mjs "$env:USERPROFILE/Downloads/property-brief.json" ./nws-preview-001.json
# Omitting the output argument prints JSON to stdout instead.
node --test normalize-nws.test.mjs
```

The output path must be new; an existing file is refused. Full source-envelope, provider-host and raw-text SHA-256 validation uses the existing importer before any output is written. A tampered source anywhere in the input rejects the entire packet. Invalid individual NWS records are explicitly listed under `sources[].rejected`. Failed, unsupported, empty and partial source runs remain visible; unsupported records are not normalized. The importer still accepts the prototype's nine export IDs mapped to its 17-entry registry.

## Row contract and provenance

`tables.hazard_record` and `tables.measurement` use the current proposed SQL column names. `rowProvenance` maps every row ID to the exact verified run ID, original raw-response SHA-256, content-addressed raw-file key, JSON pointer and request URL. Measurement pointers name the original observation quantity. Raw-file paths and run IDs match the separate import bundle; this preview does not duplicate or overwrite that bundle. The top-level input hash identifies the export file. Analyst notes, property labels, portfolio exposures and scenario assumptions are not imported.

Record identity uses the supplied observation/alert ID; observations can fall back to station plus observation time. `revision_key` hashes canonical source-feature JSON (sorted object keys, preserved array order). Identical records deduplicate across requests while retaining every distinct run in provenance; different source revisions remain separate. Adapter `nws-observation-alert-preview-v2` prefers a run with known retained-body completion as the representative for an identical revision, then sorts by deterministic run ID. This keeps results independent of packet order and preserves legacy/new origins; it is not a newest-record selection. Every `is_current` flag is **0**. The adapter does not resolve alert cancellations/references or claim historical completeness.

New browser exports capture optional timing metadata. After importer validation, `retrieved_at` uses the actual full-body-read time of retained, hash-verified bytes. Provenance separately retains request start, response-header time, body-read time and later processing completion. All times are client wall-clock observations, not server-certified metadata. Legacy exports without timing still produce `retrieved_at: null`, while `schema.sql` requires NOT NULL; that gap remains explicit in `reviewIssues`. Request start and processing completion never substitute for retrieval. Failed sources remain visible with their timing but do not become hazard rows. See [request timing contract](README.md#request-timing-in-new-exports).

Missing measurement units similarly stay null instead of inventing a unit. The preview always has `previewOnly: true` and `readyForDatabase: false`, even if a new capture resolves its timing gap. Review the remaining schema/semantic issues before a later migration. This tool does not alter the schema or database. Use the updated importer and normalizer together; offline download dependencies remain the same three files.

## Station observation adapter

Seven quantities are retained: `temperature`, `dewpoint`, `windSpeed`, `windGust`, `relativeHumidity`, `barometricPressure`, and `precipitationLastHour`. `value` is a finite source number or null; `unit` and `original_unit` retain the source `unitCode` verbatim. No unit conversion is performed. Recognized codes are annotated; unfamiliar codes are preserved and flagged, without discarding a numeric value or assigning a default unit.

| Source condition | Preview behavior |
| --- | --- |
| Numeric zero | Retain `0` with `reported_number` label |
| Explicit `value: null` | Retain null and `null_value` |
| Quantity absent | Emit missing row with `absent_quantity` |
| Quantity lacks `value` | Retain null and `absent_value` |
| Invalid value type | Retain null and `invalid_value_type`, preserving original quantity |
| Unit missing | Keep unit null and a schema blocker |
| Quality-control flag | Retain original code without inferring pass/fail |

The observation timestamp is normalized to UTC; the original stays in the payload. Explicit RFC3339 timestamps with up to millisecond precision are accepted. Invalid required times reject that record visibly. Station-point longitude/latitude are used only when valid; the original payload retains other geometry. Station data are not property measurements. `ageAtRequestSeconds` is relative to exported request start, not the present time; negative ages remain visible.

For `precipitationLastHour`, the preview labels an accumulation and derives the one-hour interval ending at observation time. Quality metadata identifies that interval as inferred from the field name. No interval is invented for wind/gust or other quantities. Vertical datum and source update time remain unknown.

## Alert adapter

`issued_at` comes from `sent`. `valid_start` / `valid_end` use `effective` / `expires`, describing **message information** validity. Event `onset` / `ends` remain separate in `quality_json` and the payload; event end never substitutes for message expiry. Missing/invalid optional times remain unknown; contradictory message dates are flagged instead of corrected.

Status (including Test), message type (including Cancel), severity, certainty, urgency, affected zones, geocodes and prior references remain explicit. No alert is promoted into an active warning, cancellation lifecycle is inferred, or damage decision made. Null geometry stays null. Polygon geometry stays in the source payload but is not normalized or overlaid onto a property.

## Bounds, evidence and handoff

Importer limits: 32 MB input, 128 exported sources, 6 MB per raw response and 24 MB combined raw responses. Adapter limits: 1,000 candidate records, 7,000 measurement rows and 24 MB serialized output. Exceeding a limit rejects the preview, without silent truncation. Capped/paginated responses stay partial. Hash consistency does not prove authenticity or completeness.

Field definitions were checked against the official [NWS OpenAPI schema](https://api.weather.gov/openapi.json), specifically `Observation`, `QuantitativeValue` and `Alert`, and [NWS API documentation](https://www.weather.gov/documentation/services-web-api) on October 10, 2026 (local time). Documentation reads were separate from the offline tool. No fresh observation or alert request was needed to build or test it.

Four focused tests use synthetic records. They check zero/null/absent/invalid values, native/unknown units, schema blockers, separate message/event times, Test/Cancel labels, duplicate provenance, partial/failure visibility, invalid timestamps, record caps, hash-tamper rejection before output and refusal to overwrite. The added completion test verifies legacy nulls, captured body versus processing times, stable revision IDs and order-independent mixed-run provenance. No database was created or populated, and the blocked browser was not retried.

After publishing, a static smoke can confirm the command, importer dependency, registry and this document are downloadable. A local smoke can reuse an existing export: run the command into a new file, inspect `summary`, `sources` and `reviewIssues`, and confirm `readyForDatabase` is false. Draft rows are not a completed migration.
