Skip to content

Merge upstream v3.19.0 - #8

Merged
kesh33w merged 16 commits into
masterfrom
sacmesh/merge-v3.19.0
Nov 24, 2026
Merged

kesh33w merged 16 commits into
masterfrom
sacmesh/merge-v3.19.0

Conversation

@kesh33w

@kesh33w kesh33w commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Brings the fork up to upstream v3.19.0 (Kpa-clawbot c5b2d5d7): 16 upstream commits. Full notes: docs/release-notes/v3.19.0.md.

What upstream brings

Fork changes the merge needed

  • Grouped commits + observers rebuild: the rebuild opens its own BEGIN IMMEDIATE on a pinned connection, and our batch wrapper then tried to start its shared transaction inside it. On the WAN copy the ingestor refused to start (cannot start a transaction within a transaction). The wrapper now passes a caller-opened transaction through. New tests: TestBatchCommitCallerBeginStatementRunsAsIs, TestBatchCommitOpenRebuildsLegacyObservers.
  • Observation cleanup: archives copied observers.* by position, so after the rebuild every cleanup would be refused ("archive schema mismatch"). Archives now copy and restore by column name and gain new source columns. A restored observer gets a fresh idx. New test: TestObservationCleanupArchiveGainsNewSourceColumn. The fail-closed test now covers a broken archive key instead.
  • Fork queries join observers.idx instead of the implicit rowid. rowid would still work in SQLite, but this matches upstream.
  • Tiles: our 11-12 maxZoom fix is covered by upstream's helper, so our MC_updateTileLayer and its test are removed.

Testing

  • go vet + go test for every Go module: all pass.
  • Ingestor with CORESCOPE_TEST_BATCH_COMMIT_MS=50: one failure, TestObservationCleanupIndependentReaderSnapshot. It already fails the same way on current master; the merge added 4 failures here before the batch fix, and they now pass.
  • 263 JS unit tests from test-all.sh: all pass.
  • Offline run on copies of the live scope and WAN databases (brokers pointed at a dead port):
    • observers rebuilt (52 and 151 rows), local indexes kept
    • WAN starts with batch commits
    • server: observers/nodes/packets/channels/analytics, region=910.525 and 910.525,SJC, node reach, observer comparison, frequency config and cleanup preview all return 200 with data

Deploy notes

  • Upgrade is one-way: v3.18 refuses users.db after v10. Scope and WAN don't use user accounts, but back up all DBs first as usual.
  • Replace both ingestor and server on both instances. The rebuild needs the new ingestor, and the new server expects observers.idx.

🤖 Generated with Claude Code

anieto and others added 16 commits November 20, 2026 16:25
Follow-up to Kpa-clawbot#2415, see Kpa-clawbot#2414.

## Situation

A user can claim repeaters, but no page lists the ones they claimed.
Claims show on each node page ("Maintained by"), in the admin user
detail and in the "Download my data" export. A maintainer of several
repeaters has to remember them and open each node page to see whether
one went quiet.

## Change

**`GET /api/account/repeaters`** (browser session; device tokens answer
403) returns the caller's claims. For each one:

- `pubkey` and `name`.
- `known`: false once the node left the analyzer database. The claim
stays.
- `role` and `claimedAt`.
- `lastHeard`: the newer of the last advert and the last transmission
certainly from the node, the same sources as the node page's Last Heard.
- `lastRelayed`: when its hop prefix last relayed. Only used to mark a
silent repeater as uncertain, since the prefix can be shared.
- `status`: the saved repeater status, or null.
- `comaintainers`: the other active claimers' display names.

The list is sorted by name, with unnamed repeaters after, by pubkey.
It's built on the existing `RepeaterClaimsByUser`, `NotifyNodes` and
`LastHeardMap`.

**My account, My repeaters**, a new section after Companions:

- Silent repeaters come first. Health uses `getNodeStatus`, so the
threshold matches the node pages and map (`infraSilentMs`):
  - green "heard 2h ago";
  - yellow "last heard …, its prefix still relays";
  - red "silent, last heard 184d ago" or "never heard";
  - grey "no longer in the database".
