diff --git a/.changeset/six-lens-review-relay-storage.md b/.changeset/six-lens-review-relay-storage.md new file mode 100644 index 000000000..3985809fb --- /dev/null +++ b/.changeset/six-lens-review-relay-storage.md @@ -0,0 +1,16 @@ +--- +--- + +docs: record the six-lens review of nostream-relay and nostream-storage + +Six lenses read the 68 files and 28,560 lines of the rewrite's two largest crates at +`8488bf13`, plus the four standing surfaces the row names: MCP authentication and +authorisation, the settings loader and its precedence, the PG-to-LMDB migration tool, +and LMDB file permissions and directory creation. + +`docs/rewrite/reviews/2026-11-30-relay-storage.md` is the record: each lens's scope with +a command and a quoted line per file, 42 findings each carrying a `path:line`, a one-line +severity with its loss, a dedupe check and a disposition, the four surface sections, the +filed issues and an explicit "not covered" section. Nothing is fixed in this row and no +source file changes; every defect a maintainer would change is an issue, deduped against +the open list first. diff --git a/docs/rewrite/reviews/2026-11-30-relay-storage.md b/docs/rewrite/reviews/2026-11-30-relay-storage.md new file mode 100644 index 000000000..ab4c98488 --- /dev/null +++ b/docs/rewrite/reviews/2026-11-30-relay-storage.md @@ -0,0 +1,884 @@ +# The six-lens review of `nostream-relay` and `nostream-storage` + +Phase 6 row 5 of #868. Six lenses read the rewrite's two largest crates as they stand, and the four standing surfaces whose risk is a design rather than a change: MCP authentication and authorisation, the settings loader and its precedence, the PG→LMDB migration tool, and LMDB file permissions and directory creation. Nothing in this row is fixed — a fix makes the diff the thing under review — so every defect a maintainer would change is an issue that carries the evidence already gathered. + +- **Reviewed tree:** `8488bf135808c3ca77191558d747c7beabcad966` — `git rev-parse HEAD` in the review's checkout, with `git status --porcelain` empty. The row adds only this document and one changeset, so every finding below is measured at base and at head alike, and a later reader can tell whether it still holds by running its evidence command on that tree. +- **Review date:** 2026-11-30. +- **Subject, relay:** `nostream-relay` — 39 files, 10,795 lines of `src`, measured with `find crates/nostream-relay/src -name '*.rs' | wc -l` and `find crates/nostream-relay/src -name '*.rs' -exec cat {} + | wc -l`. +- **Subject, storage:** `nostream-storage` — 29 files, 17,765 lines, the same two commands over `crates/nostream-storage/src`. +- **Subject, both:** 68 files, 28,560 lines. +- **Test baseline:** 543 passed, 0 failed, 9 ignored across 25 targets in 97 s, from `cargo test -p nostream-relay -p nostream-storage --no-fail-fast`. The nine ignored tests are Postgres/TLS: eight need `PARITY_ADMIN_URL` and one `PARITY_TLS_ADMIN_URL`. +- **Open issues when the row was cut:** 147, from `gh issue list --state open --limit 400 --json number --jq length` at 2026-11-30T06:04Z. The same command at assembly (2026-11-30T08:38Z) prints 182; the difference is this row's own filings plus the nine the lenses filed during the round. The count moves, so this record states the snapshot it measured rather than a number a later reader should expect: a different count is not a defect in it. +- **Dedupe checklist:** the open list above, plus the 31 known defects in this area named at `recon.md:253-283` (`grep -oE '#[0-9]{3,4}' | sort -u | wc -l` → 31). + +**How to read it.** Each lens has a section with the files it read, the command it ran against each, a line quoted from inside the cited range, and its findings. A finding is a `### F` block whose six lines give the lens, one `path:line`, a severity band with what a person loses, the evidence (a command and the line it printed, or a reading and what it rests on), the dedupe check, and the disposition. The four `## Surface:` sections cover the standing designs the row names. `## Filed issues` is the set of issues this row opened, and `## Not covered` says what the review does not vouch for. + +**Cost and depth.** The six lenses ran under one row. The cost is the orchestrator's measurement of each lens's own run; the depth is the lens's own statement of what it read. + +| Lens | Cost (USD) | Depth | +|---|---|---| +| code | 0.59 | 59 files as the 60 scope rows, 19,725 distinct-file lines: the whole relay `src` outside `testing.rs`, `unavailable.rs` and `wot.rs`, and the whole storage `src` outside the Postgres metadata and notification arms and the two crates' unit-test halves | +| architecture | 0.17 | 16 scope rows and 1,670 distinct-file lines, plus the manifests for the import direction; no Rust toolchain, so every dependency claim rests on the manifests and on grep, not on cargo's own graph | +| security | 0.23 | 16 scope rows over the four surfaces, read in full, plus the relay's transport and subscription bounds as an optional fifth subject | +| performance | 0.18 | fourteen files in fifteen ranges, about 5,000 lines read end to end, plus every `shortcut:` marker in `lmdb/events.rs` and `lmdb/search.rs`; six measurements, no wall-clock throughput | +| ux | 0.29 | the console page and five of its six scripts (3,202 lines), twelve `nostream-admin` files (2,280 lines), the whole MCP server (1,426) and its stdio mode (124), the migration command (1,700) and its error renderer; no browser | +| ui | 0.10 | `dashboard.html` (680 lines), `dashboard.css` (1,842) and the six scripts (3,346), plus the whole Rust rendering path; no browser and no screenshot | + +`ui` is the one lens whose cost and depth reflect a narrow subject: it read the rendered surface and the Rust that serves it, and stopped there. + +## Review waves + +- Wave 1 — code, architecture, security — the code lens has to map the handler and storage paths before a seam or a standing surface can be judged, so it ran first and its two crate runs are the behaviour oracle the other five cite; architecture and security then read the same tree against the design records, the import graph and the four surfaces the row names. +- Wave 2 — performance, ux, ui — performance could not share the host with three other readers and produce a comparable number, so it ran on its own against named benchmarks rather than a wall clock; ux and ui read the operator-facing strings and the two rendered artifacts once the code had named the files that carry them. + +Each lens wrote its own file, `round-1/review-.md` — the repository's job tree, not the worktree — and this document is their assembly. Every `### F` block's `- where:` value, `- severity:` band and `- evidence:` command appear in the lens file its `- lens:` line names, and no finding exists here that its lens file does not carry. Three defects were found twice, from two sides, and each side keeps its own block with its own citation and one line naming its twin: the ux and ui lenses both found the console's fixed metrics failure state (F25, F41) and its permanent Redis fault (F26, F42), and the security lens's store-directory finding is the architecture lens's measured from the opener instead of the migration tool (F11, F21). A merged block would have hidden which lens measured which line, so the twins cross-reference each other instead. +The one exception is F31's citation: the ux lens writes `storage.rs:63-66`, line 63 is blank, so that block cites `64-66` and says so. + +**The behaviour oracle.** A lens's behavioural oracle is the target that decides the claim: `cargo test -p nostream-relay --all-features` or `cargo test -p nostream-storage --all-features`, or one `--test ` of them. A behaviour claim names the target and the test, never "the suite passes". The workspace run is not the oracle: on this host `cargo test --workspace --all-features --no-fail-fast` exits 101 with 1850 passed and 8 failed, all `nostream-admin --test query_limits` ten-second response-head timeouts, and that target alone passes 30/30 in 16.5 s. It is load-sensitive, so those eight are environmental and never a finding. The relay and storage crate runs give 320 passed / 0 failed / 0 ignored and 223 passed / 0 failed / 9 ignored, which is the 543 / 0 / 9 baseline above. + +**What could not run here.** This sandbox exposes no Docker daemon (`docker info` exits 1), so `scripts/storage-parity.sh` cannot run, and there is no `node_modules`, so it has no `CUCUMBER_BIN` either. Eight of the nine ignored tests need `PARITY_ADMIN_URL` and one `PARITY_TLS_ADMIN_URL`; the TLS leg runs in no workflow (#1201). Any claim that would need a live Postgres is a code reading in this record, and the finding that lands in a Postgres arm says so on its evidence line. + +## Lens: code + +The code lens read the two crates as they stand: this row carries no source diff, so the subject is the subsystem itself rather than a change. It read the whole relay `src` outside `testing.rs`, `unavailable.rs` and `wot.rs`, the whole storage `src` outside the Postgres metadata, notification, module and row arms and the two crates' unit-test halves, and cross-checked each behaviour it reports against the captured TypeScript under `src/`. Nine findings: seven defects no open issue names and two existing issues this lens measured and adds to. + +- command: `cargo test -p nostream-relay --all-features` → 320 passed, 0 failed, 0 ignored across its 14 targets (the per-target test result lines summed; doc-tests ran 0) +- command: `cargo test -p nostream-storage --all-features` → 223 passed, 0 failed, 9 ignored across its 13 targets; the 543 / 0 / 9 baseline holds for the two runs together +- command: `grep -n 'Limit too high' crates/nostream-relay/src/handlers/subscribe.rs` → `620: "Limit too high: Filter limit must be less than or equal to {max_limit}"` +- inversion: none — base and head are the same commit, so this row adds no branch to invert; every arm cited predates it, and the two crate suites are the oracle that exercises them +- not run: the Postgres arms cannot execute here (no `PARITY_ADMIN_URL`, so the nine ignored tests stay ignored) and `scripts/storage-parity.sh` needs a Docker daemon this host does not expose; any finding that lands in a Postgres arm says so on its evidence line + +**Scope.** 60 rows over 59 files, 19,725 distinct-file lines; a row whose path carries a range is a partial read and its count is the range's length. + +path | lines | responsibility | command → output | quoted line +---|---|---|---|--- + +| `crates/nostream-relay/src/broadcast.rs:1-29` | 29 | Cross-worker relay-broadcast envelope and fan-out functions, both still stubs that return NotImplemented | `grep -n 'fn deduplicate' crates/nostream-relay/src/broadcast.rs` → pub fn deduplicate(_message: &BroadcastMessage) -> Result { | `pub fn deduplicate(_message: &BroadcastMessage) -> Result {` | +| `crates/nostream-relay/src/connection.rs:1-407` | 407 | Per-socket state: subscriptions, auth session, liveness, close and the subscription gauge | `grep -n 'pub fn close' crates/nostream-relay/src/connection.rs` → pub fn close(&self) { | `pub fn close(&self) {` | +| `crates/nostream-relay/src/connection_cap.rs:1-177` | 177 | Per-IP connection accounting with the cap, the reservation guard and the refusal count | `grep -n 'pub fn acquire' crates/nostream-relay/src/connection_cap.rs` → pub fn acquire(self: &Arc, ip: &str) -> Option { | `pub fn acquire(self: &Arc, ip: &str) -> Option {` | +| `crates/nostream-relay/src/dispatch.rs:1-149` | 149 | Protocol sniffing on the accepted socket: HTTP head fallback versus a websocket upgrade | `grep -n 'pub const HEAD_TIMEOUT' crates/nostream-relay/src/dispatch.rs` → pub const HEAD_TIMEOUT: Duration = Duration::from_millis(1_000); | `pub const HEAD_TIMEOUT: Duration = Duration::from_millis(1_000);` | +| `crates/nostream-relay/src/error.rs:1-29` | 29 | The relay error enum, including the deliberate stub variant and the storage and limiter wrappers | `grep -n 'NotImplemented { module' crates/nostream-relay/src/error.rs` → NotImplemented { module: &'static str }, | `NotImplemented { module: &'static str },` | +| `crates/nostream-relay/src/handlers/auth.rs:1-38` | 38 | The AUTH handler: verify the NIP-42 event and admit its pubkey to the socket session | `grep -n 'pub fn handle' crates/nostream-relay/src/handlers/auth.rs` → pub fn handle(message: AuthMessage, context: &HandlerContext) { | `pub fn handle(message: AuthMessage, context: &HandlerContext) {` | +| `crates/nostream-relay/src/handlers/count.rs:1-103` | 103 | The COUNT handler: subscription checks, the count cap, count_by_filters and the CLOSED reason | `grep -n 'pub async fn handle' crates/nostream-relay/src/handlers/count.rs` → pub async fn handle(message: CountMessage, context: &HandlerContext) { | `pub async fn handle(message: CountMessage, context: &HandlerContext) {` | +| `crates/nostream-relay/src/handlers/event.rs:1-738` | 738 | The EVENT pipeline: validation, vanish, admission, strategy selection and the OK frame | `grep -n 'pub async fn handle' crates/nostream-relay/src/handlers/event.rs` → pub async fn handle(event: Event, context: &HandlerContext) { | `pub async fn handle(event: Event, context: &HandlerContext) {` | +| `crates/nostream-relay/src/handlers/mod.rs:1-308` | 308 | The shared handler context, the per-connection handler set and abortable read registration | `grep -n 'pub struct HandlerContext' crates/nostream-relay/src/handlers/mod.rs` → pub struct HandlerContext { | `pub struct HandlerContext {` | +| `crates/nostream-relay/src/handlers/subscribe.rs:1-737` | 737 | REQ handling: subscription checks, the storage page, the read loop, EOSE hints and metrics | `grep -n 'pub fn begin' crates/nostream-relay/src/handlers/subscribe.rs` → pub fn begin(message: SubscribeMessage, context: &Arc) -> Option { | `pub fn begin(message: SubscribeMessage, context: &Arc) -> Option {` | +| `crates/nostream-relay/src/handlers/unsubscribe.rs:1-17` | 17 | The CLOSE handler: abort the subscription's in-flight read and drop the subscription | `grep -n 'pub fn handle' crates/nostream-relay/src/handlers/unsubscribe.rs` → pub fn handle(message: UnsubscribeMessage, context: &HandlerContext) { | `pub fn handle(message: UnsubscribeMessage, context: &HandlerContext) {` | +| `crates/nostream-relay/src/hidden_content.rs:1-169` | 169 | The in-memory NIP-56 mirror of hidden targets, refreshed from actionable moderator reports | `grep -n 'pub struct HiddenContentCache' crates/nostream-relay/src/hidden_content.rs` → pub struct HiddenContentCache { | `pub struct HiddenContentCache {` | +| `crates/nostream-relay/src/lib.rs:1-72` | 72 | The crate root: module list, the documented stubs and the captured TypeScript paths | `grep -n 'pub mod broadcast' crates/nostream-relay/src/lib.rs` → pub mod broadcast; | `pub mod broadcast;` | +| `crates/nostream-relay/src/limits.rs:1-677` | 677 | The four rate-limit levels over an in-process sliding or EWMA store, and their backoffs | `grep -n 'pub struct RateLimits' crates/nostream-relay/src/limits.rs` → pub struct RateLimits { | `pub struct RateLimits {` | +| `crates/nostream-relay/src/metrics.rs:1-672` | 672 | The process-wide counters and histograms and their Prometheus text exposition | `grep -n 'pub struct RelayMetrics' crates/nostream-relay/src/metrics.rs` → pub struct RelayMetrics { | `pub struct RelayMetrics {` | +| `crates/nostream-relay/src/nip11.rs:1-344` | 344 | The NIP-11 relay information document builder and its projection of the settings | `grep -n 'pub fn document' crates/nostream-relay/src/nip11.rs` → pub fn document( | `pub fn document(` | +| `crates/nostream-relay/src/relay.rs:1-796` | 796 | The relay loop: accept, connection dispatch, live fan-out and graceful shutdown | `grep -n 'pub struct RelayConfig' crates/nostream-relay/src/relay.rs` → pub struct RelayConfig { | `pub struct RelayConfig {` | +| `crates/nostream-relay/src/relay_key.rs:1-168` | 168 | Relay key resolution and the deterministic key derivation the NIP-11 and HMAC paths use | `grep -n 'pub struct RelayKeys' crates/nostream-relay/src/relay_key.rs` → pub struct RelayKeys { | `pub struct RelayKeys {` | +| `crates/nostream-relay/src/sink.rs:1-720` | 720 | The outgoing-frame queue, its byte budget, admission and the drain task | `grep -n 'pub struct FrameSink' crates/nostream-relay/src/sink.rs` → pub struct FrameSink { | `pub struct FrameSink {` | +| `crates/nostream-relay/src/transport.rs:1-239` | 239 | The websocket transport: upgrade, message size limit, close codes and liveness pings | `grep -n 'pub enum Inbound' crates/nostream-relay/src/transport.rs` → pub enum Inbound { | `pub enum Inbound {` | +| `crates/nostream-relay/src/strategies/mod.rs:1-246` | 246 | The ordered strategy registry and the single table that maps an event kind to its strategy | `grep -n 'pub fn select' crates/nostream-relay/src/strategies/mod.rs` → pub fn select(event: &Event) -> Selection { | `pub fn select(event: &Event) -> Selection {` | +| `crates/nostream-relay/src/strategies/contact_list.rs:1-83` | 83 | The kind-3 contact-list arm: replaceable storage through upsert, and a broadcast only on insert | `grep -n 'impl EventStrategy for ContactListStrategy' crates/nostream-relay/src/strategies/contact_list.rs` → impl EventStrategy for ContactListStrategy { | `impl EventStrategy for ContactListStrategy {` | +| `crates/nostream-relay/src/strategies/default.rs:1-52` | 52 | The fallback arm: create the row, answer duplicate on a zero count and broadcast on insert | `grep -n 'impl EventStrategy for DefaultStrategy' crates/nostream-relay/src/strategies/default.rs` → impl EventStrategy for DefaultStrategy { | `impl EventStrategy for DefaultStrategy {` | +| `crates/nostream-relay/src/strategies/delete.rs:1-281` | 281 | The kind-5 deletion arm: e-tag ids and a-tag addresses, each bounded, then store and broadcast | `grep -n 'impl EventStrategy for DeleteStrategy' crates/nostream-relay/src/strategies/delete.rs` → impl EventStrategy for DeleteStrategy { | `impl EventStrategy for DeleteStrategy {` | +| `crates/nostream-relay/src/strategies/dvm_job_request.rs:1-57` | 57 | The DVM job-request arm: create the job row before the event is stored | `grep -n 'impl EventStrategy for DvmJobRequestStrategy' crates/nostream-relay/src/strategies/dvm_job_request.rs` → impl EventStrategy for DvmJobRequestStrategy { | `impl EventStrategy for DvmJobRequestStrategy {` | +| `crates/nostream-relay/src/strategies/ephemeral.rs:1-35` | 35 | The ephemeral-kind arm: answer OK and broadcast without writing storage | `grep -n 'impl EventStrategy for EphemeralStrategy' crates/nostream-relay/src/strategies/ephemeral.rs` → impl EventStrategy for EphemeralStrategy { | `impl EventStrategy for EphemeralStrategy {` | +| `crates/nostream-relay/src/strategies/gift_wrap.rs:1-84` | 84 | The kind-1059 arm: exactly one valid p tag and a NIP-44 payload, then store and broadcast | `grep -n 'impl EventStrategy for GiftWrapStrategy' crates/nostream-relay/src/strategies/gift_wrap.rs` → impl EventStrategy for GiftWrapStrategy { | `impl EventStrategy for GiftWrapStrategy {` | +| `crates/nostream-relay/src/strategies/group.rs:1-79` | 79 | The kind-445 arm: exactly one valid h tag, then store and broadcast | `grep -n 'impl EventStrategy for GroupStrategy' crates/nostream-relay/src/strategies/group.rs` → impl EventStrategy for GroupStrategy { | `impl EventStrategy for GroupStrategy {` | +| `crates/nostream-relay/src/strategies/invite_request.rs:1-45` | 45 | The kind-28934 arm: mint an invite event for an admitted requester | `grep -n 'impl EventStrategy for InviteRequestStrategy' crates/nostream-relay/src/strategies/invite_request.rs` → impl EventStrategy for InviteRequestStrategy { | `impl EventStrategy for InviteRequestStrategy {` | +| `crates/nostream-relay/src/strategies/join_request.rs:1-138` | 138 | The kind-28935 arm: write an admission row and answer OK | `grep -n 'impl EventStrategy for JoinRequestStrategy' crates/nostream-relay/src/strategies/join_request.rs` → impl EventStrategy for JoinRequestStrategy { | `impl EventStrategy for JoinRequestStrategy {` | +| `crates/nostream-relay/src/strategies/leave_request.rs:1-98` | 98 | The kind-28936 arm: revoke the admission and answer OK | `grep -n 'impl EventStrategy for LeaveRequestStrategy' crates/nostream-relay/src/strategies/leave_request.rs` → impl EventStrategy for LeaveRequestStrategy { | `impl EventStrategy for LeaveRequestStrategy {` | +| `crates/nostream-relay/src/strategies/parameterized_replaceable.rs:1-51` | 51 | The addressable-kind arm: upsert keyed by the d tag and broadcast on insert | `grep -n 'impl EventStrategy for ParameterizedReplaceableStrategy' crates/nostream-relay/src/strategies/parameterized_replaceable.rs` → impl EventStrategy for ParameterizedReplaceableStrategy { | `impl EventStrategy for ParameterizedReplaceableStrategy {` | +| `crates/nostream-relay/src/strategies/replaceable.rs:1-57` | 57 | The replaceable-kind arm: upsert keyed by author and kind, and broadcast on insert | `grep -n 'impl EventStrategy for ReplaceableStrategy' crates/nostream-relay/src/strategies/replaceable.rs` → impl EventStrategy for ReplaceableStrategy { | `impl EventStrategy for ReplaceableStrategy {` | +| `crates/nostream-relay/src/strategies/report.rs:1-121` | 121 | The NIP-56 report arm: score a trusted moderator, mark targets and record the report | `grep -n 'impl EventStrategy for ReportStrategy' crates/nostream-relay/src/strategies/report.rs` → impl EventStrategy for ReportStrategy { | `impl EventStrategy for ReportStrategy {` | +| `crates/nostream-relay/src/strategies/timestamp.rs:1-116` | 116 | The kind-1040 arm: validate the e and k tags and the OpenTimestamps proof, then store | `grep -n 'impl EventStrategy for TimestampStrategy' crates/nostream-relay/src/strategies/timestamp.rs` → impl EventStrategy for TimestampStrategy { | `impl EventStrategy for TimestampStrategy {` | +| `crates/nostream-relay/src/strategies/vanish.rs:1-55` | 55 | The kind-62 arm: delete the pubkey's events and set the vanish flag | `grep -n 'impl EventStrategy for VanishStrategy' crates/nostream-relay/src/strategies/vanish.rs` → impl EventStrategy for VanishStrategy { | `impl EventStrategy for VanishStrategy {` | +| `crates/nostream-storage/src/backend.rs:1-172` | 172 | Backend selection and the LMDB store path constants and directory helpers | `grep -n 'pub fn store_dir' crates/nostream-storage/src/backend.rs` → pub fn store_dir(root: &Path) -> PathBuf { | `pub fn store_dir(root: &Path) -> PathBuf {` | +| `crates/nostream-storage/src/event_store.rs:1-47` | 47 | Chooses the event-store backend from settings and the environment override | `grep -n 'pub fn configured_backend' crates/nostream-storage/src/event_store.rs` → pub fn configured_backend(settings: &Settings) -> nostream_core::EventStoreBackend { | `pub fn configured_backend(settings: &Settings) -> nostream_core::EventStoreBackend {` | +| `crates/nostream-storage/src/keys.rs:1-33` | 33 | The order-preserving byte encoders for integer and timestamp keys | `grep -n 'pub(crate) fn i32_key' crates/nostream-storage/src/keys.rs` → pub(crate) fn i32_key(value: i32) -> [u8; 4] { | `pub(crate) fn i32_key(value: i32) -> [u8; 4] {` | +| `crates/nostream-storage/src/lib.rs:1-91` | 91 | The crate root: the page-bound contract constants and the documented reading rules | `grep -n 'pub const MAX_PAGE_ROWS' crates/nostream-storage/src/lib.rs` → pub const MAX_PAGE_ROWS: u64 = 5_000; | `pub const MAX_PAGE_ROWS: u64 = 5_000;` | +| `crates/nostream-storage/src/lmdb/encoding.rs:1-903` | 903 | LMDB key and value encoding: hex ranges, timestamps, amounts and the event caches | `grep -n 'pub(crate) fn hex_ranges' crates/nostream-storage/src/lmdb/encoding.rs` → pub(crate) fn hex_ranges(criteria: &[String], suffix: usize) -> Vec<(Vec, Vec)> { | `pub(crate) fn hex_ranges(criteria: &[String], suffix: usize) -> Vec<(Vec, Vec)> {` | +| `crates/nostream-storage/src/lmdb/events.rs:1-2472` | 2472 | The LMDB event paths: query plan, matcher, paging, counting, deletion and retention | `grep -n 'let descending = filter.limit.is_some()' crates/nostream-storage/src/lmdb/events.rs` → let descending = filter.limit.is_some(); | `let descending = filter.limit.is_some();` | +| `crates/nostream-storage/src/lmdb/invoices.rs:1-200` | 200 | The LMDB invoice arm: find, upsert, status transitions and confirmation | `grep -n 'pub(crate) fn confirm_invoice' crates/nostream-storage/src/lmdb/invoices.rs` → pub(crate) fn confirm_invoice( | `pub(crate) fn confirm_invoice(` | +| `crates/nostream-storage/src/lmdb/metadata.rs:1-836` | 836 | The LMDB metadata arms: NIP-05 rows, invite codes, DVM jobs and report rows | `grep -n 'pub(crate) fn nip05_upsert' crates/nostream-storage/src/lmdb/metadata.rs` → pub(crate) fn nip05_upsert( | `pub(crate) fn nip05_upsert(` | +| `crates/nostream-storage/src/lmdb/migration.rs:1-179` | 179 | The LMDB migration target: table-by-table copy with the canonical checksum | `grep -n 'impl MigrationTarget for LmdbBackend' crates/nostream-storage/src/lmdb/migration.rs` → impl MigrationTarget for LmdbBackend { | `impl MigrationTarget for LmdbBackend {` | +| `crates/nostream-storage/src/lmdb/mod.rs:1-1348` | 1348 | The LMDB environment open, databases, read and write transaction helpers and the nine impls | `grep -n 'fn lock_rebuild_file' crates/nostream-storage/src/lmdb/mod.rs` → fn lock_rebuild_file(path: &Path) -> Result { | `fn lock_rebuild_file(path: &Path) -> Result {` | +| `crates/nostream-storage/src/lmdb/notifications.rs:1-673` | 673 | The LMDB notification outbox and delivery-log arms | `grep -n 'pub(crate) fn append' crates/nostream-storage/src/lmdb/notifications.rs` → pub(crate) fn append( | `pub(crate) fn append(` | +| `crates/nostream-storage/src/lmdb/rows.rs:1-217` | 217 | The table-tagged row encoding and the stored-user and related row structs | `grep -n 'fn encode' crates/nostream-storage/src/lmdb/rows.rs` → pub(crate) fn encode(table: &'static str, row: &T) -> Result, StorageError> | `pub(crate) fn encode(table: &'static str, row: &T) -> Result, StorageError>` | +| `crates/nostream-storage/src/lmdb/search.rs:1-805` | 805 | The NIP-50 index: tokeniser, postings, rank, rebuild and the searched page | `grep -n 'pub const SEARCH_INDEX_DB' crates/nostream-storage/src/lmdb/search.rs` → pub const SEARCH_INDEX_DB: &str = "events_by_term"; | `pub const SEARCH_INDEX_DB: &str = "events_by_term";` | +| `crates/nostream-storage/src/lmdb/users.rs:1-230` | 230 | The LMDB user arm: load and store, admission, balance and the vanish flag | `grep -n 'pub(crate) fn is_vanished' crates/nostream-storage/src/lmdb/users.rs` → pub(crate) fn is_vanished( | `pub(crate) fn is_vanished(` | +| `crates/nostream-storage/src/migration.rs:1-260` | 260 | The backend-neutral migration seam types and the canonical projection | `grep -n 'pub trait MigrationSource' crates/nostream-storage/src/migration.rs` → pub trait MigrationSource: Send + Sync { | `pub trait MigrationSource: Send + Sync {` | +| `crates/nostream-storage/src/opened.rs:1-67` | 67 | The opened-stores bundle the daemon hands to the relay | `grep -n 'pub struct Repositories' crates/nostream-storage/src/opened.rs` → pub struct Repositories { | `pub struct Repositories {` | +| `crates/nostream-storage/src/postgres/events.rs:60-563` | 504 | The Postgres event SQL arms: create, upsert, filters, counts, deletion and retention | `grep -n 'pub(crate) async fn upsert_many' crates/nostream-storage/src/postgres/events.rs` → pub(crate) async fn upsert_many<'e, E>( | `pub(crate) async fn upsert_many<'e, E>(` | +| `crates/nostream-storage/src/postgres/invoices.rs:1-146` | 146 | The Postgres invoice arm: find, upsert, status and the confirm transaction | `grep -n 'pub(crate) async fn confirm_invoice' crates/nostream-storage/src/postgres/invoices.rs` → pub(crate) async fn confirm_invoice<'e, E>( | `pub(crate) async fn confirm_invoice<'e, E>(` | +| `crates/nostream-storage/src/postgres/migration.rs:1-298` | 298 | The Postgres migration source: table reads and the canonical rows | `grep -n 'impl MigrationSource for PostgresBackend' crates/nostream-storage/src/postgres/migration.rs` → impl MigrationSource for PostgresBackend { | `impl MigrationSource for PostgresBackend {` | +| `crates/nostream-storage/src/postgres/repository.rs:1-667` | 667 | The nine trait implementations on the Postgres backend and the three a transaction carries | `grep -n 'impl EventRepository for PostgresBackend' crates/nostream-storage/src/postgres/repository.rs` → impl EventRepository for PostgresBackend { | `impl EventRepository for PostgresBackend {` | +| `crates/nostream-storage/src/postgres/sql.rs:99-563` | 465 | The Postgres query builder: conditions, tag and hex ranges, ordering and limits | `grep -n 'fn push_conditions' crates/nostream-storage/src/postgres/sql.rs` → fn push_conditions( | `fn push_conditions(` | +| `crates/nostream-storage/src/records.rs:1-634` | 634 | The stored-event record, its replacement key and its field-merge rules | `grep -n 'pub fn replacement_key' crates/nostream-storage/src/records.rs` → pub fn replacement_key(record: &EventRecord) -> Option<(Pubkey, u64, ReplacementKey<'_>)> { | `pub fn replacement_key(record: &EventRecord) -> Option<(Pubkey, u64, ReplacementKey<'_>)> {` | +| `crates/nostream-storage/src/repositories.rs:1-260` | 260 | The repository traits, the stream types and the page-bound declarations | `grep -n 'pub struct EventRecord' crates/nostream-storage/src/repositories.rs` → pub struct EventRecord { | `pub struct EventRecord {` | +| `crates/nostream-storage/src/repositories.rs:503-793` | 291 | The EventRepository trait with its filter, count, page, deletion and retention methods | `grep -n 'pub trait EventRepository' crates/nostream-storage/src/repositories.rs` → pub trait EventRepository: Send + Sync { | `pub trait EventRepository: Send + Sync {` | + +**Not read by this lens.** The relay's shipped support modules `testing.rs` (2,218 lines), `unavailable.rs` (354) and `wot.rs` (36), and the storage crate's `error.rs`, `postgres/metadata.rs`, `postgres/notifications.rs`, `postgres/mod.rs`, `postgres/rows.rs`, `postgres/users.rs`, and the unit-test halves of `lmdb/events.rs` (2,473-4,431), `lmdb/mod.rs` (1,349-1,748) and the other files whose rows stop at `mod tests`. The Postgres arms are read but not executed, as above, and the search index's rebuild path (`lmdb/search.rs:393` onward) is read only for the clock and rank arguments. `## Not covered` names the files no lens read and why. + +**Verified and not reported.** The live-predicate split is the recorded decision (ADR 0011:114-119, and `parity_lmdb`'s `a_soft_deleted_event_is_readable_by_filter_and_excluded_from_count`), not a defect. Postgres honouring a filter limit above `MAX_PAGE_ROWS` while LMDB clamps is the divergence `lib.rs:71-78` documents, and raising `client.subscription.maxLimit` is what makes it observable. The `#g` trailing-asterisk prefix itself matches the capture in both backends; only its LIKE escaping does not (F3). The `processNip05Metadata` omission is one of ADR 0004's census exemptions. The tag-key length refusal at `lmdb/encoding.rs:41` and `search.rs:339`'s first-term bound both carry `shortcut:` markers of their own, so they are ceilings, not findings. + +### F1 the page-bound doc cites the wrong line for the Limit-too-high refusal +- lens: code +- where: `crates/nostream-storage/src/lib.rs:76` +- severity: low — a reader following the citation lands on the EOSE-hint block and cannot find the refusal it is told is there +- evidence: `grep -n 'subscribe.rs:525' crates/nostream-storage/src/lib.rs` → 76:/// refused (subscribe.rs:525) — so the two agree only while that setting does. Raising it (backticks omitted) +- dedupe: none — checked against 147 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283 +- disposition: filed #1309 +The refusal the sentence means is the maxLimit guard at crates/nostream-relay/src/handlers/subscribe.rs:612-620, whose text is line 620; point the citation there or drop it. This is the recon finding R10/AC12 requires a block for. + +### F2 the LMDB direction note cites a line inside count_matches' doc comment +- lens: code +- where: `crates/nostream-storage/src/lib.rs:88` +- severity: low — a reader checking when LMDB walks newest-first is sent to a count-only comment and cannot verify the claim +- evidence: `grep -n 'lmdb/events.rs:1166' crates/nostream-storage/src/lib.rs` → 88:/// (lmdb/events.rs:1166) — so a caller that wants the first rows in time order, rather than (backticks omitted) +- dedupe: none — checked against 147 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283 +- disposition: filed #1310 +The decision is crates/nostream-storage/src/lmdb/events.rs:1403 (let descending = filter.limit.is_some()); line 1166 is inside count_matches' doc ("a count has no page to stop at"), a different function. + +### F3 the Postgres prefix arm interpolates an unescaped client prefix into LIKE +- lens: code +- where: `crates/nostream-storage/src/postgres/sql.rs:358` +- severity: medium — the two backends answer a geohash-prefix filter differently, and a COUNT counts rows no matcher accepts +- evidence: `grep -n 'LIKE {prefix_slot}' crates/nostream-storage/src/postgres/sql.rs` → 358: parts.push(format!("event_tags.tag_value LIKE {prefix_slot}")); (the Postgres arm cannot run here: no PARITY_ADMIN_URL) +- dedupe: none — checked against 147 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283 +- disposition: filed #1311 +The bound value is built one line above as format!("{prefix}%"), so a criterion a_b* (prefix a_b) becomes LIKE 'a_b%', where _ matches any character: Postgres over-matches, while LMDB compares the literal prefix (lmdb/events.rs:2011 value.starts_with(prefix)) and Filter::matches does the same. Escape %, _ and the escape character in the bound value, or compare left(tag_value, N) = prefix. The capture's SQL shares the over-match, so this is the backend divergence rather than a port regression; #1246's clause-by-clause verification row does not name it. + +### F4 is_vanished takes the single LMDB writer, and commits, on every EVENT +- lens: code +- where: `crates/nostream-storage/src/lmdb/mod.rs:886` +- severity: medium — every event from a non-relay pubkey serialises all writers behind a transaction that usually writes nothing +- evidence: `grep -n 'self.write(move |txn, databases| users::is_vanished' crates/nostream-storage/src/lmdb/mod.rs` → 886: self.write(move |txn, databases| users::is_vanished(txn, databases, &pubkey, now)) +- dedupe: none — checked against 147 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283 +- disposition: filed #1312 +users::is_vanished returns the stored flag at lmdb/users.rs:113 without writing, but write (lmdb/mod.rs:470-485) opens an RwTxn and commits it, and LMDB admits one writer at a time; the relay asks per event at crates/nostream-relay/src/handlers/event.rs:478. The Postgres arm reads on master and takes a write only when hydrating (postgres/repository.rs:217-226). Read with find_by_pubkey and take write only on the hydration branch. + +### F5 the storage layer's wall-clock reads sit outside the Clock seam +- lens: code +- where: `crates/nostream-storage/src/lmdb/mod.rs:522` +- severity: medium — expiry, retention and first_seen are decided against a clock no TestClock can move, so the determinism seam core defines does not reach storage +- evidence: `awk 'FNR==1{t=0} /^mod tests/{t=1} /Utc::now\(\)/{if(!t)n++} END{print n+0}' crates/nostream-storage/src/lmdb/mod.rs` → 36 +- dedupe: existing #1106 +- disposition: linked #1106 +The storage crate has no Clock import; its Utc::now() reads outside test modules number 60 at this head (36 here, 24 across seven postgres files), which is the whole of the issue's "60" now that lmdb/mod.rs has one more than the issue's 35; the relay's handler and loop code read none, and its only 9 are in the shipped test-support module relay/testing.rs. #1106 carries the mechanism and the services sites; recon.md:285-289 asks the lens to say which count it measured, and this is that measurement at this head. + +### F6 the EOSE histogram sample is taken before the sink can refuse the frame +- lens: code +- where: `crates/nostream-relay/src/handlers/subscribe.rs:542` +- severity: low — a refused EOSE is counted as sent against the HELP text's claim, so the latency series includes frames no client received +- evidence: `grep -n 'observe_eose_millis' crates/nostream-relay/src/handlers/subscribe.rs` → 542: .observe_eose_millis(context.now_ms().saturating_sub(started_ms)); +- dedupe: existing #1283 +- disposition: linked #1283 +The frame is offered at :544, and FrameSink::send (sink.rs:307) returns nothing and drops the frame on a queue-full or budget refusal and when the sender is gone, so the close path over-counts too; the comment at :537-539 claims a refused read records none. #1283 names the mechanism and the two remedies; this adds the exact site, the comment that is now false, and the closed-sender arm. + +### F7 an unavailable event limiter is answered as rate-limited +- lens: code +- where: `crates/nostream-relay/src/handlers/event.rs:101` +- severity: medium — clients are told to slow down for the relay's own outage, so every client backs off at once for a fault on this side +- evidence: `grep -n 'rate-limited: slow down", None' crates/nostream-relay/src/handlers/event.rs` → 101: context.send_ok(event.id, false, "rate-limited: slow down", None); +- dedupe: none — checked against 147 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283 +- disposition: filed #1300 +The capture separates the verdicts and answers error: rate limiter unavailable with no backoff (src/handlers/event-message-handler.ts:136-144, the string at :142), and its comment says why. The six-label vocabulary already maps an error: reason (metrics.rs:510), so the fix is the one string plus the expectation at tests/limits.rs:994, which currently asserts the wrong frame; ADR 0004:44-46 repeats the claim that the capture answers rate-limited, which the capture contradicts. + +### F8 the message limiter keys one bucket per address and drops the message type +- lens: code +- where: `crates/nostream-relay/src/limits.rs:543` +- severity: medium — a REQ burst spends the EVENT budget and vice versa, so mixed traffic is refused where the capture allowed it +- evidence: `grep -n 'let key = format!("{address}:message:{}"' crates/nostream-relay/src/limits.rs` → 543: let key = format!("{address}:message:{}", config.period_ms); +- dedupe: none — checked against 147 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283 +- disposition: filed #1301 +The capture buckets by a closed set of message types and keys ${client}:message:${type}:${period} (src/adapters/web-socket-adapter.ts:59-71 and :354), so EVENT and REQ each have a window; message_backoff (limits.rs:520) takes no type and cannot express it, and tests/limits.rs:694-724 can only ever call message_backoff(address), so the type-free key is the only one it can assert. Derive the type from the raw prefix with the capture's closed set, defaulting to OTHER, and put it in the key. ADR 0004:173 records the one-key-per-address shape as measured, not as a decision against the capture. + +### F9 two public broadcast functions are stubs with no caller in the workspace +- lens: code +- where: `crates/nostream-relay/src/broadcast.rs:16` +- severity: low — a public API that always returns NotImplemented ships, and nothing in the crate calls it +- evidence: `sed -n '16p' crates/nostream-relay/src/broadcast.rs` → pub async fn publish(_message: &BroadcastMessage) -> Result<(), RelayError> { +- dedupe: none — checked against 147 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283 +- disposition: filed #1313 +publish and deduplicate (:16, :25) both return RelayError::NotImplemented; grep -rn 'BroadcastMessage' crates --include=*.rs matches only this file, and lib.rs:33-39 records the module as an unassigned stub whose fan-out job may be re-cut. The in-process fan-out the relay needs is relay.rs's own tokio broadcast channel (:185, :546). Delete the module and re-add it with the job that wires it, rather than ship a public call that can only fail. + +## Lens: architecture + +The architecture lens judged the standing structure of the two crates and the records that claim it: `CLAUDE.md`'s "Crate layout" and "Error model" sections, and ADRs 0003, 0011, 0012, 0013 and 0017, each of which claims one of these seams. It read the import direction from the manifests themselves: `core` ← `config`, `storage`, `relay`, `services`, `scan`; `storage` ← `relay`; `relay` ← `services`, `admin`, `cli`, `mcp`, `nostreamd`; `services` ← `admin`, `cli`, `mcp`, `nostreamd`. No cycle exists in that graph; the single edge pointing up is `services` → `relay`. Six findings: three defects no open issue names, two existing issues this lens measured and adds to, and one recorded contract whose branch is unreachable here. + +- command: `grep -rn 'use nostream_storage' crates/nostream-relay/src --include=*.rs | wc -l` → 15 (every one a repositories, `StorageError` or page-bound import; no handler names a backend) +- command: `grep -rn 'impl EventRepository for' crates --include=*.rs | wc -l` → 10 (two backends, eight doubles; the cost F14 measures) +- command: `grep -rl 'nostream_relay::' crates/nostream-services/src --include=*.rs | wc -l` → 8 (the backwards edge at this head, F13) + +**What this lens could not run.** There is no Rust toolchain on this sandbox's PATH and `scripts/rust.sh` cannot reach a daemon, so no `cargo metadata` or `cargo tree` was possible: every dependency claim below rests on the manifests read directly and on `grep` over the source. Behaviour claims cite the code lens's two crate runs rather than repeating them. + +**Scope.** 16 rows and 1,670 distinct-file lines, all read in full at the cited range. + +path | lines | responsibility | command → output | quoted line +---|---|---|---|--- + +| `crates/nostream-relay/src/lib.rs` | 72 | The relay crate root: its module list, the documented stubs and the TypeScript paths it owns | `grep -n 'pub mod unavailable' crates/nostream-relay/src/lib.rs` → 68:pub mod unavailable; | `pub mod unavailable;` | +| `crates/nostream-relay/src/handlers/mod.rs:32-135` | 104 | The Stores bundle, the From impl that narrows Repositories to six handles, and the shared HandlerContext | `grep -n 'impl From<&nostream_storage::Repositories> for Stores' crates/nostream-relay/src/handlers/mod.rs` → 71:impl From<&nostream_storage::Repositories> for Stores { | `impl From<&nostream_storage::Repositories> for Stores {` | +| `crates/nostream-relay/src/unavailable.rs:1-120` | 120 | Six no-op repository impls the relay ships for a caller that has no storage backend at all | `grep -n 'pub fn stores' crates/nostream-relay/src/unavailable.rs` → 24:pub fn stores() -> Stores { | `pub fn stores() -> Stores {` | +| `crates/nostream-relay/src/testing.rs:1-60` | 60 | The always-compiled in-memory store doubles and the context factory every relay integration test shares | `grep -n 'Test support: in-memory repository doubles' crates/nostream-relay/src/testing.rs` → 1://! Test support: in-memory repository doubles and a context factory. | `//! Test support: in-memory repository doubles and a context factory.` | +| `crates/nostream-relay/src/wot.rs` | 36 | The web-of-trust trait the contact-list and report strategies take, supplied by the composition root | `grep -n 'pub trait WotGraph' crates/nostream-relay/src/wot.rs` → 25:pub trait WotGraph: Send + Sync { | `pub trait WotGraph: Send + Sync {` | +| `crates/nostream-storage/src/lib.rs` | 91 | The storage crate root: the page-bound contract constants and the reading rules a caller must honour | `grep -n 'pub const MAX_PAGE_ROWS' crates/nostream-storage/src/lib.rs` → 79:pub const MAX_PAGE_ROWS: u64 = 5_000; | `pub const MAX_PAGE_ROWS: u64 = 5_000;` | +| `crates/nostream-storage/src/opened.rs` | 67 | The nine repository handles of one opened backend and the over constructor that builds them from one store | `grep -n 'pub fn over' crates/nostream-storage/src/opened.rs` → 35: pub fn over(backend: B) -> Self | ` pub fn over(backend: B) -> Self` | +| `crates/nostream-storage/src/event_store.rs` | 47 | Backend resolution from the settings and the worker environment override the capture carries | `grep -n 'pub fn resolved_backend' crates/nostream-storage/src/event_store.rs` → 29:pub fn resolved_backend( | `pub fn resolved_backend(` | +| `crates/nostream-storage/src/migration.rs:1-175` | 175 | The migration-only seam: nine tables, the row enum, its key bytes and its canonical projection | `grep -n 'pub enum MigratedTable' crates/nostream-storage/src/migration.rs` → 37:pub enum MigratedTable { | `pub enum MigratedTable {` | +| `crates/nostream-storage/src/backend.rs` | 172 | Store-path constants, the data-dir projection and the crate's single audited unsafe LMDB open | `grep -n 'pub fn store_dir' crates/nostream-storage/src/backend.rs` → 31:pub fn store_dir(root: &Path) -> PathBuf { | `pub fn store_dir(root: &Path) -> PathBuf {` | +| `crates/nostream-storage/src/lmdb/mod.rs:1-360` | 360 | The LMDB environment open, its 30 named databases, the rebuild locks and the nine trait impls | `grep -n 'pub const REBUILD_LOCK_FILE' crates/nostream-storage/src/lmdb/mod.rs` → 278:pub const REBUILD_LOCK_FILE: &str = "search-index.lock"; | `pub const REBUILD_LOCK_FILE: &str = "search-index.lock";` | +| `crates/nostream-cli/src/store.rs:1-130` | 130 | The CLI's own backend opener over the settings, the Opened facade and its four repo accessors | `grep -n 'pub async fn open(' crates/nostream-cli/src/store.rs` → 81:pub async fn open( | `pub async fn open(` | +| `crates/nostreamd/src/stores.rs:1-64` | 64 | The daemon's backend opener, the second copy of the CLI match, with the settings gates attached | `grep -n 'pub async fn open' crates/nostreamd/src/stores.rs` → 34:pub async fn open( | `pub async fn open(` | +| `crates/nostream-services/src/unavailable.rs:1-80` | 80 | The services' eight-repository bundle and its no-op doubles for a composition that has no store | `grep -n 'pub struct ServiceStores' crates/nostream-services/src/unavailable.rs` → 27:pub struct ServiceStores { | `pub struct ServiceStores {` | +| `crates/nostream-cli/src/commands/migrate.rs:820-880` | 61 | The migration target's refusals: symlink, owner, non-directory and group-or-other write bits | `grep -n 'fn refuse_unsafe_target_for' crates/nostream-cli/src/commands/migrate.rs` → 824:fn refuse_unsafe_target_for(options: &MigrateOptions, caller: Option) -> Result<(), CliError> { | `fn refuse_unsafe_target_for(options: &MigrateOptions, caller: Option) -> Result<(), CliError> {` | +| `crates/nostream-services/src/services/payments_service.rs:145-175` | 31 | The invoice lifecycle service and the confirm_invoice writes its own doc records as unatomic | `grep -n 'pub async fn confirm_invoice' crates/nostream-services/src/services/payments_service.rs` → 165: pub async fn confirm_invoice(&self, invoice: &Invoice) -> Result<(), ServicesError> { | ` pub async fn confirm_invoice(&self, invoice: &Invoice) -> Result<(), ServicesError> {` | + +**Not read by this lens.** Within the two crates: `postgres/{events,sql,metadata,users,invoices,notifications,rows}.rs` beyond the lines a citation needed, `lmdb/{events,encoding,rows,search,metadata,users,invoices,notifications,migration}.rs` beyond the cited regions, `relay/src/{broadcast,connection,connection_cap,dispatch,error,hidden_content,limits,metrics,nip11,relay_key,relay,sink,transport}.rs`, `relay/src/strategies/*` beyond the selection table at `mod.rs:222-231`, and the two crates' unit-test halves. Outside them, `nostream-admin`, `nostream-mcp` and `nostream-scan` (out of this row's scope), and the CLI's command bodies other than `store.rs` and the two cited ranges. + +**Notes.** The ADRs that claim these seams still describe the code, which is worth recording because the row asked: 0011's "30 named databases" matches the 30 `create_database` calls at `lmdb/mod.rs:148-188`; its 55-byte value header is `ROW_FORMAT_VERSION` plus `EVENT_HEADER_LEN = 54` (`encoding.rs:14-18`); 0012's batch of 1000 is `SEARCH_REINDEX_BATCH` (`search.rs:52`), its stale-marker rule is the comparison at `lmdb/mod.rs:344`, and its D9 text carries the flock amendment the code implements at `:326-347`; 0013's D1 holds — the only importers of `nostream_storage::migration` are `nostream-cli` and the storage tests — and its D4 has one implementation, `MigrationRow::canonical` (`migration.rs:149`), which the CLI's `RowSum::add` hashes at `migrate.rs:465-472`. + +Four shapes now describe one opened store: `Repositories` (nine public fields), the relay's `Stores` (six, `handlers/mod.rs:62-69`), the services' `ServiceStores` (eight, `unavailable.rs:27-38`) and the CLI's `Opened` (four accessors over `Repositories`, `store.rs:25-49`). Each bundle is a hand-written `From<&Repositories>` and each has its own set of `Unavailable*` types. ADR 0017 D3 records the second bundle as the tree's existing answer and accepts its cost, so the bundles are not a finding — but `Opened` post-dates that ADR and is what makes F10's second opener attractive, so it belongs to that fix. + +`Databases::create` and `Databases::open` (`lmdb/mod.rs:145-232`) restate the same 30 names in the same order around one struct; a new database is added in three places and a name typo between the two lists fails only when a store is reopened (`MissingDatabase`). ADR 0011 records the hand-maintained count as the price it accepted, so this is the price, not a defect. + +`LmdbBackend::env()` (`lmdb/mod.rs:439`, "for an operator's tooling") hands out the raw `heed::Env`, which would let any crate bypass the nine traits; measured, only tests call it (`grep -rn '\.env()' crates` → `cli/tests/migrate_cli.rs`, `storage/tests/*`), so the accessor is wider than its use rather than a hole in the seam. The relay imports only `nostream_storage::{repositories, StorageError, MAX_PAGE_ROWS, DEFAULT_PAGE_ROWS}`: no handler reaches a backend arm, and the LMDB query planner staying backend-private in `lmdb/events.rs` beside Postgres' `sql.rs` is the right layer for it. + +### F10 two binaries open the same store with two copies of the same match, and one drops the settings +- lens: architecture +- where: `crates/nostream-cli/src/store.rs:96` +- severity: medium — an operator's count and the wire's count of one store disagree whenever NIP-56 is on, and no file says which opener is the intended one +- evidence: `sed -n '96p' crates/nostream-cli/src/store.rs` → Ok(Opened(Repositories::over(store))) +- dedupe: none — checked against 149 open issues (gh issue list --state open --limit 400 --json number --jq length, 149 at this head where recon measured 147) and the 31 at recon.md:253-283 +- disposition: filed #1302 +`crates/nostreamd/src/stores.rs:44-62` and `crates/nostream-cli/src/store.rs:86-109` are the same `match EventStoreBackend` over the same two constructors, ending in the same `Repositories::over(store)`, and each binary maps the error into its own type. They have already drifted in two measurable ways. First, the daemon attaches the settings gates `.with_settings(Arc::clone(settings))` at `nostreamd/src/stores.rs:53` and `:60`; the CLI's arms do not, so `Opened`'s backend answers `LmdbBackend::gates()` with `self.settings == None` and gets `Gates::default()` — `lmdb/mod.rs:443-446` states that as the rule ("Absent settings mean both features are off"). One consequence is visible in the tree: `nostream-cli info`'s `getEventCount` (`crates/nostream-cli/src/commands/info.rs:202`, comment "the live rows") counts through `count_by_filters` at `:211` with `nip56` off, while the relay's COUNT handler issues the same call at `crates/nostream-relay/src/handlers/count.rs:33` on a settings-attached store, so the two numbers answer the same question differently whenever `nip56.hide_actionable_reports` is on; `search_rule()` likewise answers `SubstringTerms` for the CLI where the daemon answers `ToTsvector` (`lmdb/mod.rs:590-597`). Second, the refusals differ: the CLI refuses a Postgres backend whose `DB_URI`/`DB_HOST` is absent (`store.rs:99-103`) while the daemon dials the assembly's default host. Nothing in either file says these differences are intended, and the LMDB data-dir message is duplicated verbatim (`store.rs:90`, `nostreamd/src/stores.rs:47`). The pattern the repository already has is one home per rule: `backend::store_dir` exists so "the openers, the CLI's target check and its messages cannot disagree about where the store is" (`backend.rs:29-33`), and `event_store::configured_backend` exists so the settings-to-backend rule has one home (the CLI calls it at `store.rs:53-55`). Opening is the one part of that contract without a home, and the next caller — a third binary or a test — will copy whichever file it reads first. Put an `open(backend, settings, data_dir, lookup)` beside `Repositories::over` that attaches the settings and refuses a missing data dir, and leave only genuinely CLI-side policy (the `DB_URI || DB_HOST` presence rule) in `store.rs`, named as policy and called before it. + +### F11 the store directory's mode is judged only by the migration tool, never by the opener that serves it +- lens: architecture +- where: `crates/nostream-cli/src/commands/migrate.rs:862` +- severity: medium — a store directory any local user can write is refused by the migration tool and served without a word by the daemon +- evidence: `sed -n '862p' crates/nostream-cli/src/commands/migrate.rs` → if mode & 0o022 != 0 { +- dedupe: none — checked against 149 open issues (gh issue list --state open --limit 400 --json number --jq length, 149 at this head where recon measured 147) and the 31 at recon.md:253-283 +- disposition: filed #1303 +The rule "a store directory is writable by its owner alone" has two halves in two crates. The owner creates one: `LmdbEnv::open` (`crates/nostream-storage/src/backend.rs:96-119`) makes the directory with `DirBuilder::mode(0o700)` and then opens it. The owner never judges an existing one: `create` is a no-op on a directory that is already there, and no code in `nostream-storage` outside its own tests reads a mode (`permissions()` appears once there, at `lmdb/mod.rs:1478`, inside `mod tests`) — the two `0o022` checks in the workspace are both in `migrate.rs`, at `:862` and `:942`. The migration target therefore refuses `/lmdb` at 0755 (`refuse_unsafe_target_for` tests both `options.target` and `store_path(&options.target)`, `migrate.rs:825`), while `nostreamd` and `nostream-cli export`/`clean-db`/`seed` open the same directory through the same `LmdbEnv::open` and serve it. A store restored from a backup, copied with `cp -r`, created by root under `umask 0`, or simply `chmod`ed is thus in a state the tool that copies rows refuses and the process that serves them accepts; the migration tool's own message ("the target must be a directory only its owner can write to") describes an invariant nothing on the serving path checks. This is the "moved rule with no single owner" shape: the invariant belongs to the crate that owns the store and the files in it (`backend.rs` already owns the create half and the `data.mdb` naming), and it is enforced by one client. Move the mode and ownership judgement for an existing store into a `backend::verify_store_dir` called from `LmdbEnv::open` before `open_with`, so both binaries and the migration target ask the same question; the CLI keeps its ancestry walk and directory pin, which are about the copy's destination and the TOCTOU window rather than the store. +The security lens measured the same rule from the opener side and its block is F21: a pre-existing `777 d` lmdb directory opens and stays 0777 (measured on `/tmp/045-store-loose`), and a symlinked `lmdb` is followed rather than refused (measured on `/tmp/045-store-sym2`, whose data lands in `/tmp/045-real2`), while `refuse_unsafe_target_for` refuses both shapes at `crates/nostream-cli/src/commands/migrate.rs:824-870`. The finding's own citation is the refusal that does the judging; the opener that does not is `crates/nostream-storage/src/backend.rs:103-110`, whose `DirBuilder::create` leaves an existing component's mode alone. + +### F12 ADR 0003's serializable transaction has no production caller, and the code points at a closed issue +- lens: architecture +- where: `crates/nostream-services/src/services/payments_service.rs:164` +- severity: medium — the atomic invoice path ADR 0003 records has no caller and the only issue tracking the gap is closed, so nothing tracks it +- evidence: `grep -n '#1206' crates/nostream-services/src/services/payments_service.rs` → 164: /// cross-repository transaction on the seam is what would close this (#1206). +- dedupe: none — checked against 149 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283 +- disposition: filed #1304 +ADR 0003 section "Transactions" records `PostgresTransaction` as implementing "exactly `UserRepository`, `InvoiceRepository` and `NotificationOutboxRepository` — the three the payments service spans". At this head the payments service spans nothing: `confirm_invoice` makes three separate `ServiceStores` calls and its own doc says so (`payments_service.rs:158-164`), and the only caller of `PostgresBackend::begin` in the tree is `crates/nostream-storage/tests/parity.rs:107`. The machinery is otherwise real — `begin` at `postgres/mod.rs:158`, three trait impls at `postgres/repository.rs:477`, `:545` and `:606`, a re-export at `storage/src/lib.rs:55` — so a public transaction type with a serializable isolation guarantee is maintained, compiled into every consumer of the crate, and exercised by no production path, for a consumer that does not exist. The comment that does name the gap points at #1206, which is closed; its acceptance ("the payments write path either gets an LMDB transaction equivalent or refuses with a typed error naming the backend") shipped neither, so a maintainer reading ADR 0003 believes the atomic path exists, triage reading the comment believes it is tracked, and it is tracked nowhere. The seam decision that produced this is ADR 0003's own "The seam has no transaction type (D3)" in ADR 0011: the LMDB backend cannot carry one, so `begin` offers a guarantee only one backend can keep. Either give the seam the transaction ADR 0011 D3 says it lacks and wire `confirm_invoice` onto it, or delete `begin`/`PostgresTransaction` and amend ADR 0003's Transactions paragraph and the comment to name an open issue; leaving both is the second way to do one thing that neither record admits. +The only tracker for that gap was #1206, which is CLOSED (gh issue view 1206 --json state → CLOSED); a closed issue is not a twin, so the defect is filed under a new number rather than linked. + +### F13 the backwards edge reaches further than #1207 measures, and one site is the services' fallback store bundle +- lens: architecture +- where: `crates/nostream-services/src/unavailable.rs:72` +- severity: medium — every fix to #1207 must also move a storage double out of the relay, and services cannot build its no-store bundle without the relay crate +- evidence: `sed -n '72p' crates/nostream-services/src/unavailable.rs` → reports: Arc::new(nostream_relay::unavailable::UnavailableReportRepository), +- dedupe: existing #1207 +- disposition: linked #1207 +#1207 measures the edge at `crates/nostream-services/Cargo.toml:13` and names four things it exists for: `WotGraph`, `RelayKeySource`, a relay event-deletion strategy and a transport helper. At this head the edge is eight files in `crates/nostream-services/src` and one of the sites is not vocabulary: the services' fallback bundle, whose own doc calls it "the doubles for a caller with no storage backend", is built partly from the relay's no-op implementation (`unavailable.rs:61-74`). So the crate that must work with no store at all cannot be built without the relay; `nostream_relay::unavailable` is a *storage* answer that lives in the protocol crate, which is F5's subject seen from the other side. A second site is test support: `nostream-services/src/testing.rs:40` takes `nostream_relay::testing::settings()`, and `:1931` takes `nostream_relay::testing::InMemoryReportRepository`. ADR 0017 D3 leans on the edge by name — "unavailable::stores() reuses nostream_relay's `UnavailableReportRepository` (the dependency already exists)" — so closing #1207 requires amending D3 and moving that double with `WotGraph` and `RelayKeySource`, not only the four things the issue lists. The direction the repository already uses for shared vocabulary is `nostream-core` (both crates depend on it and on nothing above it), which is what #1207 asks for; the new fact is that `unavailable`'s report double is part of the move, and that it is production code rather than a test. + +### F14 the test fakes are not only public, they are the seam's eighth and ninth implementations +- lens: architecture +- where: `crates/nostream-relay/src/lib.rs:66` +- severity: low — each new EventRepository method is ten bodies, eight of them fakes, and one copy is fixed while the other is not +- evidence: `sed -n '66p' crates/nostream-relay/src/lib.rs` → pub mod testing; +- dedupe: existing #1210 +- disposition: linked #1210 +#1210 names both modules and both `InMemoryEventRepository`s and asks for one implementation behind a feature. Two measurements it does not carry, both of which change its acceptance. First, `impl EventRepository for` occurs ten times in the tree: the two backends (`lmdb/mod.rs:518`, `postgres/repository.rs:20`), four shipping doubles (`relay/unavailable.rs:73`, `relay/testing.rs:430`, `services/unavailable.rs:80`, `services/testing.rs:482`) and four test-local ones (`admin/tests/common/mod.rs:481`, `mcp/tests/common/mod.rs:547`, `:703`, `storage/tests/storage.rs:65`). ADR 0017 D1 counted exactly that eight when it added `find_stored`, and calls it out. The cost is per method, not per file: the seam is 20 methods for this trait alone, so a behaviour change is ten bodies with eight of them hand-written and only two under the parity harness. Second, the fakes are cross-consumed today (`services/src/testing.rs:1931`), so "a feature that `[dev-dependencies]` enables" must be enabled from the consuming crate's dev section or the move breaks that target; the crate that would own a single test-support module is the same one #1207 needs for `unavailable`'s report double, so the two issues should land together rather than each introducing a home. + +### F15 the worker branch of backend resolution cannot run +- lens: architecture +- where: `crates/nostream-storage/src/event_store.rs:33` +- severity: low — EVENT_STORE_BACKEND is a documented configuration surface that no process reads as a worker +- evidence: reading — `resolved_backend` at `crates/nostream-storage/src/event_store.rs:29-47` reads `EVENT_STORE_BACKEND` only when `is_worker` is true, and both call sites in the tree pass `false` (`crates/nostreamd/src/main.rs:238`, `crates/nostreamd/src/mcp_stdio.rs:80`), while the constant's doc at `:10-11` says the capture's primary sets it "on every worker it forks" +- dedupe: none — checked against 149 open issues (gh issue list --state open --limit 400 --json number --jq length, 149 at this head where recon measured 147) and the 31 at recon.md:253-283 +- disposition: accepted-risk — the worker model is nostream-services' and a forked worker would pass true; the branch is inert, not wrong, and deleting it would drop the capture's contract +The function is a faithful port and its shape is the right one (settings resolved once, the environment override only for a worker), but nothing in this tree forks a worker process, so the `Some(name) => EventStoreBackend::parse(...)` arm at `:40-45` and its `UnsupportedBackend` refusal are unreachable, and the environment variable the doc advertises has no reader that is a worker. The next reader will assume a `--workers` shape that does not exist, or set the variable and see nothing happen. What makes this acceptable rather than filed: the branch is the capture's contract, it costs one `is_worker` parameter and no behaviour, and the day a worker is forked it is required; a load-time warning when the variable is set and `is_worker` is false would make the silent ignore visible without changing the seam. + +## Lens: security + +The security lens read the four named surfaces at the same tree: the MCP credential and scope gate, the settings loader and its precedence, the PG→LMDB migration tool, and LMDB file permissions. Six findings, all six below as blocks: four standing defects in those surfaces, one contract claim the code does not carry, and one test gap. The store directory's `0700` rule appears twice in this record — F11 in the architecture section, from the migration tool's side, and F21 here, from the opener's — because two lenses measured it from opposite ends and each block names its twin. The relay's transport and subscription bounds were also read as an optional fifth subject and yielded no defect. + +- command: `cargo test -p nostream-mcp --test auth` → `test result: ok. 11 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.08s` +- command: `cargo test -p nostream-config --test load` → `test result: ok. 25 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.02s` +- inversion: none — base and head are the same commit and the branch adds only review records, so no validation, assertion or guard was relaxed, skipped or deleted by it +- not run: the Postgres migration source and `scripts/storage-parity.sh` cannot run here (no database, no Docker daemon); the migration findings are code readings against the LMDB target and say so + +**Scope.** 16 rows over the four surfaces and the two bounds checks. + +path | lines | responsibility | command → output | quoted line +---|---|---|---|--- + +| `crates/nostream-mcp/src/credential.rs` | 359 | The stdio door's token document: where it is read, the mode and size rules, the closed scope set, and the grant each call is decided by | `grep -n 'GROUP_OR_OTHER' crates/nostream-mcp/src/credential.rs` → 44:const GROUP_OR_OTHER: u32 = 0o077; | `const GROUP_OR_OTHER: u32 = 0o077;` | +| `crates/nostream-mcp/src/server.rs:1100-1330` | 231 | The MCP dispatch gate: the enabled predicate, the credential read, the tool table, the write-scope refusal and the router call | `grep -n 'let Some(entry) = served' crates/nostream-mcp/src/server.rs` → 1302: let Some(entry) = served(&self.tool_router, &request.name) else { | `let Some(entry) = served(&self.tool_router, &request.name) else {` | +| `crates/nostream-mcp/tests/auth.rs` | 427 | The eleven cases that pin the credential gate, the scope table and the two delivery forms | `grep -n 'async fn a_revoked_token_refuses_every_tool' crates/nostream-mcp/tests/auth.rs` → 72:async fn a_revoked_token_refuses_every_tool() { | `async fn a_revoked_token_refuses_every_tool() {` | +| `crates/nostreamd/src/mcp_stdio.rs` | 124 | The daemon's MCP mode: flag exclusivity, the retired environment token refusal, and the credential resolved before the pipe is served | `grep -n 'RETIRED_TOKEN_ENV' crates/nostreamd/src/mcp_stdio.rs` → 37:pub const RETIRED_TOKEN_ENV: &str = "NOSTREAM_ADMIN_TOKEN"; | `pub const RETIRED_TOKEN_ENV: &str = "NOSTREAM_ADMIN_TOKEN";` | +| `crates/nostream-config/src/paths.rs` | 41 | Resolves the config base directory from NOSTR_CONFIG_DIR or the working directory, and the five paths under it | `grep -n 'NOSTR_CONFIG_DIR' crates/nostream-config/src/paths.rs` → 22: let base = match std::env::var_os("NOSTR_CONFIG_DIR") { | `let base = match std::env::var_os("NOSTR_CONFIG_DIR") {` | +| `crates/nostream-config/src/load.rs:378-439` | 62 | The loader's decision: merge, validate, fit, and the fall-back-to-shipped-defaults outcome with used_defaults | `grep -n 'settings: defaults_settings' crates/nostream-config/src/load.rs` → 421: settings: defaults_settings, | `settings: defaults_settings,` | +| `crates/nostream-config/tests/load.rs` | 544 | The twenty-five loader cases: precedence, deep merge, the fallback, and the symlink and permission refusals | `grep -n 'fn an_invalid_override_falls_back' crates/nostream-config/tests/load.rs` → 83:fn an_invalid_override_falls_back_to_the_defaults_and_reports_the_issues() { | `fn an_invalid_override_falls_back_to_the_defaults_and_reports_the_issues() {` | +| `resources/default-settings.yaml` | 462 | The shipped defaults the loader merges under every user document, and the event-store backend it names | `grep -n 'maxSubscriptions' resources/default-settings.yaml` → 424: maxSubscriptions: 10 | `maxSubscriptions: 10` | +| `crates/nostream-storage/src/migration.rs` | 260 | The migration seam: the nine tables, the row enum, the canonical projection and the two traits no other caller may use | `grep -n 'pub fn canonical' crates/nostream-storage/src/migration.rs` → 149: pub fn canonical(&self) -> Result, StorageError> { | `pub fn canonical(&self) -> Result, StorageError> {` | +| `crates/nostream-cli/src/commands/migrate.rs:800-980` | 181 | The migration target's refusals: symlink, owner, non-directory, group or other write bits, and the ancestry that could swap it | `grep -n 'if mode & 0o022 != 0' crates/nostream-cli/src/commands/migrate.rs` → 862: if mode & 0o022 != 0 { | `if mode & 0o022 != 0 {` | +| `crates/nostream-cli/src/commands/migrate.rs:150-270` | 121 | The copy loop: per-table resume, the batch write, the checksum fold, the manifest replace and the end-of-table test | `grep -n 'let complete = count < options.batch_size' crates/nostream-cli/src/commands/migrate.rs` → 254: let complete = count < options.batch_size; | `let complete = count < options.batch_size;` | +| `crates/nostream-storage/src/backend.rs` | 172 | The store-path constants and the single LMDB environment constructor, including its directory creation and the crate's one unsafe block | `grep -n 'mode(0o700)' crates/nostream-storage/src/backend.rs` → 105: .mode(0o700) | `.mode(0o700)` | +| `crates/nostream-storage/src/lmdb/mod.rs:270-300` | 31 | The per-path rebuild lock and the cross-process advisory lock file the store opens beside data.mdb | `grep -n 'fn lock_rebuild_file' crates/nostream-storage/src/lmdb/mod.rs` → 282:fn lock_rebuild_file(path: &Path) -> Result { | `fn lock_rebuild_file(path: &Path) -> Result {` | +| `crates/nostream-storage/src/lmdb/mod.rs:1340-1490` | 151 | The LMDB unit tests that pin the rebuild-lock contention and the store directory's 0700 mode | `grep -n 'the_store_directory_is_the_owners_alone' crates/nostream-storage/src/lmdb/mod.rs` → 1470: async fn the_store_directory_is_the_owners_alone() { | `async fn the_store_directory_is_the_owners_alone() {` | +| `crates/nostream-relay/src/transport.rs` | 239 | The websocket sizing policy: the payload limit resolution and the frame and message bounds it configures | `grep -n 'max_message_size(Some(max_payload))' crates/nostream-relay/src/transport.rs` → 67: .max_message_size(Some(max_payload)) | `.max_message_size(Some(max_payload))` | +| `crates/nostream-relay/src/handlers/subscribe.rs:560-630` | 71 | The REQ admission checks: subscription count, filter count, filter values, the limit ceiling and the id length | `grep -n 'Too many subscriptions' crates/nostream-relay/src/handlers/subscribe.rs` → 586: "Too many subscriptions: Number of subscriptions must be less than or equal to {max_subscriptions}" | `"Too many subscriptions: Number of subscriptions must be less than or equal to {max_subscriptions}"` | + +**Notes.** The MCP gate's remaining properties were checked and hold. There is no secret comparison to make constant-time: the token document carries scopes only (`credential.rs:92-97`), and possession of a file the daemon can open is the authentication, so a timing side channel would need a compared value that does not exist. Every call passes `grant()` before `served` (`server.rs:1280-1302`), every served write tool needs `SCOPE_WRITE` (`server.rs:1305-1312`), the table and the router are compared as sets by `only_the_writing_tool_needs_a_scope` (`tests/auth.rs:265-324`), and a refusal is a plain `isError` text, so the only information a caller gains is which of the three applies — the door's documented contract. + +The settings precedence is as documented and as tested: shipped defaults, then `settings.yaml`, else `settings.json`, deep-merged right, validated, fitted, with `used_defaults` on any failure (`load.rs:390-439`). `NOSTR_CONFIG_DIR` selects the base (`paths.rs:22`), and `RELAY_PRIVATE_KEY`, `SECRET` and `WS_DRAIN_TIMEOUT_MS` sit outside the loader (`relay_key.rs:37-38`, `transport.rs:109`); a document cannot set the relay key or the drain timeout, which is the safer direction. A relative or empty `NOSTR_CONFIG_DIR` resolves against the process's working directory, so the daemon's cwd is part of its trust boundary; nothing in the loader refuses a config directory it did not create. + +The migration's refusals are otherwise complete for the shapes they can see: a symlinked target, `lmdb` and `data.mdb`, a foreign owner, a non-directory, group or other write bits on the target and on every ancestor (with the sticky-bit and root-owner exceptions), and a created store at `0o700` (`migrate.rs:808-1100`); `TargetPin` holds the directory inode across the open and `verify` cross-checks device and inode. The manifest is written 0600 through an exclusively created temporary file and synced before and after the rename (`migrate.rs:617-660`), which matters because it records `invite_codes.after`, a bearer code. + +The relay's bounds are enforced before dispatch and agree with NIP-11: `max_payload_size` resolves `network.maxPayloadSize` with a 131072 fallback for absent or zero (`transport.rs:49-58`) and is applied to both `max_message_size` and `max_frame_size` (`transport.rs:60-70`), so a fragmented message cannot outgrow it; `max_subscriptions` and the three filter bounds are checked at REQ admission against the shipped 10/10/2500/256 (`subscribe.rs:575-620`, `resources/default-settings.yaml:423-429`), and an omitted or zero value means unlimited, the capture's semantics. + +The MCP payload-ceiling signal (#1267/#1268) is present at this head: `offset_bound` refuses above 5000 before any store call (`server.rs:1180-1205`). #1268 is still open; that is a tracking state, not a defect. + +### F16 a settings document the loader rejects silently swaps an LMDB deployment onto the default Postgres backend +- lens: security +- where: `crates/nostream-config/src/load.rs:417-424` +- severity: medium — one bad field anywhere in settings.yaml silently swaps an LMDB deployment onto the old Postgres store, so the relay serves and accepts writes into the wrong dataset while the data directory it was pointed at sits unused +- evidence: `sed -n '421p' crates/nostream-config/src/load.rs` → settings: defaults_settings, +- dedupe: none — checked against 149 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283 +- disposition: filed #1305 +`load` merges, validates and fits, and on any issue returns the shipped defaults with used_defaults true (load.rs:417-424; the unreadable-file arm at :395-406 does the same). The relay does not refuse those defaults: `settings_gate` logs the issues and continues unless `--check` (settings_gate.rs:41-45). The shipped `eventStore.backend` is postgres (resources/default-settings.yaml:232), and `resolved_backend(&settings, false)` takes it (nostreamd/src/main.rs:238) into `stores::open`, which dials the DB_* family (nostreamd/src/stores.rs:56-62). The store path is not the hazard the ADR's rule is safe for — `--data-dir` and the fixed 64 GiB map size ([`LMDB_MAP_SIZE`], lmdb/mod.rs:51) do not come from settings — but the backend selection does: a typo on an LMDB deployment lands on Postgres. If DB_URI is set (it is for the migration run), the daemon serves and writes the old database; if it is unset, the start fails. The loader's preference is deliberate (the capture's rule) and the fallback's privileged features are off (admin, payments, NIP-43), so this is a store-selection hazard rather than a privilege one; the fix is either a refusal when the rejected document named a backend the defaults disagree with, or a louder startup signal than one stderr line. + +### F17 search-index.lock is the one in-store file created without a mode +- lens: security +- where: `crates/nostream-storage/src/lmdb/mod.rs:284-288` +- severity: low — search-index.lock is the one in-store file created without a mode, so it is 0644 under umask 022; it holds no data and sits inside the 0700 directory, but the crate's 0600-for-store-files invariant is unenforced and no test asserts it +- evidence: reading — crates/nostream-storage/src/lmdb/mod.rs:284-288 opens search-index.lock through OpenOptions::new().create(true).truncate(false).write(true) with no .mode(), so the file takes the umask; measured 644 under umask 022 beside 700 directories and 600 LMDB files, with the find in the LMDB surface +- dedupe: none — checked against 149 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283 +- disposition: filed #1316 +The chain at lmdb/mod.rs:284-288 is `create(true).truncate(false).write(true).open(&lock_path)` with no `.mode`, so the file takes the umask; measured `644 f …/lmdb/search-index.lock` beside `700 d` directories and `600 f` LMDB files on a fresh store. Nothing is readable today because the file is empty of data and its parent is 0700, and the file is a lock, not a credential; the defect is that the crate's rule ("the store directory holds the whole dataset, so it is the owner's alone", lmdb/mod.rs:1462-1470) is a create-time comment with no test on any file mode (`grep -rn 0o600 crates/nostream-storage/src` finds nothing in the crate's src). One `.mode(0o600)` on the chain plus an assertion in `the_store_directory_is_the_owners_alone` closes it. Open #1187 is the same class on a different file (the admin audit log, created 0644); it does not name this site, so this finding is not linked to it, but a fix may cite it as the pattern. + +### F18 the migration's copy and verify loops have no executing test +- lens: security +- where: `crates/nostream-cli/src/commands/migrate.rs:153` +- severity: low — the copy and verify loops have no executing test: migrate_with and verify_with are driven by nothing that runs here and the Postgres replay target is ignored, so a cursor or checksum regression reaches a cutover unmeasured +- evidence: `grep -n 'pub async fn migrate_with' crates/nostream-cli/src/commands/migrate.rs` → 153:pub async fn migrate_with( +- dedupe: none — checked against 149 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283 +- disposition: filed #1314 +The fourteen in-file tests cover the target refusals, the pin and the checksum arithmetic (migrate.rs:1245-1700); none drives `migrate_with` or `verify_with`. The one test that replays a batch and folds the checksum is `crates/nostream-storage/tests/migration_pg.rs`, which is `#[ignore]`d and needs PARITY_ADMIN_URL, so it runs in CI's storage job and nowhere a CLI change is developed. Resumability is therefore proven by construction and by a comment (the batch commits first, the manifest is replaced second, every write is a put of the source's key and value), not by a case that kills a run mid-table and resumes it. The security relevance is the cutover: a cursor that skips a batch or a checksum that folds the same row twice is exactly the class the manifest exists to catch, and no test that runs here would fail. #1176 is a different test (the pin swap), so this is filed rather than linked. + +### F19 the verify pass proves the store matches the manifest, not the source +- lens: security +- where: `crates/nostream-cli/src/commands/migrate.rs:254` +- severity: medium — a clean verify proves the store matches the manifest the copy itself wrote, not the source, so a copy that lost the source's tail (a short keyset page) verifies clean and an operator reads it as proof the migration is complete +- evidence: `grep -n 'let complete = count < options.batch_size' crates/nostream-cli/src/commands/migrate.rs` → 254: let complete = count < options.batch_size; +- dedupe: none — checked against 149 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283 +- disposition: filed #1306 +The manifest's rows and checksum are folded from the same batches the store receives (migrate.rs:236-258), and `verify_with` reads only the target (migrate.rs:294-350). A store truncated after the copy fails (row count or checksum), and a store replaced beside the manifest is refused up front (the `held.is_empty()` probe at migrate.rs:183-201). What no check covers is a source read that ends a table early: the table is marked complete on `count < batch_size` (the trait's own end marker, migration.rs:228), so a short page is indistinguishable from an end of table, and the manifest records the short total as the complete one. ADR 0013 D4 says "any added, removed or altered row moves it" and calls it a completeness check; that is true of the target against the manifest and false of the source against the target, and an operator reading "Verified 9 tables, N rows" can reasonably take it as the stronger claim at a cutover. The fix is either a source-side count per table (forbidden by D12's nine reads, so D4 needs the limit stated) or a manifest field recording that verification is self-consistent, not source-complete. + +### F20 the token document's mode check does not compare the file's owner to the daemon +- lens: security +- where: `crates/nostream-mcp/src/credential.rs:273-292` +- severity: low — the token document's mode check never compares its owner to the daemon's euid; a root-run door accepts another user's 0600 document and that owner can widen it to write, though only a root-run door with a foreign-owned path is exposed +- evidence: `grep -n 'if mode & GROUP_OR_OTHER != 0' crates/nostream-mcp/src/credential.rs` → 278: if mode & GROUP_OR_OTHER != 0 { +- dedupe: none — checked against 149 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283 +- disposition: filed #1315 +`checked` judges type, permission bits and size only (credential.rs:273-292); the refusal text claims "no one but its owner can read or rewrite it", but the owner it names is never compared to the process. The file form re-reads the document on every call, so this is a live grant: an owner other than the daemon's euid can rewrite `{"scopes":["write"]}` between a read call and a write call. The exposure needs a root-run `--mcp-stdio` pointed at a file another user owns (a non-root daemon cannot open a foreign 0600 file at all, which is the fail-closed half), so it is low, not high. The code comment calls this a shortcut that "needs a dependency this crate was not given" (credential.rs:218-221); that reason is not true at the workspace level — the CLI's migration target reads the same fact from `/proc/self/status` with no dependency (migrate.rs:817 `effective_uid`) and refuses a target owned by another uid (migrate.rs:844-853). Reuse that helper or move it to a shared crate, and add a case beside `a_group_readable_descriptor_refuses_to_start` in tests/auth.rs. + +### F21 the store's `0700` directory rule is create-time only, and a symlinked `lmdb` directory is followed +- lens: security +- where: `crates/nostream-storage/src/backend.rs:103-110` +- severity: medium — the 0700 rule is enforced only on a directory the open creates, so a pre-existing group- or world-writable lmdb directory is opened as-is and a symlinked one is followed, letting a local user who can write the data root replace or redirect the environment the daemon maps +- evidence: `grep -n 'create(&path)' crates/nostream-storage/src/backend.rs` → 106: .create(&path) +- dedupe: none — checked against 182 open issues (`gh issue list --state open --limit 400 --json number --jq length` → 182) and recon.md's 31-issue table; #1303 is this row's own filing for the same rule, recorded from the migration tool's side as F11, so it is a twin rather than a pre-existing issue +- disposition: filed #1303 + +Same defect as F11, which records the migration tool's side of it. `DirBuilder::create` with mode `0o700` creates missing components and leaves an existing `lmdb` component untouched: measured with the bench example under umask 0022, a fresh store is `700 d /tmp/045-store-fresh`, `700 d /tmp/045-store-fresh/lmdb`, `600 f …/data.mdb`, `600 f …/lock.mdb`; the same open against a pre-created `777 d /tmp/045-store-loose/lmdb` exits 0 and the directory stays 0777; and an `lmdb` that is a symlink is followed, with the store's files created under the link's target (`/tmp/045-store-sym2` → `/tmp/045-real2`). `refuse_unsafe_target_for` refuses both shapes at `crates/nostream-cli/src/commands/migrate.rs:824-870`, so the two openers of one directory disagree. Change: judge the mode and the link of an existing `lmdb` in `LmdbEnv::open` and refuse rather than adopt a directory another user can rewrite. + +## Lens: performance + +The performance lens read the relay's frame path and the storage layer's read and write paths at the same tree. Nothing in the row changes a source file, so every pair the lens compares is the same file against itself: the "before" column is `git show 8488bf13:` and the "after" column is the worktree's copy, byte-identical. Each line below therefore states the standing shape and the highest hand-counted McCabe figure among the functions the lens read, and says how it was settled. No judge tool is in the lens's tool list, so every moderate band is settled by reading, and that is stated. Three findings: the per-row rebuild of the NIP-42 read guard, the per-candidate rebuild of the search verdict's structures, and the fan-out serialisation #1211 already names, linked with the per-frame measurement it does not carry. + +- command: `cargo test -p nostream-relay --all-features` → 320 passed, 0 failed (cited from the code lens; not re-run by this lens, per the round's one-suite rule) +- command: `grep -c 'shortcut:' crates/nostream-storage/src/lmdb/events.rs` → 8 (the tree's own list of shapes it declines to optimise; every planner line below was read against it) +- inversion: none — base and head are the same commit, so nothing was relaxed to make a cost appear; the two new findings are measured through the public types the code uses and the third reproduces an already-open issue's mechanism + +**Complexity.** `transport.rs` — O(1) framing work per message with one copy of the payload in `classify`, complexity 7 · `sink.rs` — O(L) in frame bytes per send, one serde pass per frame, complexity 12 in `send` · `relay.rs` — O(S × K) serde passes per broadcast event in `dispatch_live` · `handlers/subscribe.rs` — O(R) per REQ in delivered rows, each row paying a guard build, a filter re-match and a clock read · `handlers/mod.rs` — `read_authorization_guard` is O(a) in the socket's authenticated pubkeys per call, and the stored read calls it per row · `connection.rs` — O(K log K) per event per socket in `matching_subscription_ids` · `metrics.rs` — O(log d) under one process-wide mutex per received event, d bounded at 1024 · `handlers/event.rs` — a fixed number of storage round trips and one limiter pass per EVENT · `lmdb/events.rs` — a page is O(keys walked × log L) with L the page limit, and stops early on the two ordered index shapes; a count is O(keys in the range) with no page to stop at · `lmdb/search.rs` — a searched read is O(P × T + P × V) in P postings of the first term, T the terms intersected and V the per-row body verdict · `lmdb/encoding.rs` — O(C log C) per filter · `lmdb/mod.rs` — one `spawn_blocking` and one write transaction per repository call · `event_store.rs` — O(1) at start-up. + +**Scope.** fourteen files in fifteen ranges, about 5,000 lines. + +path | lines | responsibility | command → output | quoted line +---|---|---|---|--- + +| `crates/nostream-relay/src/transport.rs` | 239 | The websocket handshake, the payload and frame size limit, the close codes and the inbound message classification | `grep -n 'pub fn classify' crates/nostream-relay/src/transport.rs` → 165:pub fn classify(message: Message) -> Inbound { | `Message::Text(text) => Inbound::Text(text.as_str().to_owned()),` | +| `crates/nostream-relay/src/sink.rs:1-460` | 460 | The per-socket outbound queue, its byte bound, the admission arithmetic and the one encoder call every frame passes | `grep -n 'pub fn send(&self' crates/nostream-relay/src/sink.rs` → 307: pub fn send(&self, message: &RelayMessage) { | `let text = message.to_text();` | +| `crates/nostream-relay/src/relay.rs:400-796` | 397 | The per-socket loop, the inbound message dispatch and the live event fan-out over a socket's subscriptions | `grep -n 'fn dispatch_live' crates/nostream-relay/src/relay.rs` → 705: fn dispatch_live(&self, context: &HandlerContext, event: &Arc) { | `for subscription_id in context.connection.matching_subscription_ids(event) {` | +| `crates/nostream-relay/src/handlers/subscribe.rs:255-620` | 366 | The REQ read: the probe, the storage stream, the per-row admission checks, the eight-variable completeness rule and EOSE | `grep -n 'fn fetch_and_send' crates/nostream-relay/src/handlers/subscribe.rs` → 255:async fn fetch_and_send( | `if !context.read_authorization_guard().allows(&event) {` | +| `crates/nostream-relay/src/handlers/mod.rs` | 308 | The shared handler context, the five handlers' entry points and the per-call construction of the read-authorisation guard | `grep -n 'pub fn read_authorization_guard' crates/nostream-relay/src/handlers/mod.rs` → 146: pub fn read_authorization_guard(&self) -> ReadGuard { | `authenticated: self.authenticated_pubkeys(),` | +| `crates/nostream-relay/src/connection.rs:200-407` | 208 | The per-socket subscription table, its matching query and the in-flight read table the drains and CLOSEs share | `grep -n 'pub fn matching_subscription_ids' crates/nostream-relay/src/connection.rs` → 213: pub fn matching_subscription_ids(&self, event: &Event) -> Vec { | `matches.sort();` | +| `crates/nostream-relay/src/metrics.rs:1-330` | 330 | The process-wide counters: the per-kind receive map, the verdict atomics and the EOSE histogram | `grep -n 'pub fn event_received' crates/nostream-relay/src/metrics.rs` → 205: pub fn event_received(&self, kind: u64) { | `events_received: Mutex>,` | +| `crates/nostream-relay/src/handlers/event.rs:380-520` | 141 | The EVENT handler's admission gates: the vanish read, the NIP-42 write check and the user-admission read | `grep -n 'fn is_blocked_by_request_to_vanish' crates/nostream-relay/src/handlers/event.rs` → 465:async fn is_blocked_by_request_to_vanish( | `match context.stores.users.is_vanished(&event.pubkey).await {` | +| `crates/nostream-storage/src/lmdb/events.rs:46-300` | 255 | The LMDB event writes: the existence check, the row plus every index entry, the replaceable pointer and the migration writer | `grep -n 'fn write_event' crates/nostream-storage/src/lmdb/events.rs` → 221:fn write_event( | `let stored = EventRecord {` | +| `crates/nostream-storage/src/lmdb/events.rs:940-2000` | 1061 | The query planner, the bounded page and its heap, the count walk, the tag and author range builders and the matcher | `grep -n 'fn page_limit' crates/nostream-storage/src/lmdb/events.rs` → 1342:fn page_limit(filter: &Filter) -> usize { | `let mut union = Vec::new();` | +| `crates/nostream-storage/src/lmdb/events.rs:2050-2470` | 421 | The two storage streams: the page's value batches and the reconciler's resumable key batches, one read transaction per poll | `grep -n 'fn scan_batch' crates/nostream-storage/src/lmdb/events.rs` → 2337:fn scan_batch( | `let mut items = Vec::new();` | +| `crates/nostream-storage/src/lmdb/search.rs:137-470` | 334 | The NIP-50 tokeniser, the per-body rank, the posting walk that intersects the terms and the ranked page | `grep -n 'pub(crate) fn verdict' crates/nostream-storage/src/lmdb/search.rs` → 189:pub(crate) fn verdict(content: &str, terms: &[String]) -> Option { | `let wanted: HashMap<&str, usize> = terms` | +| `crates/nostream-storage/src/lmdb/encoding.rs:415-560` | 146 | The key builders the planner hands to LMDB: hex and tag ranges, the range-disjointness pass and the resume bound | `grep -n 'pub(crate) fn tag_ranges' crates/nostream-storage/src/lmdb/encoding.rs` → 523:pub(crate) fn tag_ranges<'a>(name: &str, criteria: &'a [String]) -> Vec> { | `pub(crate) fn tag_ranges<'a>(name: &str, criteria: &'a [String]) -> Vec> {` | +| `crates/nostream-storage/src/lmdb/mod.rs:380-700` | 321 | The environment's read and write transaction helpers on the blocking pool, the gates and the two event-read entry points | `grep -n 'pub(crate) async fn write' crates/nostream-storage/src/lmdb/mod.rs` → 470: pub(crate) async fn write(&self, work: F) -> Result | `let mut transaction = env.write_txn()?;` | +| `crates/nostream-storage/src/event_store.rs` | 47 | Backend resolution from the settings and the worker environment override; it holds no writer and no queue | `grep -n 'pub fn resolved_backend' crates/nostream-storage/src/event_store.rs` → 29:pub fn resolved_backend( | `env::var(EVENT_STORE_BACKEND_ENV).ok()` | + +**Checks.** Every figure below was taken in one process on this host, release profile, three consecutive runs, with the round's other lenses running concurrently; the ratios, not the absolute seconds, are what the findings rest on. + +- Measurement 1 — `Nip42Session::authenticated_pubkeys(now)` on a session holding n pubkeys, 5,000 calls per run: n=1 50-57 ns/call (0.25-0.28 ms per 5,000-row read), n=10 312-325 ns, n=100 2.9-3.1 µs, n=1000 28.4-29.7 µs (142-149 ms per read). +- Measurement 2 — `RelayMessage::to_text` for a 777-byte EVENT frame, 20,000 calls, against a `Vec::clone` of the identical bytes: 532-609 ns/frame versus 18-25 ns/copy, a 22-30× gap. +- Measurement 3 — `search::verdict` on a 685-byte body of 100 tokens with three query terms, 20,000 calls, with a counting global allocator: 6.95-7.37 µs/row and 110.0 allocations/row (1,785 bytes/row) as written; 3.24 µs/row and 3.0 allocations/row for a variant that builds the term map once and borrows the tokens. +- Measurement 4 — `sort_by` over 5,000 `(i64, EventId)` entries with the planner's own comparator: 114-119 µs from unsorted input, 38-40 µs from already-sorted input. +- Measurement 5 — `messages::decode` of a 777-byte frame: 1.9-2.3 µs/frame, the relay's per-EVENT decode cost before any signature check. +- Measurement 6 — `Event::clone` for the same event: 129-132 ns/clone, the unit cost of the storage write path's per-record copies. +- Not measured — end-to-end throughput of any shape. The bench rig was not run: its artifact is a wall-clock throughput per read shape, and with three lenses running at once on this host such a number cannot be compared to anything, so no finding cites one. + +**Not read by this lens.** `relay/src/{dispatch,connection_cap,relay_key,nip11,error,lib,broadcast,testing,unavailable,wot}.rs`, `relay/src/strategies/*`, `metrics.rs` after line 330, `limits.rs` outside 480-620, `subscribe.rs` outside 1-200 and 255-620, `relay.rs` outside 400-796, `connection.rs` outside 1-120 and 200-407, `lmdb/events.rs` outside 46-300, 940-2000 and 2050-2470, `lmdb/{users,metadata,notifications,invoices,rows,migration}.rs`, `lmdb/search.rs` outside 137-470 (the rebuild is unread), and every file of `nostream-postgres`' arms. + +**Notes, not findings.** The storage write path makes two further full `Event` copies per stored event that #1211's count of two does not include: `LmdbBackend::create` clones the borrowed record into the blocking closure (`lmdb/mod.rs:521`) and `events::create` clones the event again to stamp `first_seen` (`lmdb/events.rs:61-70`), about 260 ns per stored event, worth folding into #1211's fix rather than its own issue. `page()` sorts the union a second time after `branch` already returned it sorted (`lmdb/events.rs:1050` against `:1507`); for a single filter the input is already in page order, and the second sort measured 38-40 µs for 5,000 entries against 114-119 µs for the real one, under 0.5 % of a maxLimit REQ — a micro-optimisation, so a note. The inbound frame is copied once and parsed twice before any handler runs (`transport.rs:167`, `messages.rs:383-401`); at 1.9-2.3 µs/frame against the 40-60 µs a Schnorr verification costs, both are the price of reproducing zod's message ordering, which the module doc records as a decided tolerance. `message_backoff` and `event_backoff` build a `String` key per configured window per message (`limits.rs:506`, `:542`, `:606`, `:641`), about ten allocations per EVENT at the shipped rates — below the finding bar. The planner's eight `shortcut:` markers name exactly the walks that cannot stop early, each bounded in memory by `MAX_PAGE_KEYS` and argued against a measurement in ADR 0003 or 0011; the two shapes that matter most at the spec's scale both stop as soon as the page is full, which the crate's own probe tests assert without a wall clock. The `ValuesStream` drain issues one `spawn_blocking` and one read transaction per 256 values (`lmdb/mod.rs:78`, `events.rs:2152`), so a 5,000-row REQ crosses the blocking pool twenty times; ADR 0011:156-160 records that as the price of never pinning a reader's pages while the writer works. + +### F22 the search verdict rebuilds the terms map and one String per body token on every candidate row +- lens: performance +- where: `crates/nostream-storage/src/lmdb/search.rs:193` +- severity: medium — every NIP-50 search pays about 110 allocations and 7 µs per candidate row for structures that are constant for the whole read, so a common term on a large store spends hundreds of milliseconds per request in allocation churn before any ranking happens +- evidence: `grep -n 'let wanted: HashMap' crates/nostream-storage/src/lmdb/search.rs` → `193: let wanted: HashMap<&str, usize> = terms` +- dedupe: none — checked against 154 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283; #1112 is why so many rows reach the verdict (proposals sharing a term's first bytes), not what each call costs +- disposition: filed #1307 +`verdict` (search.rs:189-233) is called once per candidate row from `Matcher::matches` (lmdb/events.rs:1946) inside `search::walk` (search.rs:374), and each call re-derives two things that belong to the read: the `wanted` map at :193, a pure function of `terms`, which is fixed for the whole read and already carried on the `Matcher`; and `tokens(content)` (:137-151), which lowercases the whole body into a fresh `String` and then allocates one `String` per token. Measured (Checks 3): 110.0 allocations and 1,785 bytes per row, 6.95-7.37 µs/row; the same body with the map built once and the tokens borrowed costs 3.24 µs/row and 3.0 allocations. The walk has no early stop — rank order is not key order (search.rs:298-299 says so) — so the row count is the whole posting list of the first term: a 100,000-posting walk is 695-737 ms in this function alone. The change: build the map once in the read (`Matcher` already owns `terms`), and make `tokens` yield borrowed slices over one lowercased buffer, so a row costs one lowercase pass and no per-token allocation. + +### F23 the read-authorisation guard is rebuilt for every delivered row, and the default configuration never consults it +- lens: performance +- where: `crates/nostream-relay/src/handlers/mod.rs:146` +- severity: medium — a REQ's delivery cost grows with the number of AUTHs the same socket has made (0.26 ms per 5,000 rows at one pubkey, 143 ms at a thousand), and with restricted reads off, the shipped default, every row pays two allocations and a session lock for a decision that is a constant true +- evidence: `grep -n 'authenticated: self.authenticated_pubkeys(),' crates/nostream-relay/src/handlers/mod.rs` → `149: authenticated: self.authenticated_pubkeys(),` +- dedupe: none — checked against 154 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283 +- disposition: filed #1308 +`read_authorization_guard` (:146-151) builds a `ReadGuard` — a fresh `Vec` from `restricted_read_kinds` and a fresh `HashSet` from `authenticated_pubkeys` (connection.rs:243-247, which locks the session mutex and walks the `BTreeMap` in `Nip42Session::authenticated_pubkeys`, nip42.rs:205-208) — and the stored read calls it per delivered row at subscribe.rs:422 while the live fan-out calls it per event at relay.rs:706. Nothing in the guard depends on the row: `ReadGuard::allows` (handlers/mod.rs:232-234) is a pure function of the settings' kind list, the socket's authenticated set and the event's kind, and `is_read_authorized` (nip42.rs:290-303) returns `true` before reading the set whenever no restricted kind covers the event's kind — with `nip42.restrictedReads.enabled: false`, the shipped value (resources/default-settings.yaml:94), that is every event. Measured (Checks 1): 50-57 ns per call at one authenticated pubkey, 312-325 ns at ten, 2.9-3.1 µs at a hundred, 28.4-29.7 µs at a thousand — 0.26 to 143 ms per 5,000-row REQ, on top of the same three locks taken per row for the event itself. The set is client-growable: `Nip42Session::authenticate` inserts into `sessions` and `accepted_auth_event_ids` with no cap and, at the shipped `sessionExpirySeconds: 0`, no pruning (nip42.rs:189-196, :230-237), and the message limiter allows 240 AUTHs a minute per address. The change: take the guard's snapshot once per read and refresh it when the session changes (a generation counter bumped by `authenticate`/`clear` is enough, and a per-row atomic load keeps the capture's AUTH-mid-read semantics), and skip building it entirely while no restricted kind is configured. + +### F24 the live fan-out serialises the whole event once per matching subscription +- lens: performance +- where: `crates/nostream-relay/src/sink.rs:316` +- severity: medium — N matching subscribers cost N full JSON serialisations of one event, so fan-out CPU grows linearly with the subscriber count for work that is identical in every frame +- evidence: `grep -n 'let text = message.to_text' crates/nostream-relay/src/sink.rs` → `316: let text = message.to_text();` +- dedupe: existing #1211 +- disposition: linked #1211 +`dispatch_live` (relay.rs:720-727) builds one `RelayMessage::Event` per matching subscription and hands it to `FrameSink::send`, which encodes it at :316 through `RelayMessage::to_text` → `event_frame` (nostream-core/src/messages.rs:297-313). The frames differ only in the subscription id: the event is one `Arc` shared by every frame, so the serde pass over the event's id, pubkey, tags, content and signature is repeated per subscriber — across every socket as well, since each connection task runs the same path on its own copy of the broadcast event. Measured (Checks 2): 532-609 ns to serialise a 777-byte frame against 18-25 ns to copy the same bytes, so a 1,000-subscriber fan-out spends about 0.55 ms serialising one publish where 0.02 ms of copy would do; at the 100 events/s a busy relay sees that is 55 ms/s against 2 ms/s. The change is #1211's: serialise the event body once per publish — the hub's `Arc` is the natural place for a `OnceLock` body — and assemble each frame's prefix around it, so one serde pass serves every subscriber. What the issue does not say, and this measures, is the size of the per-frame cost and that the shared value is already an `Arc` at the fan-out site, so the fix needs no new ownership. +**Notes.** +- The storage write path makes two further full `Event` copies per stored event that #1211's count of two does not include: `LmdbBackend::create` clones the borrowed record to move it into the blocking closure (lmdb/mod.rs:521) and `events::create` clones the event again to stamp `first_seen` (lmdb/events.rs:61-70). Measured at 129-132 ns (Checks 6), so about 260 ns per stored event against a write that costs far more; worth folding into #1211's fix, not worth a finding of its own. +- `page()` sorts the union a second time after `branch` already returned it sorted by `Page::finish` (lmdb/events.rs:1050 against :1507). For a single filter the input is already in page order, and the second sort measured 38-40 µs for 5,000 entries (Checks 4) against 114-119 µs for the real one, i.e. under 0.5 % of a maxLimit REQ. A `filters.len() > 1` guard on the second sort would remove it; micro-optimisation, so it is a Note. +- The inbound frame is copied once and parsed twice before any handler runs: `classify` allocates a `String` for the payload (`transport.rs:167`) though tungstenite's `Message::Text` holds a `Bytes`-backed `Utf8Bytes` that moves for free, and `messages::decode` parses to a `serde_json::Value` and then to the typed event (messages.rs:383-401). Measured: 1.9-2.3 µs/frame for the decode (Checks 5), against the 40-60 µs a Schnorr verification costs, so the double parse is a few percent of the EVENT path and the copy is one memcpy of at most the 131 072-byte payload. Both are the price of reproducing zod's message ordering, which the module doc records as a decided tolerance; noted so a future profiler does not rediscover it. +- `count_matches`'s `already_counted` clones the earlier filter's resolved terms per candidate row (lmdb/events.rs:1150), which the code marks `shortcut:` itself; the cost is one `Vec` per earlier predicate per row, only on a multi-filter COUNT. Correctly parked in the tree's own list. +- `event_received` takes a process-wide `Mutex>` per received event (metrics.rs:205-220). One lock, held for one lookup-and-increment, with the label set capped at 1,024 kinds; at a few thousand events a second it is invisible beside the signature check, and it is the cheap way to keep an unbounded label space bounded. No change wanted. +- `message_backoff` and `event_backoff` build a `String` key per configured window per message (limits.rs:506, :542, :606, :641) and the event whitelist formats `event.pubkey.to_string()` inside its `any` closure (limits.rs:583), so an EVENT costs roughly one allocation and one lock per configured event window plus one per whitelist entry. With the shipped eight-plus event windows that is about ten allocations per EVENT; a precomputed per-window key prefix would remove them. Below the finding bar at the shipped rates, so a Note. +- The planner is the tree's most carefully accounted-for code and this lens found no shape it optimises badly beyond its own `shortcut:` markers: the eight markers in `lmdb/events.rs` name exactly the walks that cannot stop early (a bare author, a `#g` prefix, an id prefix, an author × kind product past `MAX_PAGE_KEYS`), each of which is bounded in memory by `MAX_PAGE_KEYS` and argued against a measurement in ADR 0003 or 0011. The two shapes that matter most at the spec's scale — one author with a kind, and one exact tag value — both stop as soon as the page is full, which the crate's own probe tests (`a_limited_author_page_evaluates_only_the_keys_it_needs`, `a_limited_page_stops_at_the_limit_inside_one_author_and_kind`) assert without a wall clock. +- The `ValuesStream` drain issues one `spawn_blocking` and one read transaction per 256 values (lmdb/mod.rs:78, events.rs:2152), so a 5,000-row REQ crosses the blocking pool twenty times; ADR 0011:156-160 records that as the price of never pinning a reader's pages while the writer works, and 20 round trips is not a finding at any rate this relay has. +What #1211 does not carry: the per-frame measurement (532-609 ns to serialise a 777-byte frame against 18-25 ns to copy the same bytes, so a 1,000-subscriber fan-out spends about 0.55 ms serialising one publish where 0.02 ms of copy would do), the exact site (`sink.rs:316`), and the fact that the frames differ only in the subscription id while the event is one shared `Arc`. + +## Lens: ux + +The ux lens read the operator's two surfaces: the console page and five of its six scripts (3,202 lines), twelve `nostream-admin` files (2,280 lines of routes, controllers and utils), the whole MCP server (1,426) and its stdio mode (124), the migration command (1,700) and its error renderer in `app.rs`, the relay's metrics exposition, and ADRs 0013, 0014 and 0021. No browser is in this definition's tool list, so no route was walked: the flows below were exercised by reading — open the console, read the snapshot, act on a report, run a migration, ask the MCP server a question — and where each dead-ends or misleads is a finding. + +- command: `grep -n 'unavailable_snapshot' crates/nostream-admin/src/utils/metrics.rs` → 53:pub fn unavailable_snapshot(now_ms: u64, health: &HealthSnapshot) -> Value { +- command: `grep -n 'Limits updated' resources/admin/assets/admin-moderation.js` → 148: showSuccess('Limits updated.') +- command: `grep -n 'Migrated {total}' crates/nostream-cli/src/commands/migrate.rs` → 270: writeln!(out, "Migrated {total} rows in {ms} ms").map_err(write_failed)?; + +**Scope.** 25 rows over the console's markup and scripts, the admin controllers that feed them, the MCP server, the migration command and the documents that claim them. A row whose path carries a range is the region the finding rests on; the depth line above names what the lens read whole, and the console page and its main script are the ui lens's rows rather than duplicated here. + +path | lines | responsibility | command → output | quoted line +---|---|---|---|--- + +| `resources/admin/assets/admin-ops.js` | 345 | Worker rows, NIP-05 verifications and the storage-count panel | `grep -n 'const renderStorage' resources/admin/assets/admin-ops.js` → `160: const renderStorage = (counts) => {` | ` const renderStorage = (counts) => {` | +| `resources/admin/assets/admin-moderation.js` | 202 | Moderation quick actions, the 7-day activity tables and the current limits | `grep -n 'Limits updated' resources/admin/assets/admin-moderation.js` → `148: showSuccess('Limits updated.')` | ` showSuccess('Limits updated.')` | +| `resources/admin/assets/admin-trust.js` | 215 | The admin audit log and the diagnostics export/preview | `grep -n 'const loadAuditLog' resources/admin/assets/admin-trust.js` → `101: const loadAuditLog = async () => {` | ` const loadAuditLog = async () => {` | +| `resources/admin/assets/notifications.js:230-290` | 61 | The notification target card: its labels, its inputs and the enabled switch | `sed -n '236p' resources/admin/assets/notifications.js` → urlLabel.textContent = 'Webhook URL' | `urlLabel.textContent = 'Webhook URL'` | +| `crates/nostream-admin/src/routes/mod.rs` | 420 | The 30-route admin table and the mount that fixes the prefix at build time | `grep -n 'pub const ADMIN_ROUTES' crates/nostream-admin/src/routes/mod.rs` → `38:pub const ADMIN_ROUTES: [AdminRoute; 30] = [` | `pub const ADMIN_ROUTES: [AdminRoute; 30] = [` | +| `crates/nostream-admin/src/controllers/get_metrics.rs` | 65 | The SSE handler: one frame immediately, then one per interval | `grep -n 'unavailable_snapshot' crates/nostream-admin/src/controllers/get_metrics.rs` → `25: frame(&crate::utils::metrics::unavailable_snapshot(` | ` frame(&crate::utils::metrics::unavailable_snapshot(` | +| `crates/nostream-admin/src/utils/metrics.rs` | 118 | The snapshot the SSE stream carries | `grep -n 'fn unavailable_snapshot' crates/nostream-admin/src/utils/metrics.rs` → `53:pub fn unavailable_snapshot(now_ms: u64, health: &HealthSnapshot) -> Value {` | `pub fn unavailable_snapshot(now_ms: u64, health: &HealthSnapshot) -> Value {` | +| `crates/nostream-admin/src/utils/health.rs` | 102 | The dependency health the snapshot carries | `grep -n 'redis = DependencyHealth' crates/nostream-admin/src/utils/health.rs` → `69: let redis = DependencyHealth { ok: false };` | ` let redis = DependencyHealth { ok: false };` | +| `crates/nostream-admin/src/utils/workers.rs` | 297 | The worker rows `GET /ops/workers` reports | `grep -n 'worker_type: "relay-monitor"' crates/nostream-admin/src/utils/workers.rs` → `80: worker_type: "relay-monitor".to_owned(),` | ` worker_type: "relay-monitor".to_owned(),` | +| `crates/nostream-admin/src/utils/storage.rs:64-66` | 3 | The storage-count window: the default when the caller sends no bounds, and the reply fields it fills | `sed -n '65p' crates/nostream-admin/src/utils/storage.rs` → let effective_since = since.unwrap_or(effective_until - DEFAULT_WINDOW_SECONDS); | `let effective_since = since.unwrap_or(effective_until - DEFAULT_WINDOW_SECONDS);` | +| `crates/nostream-admin/src/controllers/get_ops_storage_counts.rs` | 96 | The count reply: `since`, `until`, `counts` | `grep -n 'count_by_filters' crates/nostream-admin/src/controllers/get_ops_storage_counts.rs` → `54: let count = events.count_by_filters(std::slice::from_ref(&filter)).await;` | ` let count = events.count_by_filters(std::slice::from_ref(&filter)).await;` | +| `crates/nostream-admin/src/controllers/patch_settings.rs` | 252 | The settings write and the `reload` class it reports | `grep -n 'pub fn reload_behavior' crates/nostream-admin/src/controllers/patch_settings.rs` → `36:pub fn reload_behavior(path: &str) -> &'static str {` | `pub fn reload_behavior(path: &str) -> &'static str {` | +| `crates/nostream-admin/src/controllers/get_moderation_stats.rs` | 115 | The moderation activity summary (empty by D4) | `grep -n 'topPublishingPubkeys' crates/nostream-admin/src/controllers/get_moderation_stats.rs` → `82: "topPublishingPubkeys": [],` | ` "topPublishingPubkeys": [],` | +| `crates/nostream-admin/src/controllers/post_network_health_run.rs` | 80 | The manual probe run and its three refusals | `grep -n 'Probe run produced' crates/nostream-admin/src/controllers/post_network_health_run.rs` → `78: "Probe run produced no results",` | ` "Probe run produced no results",` | +| `crates/nostream-admin/src/controllers/post_login.rs` | 95 | The password check, the session mint and their two failure statuses | `grep -n 'Internal Server Error' crates/nostream-admin/src/controllers/post_login.rs` → `56: "Internal Server Error",` | ` "Internal Server Error",` | +| `crates/nostream-admin/src/utils/moderation.rs` | 471 | Moderation actions: pubkey/IP normalisation and refusal text | `grep -n 'PUBKEY_REQUIRED:' crates/nostream-admin/src/utils/moderation.rs` → `115:const PUBKEY_REQUIRED: &str = "pubkey is required and must be a 64-character hex pubkey or npub";` | `const PUBKEY_REQUIRED: &str = "pubkey is required and must be a 64-character hex pubkey or npub";` | +| `crates/nostream-mcp/src/server.rs:925-945` | 21 | The `reports_action` reply: the unknown-id branch that answers a success-shaped no-op | `sed -n '934p' crates/nostream-mcp/src/server.rs` → return Ok(json!({ "reports": [], "changed": 0 })); | `return Ok(json!({ "reports": [], "changed": 0 }));` | +| `crates/nostream-mcp/src/server.rs:1090-1110` | 21 | The `list_events` reply: the page limit, the truncation flag and the rows it returns | `sed -n '1101p' crates/nostream-mcp/src/server.rs` → let truncated = slots >= page; | `let truncated = slots >= page;` | +| `crates/nostream-mcp/src/server.rs:1370-1390` | 21 | The success envelope every tool result is wrapped in | `sed -n '1382p' crates/nostream-mcp/src/server.rs` → result.structured_content = Some(payload); | `result.structured_content = Some(payload);` | +| `crates/nostreamd/src/mcp_stdio.rs` | 124 | The `--mcp-stdio` mode: credential resolution and the store it opens | `grep -n 'RETIRED_TOKEN_ENV' crates/nostreamd/src/mcp_stdio.rs` → `37:pub const RETIRED_TOKEN_ENV: &str = "NOSTREAM_ADMIN_TOKEN";` | `pub const RETIRED_TOKEN_ENV: &str = "NOSTREAM_ADMIN_TOKEN";` | +| `crates/nostream-cli/src/commands/migrate.rs:265-275` | 11 | The two closing lines the copy prints: the row total and the elapsed time | `sed -n '270p' crates/nostream-cli/src/commands/migrate.rs` → writeln!(out, "Migrated {total} rows in {ms} ms").map_err(write_failed)?; | `writeln!(out, "Migrated {total} rows in {ms} ms").map_err(write_failed)?;` | +| `crates/nostream-relay/src/metrics.rs` | 672 | The process-wide counters the console could read and the exposition names | `grep -n 'CONNECTIONS_ACTIVE' crates/nostream-relay/src/metrics.rs` → `64:const CONNECTIONS_ACTIVE: &str = "nostream_connections_active";` | `const CONNECTIONS_ACTIVE: &str = "nostream_connections_active";` | +| `docs/rewrite/decisions/0014-admin-http-surface.md` | 520 | D2–D5 and D8: what the console was built to show and the hot-reload narrowing | `grep -n 'Applying a hot reload' docs/rewrite/decisions/0014-admin-http-surface.md` → `150:Applying a hot reload to a running subsystem from a PATCH is out of scope: the relay has no` | `Applying a hot reload to a running subsystem from a PATCH is out of scope: the relay has no` | +| `docs/rewrite/decisions/0013-pg-to-lmdb-migration.md` | 297 | The migration's resume, measurement and stopping contract (D5, D8, D9, D10) | `grep -n 'Migrated {total} rows' docs/rewrite/decisions/0013-pg-to-lmdb-migration.md` → `237:Migrated {total} rows in {ms} ms` | `Migrated {total} rows in {ms} ms` | +| `docs/rewrite/decisions/0021-prometheus-metrics.md` | 168 | The scrape endpoint and the counters it serves at this head | `grep -n 'one HTTP surface' docs/rewrite/decisions/0021-prometheus-metrics.md` → `12:The process has one HTTP surface.` | `The process has one HTTP surface.` | +### F25 the console's whole metrics view reports a collection failure the process no longer has + +- lens: ux +- where: `crates/nostream-admin/src/utils/metrics.rs:53-65` +- severity: high — the operator cannot tell a healthy relay from a broken one; the headline tile and every rate read as dead while traffic flows +- evidence: `grep -n 'fn unavailable_snapshot' crates/nostream-admin/src/utils/metrics.rs` → `53:pub fn unavailable_snapshot(now_ms: u64, health: &HealthSnapshot) -> Value {` +- dedupe: none — checked against 154 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283 +- disposition: filed #1317 + +The ui lens reports the same defect as F41, which cites `utils/metrics.rs:56` from the rendered side; each lens keeps its own block so the two measurements stay separate, and this block carries the ux lens's scope-row command rather than its `- evidence:` line, which is the same line print F41 quotes. `unavailable_snapshot` writes `"status": "unavailable"`, seven numeric keys at zero and `prometheus {available:false, error:"Prometheus query returned no data"}`, discarding the `health.status` argument and ignoring the counters the same process now has. The SYS and PROM cards read `[NULL]`, every Throughput and Events number reads `0`, and the banner "`[NULL] Metrics unavailable — Prometheus returned no data`" (`dashboard.js:253`, `:1594-1634`) sits over a relay that is serving. D5's own upgrade trigger ("when the relay grows accepted/rejected counters or a Prometheus endpoint") was met by ADR 0021 at this head, and the daemon already holds the handle (`main.rs:317-321`). + +### F26 the RDS Redis health card is a permanent fault naming a dependency the rewrite deleted + +- lens: ux +- where: `crates/nostream-admin/src/utils/health.rs:66-73` +- severity: medium — a permanent false fault on the first screen; every incident review starts by ruling it out +- evidence: `grep -n 'redis = DependencyHealth' crates/nostream-admin/src/utils/health.rs` → `69: let redis = DependencyHealth { ok: false };` +- dedupe: none — checked against 154 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283 +- disposition: filed #1334 + +The ui lens reports the same line as F42; each lens keeps its block, and this block carries the ux lens's scope-row command rather than the line print F42 quotes. The cache is gone by design (ADR 0010 D2, "No Redis client is added; the cache is embedded"), so `redis` is `{ok:false}` unconditionally and `collect` can never return `ok` because it ANDs the two dependencies. The console's fourth health card, labelled "RDS Redis" (`dashboard.html:100-104`), is painted `[FAULT]` in the palette's strongest error treatment on every frame, and the system card is always `[WARN]` or `[NULL]`. An operator reads a permanent dependency failure they cannot clear and will hunt a Redis that is not part of the deployment. + +### F27 the worker ops panel is generated from the capture's worker model, so it shows rows that are not workers + +- lens: ux +- where: `crates/nostream-admin/src/utils/workers.rs:56-100` +- severity: medium — an operator reading the panel concludes half the workers are dead when they do not exist +- evidence: `sed -n '80p' crates/nostream-admin/src/utils/workers.rs` → ` worker_type: "relay-monitor".to_owned(),` +- dedupe: none — checked against 154 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283 +- disposition: filed #1318 + +One "Client worker N" row is generated per CPU/tokio thread, one "DVM orchestrator N", and "Relay monitor (NIP-66)" whenever `nip66.enabled`. The rewrite forked no client workers (`WORKER_COUNT` selects runtime threads, ADR 0010 D3), only `maintenance` is ever published (`crates/nostreamd/src/admin_http.rs:109-115`), and `crates/nostreamd/src/workers.rs:18` says the relay-monitor worker "is issue #865's and is not registered here" — so the table shows rows that are not workers and, with NIP-66 on, a permanent red "Stale" row nothing can refresh. + +### F28 every settings write outside three prefixes reports hot-reload, and nothing reloads + +- lens: ux +- where: `crates/nostream-admin/src/controllers/patch_settings.rs:34-42` +- severity: high — the operator believes a moderation or limit change is in force while the relay still admits the banned pubkey; the settings view also re-reads and shows the new value, so nothing on the page contradicts the promise +- evidence: `sed -n '41p' crates/nostream-admin/src/controllers/patch_settings.rs` → ` "hot-reload"` +- dedupe: none — checked against 154 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283 +- disposition: filed #1319 + +With `post_moderation_actions.rs:58-60` hard-coding the same three labels: the console says "Settings saved atomically with a backup. Changes will hot reload." (`dashboard.js:1516`) and "Limits updated." (`admin-moderation.js:148`), while the daemon builds `RelayConfig::from_settings` and `RateLimits::new(&settings, …)` once at start (`crates/nostreamd/src/main.rs:243`, `crates/nostream-relay/src/relay.rs:190`) and there is no reload seam — ADR 0014 D8 records it as "reported faithfully rather than acted on". + +### F29 the moderation activity endpoint answers three empty aggregates as if they were measurements + +- lens: ux +- where: `crates/nostream-admin/src/controllers/get_moderation_stats.rs:82-84` +- severity: medium — a false zero on the moderation page sends the operator looking for a quiet window instead of an unmeasured one +- evidence: `sed -n '82p' crates/nostream-admin/src/controllers/get_moderation_stats.rs` → ` "topPublishingPubkeys": [],` +- dedupe: none — checked against 154 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283 +- disposition: filed #1320 + +The endpoint answers `200` with three empty aggregates by D4, and the console renders that as measurement: "No events in window." for both top tables and "No rate-limit hits recorded yet." (`admin-moderation.js:127`, `:94`). An operator investigating spam sees an idle relay, not an unmeasured one; the fix is a marker (`aggregatesAvailable:false`) rendered as "activity aggregation is not collected by this build", or the grouped aggregate itself. + +### F30 the ban form advertises an npub and refuses it, with a message that repeats the advertised form + +- lens: ux +- where: `crates/nostream-admin/src/utils/moderation.rs:114-115` +- severity: high — a moderator pasting the npub they have in hand cannot ban the pubkey, and the error asserts the input was the right shape +- evidence: `sed -n '115p' crates/nostream-admin/src/utils/moderation.rs` → `const PUBKEY_REQUIRED: &str = "pubkey is required and must be a 64-character hex pubkey or npub";` +- dedupe: none — checked against 154 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283 +- disposition: filed #1321 + +The field is labelled "Pubkey or npub" (`dashboard.html:536`, and the client-side guard says "Enter a pubkey or npub to ban", `admin-moderation.js:168`) and the refusal repeats "or npub", but `is_hex_pubkey` accepts 64 lowercase hex characters only and `require_pubkey` (`:229-240`) returns that same npub-inclusive message for an npub. The capture decodes the npub first (`src/utils/admin-moderation.ts:231`, `parseRelayPubkey`); the rewrite has no bech32 decoder. + +### F31 the storage count is silently the last 24 hours, and the console renders it as the store's total + +- lens: ux +- where: `crates/nostream-admin/src/utils/storage.rs:64-66` +- severity: high — an audit answer is off by the store's whole history and nothing on the page says so +- evidence: `sed -n '65p' crates/nostream-admin/src/utils/storage.rs` → ` let effective_since = since.unwrap_or(effective_until - DEFAULT_WINDOW_SECONDS);` +- dedupe: none — checked against 154 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283 +- disposition: filed #1322 +With `since`/`until` absent the count is the last 86,400 s (`DEFAULT_WINDOW_SECONDS`); the reply carries `since`/`until` (`get_ops_storage_counts.rs:88-92`) and the console renders neither — `renderStorage` prints only `kinds` and `count` (`admin-ops.js:160-174`) under a column headed "Count", while the page calls the bounds "optional since/until unix seconds" (`dashboard.html:317`). The ux lens cites this range as `63-66`; line 63 is blank, so this citation starts at its first non-blank line, `64`, and says so here. + +### F32 the network-probes panel's only action fails silently, and its three refusals reach the operator as one string + +- lens: ux +- where: `crates/nostream-admin/src/controllers/post_network_health_run.rs:53-79` +- severity: medium — the panel's one button fails silently forever and the operator cannot tell misconfiguration from an unimplemented feature +- evidence: `sed -n '78p' crates/nostream-admin/src/controllers/post_network_health_run.rs` → ` "Probe run produced no results",` +- dedupe: none — checked against 154 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283 +- disposition: filed #1323 + +A configured, valid run always answers `502 "Probe run produced no results"` because the probe is #865's stub, and the console discards the body and the status, printing only "manual probe failed" (`dashboard.js:757-762`). The three causes the controller already distinguishes — 409 "NIP-66 monitoring is disabled", 400 "No valid probe targets configured" with the invalid list, and the 502 — reach the operator as one string with no next step, and the empty state ("Enable NIP-66 relay monitoring to populate this panel") tells them to enable what may already be on. #1036 covers the missing probe behaviour, not the console's refusal to show the cause. + +### F33 every successful MCP tool call returns its payload only in structuredContent + +- lens: ux +- where: `crates/nostream-mcp/src/server.rs:1374-1385` +- severity: high — for a whole class of MCP clients every answer is blank; the operator's agent cannot act on a success it cannot read +- evidence: `sed -n '1382p' crates/nostream-mcp/src/server.rs` → ` result.structured_content = Some(payload);` +- dedupe: none — checked against 154 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283 +- disposition: filed #1324 + +MCP's own rule for a tool that returns structured content is that it SHOULD also return the serialized JSON in a `TextContent` block, precisely so older clients keep working; a client that reads `content` (every client before structured output existed) sees a successful result with nothing in it. The omission is deliberate and pinned by `a_success_carries_one_copy_of_the_payload` (`crates/nostream-mcp/tests/tool_payloads.rs:653-661`), which asserts `content.is_empty()` — so the fix changes that expectation as well as the envelope. + +### F34 reports_action on an unknown id answers a success-shaped no-op where delete_event names not_found + +- lens: ux +- where: `crates/nostream-mcp/src/server.rs:933-935` +- severity: medium — a triage call that did nothing reads as done, so the report stays actionable and the agent believes it acted +- evidence: `sed -n '934p' crates/nostream-mcp/src/server.rs` → ` return Ok(json!({ "reports": [], "changed": 0 }));` +- dedupe: none — checked against 154 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283 +- disposition: filed #1325 + +An agent that passes the reported event's id (the mistake the description warns about) or a stale or typo'd id gets `{"reports": [], "changed": 0}` with `isError: false`, where the sibling `delete_event` names `outcome: "not_found"`. The two tools answer the same operator question and disagree about how a miss looks. + +### F35 list_events reports truncated without a continuation, so an enumerate request stops at 500 rows + +- lens: ux +- where: `crates/nostream-mcp/src/server.rs:680` +- severity: medium — an "enumerate" request silently stops at 500 rows with no documented next call +- evidence: `sed -n '1101p' crates/nostream-mcp/src/server.rs` → ` let truncated = slots >= page;` +- dedupe: none — checked against 154 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283 +- disposition: filed #1326 + +The reply says `truncated: true` when the page fills but offers no offset, cursor or `since` continuation and never says how to get the rest; rows are oldest first and capped at 500, so an agent asked to enumerate a larger store must invent a `since = last row's created_at` loop from the schema. #1267 is the invoice walk's ceiling, not this read. + +### F36 the migration CLI writes nothing until the last row, so a long copy is indistinguishable from a hang + +- lens: ux +- where: `crates/nostream-cli/src/commands/migrate.rs:212-273` +- severity: medium — the operator cannot tell a slow copy from a stuck one and may kill a run that is working +- evidence: `sed -n '270p' crates/nostream-cli/src/commands/migrate.rs` → ` writeln!(out, "Migrated {total} rows in {ms} ms").map_err(write_failed)?;` +- dedupe: none — checked against 154 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283 +- disposition: filed #1327 + +The first stdout after the loop is "Migrated {total} rows in {ms} ms", and per-batch progress exists only inside `migration-manifest.json`; a resumed run prints only the rows this invocation wrote, as though that were the migration's size. ADR 0013 D8 defines the two closing lines and says nothing about progress. + +### F37 a failed migration does not say a re-run resumes, the one moment the operator needs it + +- lens: ux +- where: `crates/nostream-cli/src/app.rs:840` +- severity: medium — the recovery step exists and is documented everywhere except the moment it is needed +- evidence: `sed -n '840p' crates/nostream-cli/src/app.rs` → ` CliError::Migrate(message) => (vec![format!("Migration failed: {message}")], 1),` +- dedupe: none — checked against 154 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283 +- disposition: filed #1328 + +The message names the table but never the state the operator is left in. The help and ADR 0013 both say a re-run resumes from the manifest, but the failure itself does not, so the operator who just watched it stop does not know a second run continues rather than restarts (or that a fresh `--target` is the only way to start over). + +### F38 the notification target cards' labels are not bound to their inputs + +- lens: ux +- where: `resources/admin/assets/notifications.js:234-283` +- severity: low — a screen-reader or keyboard operator cannot tell the notification fields apart +- evidence: `sed -n '236p' resources/admin/assets/notifications.js` → ` urlLabel.textContent = 'Webhook URL'` +- dedupe: none — checked against 154 open issues (gh issue list --state open --limit 400 --json number) and the 31 at recon.md:253-283 +- disposition: filed #1329 + +Each target card builds its labels as siblings of the inputs with no `for`/`id` binding ("Webhook URL", "Signing secret", "Bot token", "Chat ID"), and the type `