- Each row links to the node page and shows the saved status ("no
details yet" without one), the claim date and "also maintained by …".
- *Unclaim* asks for confirmation, then uses the existing `DELETE
/api/repeaters/{pubkey}/claim`.
- The empty state says how to claim.
- `#/account?section=repeaters` deep-links to the section, like
`section=notifications`.

Editing stays on the node page, so there's only one editor. The admin
user detail and the export are unchanged.

Docs: `openapi.go` and the Repeater info section of
`docs/user-guide/accounts.md`.

## Notes

- A mobile client will want the same list. Kpa-clawbot#2429 proposes device-token
scopes for repeater claims. If it lands, letting a `repeater:claim`
token read this route is a one-line addition to the bearer route table,
and I'd rather do that there than here.
- The two PRs touch nearby lines in `openapi.go`, `repeater_handlers.go`
(route registration) and `public/account.js`. Whichever merges second
needs a small rebase.

## Tests

- `cmd/server/my_repeaters_test.go`:
  - empty list;
  - ordering (named first, case-insensitive);
  - unheard, heard and departed nodes;
  - saved status;
  - co-maintainers, excluding the caller and disabled users;
  - another user's view;
  - unclaim removes the row;
  - anonymous gets 401 and a device token 403;
  - no analyzer DB.
- `tests/unit/test-user-management-ui.js`: health sort and chips,
escaping, the short-pubkey fallback, status and co-maintainer lines,
Unclaim on every row, and the empty state.
- `tests/e2e/test-user-management-e2e.js`:
  - the claimed repeater appears with its status and node link;
  - axe on the section;
- Unclaim: dismissing the confirm keeps the claim, accepting empties the
list.

Run locally:

- `make test`: all 16 modules OK.
- `sh test-all.sh` and `node tests/e2e/test-lint-network-calls.js`:
pass, run in `node:24-bookworm`.
- `npx eslint public/*.js`: 0 errors, the same 87 warnings as master.
- `test-user-management-e2e.js` against local e2etest servers with the
CI config: 46/46.
- Manually in Chrome, light and dark: heard, silent and co-maintained
rows, and the deep link.

Not run: the full Playwright shard matrix from CI.

---------

Co-authored-by: Adam <196335+anieto@users.noreply.github.com>
…al (Kpa-clawbot#2438)

## Summary

`TestNodeAnalyticsWindowIgnoresLocalZone` set the zone by assigning the
global `time.Local`. Every `time.Now()` reads that variable, so if a
timer left over from an earlier test fires during this test, the race
detector reports a data race. It counts as a failure of this test,
whichever test left the timer.

It showed up as an intermittent failure of the server race detector
(shard 3/4) on a PR run (Kpa-clawbot#2436). Three local runs of the same shard
passed. The code under test is fine; only the test was racy.

## Change

The test now re-runs itself in a child process with `TZ=Etc/GMT-2`
(UTC+2) and writes nothing global:
- **Embedded zone data:** `time/tzdata` is embedded in the test binary,
so the zone resolves without the host's zoneinfo.
- **Zone check:** the child first checks that its local offset really is
+02:00.
- **Test name:** the child's `-test.run` pattern is built from
`t.Name()`.
- **Vacuous pass guarded:** the parent requires `--- PASS: <name>` in
the child's output, so a rename can't make it pass without running.
- **Windows:** the test is skipped there before the re-exec. Go on
Windows takes the local zone from the OS and ignores `TZ`, so the child
cannot be put in UTC+2.
- **Bounded child:** the child runs under a 60 s context, so a hung
child fails with its output.

This follows the existing re-exec pattern in
`distance_background_fill_test.go`. `TestMain` is just
`os.Exit(m.Run())`, so the child runs only this test. It works under the
sharded `-test.run` in the race job, and in coverage builds.

## Testing

- `go test -race -run TestNodeAnalyticsWindowIgnoresLocalZone`: pass.
gofmt and vet are clean.
- **Still guards the original bug:** with `time.Now().UTC()` changed
back to `time.Now()` in `GetNodeAnalytics`, it fails as before. The 7d
window holds 166 of 168 packets, and `From` is `...+02:00`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…Kpa-clawbot#2440)

Follow-up to Kpa-clawbot#2430, covering the two points from @efiten's re-review.

- **Unclaim and Unlink stay disabled until the list reloads.** Both
click handlers now return the list reload from the DELETE's `.then`
(`public/account.js`), so the button is re-enabled only after the
redrawn list has replaced it. Before, a click between the DELETE's
answer and the list GET's answer sent a second DELETE.
- **The dropped-from-node-list note shows in every state.**
`repeaterHealth` adds "no longer in the node list" whenever `r.inactive`
is set, so an inactive repeater that was heard recently or whose prefix
still relays is marked too, not only a silent one.

Tests (`tests/unit/test-user-management-ui.js`, 103/103):
- For both Unclaim and Unlink, the button stays disabled while the list
GET after the DELETE is pending, and a click in that window sends no
second DELETE.
- An inactive repeater carries the note when active, uncertain, stale
and never heard, and none of those rows links to a node page.

`tests/e2e/test-lint-network-calls.js` 47/47.

Co-authored-by: Adam <196335+anieto@users.noreply.github.com>
…hade overlay and custom tile servers (Kpa-clawbot#2434)

Closes Kpa-clawbot#2428.

Adds free and open map providers (topographic, satellite, gray and
vector basemaps), a hillshade overlay, and support for operators' own
tile servers. Everything is additive and opt-in: Carto stays the
default, every new provider group is off until the operator turns it on,
and no existing config key or provider was removed. An upgrade with an
untouched config changes nothing in the picker.

> **Dependency:** Kpa-clawbot#2426 has merged. The branch is rebased onto current
`master` (`6c78a1d2`) with no conflicts.

## What's new

- **Provider registry** (`public/map-tile-providers.js`). New groups are
**opt-in**: each is off until `map.tiles.providers.<group>.enabled` is
`true` (the boolean), so licences and volunteer servers are the
operator's call:
- **EOX**: Sentinel-2 satellite (2025 and 2016), Terrain Light, and a
place-labels overlay. EOX 2025 imagery is CC BY-NC-SA 4.0
(non-commercial); a commercial deployment should leave `eox` off or
license it.
- **OSM France**: Humanitarian, CyclOSM, OSM Gray and OSM Gray Dark
(volunteer-run, fair use).
- **OpenFreeMap** and **VersaTiles** vector styles: Liberty, Bright,
Positron, Dark, Fiord, Colorful, Muted and the Gray variants.
- **Hillshade** (below) is opt-in the same way. **OpenTopoMap**, the OSM
community server, Stamen and USGS keep their existing opt-in.
- **Custom tile servers**: `map.tiles.custom` adds raster (XYZ), vector
(MapLibre style URL) and raster-overlay entries as `custom-<id>`. They
can be used in `darkDefault` / `lightDefault`. Invalid entries are
skipped with a console warning.
- **Hillshade overlay** (`public/map-hillshade.js`): shaded in the
browser from Terrarium elevation tiles.
`map.tiles.providers.hillshade.url` can point at a mirror.
- **Vector basemaps** (`public/map-vector.js`) use a vendored MapLibre
GL 5.24.0 (CSP build) and `@maplibre/maplibre-gl-leaflet` 0.1.4.
- They are lazy-loaded only when a vector map is picked (about 380 KB
gzipped).
  - The load times out after 15 s.
  - Without WebGL the map falls back to the theme's default raster map.
- **One picker on Map, Live and Repeater Planner**: Auto, Street,
Topographic, Satellite, plus an Overlays group.
- **A map picked there is saved** (`localStorage` `mc-tile-pinned`,
untrusted: honoured only while registered). Every picker reopens on it
after a reload or on another page, until the visitor picks **Auto**.
- The other maps (home mini-map, node detail, node reach, analytics)
follow the visitor's choice through the shared builder: the saved pick
when it suits the current theme (satellite always does), otherwise the
theme's map.
- Those small maps never load MapLibre, so a vector choice shows the
theme's default raster map there.
- **Security contract**: the `CONTRACT` block at the top of
`map-tile-providers.js` (S1 to S7) covers one shared tile-URL validator
(`https?://` or a same-origin path, no credentials in the authority,
whitelisted placeholders), attribution HTML-escaped once, picker labels
set with `textContent`, explicit MapLibre options, pinned vendored
versions, CORS-safe hillshade decoding, and treating stored picks as
untrusted input. `map.tiles` is served publicly in `/api/config/client`,
so keys put there are public (the docs warn about this).

## Fixes included

The race stress suite written for this PR found teardown races when
leaving map pages mid-load:
- a lazy MapLibre load finishing after navigation;
- a hillshade tile decoding after `remove()`;
- a provider-change event arriving during teardown.

It also found a pre-existing document-listener leak in `AreaFilter` /
`RegionFilter`. All of these are fixed in `e6709e74`, with regression
tests in `tests/e2e/test-map-teardown-races.js`.

The first CI run then caught a bug in that fix (`7f8d792c`).
`MC_safeRemoveMap` called `map.off()` before `map.remove()`, so the
map's `unload` event reached no one. Leaflet relies on that event to
detach controls and clean up the zoom-animation proxy and BoxZoom, and
`test-issue-1206` watches it to confirm node maps are disposed. `off()`
now runs after `remove()`, and a new regression test checks that
`unload` fires, controls detach and no listener is left.

A later stress run (a new seed) found a real two-tab bug, fixed in
`0506fc1d`. When another tab's overlay pick is already in localStorage
but its `storage` event hasn't arrived, a layer-picker click here
triggered a sync that added that overlay while Leaflet was still
applying the click. Leaflet doesn't redraw the list for changes it sees
mid-click, so the overlay's checkbox stayed unticked, and the next click
on any overlay removed it and wrote the removal back to every tab. The
overlay set now defers a sync until the click has finished. New E2E
check `4b` in `test-map-providers-e2e.js` plants another tab's pick and
clicks twice: one write per click, the planted overlay stays ticked. It
fails on the previous code.

## Docs

- `docs/deployment.md`, "Map Tile Providers" section, rewritten. It
covers every provider and its licence, turning groups on and off, custom
servers, vector maps, hillshade, self-hosting, and what is public.
- User guide:
  - `map.md` gets a "Map style and overlays" section;
  - `live.md` notes the picker;
  - `configuration.md` gets a "Map tiles" section;
  - the FAQ gets a new entry on satellite, terrain and gray maps.
- `CHANGELOG.md`: an Unreleased entry.

## Test data

Two datasets were used, so every number below says which one it came
from.

**1. Large synthetic dataset** (perf A/B and screenshots). It is
generated, contains no real mesh data, and is not checked in.

- **Generator:** `synthgen` 1.0.0, seed 1, "full" scale. Built from
upstream `be16173e` and retimed so its 18-day window (2026-10-31 to
2026-11-18) ends at the time of the run.
- **Database:** SQLite, 3.94 GB (586 MB as zstd), 11.6 M rows in all.

| Table | Rows |
|---|---|
| Nodes | 18,102 (12,606 companions, 3,652 repeaters, 953 rooms, 891
sensors) |
| Nodes with a location | 13,452, spread worldwide (latitude −37° to
60°, longitude −123° to 175°) |
| Observers | 1,175, in 42 regions on six continents |
| Transmissions | 759,133 |
| Observations | 10,569,668 |
| Neighbour edges | 42,806 |
| Advert route evidence | 212,142 |

During the perf runs, the server's packet store was pinned to the newest
48 h with a 1.5 GB memory cap. Each server held about 65 k transmissions
and 0.9 M observations in memory (baseline 65,647 / 906,467; candidate
64,862 / 896,248), plus all 18,102 nodes (about 17,650 active) and 1,175
observers. The tracked store was about 450 MB.

**2. The repo's CI fixture** (`test-fixtures/e2e-fixture.db`, 704 KB).
All E2E suites and the race stress gates ran against it, freshened the
way CI does: 204 nodes, 31 observers, 500 transmissions, 502
observations. A second copy with the Repeater Planner enabled was used
for the planner-on stress runs.

**Perf environment:**
- Headless Chromium 158 via Playwright 1.58.2, at 1280×800 with device
scale factor 1.
- 9 measured runs per scenario plus 1 warm-up, on each of `master` and
this branch.
- Host: Linux, AMD Ryzen 7 3700X (16 threads), 63 GB RAM.
- **Tiles were stubbed.** The harness answers every tile, elevation and
style request locally with the same stub on both sides (`--mode stub`),
so perf timings involve no network. Only the screenshot gallery uses
real tiles.

## Screenshots

These were taken from the synthetic dataset with real tiles in a real
browser (headless Chromium, 1280×800). Click a thumbnail for the full
size. The images are hosted on a separate assets branch, so they are not
in this diff.

#### Street

| | | |
|---|---|---|
| <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/street-carto-light.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/street-carto-light.png"
width="260" alt="Street: Carto (default) (light)"></a><br>Carto
(default) (light) | <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/street-carto-dark.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/street-carto-dark.png"
width="260" alt="Street: Carto (default) (dark)"></a><br>Carto (default)
(dark) | <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/street-osmfr-hot-light.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/street-osmfr-hot-light.png"
width="260" alt="Street: OSM France Humanitarian (light)"></a><br>OSM
France Humanitarian (light) |

#### Gray

| | | |
|---|---|---|
| <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/gray-osmfr-light.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/gray-osmfr-light.png"
width="260" alt="Gray: OSM France (light)"></a><br>OSM France (light) |
<a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/gray-osmfr-dark.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/gray-osmfr-dark.png"
width="260" alt="Gray: OSM France (dark)"></a><br>OSM France (dark) | <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/gray-versatiles-light.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/gray-versatiles-light.png"
width="260" alt="Gray: VersaTiles (light)"></a><br>VersaTiles (light) |
| <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/gray-versatiles-dark.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/gray-versatiles-dark.png"
width="260" alt="Gray: VersaTiles (dark)"></a><br>VersaTiles (dark) | <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/gray-openfreemap-light.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/gray-openfreemap-light.png"
width="260" alt="Gray: OpenFreeMap Positron (light)"></a><br>OpenFreeMap
Positron (light) | <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/gray-openfreemap-dark.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/gray-openfreemap-dark.png"
width="260" alt="Gray: OpenFreeMap Dark (dark)"></a><br>OpenFreeMap Dark
(dark) |

#### Topographic

| | | |
|---|---|---|
| <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/topo-cyclosm-light.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/topo-cyclosm-light.png"
width="260" alt="Topo: CyclOSM (light)"></a><br>CyclOSM (light) | <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/topo-eox-terrain-light.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/topo-eox-terrain-light.png"
width="260" alt="Topo: EOX Terrain Light (light)"></a><br>EOX Terrain
Light (light) | <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/topo-opentopomap-light.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/topo-opentopomap-light.png"
width="260" alt="Topo: OpenTopoMap (opt-in) (light)"></a><br>OpenTopoMap
(opt-in) (light) |

#### Satellite

| | | |
|---|---|---|
| <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/sat-s2-2025-light.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/sat-s2-2025-light.png"
width="260" alt="Satellite: Sentinel-2 2025 (light)"></a><br>Sentinel-2
2025 (light) | <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/sat-s2-2025-labels-light.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/sat-s2-2025-labels-light.png"
width="260" alt="Satellite: Sentinel-2 2025 with labels
(light)"></a><br>Sentinel-2 2025 with labels (light) | <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/sat-s2-2025-dark.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/sat-s2-2025-dark.png"
width="260" alt="Satellite: Sentinel-2 2025 (dark)"></a><br>Sentinel-2
2025 (dark) |
| <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/sat-s2-2025-labels-dark.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/sat-s2-2025-labels-dark.png"
width="260" alt="Satellite: Sentinel-2 2025 with labels
(dark)"></a><br>Sentinel-2 2025 with labels (dark) | <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/sat-s2-2016-light.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/sat-s2-2016-light.png"
width="260" alt="Satellite: Sentinel-2 2016 (light)"></a><br>Sentinel-2
2016 (light) | <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/sat-s2-2016-labels-light.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/sat-s2-2016-labels-light.png"
width="260" alt="Satellite: Sentinel-2 2016 with labels
(light)"></a><br>Sentinel-2 2016 with labels (light) |

#### Vector (MapLibre)

| | | |
|---|---|---|
| <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/vector-liberty-light.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/vector-liberty-light.png"
width="260" alt="Vector: OpenFreeMap Liberty
(light)"></a><br>OpenFreeMap Liberty (light) | <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/vector-dark-dark.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/vector-dark-dark.png"
width="260" alt="Vector: OpenFreeMap Dark (dark)"></a><br>OpenFreeMap
Dark (dark) | <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/vector-versatiles-colorful-light.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/vector-versatiles-colorful-light.png"
width="260" alt="Vector: VersaTiles Colorful (light)"></a><br>VersaTiles
Colorful (light) |
| <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/vector-versatiles-colorful-dark.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/vector-versatiles-colorful-dark.png"
width="260" alt="Vector: VersaTiles Colorful Dark
(dark)"></a><br>VersaTiles Colorful Dark (dark) | | |

#### Hillshade overlay

| | | |
|---|---|---|
| <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/overlay-hillshade-s2-light.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/overlay-hillshade-s2-light.png"
width="260" alt="Overlay: hillshade over Sentinel-2
(light)"></a><br>hillshade over Sentinel-2 (light) | <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/overlay-hillshade-carto-light.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/overlay-hillshade-carto-light.png"
width="260" alt="Overlay: hillshade over Carto
(light)"></a><br>hillshade over Carto (light) | <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/overlay-hillshade-s2-dark.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/overlay-hillshade-s2-dark.png"
width="260" alt="Overlay: hillshade over Sentinel-2
(dark)"></a><br>hillshade over Sentinel-2 (dark) |
| <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/overlay-hillshade-carto-dark.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/overlay-hillshade-carto-dark.png"
width="260" alt="Overlay: hillshade over Carto (dark)"></a><br>hillshade
over Carto (dark) | | |

#### Repeater Planner

| | |
|---|---|
| <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/planner-s2-hillshade-light.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/planner-s2-hillshade-light.png"
width="260" alt="Planner: Sentinel-2 + hillshade
(light)"></a><br>Sentinel-2 + hillshade (light) | <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/planner-s2-hillshade-dark.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/planner-s2-hillshade-dark.png"
width="260" alt="Planner: Sentinel-2 + hillshade
(dark)"></a><br>Sentinel-2 + hillshade (dark) |

#### Layer picker

| | |
|---|---|
| <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/picker-light.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/picker-light.png"
width="260" alt="Layer picker open (light)"></a><br>Layer picker open
(light) | <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/picker-dark.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/picker-dark.png"
width="260" alt="Layer picker open (dark)"></a><br>Layer picker open
(dark) |

#### Custom tile server

| | |
|---|---|
| <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/custom-map.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/custom-map.png"
width="260" alt="Custom raster provider on the map"></a><br>Custom
raster provider on the map | <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/custom-picker.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/35ce760b31b8365e511884fdc5e5ae873f4e28bb/map-providers-2428/thumbs/custom-picker.png"
width="260" alt="Custom raster provider in the picker"></a><br>Custom
raster provider in the picker |

## Testing

The full suite ran twice, each time on a fresh clone:

| | Pass 1 | Pass 2 |
|---|---|---|
| Commit (before rebase) | `8a56e841` | `9355169b` |
| `test-all.sh` (unit) | pass | pass |
| `npm run lint` | 0 errors (87 warnings, all pre-existing) | 0 errors
(87 warnings, all pre-existing) |
| Go `cmd/server` / `cmd/ingestor` | ok / ok | ok / ok |
| E2E, map-related files (CI fixture) | 44/44 | 44/44 + planner-on run |
| `test-e2e-playwright.js` | 149 passed, 3 skipped | 149 passed, 3
skipped |
| Race stress gate (seeds) | 101, 202: all pass | 303, 404: all pass |
| Stress with planner enabled | pass | pass (seed 505) |
| Gallery | 32/32 | 32/32 |

The rebased equivalents of the pass 1 and pass 2 commits are `fde2552c`
and `e4d5c447`.

**After the first CI run.** The two passes covered only the map-related
E2E files, and CI exposed two problems:

1. `test-issue-1206` failed 7 checks. This was the `unload` bug
described under "Fixes included".
2. The JS unit gate runs without `node_modules`, so the two new jsdom
suites crashed `test-all.sh`. Locally, jsdom was reachable from a parent
checkout, which hid this.

The second problem is fixed in `57720bf3`, following the
`domIntegration` convention in `scripts/non-unit-tests.json`.
`test-map-teardown-races.js` moved to `tests/e2e/`, and the three jsdom
zoom-limit tests split out into
`tests/e2e/test-map-vector-leaflet-zoom.js`, so 30 + 3 = 33 tests are
kept. Both run from E2E shard 2 and take a few seconds. The heavy suites
(race stress, perf, gallery) stay local-only and are not run in GitHub
Actions.

These checks ran on the fixed, rebased tree (`57720bf3`):

| Check | Result |
|---|---|
| `test-all.sh` from a copy with no `node_modules` (as CI runs it) |
pass |
| `test-test-inventory.js` | 399 suites classified |
| `npm run lint` | 0 errors |
| Go `cmd/server` / `cmd/ingestor` | ok / ok |
| `test-issue-1206-resize-observer-leak-e2e.js` | 13/13 (7 were failing)
|
| `test-e2e-playwright.js` | 149 passed, 3 skipped |
| `test-map-providers-e2e.js` / harness E2E | 17/17, 16/16 |
| `test-map-teardown-races.js` / `test-map-vector-leaflet-zoom.js` |
19/19, 3/3 |
| Race stress (3 iterations) | all scenarios pass |

The commits since pass 2 are `76c67184` (docs only), `7f8d792c` and
`57720bf3`.

**GitHub Actions on `0506fc1d` (rebased onto `master`, with the two-tab
fix): every check passed** (13 passed, 4 skipped as usual for a PR).
That covers Go build and test, all three E2E shards, the server race
detector and both image builds. The moved suites ran in shard 2
(`test-map-teardown-races.js` 19/19, `test-map-vector-leaflet-zoom.js`
3/3), and the unit gate ran `test-map-vector.js` (30/30).

**Race stress suite** (`tests/e2e/test-map-race-stress-e2e.js`). Each
gate run does 20 iterations of scenarios a to e and 50 cycles of f. The
scenarios cover:
- rapid provider switching;
- theme flips during a vector load;
- navigating away mid-load (including a 15 s MapLibre timeout);
- repeated map-page navigation with heap checks;
- overlay toggles;
- cross-page picker persistence.

Results for each run:
- Listener counts stay flat: at most 3 `mc-tile-provider-changed`
listeners and 5 `storage` listeners.
- At most one live WebGL context at a time.
- Heap growth in the second half of scenario d was 0.25 to 0.45 MB
across the four gate runs.
- Upstream `master` grows about 0.39 MB per map navigation loop in the
same scenario; this branch levels off.

## Maintainer review (addressed)

1. **Licence default.** All five new groups (`eox`, `osmfr`,
`openfreemap`, `versatiles`, `hillshade`) are opt-in: off unless
`enabled: true` (`"true"`, `1` or `{}` don't count). With an untouched
config the picker lists the same 6 base maps as before. Docs,
`config.example.json` (now `enabled: false` for each) and the changelog
say so, and each group's terms are listed before you turn it on.
2. **Saved pick.** The on-map picker now saves the pick (option 1 of
your two), as the docs promised. Behaviour, and what an other-theme pick
does:
- Every picker opens on the pinned map, on any page and after a reload,
until **Auto** is picked. A pin is shown whatever the theme, as an
explicit pick already was.
- Maps without a picker show it when it fits the current theme (`type`
is the theme or `any`), otherwise the theme's map. So a light pin isn't
drawn on a dark node map; satellite always is.
- A stored pin whose group is turned off reads as Auto, and comes back
if the group is turned on again; only picking Auto clears it.
- On a map with a picker, Auto always means the theme's map: the pin is
only the explicit layer, never loaded into the hidden Auto layer. A
choice in the customizer, and Reset All, clear the pin. A failed write
(quota full) never brings back an older stored pin.
- E2E `7a` to `7c` in `test-map-providers-e2e.js`: pick, reload, the
radio and tiles are the pick, the node detail map draws it, and a light
pin in dark is kept but not drawn. Auto clears the key; junk in it gives
Auto; an untouched config lists none of the new groups. 7a and 7b fail
with the save line removed. Unit tests are in `test-map-tile-pin.js`
(21).
3. **CI.** `test-map-providers-e2e.js` (24 checks, including `4b`, the
two-tab regression check) and `test-map-providers-harness-e2e.js` (16)
now run in E2E shard 3 against the fixture server: every tile host is
stubbed.

Non-blocking:
- `getTileUrl()` now returns the raster fallback for a vector pick
(`MC_rasterTileUrl`). There's a test in `test-tile-resolver.js` that
fails on the old code.
- The `map-vector.js` header and the binding's vendor README list the
Leaflet and binding internals to recheck on an upgrade.
- `docs/deployment.md` says SRI makes a JS-rewriting proxy drop vector
maps to raster, so serve `public/vendor/` unmodified.
- `scripts/map-perf/README.md` says where `SEED_DB` and `SHIFT_SH` come
from.
- The maps with `attributionControl: false` are left as they are. That
predates this PR, and with every new group opt-in, an upgrade adds no
uncredited imagery. Follow-up for all of them: Kpa-clawbot#2441.
- The OpenFreeMap credit line is `OpenFreeMap © OpenMapTiles Data from
OpenStreetMap` (`2424f3c3`), the line OpenFreeMap gives for clients that
don't add it automatically.

Verified after these changes:
- `test-all.sh` and lint pass, with 0 errors.
- Both provider E2E suites pass: 24/24 and 16/16.
- Race stress, seed 979: scenarios a, b, d and e pass. c (15/15) and f
(37/37) pass after updating their model of the pick: they expected Auto
after a return, which was the old unsaved behaviour.
- The stress suite now enables the five groups itself, so it keeps
exercising them.

## Performance

A/B test: `master` against this branch on the large synthetic dataset,
with 9 runs per scenario and stubbed tiles (see Test data;
`scripts/map-perf/`). The full HTML report is not attached; ask if you
want it.

- **No budget failures** in either pass. The `raster-no-maplibre` budget
holds: no raster scenario loads MapLibre.
- **DOMContentLoaded is unchanged on every page**, even with the two new
scripts (`map-hillshade.js` and `map-vector.js`, about 635 lines in all;
MapLibre itself loads only on demand).
- **Switching providers 50 times (raster only), median ms per switch:**
  - dark: 146 → 108.5;
  - light: 208 → 208.5.
  - Heap growth during the run: 0.3 to 0.4% on both sides.
- **Flagged and checked:**
- Live and Analytics `loadEventMs` are flagged in some runs. This metric
has two modes on **both** branches: `load` fires either before Leaflet
adds its first tile `<img>`s (about 150 ms) or after they finish (about
400 ms). A direct probe of `master` alone gave 428, 404 and 124 ms. On
these scenarios, map creation, first tile, all tiles, first marker and
wall time are within a few ms on both sides.
- Carto and Positron `allTilesSinceMapMs` are 4 to 6 ms slower, just
above `master`'s p95. Tiles are stubbed locally, so this is not network
noise. The cause is not isolated. Both providers now go through the
shared layer builder, and on the same scenarios first tile, all tiles
and wall time are within 10 ms of `master` (Carto Voyager +2 to +3 ms;
Positron Dark +6 to +9 ms).
- The Analytics map shows one long task of about 50 ms against a
`master` median of 0, but `master`'s p95 is 52 to 84 ms. This is
disclosed in case it shows up for you.
- Other desktop apps were running during the perf runs, so expect some
noise.

## Commits

1. `c6bf12ed` feat(map): tile provider registry with custom servers,
gray, topo and satellite maps, and overlays
2. `9237230b` feat(map): client-side hillshade overlay
3. `781e41b4` feat(map): vector basemaps via vendored MapLibre GL 5.24.0
4. `dae36d2e` refactor(map): every map surface uses the shared basemap
builder
5. `3d4afcdc` fix(map): teardown races and listener leaks when leaving
map pages
6. `b798b2fe` test(server): pin map.tiles passthrough in
/api/config/client
7. `171b1bc4` test(map): E2E, race stress suite, perf harness and
screenshot gallery
8. `61f73875` docs(map): providers, custom tile servers, overlays and
self-hosting
9. `135a9b12` test(map): gallery shows opt-in OpenTopoMap and retries
slow tile servers
10. `3833572b` test(map): harness waits for vector basemaps; stress
suite fixes from test pass 1
11. `3e543cad` test(map-perf): redact tile-URL credentials; compare
switch50 like with like
12. `d5006111` docs(map): user guide for map styles, overlays and
map.tiles
13. `90ee1d5d` fix(map): MC_safeRemoveMap lets unload listeners run
before dropping them
14. `5fc57b5c` test(map): run the jsdom map suites in the E2E job, not
the unit gate
15. `bd36b634` fix(map): another tab's overlay pick that lands mid-click
is no longer removed
16. `38df65d2` fix(map): new tile groups are opt-in; a map picked in the
picker is saved
17. `eafbcac9` ci(e2e): run the map provider E2E suites in shard 3
18. `65b223ec` fix(map): getTileUrl() never returns a vector style url;
review notes
19. `f3402c5d` test(map): race stress enables the opt-in groups and
expects the saved pick
20. `e92b8631` fix(map): Auto on a picker map ignores the saved pick;
customizer clears it

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…wbot#2407)

## Summary

`observations.observer_idx` points at the **implicit rowid** of
`observers`, whose declared key is `id TEXT`. Implicit rowids are not
stable:

- a dump-and-reload (`sqlite3 .dump`, `iterdump`) renumbers them, which
silently re-links observations to the wrong observer;
- PostgreSQL has no rowid at all.

This change makes the key explicit. Split out of Kpa-clawbot#2396 at review's
request, so SQLite installs get it independently of the Postgres work.

## What changes

- **One-time rebuild, in the ingestor.** On first start, `observers` is
rebuilt as `idx INTEGER PRIMARY KEY AUTOINCREMENT`, copying every rowid
into `idx` in one transaction. It fails closed on unknown columns or
NULL ids.
- **Rollback-safe.** In SQLite an `INTEGER PRIMARY KEY` *is* the rowid,
so `rowid == idx` forever. Older binaries that still join on
`observers.rowid` keep working, so both upgrade and rollback are safe.
- **No inherited orphans.** `AUTOINCREMENT` is seeded past
`MAX(observations.observer_idx)`, so a new observer can never inherit a
deleted observer's leftover rows.
- Fresh installs create the new shape directly, and `AssertReady`
requires `observers.idx` as the primary key (a plain column named `idx`
does not pass).
- **Observer writes update first.** With `AUTOINCREMENT`, SQLite
advances `sqlite_sequence` for every INSERT it attempts, even one `ON
CONFLICT` turns into an update. The per-packet observer upsert and the
clock-skew upsert now run an `UPDATE` and fall back to the unchanged
`INSERT ... ON CONFLICT` only for a new observer. So the sequence moves
only when an observer is added, and the next new observer gets `max(idx)
+ 1`.
- `packets_v` now has a single definition
(`dbschema.EnsurePacketsView`).
- Every server and ingestor query, the fixture capture script and the
test schemas use `idx`. Guard tests fail if `observers.rowid` comes
back.

## Operator impact

Every SQLite install gets this on its next ingestor start, with no
config change. The rebuild is one transaction over `observers`, which
holds one row per observer (typically hundreds), so it's quick.

**When the rebuild refuses.** It refuses rather than lose data in two
cases, and then the ingestor stops on every start until the cause is
fixed:

- `observers` has a column CoreScope doesn't know (one added locally).
The rebuild would drop it. Save its data, then drop or rename it: `ALTER
TABLE observers DROP COLUMN <name>`.
- A row has a NULL `id` (the legacy `TEXT PRIMARY KEY` allows one). Find
it with `SELECT rowid, * FROM observers WHERE id IS NULL`, then delete
or fix it.

The error message names the column or the row count and these steps.
Starting the previous version also works: nothing was changed, and
`packets_v` stays readable for external SQLite readers in the meantime.

**A refusal stops the server too, not only ingest.** The server checks
the schema at startup (`AssertReady`) and exits when `observers.idx` is
not the primary key, so the whole site is down until the cause above is
fixed or the previous version is started again. Check for a locally
added column or a NULL `id` before upgrading if you are unsure.

**Ingest cost.** Measured with `BenchmarkUpsertObserverAtExisting`
(`cmd/ingestor`): 20000 `UpsertObserverAt` calls over 500 existing
observers, on a store opened by `OpenStore` with its own pragmas (WAL,
`synchronous=FULL`), Ryzen 3700X in Docker. A plain upsert on the new
table writes 5.23 WAL frames per call; update-first writes 4.23, one
frame less. The pre-PR table was not measured. Time per call is 676 to
726 µs before and 665 to 668 µs after; it is bound by fsync, so the
difference is within noise.

## Testing

- `internal/dbschema/observers_idx_test.go`: the rebuild keeps every
observation linked to the same observer, refuses an unknown column or a
NULL id, never reuses an `idx` (including one only orphaned observations
still reference), is idempotent, and handles the full legacy table.
- `TestObserversIdxPreservesLinksOnE2EFixture`: on a copy of
`test-fixtures/e2e-fixture.db`, 499/499 observations keep the same
observer.
- Refusals and rollback: a refused rebuild leaves the table, its rows,
`foreign_keys` and a readable `packets_v` as they were; a failure after
the old table is dropped rolls all of it back, leaves no
`observers_new`, and the next start completes the rebuild
(`TestObserversIdxRollsBackMidRebuild`,
`TestPacketsViewFollowsObserversShape`).
- Guards: `TestNoObserversRowidInSource` (ingestor) and
`TestNoObserversRowidInServerSources` fail if a query joins on
`observers.rowid` again. `TestFreshObserversMatchesRebuiltShape` pins
that a fresh install and a rebuilt one end up identical.
- `TestUpsertObserverAtLeavesSequenceAlone` and
`TestRecordNaiveSkewLeavesSequenceAlone`: 1000 calls on an existing
observer leave the sequence alone (on the previous head both moved it 1
-> 1001), and a new observer then gets `max(idx) + 1`.
`TestUpdateObserverMatchesUpsert` and `TestUpdateNaiveSkewMatchesUpsert`
check that the update path writes the same row as the upsert (COALESCE
of empty fields, `last_seen` never going back, the `can_relay`
tri-state, the 24 h skew counter).
- `TestAssertReadyRequiresObserversIdxPrimaryKey`: the rebuilt shape
passes; a plain `idx` column or none fails.
`TestOpenStoreRefusesUnconvertibleObservers`: through `OpenStore`, an
unknown column or a NULL id fails the open and leaves the table, its
rows and `packets_v` as they were.
- `go vet` and `go test` pass on all modules (`scripts/allmod.sh`), with
gofmt clean.

🤖 Generated with [Claude Code](https://claude.com/claude-code)



---

## Merge order

These four PRs were split out of Kpa-clawbot#2396 and are **independent — they can
merge in any order.** Verified: every pair is conflict-free, and all
four merged together pass `go vet`, `go test ./...` (all 16 modules) and
`sh test-all.sh`.

Suggested order, none of it urgent:

1. **Kpa-clawbot#2408** — never lose rows during startup / a failed poll.
2. **Kpa-clawbot#2407** — explicit `observers.idx` primary key.
3. **Kpa-clawbot#2409** — content-hash migration moved into the ingestor.
4. **Kpa-clawbot#2410** — pin musl thread stacks at 8 MiB. Released images are not
affected (zig already links them with 8 MiB thread stacks); it fixes
native Alpine builds.

After these land, Kpa-clawbot#2396 (Postgres) will be rebased onto master.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…ot#2429)

Draft for feedback: a working version of native repeater claims and
edits from mobile clients, built on the repeater info feature from
Kpa-clawbot#2415. Four open questions are at the end.

## Situation

Repeater info (Kpa-clawbot#2415) can only be claimed and edited from a browser
session. Device tokens from `POST /api/auth/device-token` are limited to
`rx` (CoreDrive RX: settings and companion linking), and `GET
/api/repeaters/{pubkey}/info` treats a bearer token as anonymous. A
mobile client can show a repeater's details but can't offer "claim" or
"edit" natively.

`PUT /api/repeaters/{pubkey}/info` is also a full replace with no
precondition. Two people editing from the same copy silently overwrite
each other. That's rare in the browser, but likelier from an app that
keeps a cached copy.

## Change

Three commits, one per piece.

**1. Device-token scopes for the repeater routes** (`8aba3715`)

- `POST /api/auth/device-token` takes an optional `scopes` list. Omitted
(or `null`) still means `["rx"]`, so CoreDrive RX and every existing
token keep exactly their current permissions. An empty list or an
unknown scope answers 400, checked before the password.
- New scopes:
- `repeater:claim`: `POST` and `DELETE /api/repeaters/{pubkey}/claim`.
These already only add or remove the caller's own claim. Several
claimers per repeater, idempotent `POST`, unchanged.
- `repeater:edit`: `PUT /api/repeaters/{pubkey}/info`, still subject to
`CanEditRepeater`.
- Every device token may use `/api/auth/me` and `/api/auth/logout`, so a
repeater-only token can check and end its own login.
- `GET /api/repeaters/{pubkey}/info` with a token holding either
repeater scope returns `canEdit` and `claimedByMe`. An unknown or
expired token answers 401 rather than passing as anonymous, so a client
learns its login is gone. A valid token without a repeater scope still
gets the public view. A cookie still wins over a bearer header, as
elsewhere.
- `GET /api/account/repeaters` (My repeaters, from Kpa-clawbot#2430) also takes a
token holding either repeater scope, so an app gets the account's claims
in one request. It can't build that list from the public catalog, where
claimers are display names, and reading repeaters one at a time would
miss a claimed repeater that has left the node list. An `rx`-only token
still answers 403.
- Scope checks are method-aware (`bearerScopesFor(method, path)`). The
repeater paths are added to the bearer CORS paths.
- Same handlers, validation, rate limit (`repeater`, 120/h per user and
per IP), audit actions and admin claim removal as the browser. Token
writes add `via: device` to the `repeater.claim`, `repeater.edit` and
`repeater.unclaim` rows, and the `user.login` row records the granted
scopes. The admin route keeps refusing bearer tokens.

**2. Conditional edits with a revision** (`9f9bf47b`)

- `users.db` schema v10 adds `repeater_info.revision`. Existing rows
start at 1; a repeater with no saved details is at 0. Claims don't
change it.
- `GET` (single and list) and `PUT` responses include `revision`.
- `PUT` accepts an optional `baseRevision`. The check is part of the
write statement, so of two saves from the same base exactly one lands:
- `baseRevision: 0` (first save): `INSERT … ON CONFLICT(pubkey) DO
NOTHING`.
- `baseRevision: n`: `UPDATE … SET revision = revision + 1 … WHERE
pubkey = ? AND revision = ?`.
- No match answers `409` with the stored details
(`canEdit`/`claimedByMe` included) and writes nothing. That's the same
shape `PUT /api/account/settings` uses for its conflicts.
  - A stale base is refused even when the body would change nothing.
- Permission is checked first, so a 409 never shows details to someone
who can't edit.
- Without `baseRevision` the save is unconditional and bumps the
revision, so `public/repeater-info.js` works unchanged.
- `/api/config/client` adds `userManagement.repeaterTokens: true`, so a
client can tell this server from one without the scopes or
`baseRevision` (older servers answer the device-token request with the
SPA page, as noted for `companionLinking`).

**Discovery and conflict recovery, for a client:**

1. Check `userManagement.repeaterTokens` in `/api/config/client`.
Without it, keep the claim and edit actions hidden.
2. Log in with `scopes: ["repeater:claim", "repeater:edit"]` (or just
what the client offers). The response echoes the granted `scopes`.
3. Read `GET /api/repeaters/{pubkey}/info` with the token. Show
Claim/Unclaim from `claimedByMe` and Edit from `canEdit`, and keep
`revision`.
4. Save with `PUT …/info` and `baseRevision` set to that revision. On
200, keep the new `revision` from the response. On 409, the body is the
current record: show or merge it, then retry with its `revision`. On
401, log in again. On 403, the account can no longer edit (for example
someone claimed it), so refresh from `canEdit`.

**3. Account page device list** (`d28374aa`)

My account, Devices labelled every device token "CoreDrive RX".
`/api/account/sessions` now includes a device token's `scopes`. The page
keeps the CoreDrive RX label for `rx` tokens (and rows without scopes).
It shows other tokens under the device name the app sent, with a line
such as "can claim repeaters and edit repeater details".

Docs: `openapi.go`, `docs/api-spec.md` and the Repeater info section of
`docs/user-guide/accounts.md`.

## Questions

1. **One scope or two?** This uses separate `repeater:claim` and
`repeater:edit`, so a client can ask for less, and a token that only
edits can't put the user's name on a repeater publicly. One `repeater`
scope would be simpler if you'd rather not split it.
2. **Editing unclaimed repeaters from mobile.** This keeps web parity:
any active user may edit a repeater nobody has claimed, and once it has
claimers only they (and admins) can. The alternative is to require a
claim before a token may edit. That's stricter, but then app and browser
rules differ.
3. **Operator switch.** There's no new setting: the scopes are available
whenever `userManagement` is on, and the user opts in when the app asks
for them at login. Would you want an explicit opt-in such as
`userManagement.mobileRepeaterWrites`?
4. **Stale-edit contract.** Does `revision` plus `baseRevision` in the
body, with 409 returning the current record, fit? I matched account
settings rather than `ETag`/`If-Match`, to keep one pattern in the API.
The browser editor doesn't send `baseRevision` yet. Making it send one
would be a small follow-up, if you want browser saves protected too.

## Tests

- `cmd/server/repeater_device_token_test.go`:
- default and requested scopes, rejected scopes, and the method-aware
route table;
- per-scope allowed and denied routes, logout with a repeater-only
token;
  - claim and unclaim of own claim only, alongside another claimer;
- edit permission (unclaimed repeater, claimer, non-claimer, admin) and
a disabled account;
  - the admin route refusing tokens;
  - authenticated, public and expired-token reads;
- `via: device` audit rows, cookie writes still needing CSRF, and
session scopes.
- My repeaters with a claim or edit token (own claims only), and 403 for
an `rx`-only token.
- `cmd/server/repeater_revision_test.go`:
- revision on reads, a first edit with no saved row, and a stale base
returning 409 with the current record and no audit row;
  - unconditional browser saves, validation and permission order;
- two concurrent saves from the same revision (one 200, one 409), and
the client config flag.
- `internal/users/repeater_revision_test.go`:
  - revision counting and conditional first and later saves;
  - an 8-way race for both cases (`-race`);
  - the v9 to v10 upgrade.
- `tests/unit/test-user-management-ui.js`: app token labels and scope
line.

Run locally:

- `make test`: all 16 modules OK.
- `sh test-all.sh`: all suites pass, run in `node:24-bookworm`. On
macOS, `test-manage-workflow.js` fails 2 cases on unchanged master
because of the BSD tools.
- `npx eslint public/*.js`: 0 errors, the same 87 warnings as master.
- `node tests/e2e/test-lint-network-calls.js`
- `tests/e2e/test-user-management-e2e.js` against local e2etest servers
with the CI config: 44/44.
- Manually against a local instance:
  - in the browser: claim, edit, unclaim, and the Devices list;
  - with curl: the token flow, including a 409 after a browser save.

Not run: the full Playwright shard matrix from CI.

---------

Co-authored-by: Adam <196335+anieto@users.noreply.github.com>
…elongs to no node (Kpa-clawbot#2451)

## Situation

An SNR on an observation is the observer's reception of whichever node
transmitted that copy last. It belongs to a node only when the observer
heard that node's own transmission. Several places on `#/analytics` (and
two on home/live) showed it otherwise:

| Where | What it showed | Source |
|---|---|---|
| Nodes tab "Avg SNR", Best Signal Quality ranking; home "My Mesh" card
and health banner; live node panel | mean of `pkt.SNR` over every
transmission in `byNode`, including packets the node only relayed or was
addressed to | `GetBulkHealth`, `GetNodeHealth` in `store.go` |
| Distance tab, Top 20 Longest Hops, Best/Median SNR | the transmission
SNR on every hop A to B of the resolved chain; the observer is not in
that chain | `computeDistancesForTx`, `dedupeHopsByPair` |
| Topology "Hops vs SNR" | last-hop SNR plotted against the total path
length | `computeAnalyticsTopology` |
| RF tab | observer receptions, without saying so | |

## Read before upgrading: API change

For external consumers of the API:

- `GET /api/nodes/:pubkey/health` and `/api/nodes/bulk-health`:
`stats.avgSnr` is now the mean over direct receptions only (the samples
behind `observers`). It is `null` for every node no observer heard
directly, which is more nodes than before.
- `GET /api/analytics/distance`: `topHops[].bestSnr` and
`topHops[].medianSnr` are removed.
- `GET /api/analytics/topology`: `hopsVsSnr` is removed. Proto field 8
of the topology response and `DistanceHop.snr` (7) are reserved.

## Changes in this PR

Three commits, one per part:

1. **`fix(health)`**: `stats.avgSnr` on `/api/nodes/{pk}/health` and
`/api/nodes/bulk-health` now comes from the direct-heard index
(`direct_heard.go`), the same source as the "Heard By" rows: the mean
over every direct reception that carried an SNR, across all observers.
`null` when there is none. New helper `directAvgSNR`.
2. **`fix(analytics)` longest hops**: `bestSnr`/`medianSnr` are removed
from `topHops`, along with the `SNR` field on `distHopRecord` and the
two table columns. A hop between two nodes has no measured SNR in this
data.
3. **`fix(analytics)` labels**: "Hops vs SNR" is removed from the page,
the API, `docs/api-spec.md`, the golden shapes and `analytics.proto`
(field 8 reserved). The remaining SNR now names its source:
- Nodes tab: the column is "Direct SNR". A node without a direct
reception shows a dash titled "No direct reception". Best Signal Quality
says it ranks direct receptions only, and shows an empty-state row when
no node qualifies.
- RF tab: a note that every value is an observer receiving the last
transmitter. The overview card reads "Avg Receive SNR".
- Home: "Direct SNR", graded `n/a` when there is no direct reception.
The grey fallback colour is now `var(--text-muted)` instead of a hex
value.

## Effect, measured on a live deployment

`/api/nodes/bulk-health?limit=50` on 2026-11-22:

| | nodes |
|---|---|
| had an `avgSnr` before | 50 |
| `avgSnr` becomes `null` (no direct reception with an SNR) | 19 |
| keep a value | 31 |

For those 31 nodes, the old value differs from the direct-reception mean
by a median of 10.3 dB (max 20.4 dB). That mean was approximated from
the per-observer rows, weighted by packet count rather than SNR sample
count, so treat it as an indication.

## Perf

`directAvgSNR` loops over one node's direct-observer map, which is
already looked up for the "Heard By" rows. The per-packet SNR sum leaves
both health loops. The topology pass no longer builds the `hopSnr` map.
Nothing new on a hot path.

## Verification

- `go test ./...` in `cmd/server`: ok. New: `TestDirectAvgSNR`,
`TestNodeHealth_AvgSnrIgnoresRelayedCopies` (adds a relayed copy with
SNR -99 and asserts `avgSnr` on both endpoints does not move; red before
the fix: `/health avgSnr moved from 11.25 to -25.5`),
`TestDedupeTopHopsCarryNoSNR`, and a `hopsVsSnr` absence check in
`TestAnalyticsTopology`. `TestParityShapes` / `TestParityArraysNotNull`
pass with the updated golden.
- Frontend unit: `test-frontend-helpers.js` 825 passed (new block for
`directSnrCell` and `snrQualityLabel`).
`test-secondary-map-tile-builder.js` stubs the new home helper.
- E2E against a local server on the CI-prepared fixture:
`test-e2e-playwright.js` 149 passed. New
`test-analytics-direct-snr-e2e.js` 7 passed (wired into `deploy.yml` and
`scripts/non-unit-tests.json`). `test-analytics-fluid-charts.js`,
`test-issue-1997-distance-building-e2e.js`,
`test-issue-1648-m4/m5-icons-e2e.js` pass.
- Browser check: screenshots of the Nodes, RF, Topology and Distance
tabs on the local fixture server.

Not run: the new E2E against the code before this PR, and the whole
suite on Linux. Two local-only Windows failures were skipped, as on
master: `TestSaveGeoFilterPreservesFileMode` and
`test-manage-workflow.js` (CRLF).

## Not in this PR

- The neighbour graph's `avg_snr` (Neighbors tab, map popup) follows in
a separate PR, because that change also changes which edges exist.
- The subpath detail "Observer Receive Signal" already reads "Last hop →
observer only" and is unchanged.
- The RF tab charts keep their data. They are valid as observer
reception and now say so.
…Kpa-clawbot#2452)

Follows Kpa-clawbot#2451, which does the same for node-level SNR on the analytics,
home and live pages. Independent of it: no shared files.

## Situation

The neighbour graph is built from every observation, in two places: in
memory by the server (`BuildFromStoreWithOptions`, `neighbor_graph.go`)
and persisted by the ingestor (`buildAndPersistNeighborEdges`,
`neighbor_builder.go`). The server loads `neighbor_edges` back at
startup. Both derive `observer <-> path[last]` and, for ADVERT and
ANON_REQ, `originator <-> path[0]`. The server also attaches the
observation SNR to each edge it derives.

That holds for a flood route. Two cases and one SNR attribution fall
outside it, following the firmware:

- **Direct routes (2, 3)** carry the REMAINING route. A forwarder calls
`removeSelfFromPath` before it retransmits (`Mesh.cpp`), so a non-empty
path names a node still to come, not the one the observer heard and not
a neighbour of the originator. An empty path on a direct route is also
what the last forwarder of a `sendDirect` leaves behind, so it only
proves the originator was heard for an ADVERT (`Mesh::sendZeroHop`).
- **TRACE** reuses the path bytes for per-hop SNR values
(`packetpath.PathBytesAreHops`). Read as hop prefixes, they name
arbitrary nodes.
- **`originator <-> path[0]`** received the observer's SNR, which the
observer measured on its reception of `path[last]`.
- **Reach page** (`attributeDirections`, `node_reach.go`) has the same
flaw: a direct-route or TRACE row added direction counts and its SNR to
the observer's `avg_snr`.

## Changes in this PR

1. **`fix(neighbors)`**, server graph: TRACE builds no edge. A direct
route builds only its zero-hop edge. `originator <-> path[0]` stays as
topology without an SNR sample. Edges without a sample already return
`avg_snr: null` (`neighbor_api.go`), so the Neighbors tab and map popup
show no number for them.
2. **`fix(ingestor)`**, persisted edges: the same rule. The query now
also selects `t.route_type`.
3. **`fix(neighbors)` shared rule** (review follow-up): both builders
use two predicates in `internal/packetpath`. `PathHopsTransmitted`
(flood, not TRACE) replaces the ingestor's own `pathHopsTransmitted`.
`EmptyPathHeardOriginator` keeps an empty path on a direct route for an
ADVERT only, so a direct ANON_REQ with an empty path builds no edge. A
transmission without a route type or payload type builds no edge, the
same fail-closed rule as `directHeardNode`.
4. **`fix(reach)`**: both reach scans select `t.route_type`, and
`attributeDirections` skips rows that fail `PathHopsTransmitted`.

## Effect, measured on a live deployment

Observations in the last 7 days (read-only query, 2026-11-22):

| category | observations |
|---|---|
| flood, with path | 1,186,468 |
| flood, zero hop | 11,289 |
| direct, zero hop | 66,824 |
| direct, with path (no edge any more) | 13,301 |
| TRACE, any route (no edge any more) | 1,145 |

The direct rows exclude TRACE: TRACE is counted once, in its own row.

Distinct `(observer, last path prefix)` pairs over the same window:
1,275. Of those, 302 only occur on direct-route or TRACE observations,
so they lose their observer edge. This is counted on raw prefixes before
candidate resolution, so it is not the exact number of graph edges that
disappear.

Affinity scores and hop resolution read this graph, so prefixes that
only had such an edge can resolve differently or become ambiguous.

## Perf

One payload-type check and one route-type check per transmission in the
server pass, one extra column and the same two checks per row in the
ingestor batch. No new allocations.

## Verification

- `cmd/server`: new `TestBuildNeighborGraph_TraceBuildsNoEdges`,
`_DirectRouteNoObserverEdge` (route 2 and 3),
`_DirectRouteNoOriginatorEdge` (ANON_REQ on a direct route),
`_DirectZeroHopAdvertKeepsSNR`, `_OriginatorEdgeCarriesNoSNR`. Four were
red before the fix, the zero-hop one passed before and after.
- `cmd/server` (review follow-up): `_DirectAnonReqEmptyPathNoEdge`,
`_DirectAdvertWithPathNoEdge`, `_TransportFloodBuildsEdges`,
`_UnknownRouteTypeBuildsNoEdges`,
`TestAttributeDirections_SkipsDirectRouteAndTrace`. Test fixtures that
built an ADVERT without a route type now set `RouteFlood`, and the reach
test schemas gained `route_type INTEGER DEFAULT 1`.
- `internal/packetpath`: `TestPathHopsTransmitted`,
`TestEmptyPathHeardOriginator`.
- `cmd/ingestor`: new
`TestNeighborEdgesBuilderSkipsTraceAndDirectRoutePaths`, extended with a
direct ANON_REQ with an empty path. Before the fix it persisted
`aaaa|bbbb`, `bbbb|obs-1`, `cccc|obs-1`, after the fix only
`cccc|obs-1`.
- Full `go test ./...`: `cmd/server` ok. `cmd/ingestor` ok apart from
`TestOpenStoreRefusesUnconvertibleObservers`, which fails the same way
on upstream master on Windows (TempDir cleanup: `legacy.db` still held
open). Not run on Linux locally.

## Not in this PR

- Edges already in `neighbor_edges` stay until they age out (`last_seen`
pruning, 5 days by default). This PR adds no cleanup migration. A pair
that also has flood evidence keeps its edge, and its `count` keeps the
direct-route observations it already counted before this change.
- The 1-byte prefix handling and `PathTrust` are unchanged.
…CE, failed-signature advert, retired prefix) (Kpa-clawbot#2453)

## What

One rule decides which node an observation heard directly:
`packetpath.HeardKey` (`internal/packetpath/heard.go`). The ingestor
(client receptions, `deriveHeardKey`) and the server ("Heard By, direct"
on the node page, `directHeardNode`) both use it.

The server rule gets stricter. These no longer credit a node as heard
directly:

1. **A 1-byte last hop**, even when exactly one known node has that
byte. A node CoreScope does not know can share it, and 1 byte is the
firmware default hop size.
2. **TRACE**: its path bytes are per-hop SNR, not node hashes.
3. **A zero-hop ADVERT with `signatureValid: false`**: the pubkey is not
proven to be the transmitter's. An advert without the field still
counts.
4. **A 2-byte or longer hop that a retired repeater shares** (moved to
`inactive_nodes`, may still relay), the same check `uniqueHopPrefix`
already does for certain liveness (Kpa-clawbot#2260).

Unchanged: flood last hop of 2 bytes or more with exactly one candidate,
zero-hop adverts on flood and direct (`sendZeroHop`), direct routes with
a path never attribute. The ingestor's behaviour is unchanged:
`TestDeriveHeardKey_MatchesPacketpath` pins it to `HeardKey`, and the
node-discover branch stays in the ingestor.

The node page tooltips ("Heard By, direct" title and its empty state)
now say a 1-byte hop is not taken as proof.

This is PR 1 of the node analytics series (only what a node itself did).
The analytics page itself is unchanged here; PR 2 (stacked on this
branch) moves its signal onto this rule.

Relation to Kpa-clawbot#2451: that PR takes a node's `stats.avgSnr` on `/health`
and `/bulk-health` from the same direct-heard index, so this stricter
rule also narrows that number. The two PRs share no lines.

This series has run on one fork deployment since 2026-11-13
(v3.17.0-on8ar.3). The commits are cherry-picked unchanged onto current
master.

## Measured on staging (fork, v3.17.0 base)

Same deployment, same config, two restarts about 10 minutes apart: old
rule (`staging/2391`, e41bcfe) then this branch (`staging/2391-dh`,
80a600a). Each snapshot was taken once the packet store stopped growing
(130,896 and 130,869 packets), from `/api/nodes/<pk>/health` for all
1932 nodes.

| | old rule | this branch |
|---|---|---|
| nodes with at least one direct observer | 302 | 298 |
| direct observer rows | 512 | 499 |
| direct packets credited | 945,144 | 801,783 (-15.2%) |
| relay-only observer count | 20,828 | 20,771 |

- 11 nodes lost direct observers, 0 gained, 4 went to zero.
- The largest effect is on packets, not observers: an observer that
really hears a repeater was also credited with traffic from other nodes
sharing its 1-byte prefix. Example repeater `502a3b3f`: 5 observers /
15,224 packets before, 3 / 550 after. Repeater `2f0942c8`: 21,882
packets before, 825 after.
- The snapshots do not say which of the four refusals caused each drop;
the API does not expose that.
- About 10 minutes of new traffic separate the two snapshots.

Browser check on staging: the node pages of `502a3b3f` and `f307fa08`
render the direct table with the same rows and totals as the snapshot,
and the new tooltip text.

## Performance

`directHeardNode` runs for every observation on each recompute pass
(about 3M on a large instance). Old and new test binaries run
alternately, minimum ns/op:

- `BenchmarkBuildDirectHeardIndex` (existing, 3M observations, 2-byte
hops): 64.1 ms old, 68.0 ms new (with the retired check; its prefix map
has no retired prefixes).
- `BenchmarkBuildDirectHeardIndex_MixedHops` (new, 500k observations,
1/2/3-byte hops, 5% zero-hop adverts): 42.9 ms old, 39.4 ms new. 1-byte
hops now stop before the map lookup.

The signature check runs only for ADVERTs, so a zero-hop message does
not parse its decoded JSON in this pass
(`TestDirectHeardNode_ZeroHopNonAdvertLeavesDecodedCacheCold`).

## Tests

Run on this branch (Windows, cgo on), 2026-11-22:

- `internal/packetpath`: `go test ./...` ok.
- `cmd/server` and `cmd/ingestor`: `go vet` clean; the direct-heard,
health, certain-liveness and heard-key tests (`-run
'DirectHeard|Certain|NodeHealth|HeardBy'`, `-run
'HeardKey|ClientReception'`) ok. The full suites ran on PR 2's branch,
which contains these commits: ok, with
`TestSaveGeoFilterPreservesFileMode` and
`TestOpenStoreRefusesUnconvertibleObservers` skipped (Windows-only
failures, they fail the same way on master here).
- `node tests/unit/test-direct-rf-heard-by.js`: 10 passed.
- New tests: `TestHeardKey` (11 cases),
`TestDeriveHeardKey_MatchesPacketpath`, 5 new `TestDirectHeardNode`
cases, `TestDirectHeardNode_RetiredPrefixCreditsNobody`,
`TestDirectHeardNode_ZeroHopNonAdvertLeavesDecodedCacheCold`, and an
empty-state title assertion.

## Not done

- The ingestor still accepts a zero-hop advert with a failed signature
for client receptions (the companion app verifies signatures itself);
this PR keeps ingestor behaviour unchanged on purpose.
- PRs 3 and 4 of the series (sent/forwarded counts, advert reach, prefix
sharing on the analytics page) are not written yet.
…servers card (Kpa-clawbot#2454)

Follows Kpa-clawbot#2453 (merged), which this branch builds on. Upstream master is
merged in, so the diff against master is this PR only.

## Situation

The node analytics page (`#/nodes/{pk}/analytics`) grades a node on the
representative observation of every packet attributed to it: `snrTrend`,
`snrMean`, `snrStdDev` and `signalGrade` in `GetNodeAnalytics`. Most of
those observations are relayed copies, so their SNR is what an observer
measured on the last relay, not on the node. A node no observer heard
directly gets `snrMean = 0` and grade "D".

## Changes in this PR

1. **`feat(server)` hourly SNR histograms**: the direct-heard pass also
keeps, per (node, observer), hourly reception counts with an SNR
histogram at 0.25 dB (the firmware reports SNR in quarter dB, so the
bins lose nothing), plus a ring of the 500 newest receptions.
2. **`feat(server)` analytics signal from direct receptions only**: `GET
/api/nodes/{pubkey}/analytics` reads that snapshot.
- New `heardBy`: per fixed observer that heard the node itself,
reception count, median, p10 and p90 SNR, and the medians of the last 24
h and the rest of the window (only for windows of 3 days or more, with 3
receptions in each part).
   - `snrTrend`: direct receptions only, the newest 500 in the window.
- `snrMean`, `snrStdDev`, `signalGrade` over the per-observer medians,
so each observer counts once.
   - `uniqueObservers` counts the observers in `heardBy`.
3. **`feat(server)` mobile receptions summary**: with `clientRxCoverage`
enabled, the response carries `mobileReceptions` (receptions, distinct
receivers, median SNR, furthest reception). A reception counts when its
heard key is the node's full key, its 8-byte discover prefix, or a 2- or
3-byte prefix no other known node and no retired repeater shares. The
query runs after `GetNodeAnalytics` released `s.mu`. Absent when the
feature is off or there are no receptions.
4. **`feat(node-analytics)` Heard by observers card**: one full-width
card replaces the SNR Trend and Observer Coverage charts. Per observer:
receptions, an SNR strip on a -20 to +20 dB scale (bar p10 to p90, dot =
median), the median, and the 24 h change (3 dB or more is coloured, less
reads "="). Ten rows, then "Show all N". The empty state says an empty
list is missing evidence and links to the node page's "Heard By, direct"
table.
5. **`fix(node-analytics)`**: Signal Grade reads "n/a" in the muted
colour when no direct observer reported an SNR. The API still sends "D"
there, unchanged.
6. **`fix(node-analytics)` Show all**: every row is rendered once, rows
after the tenth with the `hidden` attribute; "Show all" removes the
attribute and the button. The first version re-rendered the card through
`innerHTML`, which the preflight XSS gate flagged (the node key in the
sink argument, although it only reaches an `encodeURIComponent` link).
No second render now, and the unit test checks an observer name renders
inert.
7. **`ci`**: `test-node-analytics-heard-by-e2e.js` was listed in
`scripts/non-unit-tests.json` but not run by `deploy.yml`; it now runs
in suite 2.

## Read before upgrading: API change

`GET /api/nodes/{pubkey}/analytics`: `snrTrend`, `snrMean`, `snrStdDev`,
`signalGrade` and `uniqueObservers` keep their names and change meaning
(direct receptions only, see above). `heardBy` and `mobileReceptions`
are new. `observerCoverage`, `hopDistribution`, `peerInteractions` and
`relayPct` are unchanged and now documented as deprecated in
`docs/api-spec.md`.

## Perf

- Direct-heard pass, old and new test binaries alternated, 30
iterations: `BuildDirectHeardIndex_MixedHops` (500k observations, most
credited) 43.4-48.4 ms old, 59.3-63.4 ms new. `BuildDirectHeardIndex`
(3M observations, none credited) unchanged, 71.9-74.9 ms both. The pass
runs on the recompute interval, not per request.
- Per request: the snapshot is read before `s.mu`; the work is bounded
by the hours in the window times the node's direct observers.
- Memory, a bound and not a measurement: per (node, observer) pair a
ring of at most 500 samples of 8 bytes (4 KB) and one sparse hour entry
per hour with receptions inside the store's window. I did not measure
heap before and after on a deployment.

## Verification

Run on this branch (Windows, cgo on), 2026-11-22:

- `go test ./...`: `internal/packetpath`, `cmd/server` and
`cmd/ingestor` ok, with `TestSaveGeoFilterPreservesFileMode` and
`TestOpenStoreRefusesUnconvertibleObservers` skipped (Windows-only
failures, same on master here). `go vet` clean.
- Unit: `test-node-analytics-heard-by.js` 13 passed,
`test-issue-2218-node-analytics-stale-render.js` 115,
`test-payload-labels-surfaces.js` 94, `test-frontend-helpers.js` 821.
- E2E against a local server on the CI-prepared fixture:
`test-node-analytics-heard-by-e2e.js` 2/2,
`test-issue-748-node-analytics-coverage-e2e.js` 2/2,
`test-issue-2218-node-analytics-stale-e2e.js` 10/10,
`test-issue-1648-m2-icons-e2e.js` 41/41, `test-e2e-playwright.js` 149
passed, 3 skipped.
- Not run: browser check on a deployment of this exact branch. The same
code has rendered on the fork deployment since 2026-11-13.

This series has run on one fork deployment since 2026-11-13
(v3.17.0-on8ar.3). The commits are cherry-picked unchanged, apart from
the `ci` and Show all commits, which are new. The merge of upstream
master (after Kpa-clawbot#2451 and Kpa-clawbot#2453) kept both test blocks in
`direct_heard_test.go`; `go test ./...` in `cmd/server` and
`cmd/ingestor` ok on the merge, the heard-by E2E passes locally after
the Show all change.

## Not in this PR

- Values chosen in the design (10 rows, 3 dB change threshold, 3
receptions per part, 3-day minimum window) are hardcoded; exposing them
in the customizer is a later step.
- PRs 3 and 4 of the series (sent/forwarded counts, advert reach, prefix
sharing) are not written yet.
… scope comments (Kpa-clawbot#2450)

Two follow-ups from the Kpa-clawbot#2429 review, split out of Kpa-clawbot#2447 so they don't
wait on it.

## Change

- **Restored drafts keep the "saved meanwhile" block**
(`public/repeater-info.js`). When a save answers 409, the editor shows
the record someone else saved under the form. If the panel re-rendered
before the user saved again, the restored draft kept the typed values
and the stored revision but lost that block. The draft now stores the
conflicting record and restores it with the form.
- **Comments only** (`cmd/server/auth_session.go`,
`cmd/server/cors.go`): the `bearerCORSPath` and CORS comments now
describe the current bearer routes, including the My repeaters list from
Kpa-clawbot#2430. No behavior change.

## Tests

- `tests/unit/test-repeater-info.js`: a re-mount after a 409 keeps the
typed values, the stored revision and the saved-meanwhile block. 32
pass; the new case fails without the fix.
- `npx eslint public/repeater-info.js`: clean.
- `go build ./...` and `go vet` in `cmd/server`.

Co-authored-by: Adam <196335+anieto@users.noreply.github.com>
…from CORESCOPE_URL (Kpa-clawbot#2442)

## Summary

Three follow-ups to the map deep links from Kpa-clawbot#2376 and the og tags from
Kpa-clawbot#1890, plus fixes from review.

1. **`observer=` isolates that observer's shortest path.** An observer
that heard a packet more than once got its earliest observation. When
the timestamps were the same, the lower id won, and that was sometimes
the longer path. For example, with a 4-hop and a 3-hop observation in
the same second, the link drew the 4-hop path.
2. **The path picker writes its view to the URL.** All writes
`paths=all` and a row writes `paths=<hop>-<hop>-…`, so people find the
deep link by using the picker, and a reload shows what they picked.
3. **`og:url` is back as an opt-in, only when `CORESCOPE_URL` is set.**
Kpa-clawbot#1890 removed it because the URL was hardcoded. `og:image` and
`twitter:image` now point at the instance's own `og-image.png` instead
of `raw.githubusercontent.com`.

## Changes

### 1. Shortest path (`fix(map)`)

- `public/route-view-utils.js`: `resolveDeepLinkObservation` ranks an
observer's observations by:
  - hop count first;
  - then timestamp;
  - then the lower id.
- An empty or unparseable `path_json` ranks last, since there is nothing
to draw.

### 2. Path picker (`feat(map)`, `fix(map)`)

- `public/route-view-utils.js`:
- `withPathsParam(hash, value)` sets `paths` and keeps the other params.
It only touches `#/map?packet=…` hashes: a sessionStorage route
(`?route=1`) would not reload from it.
- `resolveDeepLinkObservation` accepts `paths=all` or an observed path's
raw hops joined with `-`. A path nobody observed falls back to the
`observer=` or default view.
- `public/route-view.js`:
- The All button and the "tap to see all" map badge write `paths=all`. A
row writes its path.
- The hash is rewritten with `history.replaceState`, so the router
doesn't re-run the deep link and no history entry is added.
  - Opening an `observer=` link does not rewrite it.
- With a deep-linked view to follow, the route's first fit doesn't
animate. Leaflet drops a fit asked for during a zoom, which left a
reloaded path off screen.
- `public/map.js`: the hide-1-byte-hops redraw reopens the picked view.
- **Precedence change:** `paths` now wins the view over `observer=`.
Otherwise a reload of the URL the picker just wrote would open the
observer's path again. `observer=` and `obs=` still pick the
observation, so the route's spine and "Back to packet" stay the same.

### 3. `CORESCOPE_URL` (`feat(server)`)

- `public/index.html`: `og:url`, `og:image` and `twitter:image` use a
`__CORESCOPE_URL__` placeholder.
- `cmd/server/site_url.go` (new), wired into `spaHandler` in `main.go`.
It works like `__BUST__`:

  | `CORESCOPE_URL` | What fills the placeholder |
  |---|---|
| Set and valid | The value, filled into every top-level page once at
startup. A trailing slash is trimmed. |
| Unset or invalid | `og:url` is dropped. The image tags get each
request's own origin: scheme from TLS or `X-Forwarded-Proto`, host from
`Host`. An invalid value is logged. |

- The request-origin values are held to a strict shape and HTML-escaped.
`X-Forwarded-Host` is not read. If `Host` is unusable, the URLs become
root-relative. Pages are served `no-store`; for a CDN that caches them
anyway, the docs say to set `CORESCOPE_URL`.
- Every `docker-compose*.yml` passes `CORESCOPE_URL=${CORESCOPE_URL:-}`
to the server.
- **Static host and web container:** `scripts/static/build.sh` has no
request to read, so it takes `CORESCOPE_URL` at packaging time.
`Dockerfile.web` and `docker-compose.split.yml` pass it as a build arg.
Unset, the build keeps today's output: no `og:url`, and the image on
GitHub.
- **Docs:** `docs/deployment.md` has env table rows and a new "Link
previews (og tags)" section; `deploy/static/README.md` has a Pages
variable row.

## Release note

Map links that carry both `observer=` and `paths=all` now open on all
paths. Before, they opened on that observer's path. Links with only
`observer=` still isolate one path, now the observer's shortest.

## Reviewer notes

- **nginx in front of the bundled Caddy:** the nginx example in
`docs/deployment.md` doesn't forward `X-Forwarded-Proto`, so previews
would say `http://`. The docs say to set `CORESCOPE_URL` in that case.
- **`og:url` when configured:** it can only be the site root, so
platforms that follow it may open the home page from a shared deep
link's preview. The docs say so.
- **Proxies that rewrite `Host` or serve under a path:** set
`CORESCOPE_URL`.
- **Web container:** the URL is fixed when the image is built, not when
it starts.
- **Not fixed here (already the case before this branch):** isolating a
path other than the route's spine adds the spine's first and last hops
to it (Kpa-clawbot#1423).
- **Not fixed here (already the case before this branch):** after
opening a `paths=all` deep link, the "N hops shown · tap to see all" map
badge stays visible even though every path is drawn.

## Performance

None of this is a hot path.
- The observation ranking is one pass over a single packet's
observations, once per deep-link load.
- The picker does one `replaceState` per click. Opening a named path is
one pass over that packet's observations.
- With `CORESCOPE_URL` set, pages are filled once at startup and served
as before, with no per-request scan.
- Unset, each page view adds one `bytes.Contains` and one
`bytes.ReplaceAll` over the page (measured: 23 µs and 27 KB allocated).
Static assets are untouched.
- No API calls are added.

## Config / customizer

`CORESCOPE_URL` is deployment config (an environment variable and a
build arg), not a UI value, so there's nothing to add to the customizer.

## Tests

- `tests/unit/test-map-deeplink-path-params.js` now has 60 checks. New
ones cover:
  - the 4-hop vs 3-hop same-second case;
  - a later but shorter path;
  - empty and unparseable paths;
  - the new precedence;
  - named paths and `withPathsParam`;
  - the button, badge and row wiring.
- `cmd/server/site_url_test.go` (new) covers:
- a configured URL beating `Host` and `X-Forwarded-Host` on `/`, SPA
routes and `area-map.html`;
- request origins: TLS, proxy scheme, header chains, IPv6, lowercasing,
`X-Forwarded-Host` ignored;
  - `og:url` dropped when unset or invalid, with LF and CRLF pages;
  - no leak between requests;
  - forged headers that cannot inject markup;
  - validation of `CORESCOPE_URL`;
  - the real `index.html` using the placeholder.
- `tests/unit/test-issue-1890-og-url.js` asserts the placeholder in all
three tags and no GitHub URL.
- `tests/unit/test-static-build.js` (32 checks) covers the build with
and without `CORESCOPE_URL`, a URL with a path, and the refused values
(no scheme, quote, `|`, `&`).
- Local runs:
  - `go test ./...` in `cmd/server`, plus `gofmt` and `go vet`: pass.
  - `sh test-all.sh`: pass.
  - `npx eslint public/*.js` (eslint 8): 0 errors.
- `tests/e2e/test-map-deeplink-path-params-e2e.js` against a local
server on the CI-seeded fixture: 17/17, including All, row clicks with a
reload, the redraw and the map fit.

## Browser validation

I checked this against a local server on a scratch copy of the fixture.
In it, one observer heard a packet twice in the same second, a 6-hop
path at the lower id and a 3-hop one.
- `observer=` with the full key or an 8-character prefix isolated the
3-hop path.
- All added `&paths=all` with the other params kept and no new history
entry.
- Reloading that URL opened the All view.
- The map badge added it too.
- Clicking a path row wrote that path. Reloading showed the same row,
with every located hop on screen, at desktop and phone widths.

With curl:
- **Unset:** pages used the request's origin and honoured
`X-Forwarded-Proto`, ignored `X-Forwarded-Host`, and had no `og:url`.
- **`CORESCOPE_URL=https://analyzer.example.org/`:** that URL won over
the forwarded headers, and no placeholders were left.
…wbot#2463) (Kpa-clawbot#2466)

Closes Kpa-clawbot#2463.

## What

1. **`userManagement.mail.provider: "smtp"`**: account mail through any
SMTP submission server, using only `net/smtp` and `crypto/tls` (no
`go.mod` change).
- Keys: `smtpHost`, `smtpPort`, `smtpTls` (`starttls` default, `tls`,
`none`), `smtpUser`, `smtpPassword` (`CORESCOPE_SMTP_PASSWORD` wins).
   - Default ports: 587, 465 and 25.
- `none` is accepted only for exactly `localhost`, `127.0.0.1` or `::1`.
Certificates are always verified with `starttls` and `tls`. AUTH PLAIN
only.
- One connection per mail, 30 s deadline, `multipart/alternative` (text
first, quoted-printable UTF-8), own `Message-ID`. CR/LF is rejected in
every header.
- A non-ASCII address fails with a clear error when the server does not
advertise SMTPUTF8.
   - `mail.webhookSecret` together with `smtp` is a startup error.
2. **Startup check** (SMTP only): connect, TLS, login, QUIT, nothing
sent. The log shows `[mail] SMTP ready: host:port (mode)` or `[mail]
SMTP check failed: <error>`. Startup continues either way. The check
runs in the existing auth wait group and is cancelled on shutdown.
3. **Send test mail** (every provider): button in the System card of
Admin, Overview.
- `POST /api/admin/mail/test` sends a fixed mail to the calling admin's
own address. The address is never a request parameter.
   - Limit: 3 per admin and per IP per 10 minutes.
- Every attempt writes an audit row `mail.test` with `{provider,
result}`. A sent mail is also in the mail log with purpose `test`.
- The answer is `200 {ok, provider, messageId}` or `502 {ok:false,
provider, error}`, with addresses redacted.
4. **No delivery status with SMTP**:
- `mailDeliveryStatus` (bool) is now on `GET /api/admin/stats` and `GET
/api/admin/users/{id}`.
   - When it is `false`, the Overview shows one *Sent* figure.
- The user detail shows `sent (no delivery status with SMTP)` without
*Refresh status* and without the tracking-pixel hint.
   - A missing field (older server) keeps the old UI.

Design: `docs/specs/2026-11-23-smtp-mail-provider-design.md`. Docs:
`docs/user-guide/accounts.md`, `config.example.json`,
`docs/api-spec.md`, `openapi.go`, CHANGELOG.

## Brevo and Postal

`sendMail` became a wrapper around `sendMailID`, which also returns the
provider id. The existing callers are unchanged.

A leftover `CORESCOPE_BREVO_WEBHOOK_SECRET` is ignored with `smtp`, so
it cannot fail an SMTP setup.

## Password handling

The password is only in an unexported settings field. `Describe()`
returns `host:port (mode)`. Error texts carry the server reply, never
the password: tests pin the 535 path and both startup log paths against
the secret.

## Tests

- `internal/mailer`: an in-process SMTP server on a local listener:
plain, STARTTLS and implicit TLS, with a test-only CA.
- Covered: exact MIME bytes, RFC 2047, CR/LF rejection, the EHLO name,
AUTH PLAIN, and a 535 without the password.
  - Untrusted certificate and name mismatch: no AUTH is sent.
- Timeouts and cancels: a stalled server gives
`context.DeadlineExceeded`; a mid-session cancel gives
`context.Canceled`.
  - SMTPUTF8, with and without the extension.
- `go test -race` passes. The stall and cancel tests passed 40 of 40
runs.
- `cmd/server`:
- Config: defaults per mode, exact localhost rule (`localhost.evil.com`,
`localhost.`, `127.0.0.2` rejected), bracketed IPv6, case, env priority,
user without password, `webhookSecret`, CR/LF in `fromName`.
  - Startup check: ready and failed log lines, init returns nil.
- Test-mail handler: success, 502 text, redaction, 429 with
`Retry-After` (no extra audit or mail-log row), 401, 403, missing CSRF,
and the request body ignored.
  - OpenAPI entry.
- Frontend unit:
- `test-admin-dashboard-ui.js`: 72 passed. `test-user-management-ui.js`:
106 passed.
- Covered: button state, *Sending...*, survives the 60 s rebuild, reset
when the account changes (a late answer from the old session is
dropped), escaping.
- E2E: a new step in `test-user-management-e2e.js` (button → fake
mailer, `/__e2e/last-mail` to the admin's address). 47/47 locally.

Local runs on Windows:

- Full `cmd/server` suite passes, except
`TestSaveGeoFilterPreservesFileMode`. That test is unrelated and was
skipped: Windows has no Unix file-mode bits.
- `go vet -tags e2etest`, eslint and gofmt report nothing.

## Not done

- Delivery status, DKIM, AUTH other than PLAIN, and a send queue:
non-goals in the spec.
- The startup check does not refuse a non-ASCII `fromEmail` when the
server lacks SMTPUTF8. It logs *SMTP ready*, and then every send fails
with the SMTPUTF8 error (the test mail shows it too).
- A non-ASCII domain in `fromEmail` goes into EHLO as raw UTF-8.
Converting it to IDNA would need a dependency.
- The E2E step and the browser check (390 and 1280 px, success and long
502 error) ran on `f3a18d49`. The last commit only touches the mailer,
config validation and one hint line, and was not re-checked in a
browser.
…d idx, closes DB on failed open (Kpa-clawbot#2445)

Closes Kpa-clawbot#2443. Follow-up to Kpa-clawbot#2407.

## What changes

> **Master merged in** again (`da87b2cd`, master at `007ba78a`, with
Kpa-clawbot#2442 and Kpa-clawbot#2450): no conflicts. CI is green on the head `7d2ab1a7`. One
run on `da87b2cd` failed master's new repeater-info E2E; this PR changes
nothing that suite uses, and it passed on the next run.
>
> Earlier merge (`3e5288b0`, master at `6ab97f52`, with Kpa-clawbot#2429 and
Kpa-clawbot#2451–Kpa-clawbot#2454): no conflicts, the three commits below are unchanged.
Re-tested on the merge: `go vet` and `go test` across all modules
(Alpine, cgo, 8 MiB musl stacks), all green.

Three commits, one per fix, plus `ba69a7f2` for the first review
(section 4), `0a17c0b8` from an internal review (section 5), and
`7d2ab1a7` for the approving review's three points (section 6).

### 1. `4121a791` Close the DB when `OpenStore` fails

`OpenStoreWithInterval` returned without closing the `*sql.DB` when
ping, schema setup, `dbschema.Apply` or statement preparation failed.
One deferred close now covers every error after `sql.Open`
(`cmd/ingestor/db.go:159`). This is why
`TestOpenStoreRefusesUnconvertibleObservers` could not remove its temp
dir on Windows.

- `TestOpenStoreClosesDBOnFailure` counts the descriptors open on the DB
file after a failed open, using `/proc/self/fd` on Linux, and on every
OS checks that the file can be removed afterwards (an open handle blocks
that on Windows). On the old code: `failed OpenStore left 3
descriptor(s) open on the database`.

### 2. `6cac470c` Require `observers.idx` to be the INTEGER primary key

`observersColumnsInfo` (`internal/dbschema/observers_idx.go:123`)
treated `idx` as done when it had `pk == 1`. That accepts keys that are
not the rowid alias `observer_idx` relies on. It now requires all of:

- `idx` is the only primary-key column;
- it is declared exactly `INTEGER`;
- `pragma_index_list('observers')` has no `pk`-origin index.

The last check catches `idx INTEGER PRIMARY KEY DESC` (a documented
SQLite quirk: type INTEGER, `pk=1`, but not an alias) and `WITHOUT
ROWID` tables.

`AssertReady` and the rebuild share this check. So the server reports
`observers.idx (not the rowid alias)` for these shapes, and the rebuild
no longer takes them as already migrated: it refuses with its own
message (section 4), leaving the table untouched.

- The new `AssertReady` cases (`TEXT` key, composite key, `DESC`,
`WITHOUT ROWID`) returned `err = <nil>` on the old code.
- `TestObserversIdxRefusesNonRowidIdxKey` and
`TestObserversIdxRefusesWithoutRowid` also returned `err = <nil>` on the
old code: the table was treated as migrated.

### 3. `8bca5304` Keep local indexes, triggers and views across the
rebuild

Before this change, indexes and triggers an operator added to
`observers` were dropped with the old table, without a message. Any view
on `observers` made the rename fail with a raw `error in view …: no such
table: main.observers`.

The rebuild now recreates them rather than refusing.

- **Capture.** Inside the rebuild transaction, before anything is
dropped, `captureLocalObservers` (`observers_idx.go:460`) reads from
`sqlite_master`, in creation order:
  - indexes and triggers on `observers`;
- views, and triggers on other tables, whose SQL names `observers`,
`packets_v` or an already captured view.

It repeats until nothing new is found. CoreScope's own `packets_v` and
two `observers` indexes are excluded.
- **Drop.** The captured views, and the triggers on other tables, are
dropped before the rename.
- **Recreate.** Everything is recreated from its original SQL after our
own objects. The ingestor logs one line naming what it recreated.
- **Failure.** If an object cannot be recreated, the whole transaction
rolls back. The error names the object and how to continue
(`observers_idx.go:435`): drop it and recreate it after the upgrade, or
run the previous version.

These rules come from experiments on SQLite 3.53.4:
- the rename fails for a view on `observers`, a view on a dropped view,
and a trigger on another table that mentions `observers`;
- `DROP TABLE` takes the table's own triggers with it, and `DROP VIEW`
takes its `INSTEAD OF` triggers.

**Concurrent starts.** A new test runs `Apply` 8 times at once over two
`*sql.DB` handles on one WAL file. It found a second race: a deferred
transaction that reads first fails with `database is locked` once
another process has rebuilt, and `busy_timeout` doesn't retry that
upgrade. The rebuild transaction now takes the write lock before its
first read. Since `ba69a7f2` it does this with `BEGIN IMMEDIATE`
(section 4); this commit first used a no-op `DELETE FROM observers WHERE
0`.
- `BEGIN IMMEDIATE` waits on `busy_timeout`, so concurrent rebuilds take
turns and the later one sees the table done.
- It only runs when a rebuild is needed: a migrated table returns before
the transaction.

### 4. `ba69a7f2` Review follow-ups

- **Lock without compiling triggers.** `DELETE FROM observers WHERE 0`
compiled every DELETE trigger on `observers`, so one referencing a
dropped table failed the upgrade (`lock observers: no such table:
main.gone`) where the base commit did not. The rebuild now runs as a raw
`BEGIN IMMEDIATE` … `COMMIT` on the pinned connection, which compiles
nothing against `observers`. Every exit that does not commit issues
`ROLLBACK` on that same connection, so the connection never returns to
the pool inside a transaction. If `ROLLBACK` itself fails, the
connection is discarded.
`TestObserversRebuildCarriesBrokenDeleteTrigger` failed with that error
before this change.
- **A refusal for `idx` that is not the rowid alias.** A plain `idx`
column can be dropped, and the message suggests `ALTER TABLE observers
DROP COLUMN idx`. An `idx` in the primary key cannot (`cannot drop
PRIMARY KEY column`), so that message says to recreate the table without
it. The tests execute every statement a message suggests, and check that
`DROP COLUMN` really fails for the primary-key shapes.
- **Quoted names in suggestions.** The suggested `DROP VIEW "my view"`
is quoted the same way as the `DROP` the rebuild runs itself, through a
shared `quoteIdent`.
- **Wording.** `AssertReady` says `observers.idx (not the rowid alias)`.
The unknown-column refusal no longer suggests renaming, which would not
help.
- **Tests.** There is now a direct table test for `mentionsIdentifier`
(`observers_archive`, `client_observers`, `"Observers"`,
`main.observers`, `[observers]`).

Tests:

| Test | Old code |
|------|----------|
| `TestObserversRebuildKeepsLocalObjects` (index, trigger, views, a view
on a view with an `INSTEAD OF` trigger, a view on `packets_v`, a trigger
on `observations` that writes `observers`) | the index and trigger
vanished; the view failed the rename |
| `TestObserversRebuildLocalTriggersFire` | `error in trigger
local_observations_count` |
| `TestObserversRebuildLocalViewsQueryable` | rename error |
| `TestObserversRebuildRefusesUnrecreatableLocalObject` (schema, rows,
local objects and `packets_v` unchanged after the refusal) | new
behaviour |
| `TestObserversRebuildLocalObjectsIdempotent` | new behaviour |
| `TestObserversRebuildConcurrentApply` | `drop packets_v: database is
locked` in 4 of 5 runs; 30 of 30 pass with the fix under `-race` |

### 5. `0a17c0b8` Internal review follow-ups

- **Quoted view names.** A trigger on a view whose name contains `"` is
now captured by its `tbl_name`, and mentions also match the name as
written inside double quotes. Before, an INSTEAD OF trigger on such a
view was lost without a word, and a view built on it failed the rename.
- **`DROP COLUMN` suggestions.** Each refusal that suggests `DROP
COLUMN` also says to drop any index, view or trigger that uses the
column first; SQLite rejects the drop otherwise.
- **Foreign-key refusal.** It now says how to continue: declare the
child column `REFERENCES observers(id)` (extended in section 6).
- **Rollback helper.** The rollback-or-discard step is a named helper,
`rollbackOrDiscard`, with its own tests. A table dropped between the two
reads now ends the rebuild instead of reporting a missing `id` column.
- **CHANGELOG.** The concurrency sentence now covers only what the code
serialises: concurrent rebuilds of the `observers` table.

### 6. `7d2ab1a7` Approving review's points

- **Foreign key refusal.** It names both causes and both ways out: a
child column declared `REFERENCES observers` with no column, or rows
that already reference a missing observer (list them with `PRAGMA
foreign_key_check(...)`).
- **Lock test.** A deterministic test pins `BEGIN IMMEDIATE` and the
"migrated meanwhile" exit. It fails 30 of 30 with plain `BEGIN`.
- **Backtick-quoted names.** A captured view name written in backticks
is matched too.

Tests: `TestObserversIdxForeignKeyRefusalCoversOrphanRows` (runs the
suggested `PRAGMA foreign_key_check`, deletes the orphan, then the
rebuild succeeds) and
`TestObserversRebuildWaitsForWriterThenSeesMigrated` (fails 30 of 30
with plain `BEGIN`).

## Not covered

- A view or trigger in the database that is already broken, unrelated to
`observers`, still makes the rename fail with the raw SQLite error, as
it does today.
- A local `SELECT *` view on `observers` gains the `idx` column after
the rebuild.
- Two ingestors starting on one legacy file at once can still fail in
`EnsurePacketsView` (`view packets_v already exists`). That code
predates this PR, which does not touch it.
- A WITHOUT ROWID legacy table with no `idx` column fails with a raw `no
such column: rowid` and is rolled back. That fails safe, and the shape
is exotic.

## Performance

None of this is on a hot path. The capture runs once, inside the
one-time rebuild, over the schema's few dozen `sqlite_master` rows. The
extra primary-key probe in `observersColumnsInfo` is one
`pragma_index_list` read at startup, and only when the other checks
pass.

## Testing

Run in a cgo `golang:1.27-alpine` container:

- `gofmt -l` is empty and `go vet` is clean in `internal/dbschema` and
`cmd/ingestor`.
- `internal/dbschema`: `go test -count=3 -race ./...` passes.
- `cmd/ingestor`, `cmd/server` and `cmd/migrate`: `go test -count=1
./...` passes.
- On `ba69a7f2`: `go vet` and `go test -count=1 ./...` pass in
`internal/dbschema`, `cmd/ingestor`, `cmd/server` and `cmd/migrate`.
`TestObserversRebuildConcurrentApply` passes in 15 of 15 runs.
- On `7d2ab1a7`: `gofmt -l` empty, `go vet` clean, `go test -count=1
./...` ok in `internal/dbschema` and `cmd/ingestor`; the new tests pass
in 20 repeated runs and
`TestObserversRebuildWaitsForWriterThenSeesMigrated` with `-count=50`.
- Windows (independent, on `7d2ab1a7`):
`TestOpenStoreRefusesUnconvertibleObservers` and
`TestOpenStoreClosesDBOnFailure` passed 5 consecutive runs, and the full
native ingestor suite passed; the same cleanup test fails on master
`007ba78a`.

This is backend only, so there are no frontend or browser changes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Release notes and changelog entry for v3.19.0.

- `docs/release-notes/v3.19.0.md`: the full notes, also the GitHub
release body (`deploy.yml` reads it as `body_path`).
- `CHANGELOG.md`: `[Unreleased]` becomes `[3.19.0] - 2026-11-24` with
six highlights. The SMTP and map-provider lines that were under
`[Unreleased]` are covered by the highlights and the notes.

32 commits since v3.18.0, up to `70dc4453` (Kpa-clawbot#2445): 14 fix, 8 feat, 5
test, 2 ci, 2 docs, 1 refactor. Types come from the PR titles; Kpa-clawbot#2442,
Kpa-clawbot#2429 and Kpa-clawbot#2430 have no prefix and count as feat, Kpa-clawbot#2450 as fix.

Read before upgrading, in the notes: the one-time `observers` rebuild
(Kpa-clawbot#2407, Kpa-clawbot#2445), the content-hash migration now running in the ingestor
(Kpa-clawbot#2409), `users.db` schema v10 with accounts on (Kpa-clawbot#2429), and SNR per
node from direct receptions only (Kpa-clawbot#2451-Kpa-clawbot#2454).

Left out on purpose: Kpa-clawbot#2446 (map picker follow-ups to Kpa-clawbot#2434, not yet
approved), for v3.19.1.

Not done: no staging run of master before tagging.

After merge: tag `v3.19.0` on this PR's squash commit once its `:edge`
image carries that revision.
Conflicts resolved:
- map.js/live.js: take upstream's shared MC_attachAutoTiles basemap, which
  already rebuilds a layer when maxZoom changes (our 2026-11-12 zoom fix);
  drop our MC_updateTileLayer helper and its test.
- live.js: keep loading observers alongside nodes, plus upstream's
  stale-page guard.
- node_reach.go: upstream's route type, with our scoped-observer key.
- server db.go: our region predicate, upstream's observers.idx join.
- ingestor db.go: grouped-commit open path with upstream's close-on-error;
  observer lookup by idx inside the writer transaction.

Follow-ups the merge needs:
- Fork queries join observers on idx instead of the implicit rowid.
- Grouped commits pass through a transaction the caller opens with its own
  BEGIN statement. Without this the v3.19 observers rebuild failed on a
  batched writer and the WAN ingestor would not start.
- Observation-cleanup archives copy and restore by column name and gain
  columns the source tables gained (observers.idx). Before, every cleanup
  after the rebuild was refused with "archive schema mismatch". A restored
  observer gets a fresh idx, as it got a fresh rowid before.

Tested: go vet + go test for every module (ingestor also with
CORESCOPE_TEST_BATCH_COMMIT_MS=50: only the pre-existing
TestObservationCleanupIndependentReaderSnapshot failure, same as master),
263 JS unit tests, and ingestor + server run offline on copies of the live
scope and WAN databases (observers rebuilt, 52 and 151 rows).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@kesh33w
kesh33w merged commit d34ba21 into master Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants