Commit Graph

3578 Commits

Author SHA1 Message Date
Luke Tornquist
65c7d64c94 Require relay schema owner review for migrations and schema (#9708)
## Summary

Make @TheSentinel454, @wpfleger96, @bradseiler, @salman1993 and
@ravarora2 the code owners for the relay database migrations and schema:

- `/migrations/`
- `/schema/`
- `/scripts/reconcile-schema-after-pgschema.sql`
- `/.pgschemaignore`

The `main` ruleset requires code owner review. So any PR that touches
these paths needs an approval from one of these five. Any one of them
can approve. When one of them writes a migration PR, another owner
approves it.

CODEOWNERS uses the last matching line. For these paths, this entry
replaces `@block/buzz-oss-team` as the owner. The ruleset still requires
one approval in total.

What got simpler: nothing. This adds four ownership lines and no code.

### Related issue

N/A. No duplicate found.

### Testing

`GET /repos/block/buzz/codeowners/errors` on this branch returns no
errors. All five users have write access or higher.

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

---------

Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
mobile-v1.5.0-rc.3
2026-11-19 12:36:34 -05:00
Wes
4704fbafb6 fix(relay): resurface a hidden DM when someone else messages it (#9678)
## Summary

A DM hidden with **Hide conversation** (kind 41012) stayed out of the
sidebar for good, even after new messages arrived. The only way back was
New message → same people → Send. This makes the relay clear the hide
when *another* member posts a message (kinds 9 / 40002 / 40008) in the
DM, like Slack does. The author's own hide is kept, so replying from
another device doesn't resurface it.

- `buzz-db` `dm.rs`: `unhide_dm_for_recipients` clears `hidden_at` for
every other active member. `lock_dm_visibility` takes the same advisory
lock that replacing the viewer's kind 30622 snapshot uses, then reads
that viewer's hidden DMs and latest snapshot time.
- `side_effects.rs`: `persist_dm_message` stores the message, clears the
hides and replaces each affected viewer's snapshot in **one
transaction**, then fans out after commit. A snapshot that doesn't land
rejects the message, so the client's resend tries again. When someone
hid the DM, the message takes the DM's membership lock before its
insert, as a removal does, so it can't deadlock against a removal or
reopen. The hide/open path (`publish_dm_visibility_snapshot`) shares the
same lock → read → write seam.
- Used by both message paths: client ingest (`ingest.rs`) and
relay-signed workflow messages (`workflow_sink.rs`, author resolved via
`effective_message_author`).
- `NIP-DV.md`: documents the rule.

**Deploy order:** relay first. The client companion is
block/buzz-app#3889, which rereads visibility from the writer when a
message lands in a hidden DM. Against an older client the row returns on
the next roster refresh.

### Related issue

N/A. None found.

### Testing

- New Postgres test `dm_message_from_someone_else_unhides_it`
(`membership_notice_postgres_tests.rs`): hide → the viewer's own message
keeps it hidden → a peer's message whose snapshot is blocked by a
trigger is rejected, not stored and not delivered → its resend, parked
at fan-out, already shows the DM visible and is delivered once. It is
`#[ignore]` (needs Postgres) and runs in Backend Integration CI. It was
not run locally.
- Pre-push `rust-tests` lane (`just test-unit`) and local clippy pass;
`observability_source` source-policy test updated for the new
transaction seam.
- Reviewed by the Royal Court agents. Their findings (atomicity,
lock-before-read, workflow path) are fixed in follow-up commits.
- Human test pending.

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

---------

Signed-off-by: Wes <wesbillman@users.noreply.github.com>
Co-authored-by: Carl <32a2e2c9d428ee08902cab75d956da2c1d235a22d4766b0dd4138bf6e2e5db1d@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 10:21:17 -07:00
Wes
5f08ed2511 fix(deploy): pin self-host installs to relay 0.3.0 (#9714)
## Summary

- Pin the Compose fallback and example environment to
`ghcr.io/block/buzz:0.3.0`. Document how to opt into rolling `:main`
builds and how to update the image tag before running `./run.sh
upgrade`.
- Set the Helm chart's default relay image to `0.3.0` through
`appVersion` and bump the chart and quickstart to `0.1.12`.
- Add a relay release checklist step to update both deployment defaults
after each stable image is available. The existing chart release
workflow publishes the bumped chart after merge.

### Related work

[#2824](https://github.com/block/buzz/pull/2824) also touches self-host
Compose. This PR covers release tags and upgrade instructions.

### Testing

- Rendered Compose with the example environment, the fallback, and
explicit image overrides. A fresh isolated Compose install reached
readiness with `ghcr.io/block/buzz:0.3.0` and returned `ok` from
`/_liveness`.
- Passed Helm lint and all 85 unit tests. Rendered all four chart
fixtures, verified the default image and an override, and packaged chart
`0.1.12` with app version `0.3.0`.
- The repository-wide `just ci` run passed. It started at `cf357b241`,
and the final commit changes only the Compose upgrade text.

---------

Signed-off-by: Star Lord <b89298dbe87c6b3fd8a425b535d9d161f23c88d555a47925ae0b04dfe02b201e@buzz.block.builderlab.xyz>
Co-authored-by: Star Lord <b89298dbe87c6b3fd8a425b535d9d161f23c88d555a47925ae0b04dfe02b201e@buzz.block.builderlab.xyz>
chart-v0.1.12
2026-11-19 10:09:04 -07:00
klopez4212
83eb59c631 fix(mobile): keep open shared sessions in Solo (#9704)
Sharing a Solo session as View only changes its access to open. Mobile
incorrectly required private access to recognize Solo, moving these
sessions into Channels. Recognize labeled Solo streams independently of
visibility, retaining their existing project placement and
membership/ownership checks.

Apply the same rule to iOS notification classification so reply routing
agrees with Flutter. Add regression coverage for open owned/shared Solo
sessions and exclusion from Channels. This changes presentation only;
access settings remain unchanged.

Validation: mobile-install and mobile-check passed; Solo regressions
passed in the full Flutter run (5,095 passed, 71 skipped, one failure in
community_provider_test.dart: startup and credential replacement discard
orphan snapshots and image caches). All 81 BuzzPushKit tests passed.
Independent agent review completed with its notification-routing finding
fixed.

Device workflow and human testing remain pending. To verify: share a
Solo session as View only, reopen mobile, and confirm it remains in its
Solo project and is absent from Channels. Verify notification replies
return to the same conversation.

Follow-up to #9348.

Pre-push rerun: analysis passed, but the Flutter compiler ran out of
disk space and the stalled test process was interrupted. The hook
subsequently returned success after 27 crypto-package tests passed; that
is not a full Flutter pass. The earlier complete Flutter result above
remains the applicable evidence.

Signed-off-by: kenny lopez <klopez4212@gmail.com>
Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
2026-11-19 16:39:38 +00:00
klopez4212
68d367cf23 fix(mobile): align channel indicators and Duo section menus (#9703)
Align the mobile channel-list indicators to one trailing column. The
unread dot stays at the right, with the temporary clock and mute
indicator to its left when present. Duo's native menus for built-in and
custom sections now place their ellipsis in the same 20-point slot while
preserving the full 44-point tap target and native menu behavior.

Validation: full mobile suite (5,098 passed, 71 skipped), 27 crypto
tests, clean Flutter analysis, native UIKit menu geometry/hit-target
checks, and a successful iOS release build. Installed on iPhone Air and
Duo using existing saved state; inspected the Duo's native section-menu
placement. Regression coverage checks row alignment, clock ordering,
native bridge geometry, and the full menu hit area.

---------

Signed-off-by: kenny lopez <klopez4212@gmail.com>
Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
2026-11-19 16:38:55 +00:00
klopez4212
7d116da335 fix(mobile): allow person mentions in Solo chats (#9705)
## Summary

Mobile Solo rejected a human member mention with “Not sent. Community
changed.” because it checked every recipient for agent ownership.
Explicit mentions now accept current chat members, matching desktop; the
implicit header agent still requires ownership. Fresh membership and
community checks remain in place.

This improves human-only and mixed person/agent sends without changing
default agent selection, nonmember invitation rules, or thread drafts.
It also fixes existing private shared Solo chats.

### Related issue

Separate follow-up to #9704; no dependency on its classification change.
Searched open issues/PRs: #9156 addresses misleading send-error wording
and #9699 addresses mention editing; neither changes this Solo recipient
ownership check.

### Testing

`just mobile-install mobile-check mobile-test` passed (5,122 Flutter
tests, 71 existing skips; 27 crypto package tests), along with `just
file-size-check` and diff checks. Regression coverage drives the actual
composer on iOS and Android and checks explicit-recipient
removal/community-switch boundaries, plus existing implicit-agent
ownership checks. Before the fix, the new composer journey retained the
human-mention draft on both platforms.

Manual check: in an owned shared Solo with a human member, send an
explicit mention of that person, then a mixed person/agent mention. Each
should send and clear its draft. Untagged messages should still use the
selected agent.

Native device/live-relay testing and human confirmation remain pending;
this PR stays draft under AGENTS.md.

Signed-off-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
2026-11-19 14:59:44 +00:00
Wes
8306e38742 fix(mobile): let code scroll under the code block copy button (#9612)
## What changed

The copy button on a message code block reserved a fixed 40px column
beside the horizontal scroller, so every line was clipped about 40px
short of the block's right edge. This was most visible on narrow phones.

The fix matches buzz-app desktop (`Markdown.module.css`,
`.codeActions`):

- The horizontal scroller now spans the whole block.
- The copy button floats in the top-right corner on an opaque chip, so
code scrolled under it never collides with the icon. On an own-message
bubble the chip is the code tint blended over the outgoing fill, so it
matches the block.
- The end padding moves inside the scroll content, so every line end can
still be scrolled clear of the button.
- The language label keeps its right inset, so it never runs under the
button.

## Why nothing gets worse

Same tap target, icon, copy behavior and block insets. The only visual
change is that code now uses the width the gutter used to take. Long
lines in the button's row pass under the opaque chip while scrolled, as
they do on desktop.

## Testing

- `message_content_test.dart` "renders code block with language tag" now
asserts that the scroller spans the block inside its border and that the
copy button overlaps the scroller. Without the production change it
fails (`Expected: 798.0, Actual: 746.0`), and it passes with it.
- Before/after captures were rendered with the real fonts and the mobile
appearance theme at iPhone width, for received and own (Chartreuse)
bubbles, at rest and scrolled to the end. They are in the screenshots
comment.
- Pre-commit and pre-push hooks passed.
- Not yet exercised in the native app on a device.

The iOS "Copy and Delete" screenshot paste issue from the same report is
still being diagnosed and is not in this PR yet.

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

---------

Signed-off-by: Wes <wesbillman@users.noreply.github.com>
Co-authored-by: Carl <32a2e2c9d428ee08902cab75d956da2c1d235a22d4766b0dd4138bf6e2e5db1d@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 07:28:06 -07:00
klopez4212
5bd9d2c5d2 Transcribe Bestie hold recordings into text on device (#9645)
Hold Bestie to record with the waveform and slide-up cancel interaction
from #8665, then release to send an on-device transcript as a normal
text message. Stay on Home with a loader inside Bestie until delivery
succeeds, then open chat. Failures expose Retry/Discard; saved
recordings and signed messages remain recoverable without duplicate
sends. Saved audio is excluded from OS backup. Existing composer voice
notes are unchanged.

Separate exploration from #8665. Transcription requires iOS 26 and a
supported language. Android reports unavailable before capture because
its generic recognizer cannot guarantee saved-file input.

Validation: at `b5dc83bbf5`, 5,046 Flutter tests (71 skipped), 27 crypto
tests, analysis and required push checks pass. Prior native changes at
`30a397f83c`: Android build and 33 tests pass; iOS simulator compilation
and backup-exclusion test pass, with one unchanged document-picker
timeout passing on isolated rerun. Earlier iPhone preview was tested
with saved profile preserved; these latest fixes have not been installed
on the physical phone.

---------

Signed-off-by: kenny lopez <klopez4212@gmail.com>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
Co-authored-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
Co-authored-by: corey <2dafccf60ea6d431a568f6d67fc600160d92a51e415e09dc8b213b8e360663d5@buzz.block.builderlab.xyz>
2026-11-19 10:32:12 +00:00
damienrj
b68c4edda5 feat(cli): show and search verified identity in users get (#9647)
## Summary

`buzz users get` reads only kind:0 profiles, so the CLI can't find or
confirm a person by their verified username. This adds relay-verified
profiles (kind:30382) to `users get`.

- `--pubkey` adds a `verified` object (`username`, `display_name`,
`full_name`, `issuer_label`, `verified_at`) for subjects that have one.
A requested person with a verified profile but no kind:0 is still
returned.
- `--name` uses the relay's `POST /profiles/search` when the community
advertises verified profiles with `searchable: true`, so it matches
verified names (word prefix). Otherwise, or for queries over the
endpoint's 100-character limit, it runs the existing NIP-50 substring
search and attaches verified profiles where the community advertises
them.

Verified profiles are read only when NIP-11 advertises
`federated_identity.public_profile`. A projection is trusted only if it
is kind 30382, signed by the relay's `self` key with a valid signature,
and follows the NIP-FI projection rules the mobile client applies: empty
content, exactly the projection tags (each once with one value), `p`
equal to `d`, `active` set to `true`, a valid username, names of 1–64
characters with no surrounding whitespace or control characters (looser
than mobile, which also requires NFC and rejects more Unicode
categories), and a decimal `verified_at` no later than `created_at`. The
newest projection per subject wins (the lower id breaks a same-second
tie), so a retraction clears the verified name. Any `verified` key in
user-authored kind:0 content is dropped on every path, so only a
relay-signed projection can set it.

`users get` now makes one NIP-11 request. If that request fails, the
advertisement is malformed, or the kind:30382 lookup fails, it still
prints the kind:0 results and writes a `verified_profiles_unavailable`
warning to stderr. This applies to `--pubkey`, no args, and `--name`.

### Related issue

Related: #8745 (verified profile spec), #9624 (verified-name mentions in
workflows).

### Testing

- `cargo test -p buzz-cli` passes, with tests for trust checks,
retraction, both lookup paths, search without the advertisement, and a
forged `verified` object in kind:0 (no advertisement, impostor-only
projection, and a valid projection replacing it).
- `cargo fmt` and `cargo clippy -p buzz-cli -D warnings` are clean.
- An earlier revision of the built CLI was run against a live community
with verified profiles: `--name <verified username>` found a user whose
kind:0 name differs, and `--pubkey` returned the expected `verified`
objects.

---------

Signed-off-by: damienrj <damien@squareup.com>
2026-11-18 22:02:21 -08:00
Tom Brow
39ffc3dcc5 fix(mobile): keep agent poster up until the iOS video draws (#9688)
On iOS, an animated agent avatar (a preset character with a transparent
video) blinks out for one to three frames right after navigation
settles. Opening a Solo chat blanks the header avatar; going back to
Messages blanks the bestie bubble.

The cause is the hand-off from the still poster to the video. While a
route animates, `PresetAgentAvatar` shows the poster; once it settles it
replaced the poster with a native `AVPlayerLayer`, which draws nothing
until its first video frame arrives. The avatar picker and the
create-agent page already covered this by passing a preloaded poster;
the DM and Solo header and the bestie bubble pass none, so they went
straight to the bare player.

Now every iOS caller gets that hand-off, using its own poster when it
passes none: the poster stays up, below the player, until playback
advances in that showing, then fades out over 160 ms. The poster sits
below the native layer rather than over it, because a Flutter overlay
above a platform view also costs a blank frame when the view first
appears. Each showing starts covered again and waits for playback to
advance from where the player actually is, so coming back to a chat from
a page above it doesn't blink either. The poster is keyed by its URL, so
when the avatar changes to another character (for example a synced
bestie change) it never shows the previous character's poster. Android
is unchanged; it already waits for a presented frame.

### Validation

Measured on an iPhone 17 Pro simulator, recording at 60 fps and checking
the avatar region frame by frame, opening a Solo chat with an animated
agent and going back:

| | Header blank on open | Bubble blank on back |
| --- | --- | --- |
| main, 3 runs | 1 frame every run | 2 to 3 frames every run |
| this PR, 3 runs | none | none |

Before (left) and after (right), slowed 4x: the Solo header on open,
then the bestie bubble on back.

<video
src="https://github.com/user-attachments/assets/4ddf16c0-bb8d-4d77-b53e-84f83ff45e98"
width="480"></video>

Added test: [iOS keeps the poster over a new player until playback
advances](2b172d1b68/mobile/test/shared/widgets/preset_agent_avatar_test.dart),
covering a first showing, a return to the route, and a change of
character while the video is showing.

### Regressions

- No extra work: the poster image was already loaded for the transition,
and the video plays exactly as before.
- During the 160 ms fade, poster and video overlap. They show the same
character, so the fade reads as a single image, as it already did in the
avatar picker.
- If the video never starts playing, the poster just stays up, which is
what callers showed before the video was ready anyway.





buzz-review-completed

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-18 19:57:44 -08:00
Matt Toohey
008d72a133 test(relay): stop bridge cancel_fixture tests timing out on the first replica connect (#9691)
## Problem

All seven tests that share `cancel_fixture` in
`crates/buzz-relay/src/api/bridge.rs` got a replica pool with a 1 s
`acquire_timeout`. Only
`shed_history_read_maps_to_503_on_every_bridge_branch` needs that
budget: it holds the replica full and measures how fast a read sheds.
sqlx applies `acquire_timeout` to opening connections as well as to
waiting for a free one, so the budget also governed the fixture's
initial connect and every later acquire that had to open a connection.

A transient Postgres stall on the shared CI server therefore failed
tests that never hold the replica full. CI showed `connect scratch:
PoolTimedOut` at `bridge.rs:10309` in
`aborted_history_read_logs_events_already_queued` and
`failed_history_read_closes_and_reconnect_replays_the_history` (run
44205074529 shows eight tests finishing together after a ~3 s gap, which
is the stall). Pools with sqlx's 30 s default waited the stall out; the
1 s replica did not. No connection leaked and the pool was not too
small.

The replica's 300 ms database-level `statement_timeout` had the same
flaw: migrations and seeding ran under it, so a stall during setup
failed `seed community` with 57014.

## Fix (test code only)

- The six non-shed tests now use default pool budgets.
- Only the shed test asks for the short budget, via `budgeted_reader`.
That helper pre-opens all of the reader pool's connections under the 30
s default, and does not ping on acquire, so the 1 s budget covers only
the wait for a free connection.
- sqlx still pings each connection on release and closes it if the ping
fails, so `budgeted_reader` waits until `num_idle()` equals
`max_connections` before returning. A fill-and-drain loop (acquire to
`max_connections`, drop, re-check) reopens any connection a failed
release ping closed, under one 30 s deadline, and panics with the `N of
M idle` count if the deadline passes.
- The replica's `statement_timeout` is applied after migrations and
seeding, and the replica is reopened so new sessions pick it up.
- The shed test asserts each shed `/query` case completes in under 10 s,
so a silent fallback to the 30 s default fails instead of passing
slowly.

## Verification

Reproduced locally by pausing the Postgres container for 2 s at random
intervals while running `api::bridge::postgres_tests` at CI's 8 threads:
`connect scratch: PoolTimedOut` appeared in 1 of 4 runs before the fix
and in 0 of 8 after. With the fix, the 62 bridge postgres tests passed
at 8 threads against a local Postgres (`--ignored`, including the shed,
statement-cancel, and both history-read tests). `cargo fmt` is clean.

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

---------

Signed-off-by: mtoohey <mtoohey@squareup.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 14:00:02 +11:00
Will Pfleger
a406191694 Revert "feat(relay): support community-scoped NIP-AR artifacts" (#9689)
Reverts #9650 (squash commit `eebf62b6`), except for migration `0097`
and the channel artifact sync fences it added.

Community scope adds a relay access gate based on community admission
rather than channel membership, a new relay-admin command kind (`9034`)
and an operator-run key transition. Its design and NIP-AR text need
relay maintainer review before they ship. Two integration gaps also
remain:

- Media download authorization looks up references only in `events`, so
an attachment referenced only by a community artifact is unreadable when
media-read enforcement is on.
- User erasure retires a community head in the database without
signaling live syncs, so members who are already syncing keep the erased
copy.

The feature can return as a new PR once those are resolved.

## Kept from #9650

- **Migration `0097`, byte for byte.** Published images already include
it, and databases that auto-migrated have recorded it. Dropping it would
stop those relays from starting. It only adds columns and indexes that
the channel code ignores. The declared schema matches that expanded
shape and keeps the `(community_id, artifact_id)` primary key, so the
operator key transition no longer exists.
- **Channel artifact sync fences.** Snapshot and live sends check for a
pending resync and for connection cancellation under the queue lock. A
reader who loses access, or whose content is redacted, while a frame is
in flight therefore receives no further payload. Handler-backed tests
cover a resync recorded while a snapshot payload waits for queue room
and one recorded after a live head read.

## Compatibility

This revert supports databases that applied only migration `0097`, which
is all that auto-migration runs. A database that ran #9650's operator
contract script, or was bootstrapped from #9650's declared schema, has
no `(community_id, artifact_id)` key, so channel artifact writes fail
there. Before deploying to such a database, check that
`artifact_heads_pkey` is on `(community_id, artifact_id)` and that
`artifact_heads` has no rows with `scope = 'community'`; if either check
fails, it needs a separate recovery step.

---------

Signed-off-by: Will Pfleger <wpfleger@block.xyz>
Co-authored-by: Paul <4a1bfa0013bc6d14a8d600d8bf6392efefbd2a26ac3c96c9b2a106b0d12297ca@buzz.block.builderlab.xyz>
2026-11-19 02:38:17 +00:00
Taylor Ho
db40da87b4 feat(relay): add conditional Solo member role updates (#9667)
**Category:** improvement
**User Impact:** Solo chat owners can lower the access of any current
non-owner, including people and agents.

**Problem:** Using invitations to change Solo chat access can restore a
removed member, reject a downgrade because of the target’s invitation
policy, or show a join notice for a role change.

**Solution:** Add signed role updates that require an active member at
the expected role when the relay commits the change. A Solo owner can
downgrade any current non-owner. Moving a viewer to Participating
requires a verified agent, and granting Admin requires ownership of that
agent. The relay refreshes signed group state without emitting a join
notice.

Companion to
[block/buzz-app#3704](https://github.com/block/buzz-app/pull/3704). The
[app
review](https://github.com/block/buzz-app/pull/3704#pullrequestreview-5962147206)
identified the need for conditional writes, verified agent identity and
live relay validation. [#9592](https://github.com/block/buzz/pull/9592)
introduced the atomic removal that uses the same membership lock.

<details>
<summary>File changes</summary>

**crates/buzz-core/src/kind.rs**

Register signed Solo role updates as kind 9050.

**crates/buzz-db/src/store/channel_members.rs**

Authorize the transition under the channel membership lock and commit
the active row update and signed event together.

**crates/buzz-relay/src/handlers/event.rs**

Give the new command a bounded metrics label.

**crates/buzz-relay/src/handlers/ingest.rs**

Use the shared signed ingest path and require the channel administration
scope.

**crates/buzz-relay/src/handlers/mod.rs**

Register the command handler and its PostgreSQL test.

**crates/buzz-relay/src/handlers/solo_member_role.rs**

Parse the command, route it to the conditional write, and refresh signed
group state after commit.

**crates/buzz-relay/src/handlers/solo_member_role_postgres_tests.rs**

Exercise human and agent changes, restrictive invitation policy,
promotion authorization, stale and removed membership, duplicate
receipt, and signed roster updates through the relay’s production ingest
path.

**docs/solo-mobile-contract.md**

Describe the wire format, permitted transitions, and handling when an
older relay rejects the command.

</details>

### Try it

1. Run the updated relay and the companion app against a disposable Solo
chat with a current human and agent. Open **Chat access** as the owner.
2. Lower the human to **Viewing only**. Reopen **Chat access** and
confirm the saved role. A role change should produce no join notice.
3. Downgrade an agent with a restrictive invitation policy. Confirm its
role changes. Check that **Admin** can be granted only to your own
verified agent.
4. Run `solo_owner_edits_active_members_and_publishes_the_new_roster`
with PostgreSQL to check that a pending change for a removed member is
refused and the signed roster stays clear of that member.

### Validation

- The PostgreSQL regression passes at relay commit `405f7d1da`. It
covers role and invite-policy enforcement, signed roster refresh,
duplicate receipts, and rejection after removal.
- The companion app at `a470947dc6` passes 138 administration tests. Its
production command builder, validator, and signed roster reader also
passed over WebSocket against a local relay backed by PostgreSQL and
Redis. A human moved from Admin to Participating to Viewing only, then
was removed. The app preflight and relay both refused a further role
edit, and the signed roster still excluded the member.
- The live check exercised the app’s relay code headlessly. The UI
walkthrough is pending.

---------

Signed-off-by: Taylor Ho <taylorkmho@gmail.com>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Carl <acda9e433d19dcd0e6b6840f7f4b98f3a56f1fab98049d444c087019e6d36560@feedback.communities.buzz.xyz>
Co-authored-by: Tom Brow <tomb@block.xyz>
2026-11-18 17:16:25 -08:00
Taylor Ho
fd436af846 feat(mobile): add saved channel section filters (#8479)
**Category:** new-feature
**User Impact:** Mobile users can filter each channel section by unread
or recent activity and save their choices to their account.

**Problem:** Mobile sections do not expose the account's saved All,
Unreads and Active filters, making long channel lists harder to navigate
on mobile.

**Solution:** Add per-section view settings with shared sheet chrome,
checked choices, inline Active duration and Apply/Cancel. Preserve
access to filtered channels through inline recovery and confirm
encrypted filter writes on relay readback.

**Known desktop and web sync limitation:** Mobile uses the encrypted
`channel-filter` record. The separate current desktop and web build
reads and writes `channel-workspace-filter` and falls back to the legacy
record only before a workspace filter exists. Once the workspace record
exists, filter changes are independent across the builds. The
interoperability tests below cover the older companion format from
[block/buzz-app #1297](https://github.com/block/buzz-app/pull/1297).
Current desktop and web interoperability is follow-up work.

<details>
<summary>File changes</summary>

**mobile/README.md**
Document section controls, recovery and preference behavior.


**mobile/lib/features/channels/channel_filter/channel_filter_activity.dart**
Read verified message activity with bounded concurrency and
lifecycle/live invalidation.


**mobile/lib/features/channels/channel_filter/channel_filter_manager.dart**
Preflight, publish and confirm encrypted preference changes, retaining
rollback and errors. Skip no-op deletion cleanup and allow best-effort
cleanup after local section removal.


**mobile/lib/features/channels/channel_filter/channel_filter_provider.dart**
Scope preference ownership and cache to the current account and relay.


**mobile/lib/features/channels/channel_filter/channel_filter_store.dart**
Preserve companion-compatible registers, durations, reset tombstones and
unknown fields; define filter predicates and salvage malformed
supported-v1 siblings from authenticated relay records.

**mobile/lib/features/channels/channels_page.dart**
Connect the filter owners and shared sheet header to channel navigation.

**mobile/lib/features/channels/channels_page/body.dart**
Apply filters using the same readiness predicate as unread highlights,
retain the selected channel and expose activity retry. Delete sections
locally before best-effort filter cleanup.

**mobile/lib/features/channels/channels_page/filters.dart**
Provide one draft settings sheet with checked rows, duration, pending
guards and retry. Announce retained-draft failures in a visible live
region beside the footer.

**mobile/lib/features/channels/channels_page/sections.dart**
Open section options directly and reveal hidden channels in the existing
roster.

**mobile/lib/features/channels/channels_provider.dart**
Invalidate activity for self-authored and muted messages independently
of unread state.


**mobile/test/features/channels/channel_filter/channel_filter_test.dart**
Cover record preservation, confirmed writes, malformed sibling repair
and the actual activity-provider/predicate composition, including
future-dated history.

**mobile/test/features/channels/channels_page_test.dart**
Cover staged saves, cancellation, failed drafts, saved duration and
read-only recovery at enlarged text.

**mobile/test/features/channels/channels_provider_test.dart**
Verify self-authored activity invalidates filters without changing
unread timestamps.


**mobile/lib/features/channels/channel_sections/channel_sections_provider.dart**
Emit local deletion immediately so offline removal updates the list
without waiting for a relay event.


**mobile/test/features/channels/channels_page_test/filter_feedback_tests.dart**
Verify pre-seed unread consistency and offline section deletion through
the real section provider and persistent storage, without filter
publication.


**mobile/test/features/channels/channel_filter/channel_filter_interop_test.dart**
Exercise encrypted desktop/mobile golden payloads and crossed writes
that converge on one complete winning record.

**mobile/test/fixtures/channel_filter_desktop.json**
Retain signed, encrypted synthetic-key payloads from the companion
desktop implementation and mobile manager for protocol regression
coverage.

</details>

### Reproduction

1. Open a channel section's options. Select Active and 7 days, then
Apply; reopen to see the saved choices checked.
2. Confirm older channels are hidden. Expand Show hidden channels to
navigate without clearing the filter.
3. Change a draft and Cancel. Confirm the saved filter remains
unchanged.
4. With preferences unavailable, delete an unfiltered custom section. It
should disappear and remain deleted locally without publishing a filter
reset.
5. Make a filter save fail. The draft should remain selected and the
error should be visible beside Retry and exposed as a live region.

### Validation and limits

- Follow-up fixes at `f38bf9b273402dd86e93476dde02f468747fa65a`, with
main `a93f3282c` integrated. Required pre-push checks passed on that
head: 3,742 Flutter tests passed, 16 skipped; four unconfigured-push
tests passed. Analyzer, formatting, file-size and branch-skew checks
passed.
- Repaired v1 metadata now contains exactly `v` and `g`, preserving
unknown top-level extensions. The pinned companion at `475e2afef`
verified, decrypted and adopted the repaired mobile head without
rewriting it. Sort-only Apply preserves late-loaded filters and
publishes no filter write; the existing signed-read sheet journey covers
this race.
- Affected pre-integration journeys/protocol tests: 97 passed. Removing
the production fixes produces six failures across unread readiness,
offline deletion, malformed siblings, activity classification and
accessible failed-save status; sources restored afterward.
- Protocol exercise: actual `block/buzz-app` browser-host filter code at
`475e2afef` produced the signed NIP-44 desktop golden head; the mobile
manager adopted it and published a sibling choice; desktop
decrypted/adopted that mobile write and preserved both durations on its
next edit. These are production-code exercises with synthetic keys and a
fake relay boundary, not two packaged clients exchanging against a live
relay.
- Whole-record last-write-wins applies to both mode and duration.
Preflight preserves observed sibling choices; crossed writes can
overwrite an unseen edit, even in another section. Readback checks the
requested pair, and refresh adopts the retained winner. Per-section
conflict-free merging is not promised.
- Supported-v1 malformed siblings are salvaged from the authenticated
relay head, with canonical repair published only by an explicit
confirmed save. Oversized records and unsupported schema versions remain
read-only; display cache never grants repair authority.
- Section deletion is local first. Unfiltered sections skip publication;
failed cleanup can leave unreachable settings for a never-reused section
ID. No offline filter-save queue or automatic cleanup retry is
introduced.
- Earlier iPhone 17 / iOS 26.5 testing exercised section options,
Cancel/reopen and Active/7-day filtering. The normal-flow screenshot
below predates these review fixes. Failure-path runtime/screen-reader
checks, Android, dark mode, packaged cross-device workflow and human
acceptance remain unverified.
- Preferences refresh on load/resume/pull-to-refresh; no instant
cross-device sync promise. Sort retains its existing asynchronous
persistence and is not atomic with the separate filter record.
- On `85949bcde`, 5,095 Flutter tests passed with 71 skipped, plus 27
secp256k1 tests. GitHub's required checks cleared. The duration
animation was tested on the iPhone 17 simulator against a local relay,
and the same animation is included in this head. The separate
non-required Codex Security Review run was canceled before publishing a
review.

### Screenshots

Actual iOS simulator capture, cropped to the section settings surface.

| Section view settings |
| --- |
| ![Section options with Active and seven days
selected](https://github.com/user-attachments/assets/3145394a-0efe-4177-9388-67cbdf62d48b)
|

---------

Signed-off-by: Taylor Ho <taylorkmho@gmail.com>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Carl <acda9e433d19dcd0e6b6840f7f4b98f3a56f1fab98049d444c087019e6d36560@buzz.block.builderlab.xyz>
Co-authored-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-18 16:26:10 -08:00
LordMelkor
eebf62b61d feat(relay): support community-scoped NIP-AR artifacts (#9650)
## Summary

NIP-AR clients can store community-scoped artifacts and subscribe to
live changes for one exact artifact type. Community and channel
artifacts share revision and retry semantics and use separate identity
scopes. Community owners and admins can choose whether a type accepts
edits from all admitted members or only administrators. This PR combines
the protocol from #9638 with the relay implementation.
[Protocol](0b8949f5e2/docs/nips/NIP-AR.md (community-scoped-artifacts-proposed-extension))

- Kind `45010` binds community writes to a signed tenant UUID. Explicit
community filters select signed HTTP reads and WebSocket sync. NIP-11
advertises capability after the schema transition.
- Kind `9034` sets per-type policy using compare-and-set. The relay
commits the policy update and audit entry together. Readers fetch the
current policy and its revision through the explicit policy view.
- Kind `9005` redacts a community revision. Relay peers send
tenant-scoped change metadata and re-read the authorized head for
delivery. This reuses the existing snapshot, bounded buffering, and
resync semantics.

## Rollout

Migration `0097` expands storage and retains the existing channel write
key. Deploy compatible serving backends, deletion executors and operator
tools with community scope disabled. Then run the guarded key transition
and enable the capability. The resulting rollback floor is the first
compatible relay version. [Rollout
guide](0b8949f5e2/docs/community-artifact-rollout.md)

## Why each change belongs in the relay or protocol

| Change | Necessity | Minimality |
| --- | --- | --- |
| NIP-AR community scope | The current protocol gives every artifact a
home channel and defines channel-based access. Clients need a shared
contract for community identity, admission, reads and moderation to
interoperate.
[NIP-AR.md:9](493cb4cc13/docs/nips/NIP-AR.md (L9))
[NIP-AR.md:65](493cb4cc13/docs/nips/NIP-AR.md (L65))
| An optional version-1 section reuses the artifact envelope version and
revision operations. The channel sections state where their existing
rules apply.
[NIP-AR.md:242](0b8949f5e2/docs/nips/NIP-AR.md (L242))
|
| Signed community revisions | The validator requires an `h` tag, and
the write path stores an event and mentions for that channel. A
client-defined tag cannot establish a different audience on the relay.
[artifact.rs:122](493cb4cc13/crates/buzz-core/src/artifact.rs (L122))
[artifact.rs:196](493cb4cc13/crates/buzz-db/src/store/artifact.rs (L196))
| The existing event kind accepts a mutually exclusive, signed community
UUID. HTTP and WebSocket bind it to the resolved tenant at ingest and
reuse the revision authentication checks.
[community_artifact.rs:120](0b8949f5e2/crates/buzz-relay/src/handlers/community_artifact.rs (L120))
[community_artifact.rs:174](0b8949f5e2/crates/buzz-relay/src/handlers/community_artifact.rs (L174))
|
| Scoped heads and revisions | The database key places every artifact in
one identity space per community. Only the relay can advance an accepted
head atomically across clients.
[artifact_heads.sql:2](493cb4cc13/schema/tables/public/artifact_heads.sql (L2))
[artifact.rs:187](493cb4cc13/crates/buzz-db/src/store/artifact.rs (L187))
| The head and revision ledger gain a scope discriminator. Community
revisions keep their signed payload in the ledger and reuse the
compare-and-set, replay and tombstone rules.
[community_artifact.rs:350](0b8949f5e2/crates/buzz-db/src/store/community_artifact.rs (L350))
|
| Community admission | Channel reads check channel visibility and
membership. A client can filter its own view but cannot enforce
admission for other readers or synchronize delivery with a revocation.
[artifact_query.rs:65](493cb4cc13/crates/buzz-db/src/store/artifact_query.rs (L65))
| Explicit community reads and writes share an admission check against
current membership, verified delegation and bans. Administrative
authority requires a direct role.
[community_artifact.rs:36](0b8949f5e2/crates/buzz-db/src/store/community_artifact.rs (L36))
|
| Per-type write policy | The administrative scope dispatch has no
artifact-policy command. A client preference cannot enforce an edit rule
against another client or a concurrent write.
[ingest.rs:650](493cb4cc13/crates/buzz-relay/src/handlers/ingest.rs (L650))
| One signed admin command sets policy for one exact type using
compare-and-set. A bounded map on the existing community row records the
policy and revision. A shared lock orders policy changes with writes,
and the existing audit chain commits in the same transaction.
[community_artifact.rs:183](0b8949f5e2/crates/buzz-db/src/store/community_artifact.rs (L183))
[community_artifact.rs:365](0b8949f5e2/crates/buzz-db/src/store/community_artifact.rs (L365))
[community_artifact.rs:189](0b8949f5e2/crates/buzz-relay/src/handlers/community_artifact.rs (L189))
|
| Signed HTTP reads | The artifact endpoint dispatches to the channel
store. It cannot return a community head, its history or the
authoritative write policy.
[artifact.rs:70](493cb4cc13/crates/buzz-relay/src/api/artifact.rs (L70))
[artifact_query.rs:65](493cb4cc13/crates/buzz-db/src/store/artifact_query.rs (L65))
| One scope selector on the existing signed endpoint extends the
current, history and head views and adds an exact-type policy lookup.
Counts and HTTP incremental tokens stay channel-only.
[artifact.rs:73](0b8949f5e2/crates/buzz-relay/src/api/artifact.rs (L73))
[artifact_sync.rs:154](0b8949f5e2/crates/buzz-relay/src/api/artifact_sync.rs (L154))
|
| Community WebSocket sync | The relay requires channel IDs and confirms
live interest on those channels. A client cannot register community
interest through the existing filter.
[artifact_sync.rs:51](493cb4cc13/crates/buzz-core/src/artifact_sync.rs (L51))
[artifact_sync.rs:440](493cb4cc13/crates/buzz-relay/src/handlers/artifact_sync.rs (L440))
| One exact type selects the community set. The relay reuses
subscription ownership, snapshot paging, bounded buffering, EOSE and
resync, with a current admission check before delivery.
[artifact_sync.rs:683](0b8949f5e2/crates/buzz-relay/src/handlers/artifact_sync.rs (L683))
[artifact_sync.rs:755](0b8949f5e2/crates/buzz-relay/src/handlers/artifact_sync.rs (L755))
[artifact_sync.rs:934](0b8949f5e2/crates/buzz-relay/src/handlers/artifact_sync.rs (L934))
|
| Cross-node delivery | Redis routes channel and ordinary global events.
A connected client cannot coordinate when peers reread an authorized
head.
[topic.rs:15](493cb4cc13/crates/buzz-pubsub/src/topic.rs (L15))
| One tenant-scoped topic carries the identity, exact type and change
cause. Each relay filters its own subscriptions and rereads the
authorized head or signals resync.
[artifact_sync.rs:211](0b8949f5e2/crates/buzz-relay/src/handlers/artifact_sync.rs (L211))
[artifact_sync.rs:1039](0b8949f5e2/crates/buzz-relay/src/handlers/artifact_sync.rs (L1039))
|
| Ordinary event audience | Generic queries and search apply event-store
rules. A client cannot enforce who else receives a response from those
paths, including on a relay with community writes disabled.
[event.rs:785](493cb4cc13/crates/buzz-db/src/store/event.rs (L785))
[query.rs:329](493cb4cc13/crates/buzz-search/src/query.rs (L329))
| Community payloads stay in the ledger. Ordinary reads and fan-out
enforce the channel boundary, including for rows from older paths.
Explicit artifact views enforce community admission.
[event.rs:7267](0b8949f5e2/crates/buzz-db/src/store/event.rs (L7267))
[event.rs:153](0b8949f5e2/crates/buzz-relay/src/handlers/event.rs (L153))
|
| Community redaction | The moderation path requires a channel in `h`. A
client delete cannot apply relay moderation to a stored community
revision.
[side_effects.rs:671](493cb4cc13/crates/buzz-relay/src/handlers/side_effects.rs (L671))
| The existing moderation kind gains one community-scoped target form
for direct owners and admins. Redaction preserves the accepted revision
ID and sends affected syncs through the existing resync path.
[community_artifact.rs:214](0b8949f5e2/crates/buzz-relay/src/handlers/community_artifact.rs (L214))
[community_artifact.rs:609](0b8949f5e2/crates/buzz-db/src/store/community_artifact.rs (L609))
|
| Community purge | The deletion executor retains the community row as a
tombstone. Client-side removal cannot clear authoritative policy on that
row or prove it was erased.
[deletion.rs:2448](493cb4cc13/crates/buzz-db/src/store/deletion.rs (L2448))
[deletion.rs:3488](493cb4cc13/crates/buzz-db/src/store/deletion.rs (L3488))
| The existing purge covers both ledger tables. The tombstone
transaction clears the policy map when the column exists, and the
absence check verifies it.
[deletion.rs:2451](0b8949f5e2/crates/buzz-db/src/store/deletion.rs (L2451))
[deletion.rs:3489](0b8949f5e2/crates/buzz-db/src/store/deletion.rs (L3489))
|
| Schema rollout | Older writers use the existing two-column conflict
target. Clients cannot preserve that write contract during a key change
or attest which relay binaries are serving.
[artifact.rs:196](493cb4cc13/crates/buzz-db/src/store/artifact.rs (L196))
| Migration 0097 adds columns and indexes without a backfill and
preserves the old key. A separate guarded SQL operation installs the
scoped key after the compatible fleet is in place. The rollout guide
documents the sequence and rollback boundary.
[0097_community_artifact_expand.sql:7](0b8949f5e2/migrations/0097_community_artifact_expand.sql (L7))
[community-artifact-contract.sql:13](0b8949f5e2/scripts/maintenance/community-artifact-contract.sql (L13))
[community-artifact-rollout.md:38](0b8949f5e2/docs/community-artifact-rollout.md (L38))
|
| NIP-11 and enablement | The baseline artifact descriptor supplies
neither the tenant UUID nor a signal that the scoped schema is active.
Clients cannot infer activation across mixed-version deployments.
[nip11.rs:478](493cb4cc13/crates/buzz-relay/src/nip11.rs (L478))
| One optional discovery object advertises the version, canonical tenant
UUID and policy limit. The handlers and NIP-11 share the configuration
and schema-readiness gate.
[nip11.rs:482](0b8949f5e2/crates/buzz-relay/src/nip11.rs (L482))
[community_artifact.rs:51](0b8949f5e2/crates/buzz-relay/src/handlers/community_artifact.rs (L51))
|

## Size

Measured with `git diff` from `493cb4cc1` to `0b8949f5e`. Dedicated test
files and changed lines inside Rust `#[cfg(test)]` items count as tests.
Each side of a mixed hunk is classified against its own revision.

| | Added | Removed |
| --- | ---: | ---: |
| Production, including schema and rollout SQL | 2,249 | 117 |
| Tests | 1,897 | 53 |
| Docs | 180 | 8 |
| Standalone runtime probe | 397 | 0 |
| **Total** | **4,723** | **178** |

The total includes
`crates/buzz-relay/examples/community_artifact_probe.rs`. The production
and test rows exclude it. The probe supports manual mixed-version and
feature-disabled checks against a running relay.

## Validation

Validated at `0b8949f5e29f5ccf51ec5e2d487f09e2f49bffeb` against
`493cb4cc1369ff9fdb44ae6c50f18c66d1fb6474`.

- The signed HTTP and WebSocket workflow exercised the old and new
channel writers on the expanded schema, the guarded key transition,
community snapshot and live sync, policy compare-and-set and replay,
tenant binding, scope isolation, and redaction followed by resync.
Restarting the relay with community scope disabled after the transition
withheld capability advertisement and preserved channel artifact
operations.
- The normal `buzz-db` suite passed 268 tests, including doctests. All
860 `buzz-db` PostgreSQL tests passed, including the wide `#e` read
regression from #9591.
- The full eight-package PostgreSQL run passed 1,695 of 1,696 tests.
`handlers::ingest::postgres_tests::reaction_and_deletion_h_must_name_the_target_channel`
failed while setting up its private-channel fixture. The same fixture
failed on the protocol base `27a4c8a86e9e9795bfaf5fe59f35164a6389a9ed`.
- The hosted PostgreSQL run at `686b8445` passed 1,698 of 1,699 tests.
The same test was the sole failure on the PR and on `main` at
`493cb4cc13`. In both runs, fixture setup returned `restricted: not a
channel member` while storing the private target. #9640 fixes the
fixture by invalidating the author's membership cache after creating the
private channel. Its PostgreSQL run passes the test. [PR run
44325182932](https://github.com/block/buzz/actions/runs/44325182932/job/134884438543)
· [Main run
44254013047](https://github.com/block/buzz/actions/runs/44254013047/job/134638066441)
· [Fix #9640](https://github.com/block/buzz/pull/9640) · [Passing test
on
#9640](https://github.com/block/buzz/actions/runs/44248427229/job/134618695910)
- `just test-unit` and `just test` passed on Linux in separate runs. The
commands recorded 6,611 and 7,243 passing test executions, respectively,
with overlap between the suites. These runs passed the CLI socket
ownership tests and push-gateway fixture that failed during the earlier
parallel hook run. Both Tauri Clippy configurations and 3,560 Tauri test
executions also passed at this commit.
- `just ci` passed Rust formatting, workspace Clippy, and desktop,
Tauri, and web checks. It stopped at mobile formatting after the Linux
environment failed to resolve `pub.dev` for the Flutter dependencies.


## End-user test

The PR author’s agent ran the app and plugin end to end on Linux against
a local relay built at `0b8949f5e`. The final browser rerun passed all
15 steps plus the public default-channel case. The native desktop run
passed all seven steps it covered.

- A group saved by the owner appeared in a member’s open Settings
without a reload.
- Changing the write policy to owners and admins made the member’s
editor read-only. The relay refused a signed write by that member and
preserved the current record.
- The audit log identified the policy revision as the accepted
kind-`9034` event ID. The policy change back to everyone used that ID as
`prev`.
- A second relay with community artifacts disabled advertised no
community scope, and the app withheld shared group actions.

[End-user test
evidence](https://github.com/block/buzz-app/pull/3838#end-user-test-agentsmd-step-3)

Supersedes #9646. The reviewed commit is now on an upstream branch.

---------

Signed-off-by: Krish Ray <kray@block.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Codex <codex@openai.com>
2026-11-18 18:57:40 -05:00
Tom Brow
b544fcea4a feat(mobile): add a diagnostics test report and test crash to Settings (#9676)
A way to check that a build's diagnostic reporting works end to end, per
[mobile diagnostic
reporting](https://github.com/block/buzz/blob/main/docs/mobile-diagnostic-reporting.md).
A build with a reporting destination shows a Diagnostics card in
Settings with **Send test report** and **Test crash**. A build without
one, which includes every build from this repository alone, never shows
it and still reports nothing.

| Before | After |
| --- | --- |
| ![Settings bottom,
before](https://github.com/user-attachments/assets/92fdef05-8d63-43db-8df1-32ccb92105c8)
| ![Settings bottom with the Diagnostics
card](https://github.com/user-attachments/assets/a205ab18-ed1e-49d5-8e34-88e29e4c91fa)
|

![Test crash
confirmation](https://github.com/user-attachments/assets/335eb362-3a61-4c8c-8b32-44de548cf788)

### What's in it

- The reporter gains `reporting` (whether the build has a destination),
`sendTestReport()` and `crashForTest()`. The do-nothing reporter returns
false and does nothing.
- **Send test report** sends a fixed `DiagnosticTestError` tagged with a
new `testReport` operation. It passes through the same filter as every
report.
- **Test crash** asks for confirmation, then crashes in native code
through the SDK, so native crash reports can be checked too. The report
goes out the next time the app opens.
- The spec gains a "A way to check a build" decision.

### Regressions

None expected: builds without a destination render Settings exactly as
before.

### Validation

Added widget tests for the card being absent without reporting, sending
a test report, and the crash happening only once confirmed, plus a test
of what a sent test report contains and one that a second tap sends a
second report. The screenshots come from simulator builds of main and
this branch, both with the same placeholder destination.

A full-app simulator run at dec267f (placeholder destination) passed:
channel list, opening and scrolling a channel, search, the other
Settings sections, two test reports (a toast each time), cancelling Test
crash, confirming it (a native crash in the Sentry SDK) and relaunching
signed in.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-18 14:48:25 -08:00
Wes
44e97e96f4 fix(pubsub): round the rate-limit retry hint up from PTTL (#9552)
## Summary

The Redis rate limiter built its `retry in Ns` hint from `TTL`, which
truncates to whole seconds. With 400 ms left in the window, a denied
request was told `retry in 0s`, and a client that sleeps for exactly the
hint retried straight into another refusal.

This reads `PTTL` and rounds the milliseconds up to whole seconds, so
the hint is never 0 while the window is still open. The no-expiry repair
path is unchanged.

## Testing

- New `rate_limiter::tests::retry_hint_rounds_a_partial_second_up`
(`#[ignore = "requires Redis"]`, like the other Redis tests in this
crate) seeds an exhausted window with 400 ms left and asserts the denial
reports 1 second. Against the old `TTL` code it fails with `left: 0,
right: 1`; with this change it passes.
- `cargo nextest run -p buzz-pubsub --lib`: 38 passed. Ignored Redis
`rate_limiter` and `nip98_replay` tests: 5 passed against a local Redis.
- `cargo nextest run -p buzz-relay --lib` with local Postgres and Redis:
1762 passed. The relay `rejection::`/`admission::` lane with
`--run-ignored all`: 16 passed.
- Pre-push hooks (including rust-tests) passed.

CI note: the Redis-backed pubsub tests only run in CI when they are
named in `.github/workflows/_ci-relay.yml`, so the new test isn't
selected there yet. Adding `or test(/^rate_limiter::tests::/)` to the
"Pubsub subscriber reconciliation regression" filter would cover it. I
left that out here because this branch can't push workflow file changes.

---------

Signed-off-by: Wes <wesb@block.xyz>
Co-authored-by: Groot <f4c08302591916fb4b80926bf7e18d22eef8aa0c877e4e841acc46405a45700b@buzz.block.builderlab.xyz>
Co-authored-by: Star Lord <b89298dbe87c6b3fd8a425b535d9d161f23c88d555a47925ae0b04dfe02b201e@buzz.block.builderlab.xyz>
2026-11-18 16:28:20 -05:00
Tom Brow
bf9ce1432e feat(mobile): add diagnostic reporting module with crash capture (#9613)
Step one of [mobile diagnostic
reporting](https://github.com/block/buzz/blob/main/docs/mobile-diagnostic-reporting.md),
first piece: the reporting module, plus capture of crashes and uncaught
errors.

A build given a `BUZZ_SENTRY_DSN` now reports native crashes, Flutter
framework errors and uncaught asynchronous Dart errors to that Sentry
project, attributed to the signed-in member's public key. A build
without one (every build made from this repository alone) uses a
do-nothing reporter and never initializes the SDK, as [ADR
0007](https://github.com/block/buzz/blob/main/docs/adr/0007-diagnostic-reporting-follows-the-destination.md)
requires. A destination the SDK cannot parse is treated as none, so a
configuration mistake never stops the app from starting.

### What's in it

- **One interface** in `mobile/lib/shared/diagnostics/`: report an
error, count a networking event, leave a breadcrumb, and set the member.
It has a Sentry-backed and a do-nothing implementation. Only this folder
imports the SDK. The explicit error reports and the networking counts
that use it come in the next PRs.
- **Startup** wraps `runBuzzApp` and installs the SDK's crash and error
handlers only when a usable destination is set: one with an HTTP(S)
host, a public key and a project, which the native SDKs also require. On
Android, the manifest removes the SDK's startup performance provider,
which would otherwise run before that check.
- **Member:** set from the active community's key, changed when the
account switches, cleared on sign-out. Adding the Builderlab origin and
account subject is left to a later PR. Every report also carries a
random per-install identifier the app creates on first launch, as its
own `install.id` tag, signed in or not, so a device's reports can be
matched to its members. It lives in a file that device backups and
transfers skip, so a phone restored from another gets its own: on
Android in the app's files directory, excluded in both backup rule sets;
on iOS in an Application Support folder that a small native call marks
as excluded from backup (not the caches folder, which iOS can clear when
storage runs low). Set on the SDK scope, it also reaches native crash
and hang reports. With no member set (before sign-in or after sign-out),
the SDK also fills the report's user with its own random per-install
identifier, on Dart and native reports alike.
- **One filter** runs on every Dart report, breadcrumb and count before
it leaves the device:
- It replaces every error's own text with fixed wording, since an error
can quote its input, a server's response body or a URL. The error keeps
its type, mechanism type and stack trace.
- It drops what the SDK adds about the failing platform call
(`mechanism.data`) and the failing widget (`flutter_error_details`),
which can quote what is on screen.
- It removes URL query strings and fragments, and keeps only tags and
count attributes on the allowed list.
- It drops every breadcrumb except networking events and the SDK's
foreground/background entries.
- **SDK options:** personal data, screenshots, view hierarchy, replay
and tracing stay off. The SDK's session records stay on, for a
crash-free rate. A session begins each time the app starts or returns
after 30 seconds or more in the background; the SDK sends a record when
it begins, an update each time an error is counted, and a last one when
it ends, carrying the start time, error count, outcome, time from start
to end, release, environment and the random per-install identifier.
Native auto-breadcrumbs, Android's network-change breadcrumbs (VPN
state, signal strength, bandwidth; turned off in the manifest, since the
Flutter bridge leaves them on), Cocoa's network breadcrumbs (which keep
each request's query and reach native crash reports) and print
breadcrumbs are off. With print breadcrumbs on, the SDK would replace
`debugPrint` in non-debug builds with one that prints nothing.
- **Main-thread hangs:** iOS app hang tracking, Android ANR detection
and iOS watchdog-termination tracking are set on explicitly, at the
SDK's default thresholds. iOS reports the main thread blocked, fully or
mostly, for 2 s or more while the app is active, including freezes it
recovers from; a hang still going when the system kills the app is sent
on the next launch as a fatal hang, and watchdog-termination tracking
reports a foreground run that ended with nothing else to explain it.
Android reports only system-declared ANRs: on Android 11 and later, the
most recent one that ended the process (read on the next launch, when
the system kept a thread dump); before 11, after 5 s once the system
marks the app not responding. So recoverable freezes are reported on
iOS, and on Android only before 11 once the system marks the app not
responding. Dart runs on the main thread, so blocking Dart work shows up
with the main thread's stack; Dart frames need the Dart debug symbols at
the destination, as crashes do. The spec now has a bullet and a user
story for this.
- **What the filter does not cover:** native crashes and app hangs are
captured and sent by the native SDKs, which never call the Dart filter.
They carry stack traces and, for a native exception, its reason text. No
app code puts content in a native exception today. The spec now says
this.
- **Reporting never blocks the app or reaches it with an error:** every
call returns at once, and a failure inside reporting is dropped with a
`debugPrint`.

### Regressions

None for builds without a destination, which includes every build from
this repository: they run the same startup with one extra synchronous
check, and the SDK is never initialized. The SDK still adds to the app's
binary size on both platforms.

With a destination, the first frame waits for the SDK to start, native
SDK included, and for the install ID to be read from (or, on first
launch, written to) a small file. On a debug simulator build the first
frame came about 0.3 s later (median of 6 cold launches: 768 ms with a
destination, 431 ms without), measured before the install ID was added.
Device builds will differ. Uncaught errors still reach Flutter's default
handling, and the SDK sends in the background.

### Validation

Added tests (`test/shared/diagnostics/diagnostic_reporting_test.dart`):
- A table of inputs run through the production Sentry options callbacks:
SDK HTTP and navigation breadcrumbs are dropped, network breadcrumbs
keep only their four attributes, URLs lose their query string and
fragment, unknown tags and count attributes are dropped, and the privacy
and breadcrumb options stay off.
- Errors sent through a real SDK hub, with the SDK's own platform-error
processor and Flutter error integration, into an in-memory transport:
for a parse failure, a bad argument, a server response and a platform
failure, the serialized event keeps the type and stack but none of the
error's text; a real framework build error leaves out the widget text.
- A release-mode check that `debugPrint` keeps printing with reporting
on.
- A build with no destination, one the SDK cannot parse, one without a
public key or one without an HTTP(S) host starts the do-nothing reporter
and the SDK stays disabled.
- Reporting calls whose SDK calls throw, either synchronously or
asynchronously, never reach the caller.
- Hang detection is on and its thresholds equal the SDK's defaults.
- An installation keeps one install ID across launches, a new
installation gets a new one, and the filter keeps the `install.id` tag.
- Signing in, switching accounts and signing out change the member that
later reports are attributed to.

I checked that each guard is real by removing it: the print-breadcrumb
setting, the destination check, the error-text replacement, the
`mechanism.data` and `flutter_error_details` removal, the
network-breadcrumb setting, the dropped-failure catch and the tag filter
each made a test fail.

End to end on an iPhone 17 Pro simulator, with a local server standing
in as the destination and a throwaway probe (not committed) that made an
HTTPS request with a secret in its query, then raised an uncaught Dart
error and a framework error with secrets in their text, then crashed
natively:
- All four reports arrived (two Dart, one framework, one native crash on
the next launch), and none of the secrets appeared in any envelope.
- Dart reports carried only the foreground/background breadcrumb; the
native crash carried none.
- As a control, a build with Cocoa's network breadcrumbs switched back
on put the request's secret query and fragment into the native crash
report, so that setting is what keeps them out.
- `debugPrint` lines still appeared in the device log.

Hangs, on a fresh iPhone 17 Pro simulator with no debugger attached and
the same local server: a throwaway probe busy-looped the main isolate
for 5 s after the first frame. The SDK sent an `App Hang Fully Blocked`
event ("App hanging between 5.7 and 6.5 seconds", mechanism `AppHang`)
carrying the main thread's stack: Flutter engine frames around 12 frames
of Dart code. This was a debug build, where Dart is compiled just in
time, so those frames have no image to symbolicate against; in release
builds they fall in the app's compiled Dart framework and need its debug
symbols at the destination.

Install ID, rechecked after moving it to its own file, on a fresh
simulator with the same local server, launched twice with a probe that
raised a Dart error and then crashed natively: both Dart errors and the
native crash carried the same `install.id`, while the signed-out user
was the SDK's own identifier. The ID file was in the backup-excluded
`Library/Application Support/Diagnostics` folder, not in the app's
preferences.

The merged Android debug manifest has neither of the SDK's startup
providers and has the network-change setting off. The NDK preload
provider is still merged in, but it does nothing unless its own manifest
flag is set, and it isn't.

Full mobile suite passes. Dart errors are captured in the main Flutter
engine only; the iOS sheets that start their own engine are out of scope
for this PR (native crashes while they are open are still caught), as
the spec now says. iOS simulator and Android debug builds with a
destination set both build; on iOS the SDK resolves through Swift
Package Manager.

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-18 12:50:45 -08:00
Will Pfleger
b624eb0f20 fix(mobile): recover stuck read-state updates and stale Mark Read (#9492)
## Summary

Mobile read-state fixes within the current NIP-RS text.

- **Stuck pending update.** When the relay refuses a pending update with
`invalid: event timestamp too far from server time` and the update is
older than the relay's 15-minute window by the device clock, the update
is retired. The next pass reads a fresh snapshot and sends a strictly
newer successor, journaled before it is sent, unless the relay already
holds that update or an own-slot update covering every key in it. The
marks come from the journaled local state, so nothing is lost. A refusal
of an update that is not old by the device clock reports
`ReadStateClockSkewError` and keeps the exact signed bytes. Unknown
outcomes (timeouts, lost acknowledgements) still retry the exact bytes.
- **Mark Read from the channel actions sheet.** The sheet is the only
owner of the action, for custom-section channels too. It marks through
the newest message known at the tap (the listed `lastMessageAt` or a
newer observed unread event), not the `Channel` captured when the menu
opened, so messages arriving after the tap stay unread. With no known
message time it only releases forced-unread flags.
- **Failed snapshot.** A failed snapshot, during startup or inside a
publish, retries with backoff (5 s doubling to 5 min) while connected
and on app resume; the retry re-syncs and sends journaled marks. When a
publish's own snapshot read succeeds first, the pending retry is
cancelled, the backoff resets to 5 s and the superseded snapshot error
is cleared. A reconnect still re-syncs as before. The channels list
shows a tappable "Unread status isn't syncing" notice while sync is
failing.
- **Marks in the manager gap.** A mark, seed or forced unread made after
a dependency change retired the manager, but before the rebuild, now
runs the pending rebuild and reaches the current manager instead of
being dropped.

The session-wide publishing switch-off after an unsupported-kind or
missing-scope refusal is unchanged: marks stay journaled and the next
manager (restart, re-authentication or community switch) publishes them.
In that state the notice offers no retry and says to sign in again or
restart Buzz.

## Tests

- `read_state_manager_test.dart`: expired update with only partial
coverage is renewed with a newer successor carrying every mark; expired
update the relay already holds is retired with no new send; clock-skew
refusal keeps the exact update and reports the skew error; failed
snapshot retries on the backoff timer and stops after recovery; a
snapshot failure inside a publish retries on its own and sends the
marks; after an explicit flush whose snapshot read succeeds, no extra
snapshot is read and the next failure retries after 5 s, whether the
write succeeds or fails.
- `channel_actions_sheet_test.dart`: Mark Read covers a message that
arrived while the sheet was open; with no known message time it only
releases forced unread.
- `read_state_provider_test.dart`: a mark made between a community
switch and the next manager's build is kept.

Each new test fails without its fix.

---------

Signed-off-by: Will Pfleger <wpfleger@block.xyz>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz>
Co-authored-by: Tom Brow <tomb@block.xyz>
2026-11-18 15:32:15 -05:00
Will Pfleger
8d613ce0e8 test(relay): refresh the author's membership cache after the stray-h private channel insert (#9640)
Fixes
`handlers::ingest::postgres_tests::reaction_and_deletion_h_must_name_the_target_channel`,
which fails on main in the PostgreSQL Tests jobs.

The test creates its private channel directly in the database after the
author has already published, so the per-user membership cache
(`is_member_cached`) still holds the author's snapshot from before that
channel existed. The author's post to the new channel is then refused
with `restricted: not a channel member`. The test now drops the author's
cached membership after the insert, so the channel's owner is seen as a
member. The test's assertions are unchanged.

Signed-off-by: Will Pfleger <wpfleger@block.xyz>
Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
2026-11-18 14:14:09 -05:00
Diem Nguyen
c18bed1f46 fix(mobile): name the cause of account-unavailable sign-in errors (#9628)
## Problem

Organization sign-in can fail with `Couldn't sign in
(account-unavailable)`. That code covers several different failures, so
a screenshot can't tell them apart:

- the account server can't be reached at all (DNS, connection, or TLS
failure, or a timeout), for example when a required VPN profile isn't
applied to the app;
- a redirect, since the client doesn't follow redirects, so an
access-proxy login page lands here;
- a 5xx from the server.

## Change

- `BuilderlabAccountClient` records why a request failed as
`unavailable`, in `lastUnavailableCause`, and logs it. It follows the
existing `lastRejectedRequest` pattern. The cause is one of:
- a transport category: `unreachable`, `insecure`, `timedOut` (reusing
`transportFailure`), or `network` as the fallback;
  - the status code, such as `http302`.
- `OrganizationSignIn` saves the cause at the moment the exchange fails,
so later account requests can't change it. It adds the cause to the
failure code, for example `account-unavailable-http302` or
`account-unavailable-unreachable`. Each new attempt clears it.

- The organization sign-in page now ends its failure message with advice
for that cause instead of "Try again.":
- unreachable, timeout, TLS failure, redirect: "Check your network or
VPN connection, then try again."
  - a 5xx: "The sign-in service is unavailable. Try again later."
- The in-app banner keeps "Try again.": its capsule clips longer
messages at default text size, and the existing banner layout test
caught that.
- Unexpected statuses are classified as soon as the headers arrive, so a
slow or oversized error body can't hide the status.

| Before | After |
|---|---|
|
![Before](https://github.com/user-attachments/assets/17a2a3ac-a488-46b3-9995-1bd95a529f60)
|
![After](https://github.com/user-attachments/assets/3813d1e9-7dc4-4726-9f40-ace57ed12d7a)
|

The log line contains only the host, route, and cause. It has no
headers, credentials, or response bodies.

## Validation

- A new journey test in `organization_sign_in_test.dart` covers an
exchange that fails with a 302, a 503, and a client exception, then a
successful retry. With the cause capture removed, the test fails
(`Expected: 'account-unavailable-http302'`, `Actual:
'account-unavailable'`).
- The same test checks the advice for each cause. The internal-build
landing tests pass with `--dart-define=BUZZ_DISTRIBUTION=internal`.
- The screenshots come from the real `PairingPage` rendered in a scratch
widget test with a 390×844 surface, cropped. The scratch test isn't
committed.
- `just mobile-check` passes, and the full `flutter test` run passes:
+5018, 71 skipped.
- Not yet done: a device run that reproduces an unreachable account
server and captures the new message on screen.

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

---------

Signed-off-by: Diem Nguyen <diem@squareup.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:34:49 -08:00
Wes
7cf19b713c perf(db): bound deep keyset history pages by the cursor timestamp (#9549)
## Problem

`query_events` and `get_channel_window` page history with a composite
`(until, before_id)` cursor under `ORDER BY created_at DESC, id ASC`.
The cursor predicate was only:

```sql
created_at < $u OR (created_at = $u AND id > $bid)
```

PostgreSQL cannot use that OR as the start of an index range, so a page
deep in a channel walks the `(community_id, channel_id, created_at DESC,
id)` index from the newest row and filters every newer row before it
reaches the page. The cost of a page grows with its depth.

## Fix

Add the redundant bound `created_at <= $u` next to the OR in both
queries (`store/event.rs` and `store/thread.rs`). It does not change
which rows match; it gives the planner an `Index Cond` range start at
the cursor. This is the same bound the thread window query already
carries (`store/thread_window.rs`).

`api/bridge.rs` has the pattern only in a test fake that emulates
`query_events_on`; the bridge itself routes cursors into these two store
functions, so it needs no change.

## EXPLAIN before / after

`EXPLAIN (ANALYZE, BUFFERS)` of the `query_events` page shape, `LIMIT
51`, kind 9, by cursor depth.

Copy of a real channel (2,277 messages), custom plan, shared buffers
hit:

| Depth | Before | After |
| ---: | ---: | ---: |
| 50 | 96 | 96 |
| 300 | 311 | 84 |
| 1,000 | 969 | 80 |
| 1,500 | 1,443 | 92 |
| 2,100 | 2,006 | 89 |

At depth 2,100: execution 0.709 ms to 0.058 ms, rows removed by filter
2,101 to 42. With a generic plan the after numbers are also flat (80 to
96 buffers at every depth).

Synthetic table (one channel with 20,000 kind-9 rows plus 20 other
channels of 2,000 each):

| Query | Depth | Before | After |
| --- | ---: | ---: | ---: |
| `query_events`, custom plan | 10,000 | 701 | 11 |
| `query_events`, generic plan | 50 | 874 (7.5 ms) | 11 (0.11 ms) |
| `query_events`, generic plan | 10,000 | 444 | 11 |
| `get_channel_window`, custom plan | 10,000 | 1,006 (2.35 ms) | 312
(0.49 ms) |
| `get_channel_window`, custom plan | 19,940 | 1,690 (4.35 ms) | 314
(0.47 ms) |

For `get_channel_window` at depth 19,940 the events index scan went from
1,385 buffers and 19,941 rows removed by filter to 9 buffers and 4 rows;
the rest of its plan is the thread metadata join, which is unchanged. On
the small 2,277-row channel the planner picks a sequential or bitmap
scan for the window query, so its plan is unchanged there.

## Tests

New Postgres test
`store::event::postgres_tests::deep_keyset_pages_read_from_the_cursor`:

- Inserts 1,000 kind-9 rows into one channel, two per second, so the
cursor lands on same-second ties.
- Turns off sequential and bitmap scans for the session, so the small
fixture uses the ordered index walk a large channel uses, then reads one
50-row page at depth 900 through both `query_events_on` and
`get_channel_window_on`. It asserts each page equals the expected rows
and that each read touched at most 150 event rows (summed `seq_tup_read
+ idx_tup_fetch` over the `events` partitions).
- Pages the whole channel through both paths and asserts every row comes
back once, in order.

Checked by reverting each half of the fix:

- `event.rs` bound removed: `events page at depth 900 read 950 rows for
50`
- `thread.rs` bound removed: `window page at depth 900 read 1000 rows
for 50`
- With the fix: passes (5 of 5 under `--stress-count 5`), reading 52 and
53 rows.

Runs:

- `scripts/postgres-test-run.sh -p buzz-db --lib --tests`: 763 run, 756
passed. The 7 failures were the new test before its final fixture change
(it now passes) and 6 that fail the same way on unmodified `main` in my
environment because they spawn a host `psql` binary that isn't installed
there:
`migration_schema_media_prebuild_waits_for_old_transactions_during_creation_and_cleanup`,
`script_stops_at_the_first_auth_refusal`,
`script_renames_each_planned_channel_once_whatever_its_name`,
`desired_event_follow_up_contract_app_only`,
`desired_event_follow_up_contract_dual`,
`migration_schema_event_follow_up_contract_app_only`. CI's Postgres lane
is the authoritative run for those.
- On the final head: the new test plus every `channel_window` Postgres
test, 9 of 9 passed.
- `cargo nextest run -p buzz-db --lib` (no infrastructure): 216 passed.
`--test observability_source`: 28 passed. Doc tests: 5 passed.
- `scripts/test-postgres-test-discovery.sh`: passed.
- Pre-push `rust-tests` lane: passed.

## How to test

1. Run `scripts/postgres-test-run.sh -p buzz-db --lib -E
'test(deep_keyset_pages_read_from_the_cursor)'`.
2. Optionally, in a database with a channel of a few thousand messages,
open the channel in a client and scroll back through history. Older
pages should load as quickly as the first ones, and no message should be
skipped or repeated across page boundaries.

## Related

No duplicate PR or issue found. Related: #1787 (keyset index for thread
replies) and #6004 (CLI wiring for the composite cursors).

Signed-off-by: Wes <wesb@block.xyz>
Co-authored-by: Groot <f4c08302591916fb4b80926bf7e18d22eef8aa0c877e4e841acc46405a45700b@buzz.block.builderlab.xyz>
2026-11-18 13:02:31 -05:00
Jemiah Westerman
11970789eb feat(cli)!: consistent channels list/get/search output (type, visibility, labels, real created_at) (#9617)
Closes #6390

## Summary

`buzz channels list`, `get` and `search` each projected kind:39000
channel metadata differently. `list`/`get` dropped the classification
tags, so a script couldn't tell a Solo chat from a stream or a private
channel from an open one. The three commands also disagreed on field
names, defaults and empty values, and `created_at` reported the
last-edit time (#6390).

All three now print one `ChannelSummary`, with `pubkey` added on `get`:

| Field | Source |
|---|---|
| `channel_id`, `name` | `d`, `name` tags |
| `channel_type` | first `t` tag (`stream`, `forum`, `dm`, `workflow`,
`system`) |
| `visibility` | `open` for `["public"]`, `private` for `["private"]` |
| `labels` | the `t` tags after the first, e.g. `["buzz.solo"]` |
| `archived` | `["archived","true"]` |
| `description` | NIP-29 `about` tag |
| `topic`, `purpose`, `ttl_seconds` | `topic`, `purpose`, `ttl` tags |
| `created_at` | the channel's `created_at` tag (NIP-CL), or `null` when
absent |
| `updated_at` | the event's own `created_at`, which is the last
metadata change |

Compact `list` output (`{channel_id, name}`) is unchanged.

### Breaking output changes

These are intentional, and they were discussed with a maintainer before
this change:

- **`search`:** `about` is renamed `description`, matching `list`/`get`
and `create`/`update --description`.
- **`list`/`get`/`search`:** `created_at` is now the real creation time.
The old value, the last-edit time, moves to the new `updated_at`.
- **`list`:** archived channels are hidden by default, as `search`
already did. The new `--include-archived` flag shows them. `get
--channel <id>` still returns an archived channel. `--limit` (and
`--visibility`) count the channels printed: `list` reads past filtered
channels, bounded by `MAX_QUERY_PAGES` on the default path and by 10,000
memberships with `--member`.
- **Missing values:** they print `null` instead of `""`. This mainly
affects `description`.
- **`visibility`:** it prints `open`/`private`, the values
`--visibility` takes, instead of the raw `public` tag. `search` printed
`public` before.

No in-repo consumer reads the renamed fields or the `public` value. The
benchmarks read `search`'s `channel_type`, `visibility == "private"`,
`archived` and `ttl_seconds`, all of which are unchanged.

### Related

- Closes #6390.
- Overlaps with #5664 and draft #6353, which add type and visibility to
`list`/`get`. This PR covers both: it uses `open` like #6353, plus
labels, archived, parity and the `created_at` fix. A maintainer may want
to close them as superseded. Unlike #6353, it doesn't error on missing
or contradictory visibility tags, so one malformed channel can't fail a
whole `list`.

### Testing

- `cargo test -p buzz-cli`: 699 passed. Clippy is clean. The tests build
events from the captured `test-fixtures/solo-creation.json` identity
tags and pin the full JSON shape, including the all-`null` case. They
also cover the production `listed_channels` and `search_matches`
filters: archived hiding, `--visibility`, and search's name and ID
requirement and ordering.
- An agent ran the changed commands against a live relay:
- `get` and `search --exact` return identical fields for the same
channel.
- Over 2,000 channels, `list` hides 162 archived channels unless
`--include-archived` is passed.
  - `--visibility open` returns only `open` channels.
  - 1,777 channels have `created_at < updated_at`.
  - No `description` is `""`.
  - Compact output is unchanged.
- `list --limit 10` and `--member --limit 5` return exactly 10 and 5
non-archived channels, and `--limit 2000` returns 2,000 with none
archived.
- An independent agent review found no blockers. Its one cheap nit,
`get` printing `pubkey: ""`, now prints `null`.
- The pre-push workspace `rust-tests` lane was skipped for this push.
When the push was made, `origin/main` didn't compile `buzz-db`'s lib
tests, which is unrelated to this `crates/buzz-cli`-only diff. That
breakage has since been fixed on main, so CI runs the full workspace.


buzz-review-completed

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

---------

Signed-off-by: Jemiah Westerman <jemiah@squareup.com>
Co-authored-by: Son of Anton <8e0ef2ab02d69a7ac089ef5eca90d1a3fbbdc546f6322dc34d0c4f3deecea7f4@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 09:41:04 -08:00
Luke Tornquist
f04fdef31f ci(docker): publish the push gateway only when its inputs change (#9658)
## Why

Every main push that rebuilds the relay image also published a new push
gateway image. A staging environment that promotes each published
`main-<commit UTC>-<7>` gateway image then rolls out identical gateways.
In one 29-hour window, main got 43 image-eligible commits, and only 2 of
them changed the gateway. The gateway crate depends on no other
workspace crate, so the other 41 images could not differ in behavior.

## What

- New `push-gateway-inputs` job in `docker.yml`. It runs
`scripts/push-gateway-image-inputs-changed.sh`. On a main push, the
script reads the `org.opencontainers.image.revision` label of the
current `ghcr.io/block/buzz-push-gateway:main` image. It then compares
the gateway's build inputs at that revision and at HEAD:
`crates/buzz-push-gateway`, `Cargo.toml`, `Cargo.lock`, `.cargo`,
`rust-toolchain.toml`, `Dockerfile.push-gateway`, `.dockerignore`,
`docker.yml` and the script itself. Every other event prints
`build=true`. The step appends the script's output to `$GITHUB_OUTPUT`,
so a failing check fails the run instead of skipping the build.
- `push-gateway-build` and `push-gateway-personal-dev` run only when
those inputs changed. When the build is skipped, `push-gateway-merge` is
skipped too.
- `push-gateway-merge` now moves `:main` in its own step, after
provenance is attested. The first publication sets every other tag. So
`:main`'s source label always names a completed publication, and a
failed attestation is retried on the next run.
- It compares with the published image, not `github.event.before`. Main
runs share one concurrency group, so a newer push replaces a pending
run, and a failed run publishes nothing. In both cases the next run
still sees the gateway change.
- When in doubt, it builds: an unreadable image, an unknown source, or a
source that isn't an ancestor of HEAD.
- `scripts/test-relay-image-eligibility-workflow.sh` pins the job
gating, the decision step, and `:main` moving after attestation. It runs
the script against a fixture repository with `docker` stubbed:
multi-platform and single-platform `:main` at HEAD, a non-main event, a
lookup failure, relay-only, toolchain-only, a gateway change behind a
later relay-only commit, a missing source, and a non-ancestor source. I
checked that each assertion fails when its production line is broken.

## Risk

- A base image update (`rust`, `debian:bookworm-slim`) alone no longer
publishes a new gateway image. The next gateway input change picks it
up. A manual dispatch at a `relay-v*` tag still builds.
- `:main` now moves a few seconds after the other tags on main pushes.
Deployments that follow `main-<commit UTC>-<7>` are unaffected.
- The relay image and its triggers are unchanged.

## Simpler

There are fewer published gateway images, and every one of them changes
the gateway. No new configuration.

## Testing

- `scripts/test-relay-image-eligibility-workflow.sh` passes locally.
Mutations of the script and the job gating fail it.
- `actionlint .github/workflows/docker.yml` passes.
- Checked locally that the `docker buildx imagetools inspect … --format
'{{json .Image}}'` + `jq` read returns the current `:main` gateway
source revision.

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

---------

Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 12:17:56 -05:00
Tom Brow
3689241672 feat(mobile): reply to a message from its iOS notification (#9439)
On iOS, a notification that shows a channel or DM message now offers
**Reply**. The user types a reply in the notification and sends it
without opening the app.

- The reply goes in a subthread under the notified message (its thread
root is the message's own root, or the message itself when top-level). A
Solo chat takes no thread replies, so there it goes at the chat's top
level.
- It always mentions the notified message's sender, so the person or
agent being answered is notified. Typed `@name` text stays plain, since
a notification has no mention autocomplete.
- It is sent by the app's own send path. iOS starts the Flutter engine
when it wakes the app in the background, and the reply reopens the relay
connection (closed after the background grace period), waiting a bounded
time for it before sending.
- A sent reply marks the conversation read **up to the notified
message** (newer messages stay unread) and clears that notification and
earlier ones from the same conversation.
- An unsent reply (offline, relay error, timeout, a channel the user
isn't in) keeps the typed text as a draft, after any draft already
there, and shows a "Reply not sent" notification that opens the
conversation.

For now only notifications from the community selected in the app offer
Reply: replying must not switch communities, and the app can only reach
the selected one. Forum posts and fallback notifications that show no
message offer none. The design and the options considered are in
`docs/adr/0004-notification-reply.md`.

### Before / after

Long-pressing a message notification (synthetic names and text). Before
has no reply field (captured by sending the notification without its new
reply category, which is how main presents it); after shows one with
Send.

| Before | After |
| --- | --- |
|
![before](https://raw.githubusercontent.com/block/buzz/df800599173cf3436af4d2c738447396a632fac7/pr-9439--before.png)
|
![after](https://raw.githubusercontent.com/block/buzz/df800599173cf3436af4d2c738447396a632fac7/pr-9439--after.png)
|

### Demo

With the app backgrounded past the relay grace period, replying from the
notification lands the reply in a subthread under the message:


https://github.com/user-attachments/assets/37df7e28-aa46-4521-938e-8af5faa77b83

### Regressions

Nothing existing changes unless the user taps Reply. Notifications gain
a category and a small reply context in `userInfo`; tapping a
notification still opens the conversation as before. The relay reconnect
only happens for a pending reply and then falls back to the normal
background disconnect, so idle background behavior and network use are
unchanged. Reply failures end in a draft and a "Reply not sent"
notification rather than touching other state.

### Validation

- End to end on an iOS 27 simulator against a real community: with the
app backgrounded past the relay grace period, replied from the
notification; the reply appeared in a subthread under the message,
mentioning its sender. The demo above was recorded before the review
fixes (session hold, community fence, origin-community drafts, composer
draft sync); the same run was repeated on the current head, 9b9c8b0, and
the reply again appeared in the subthread with no "Reply not sent"
notification.
- Human testing is waived for this repo's mobile client; the simulator
run above replaces it. Not yet exercised on a physical device or on a
cold launch (app not running).
- Added tests: a Dart journey covering top-level, in-thread and Solo
replies, another community (draft kept in that community), a failed
send, a channel the user isn't in (draft appended), a reply arriving
while running, an unreachable relay, and a community switch while
connecting (not sent, draft kept in the reply's community); a
relay-session test that a background-work hold keeps the grace
disconnect off, including one already waiting on cleanup, until released
or its limit; a composer step showing a draft appended elsewhere appears
in the mounted composer and survives its next edit; a relay-session test
for reconnecting a paused session and timing out (fails without the
fix); Swift tests for reply context encoding, NIP-10 root parsing
aligned with the app, and request validation.
- `relay_session.dart` was at its 1200-line cap, so the background
connect lives in a new part file and three existing test hooks moved
unchanged into another.
- Full `mobile-test`, `mobile-check` and BuzzPushKit `swift test` pass.

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-18 16:15:28 +00:00
Tom Brow
a5b3dbc00d fix(mobile): stop reporting saved images as failed on iOS (#9599)
On iOS, **Save image** in the image viewer reported a failure for a save
that worked. It asks only for permission to add photos. With that
permission the image landed in Photos, but the app showed "Could not
save image" and iOS then asked for full library access. After choosing
**Keep Add Only**, every later save did the same: saved, and reported as
failed.

Now the save reports what actually happened, and add-only permission is
all it needs, so iOS never asks for full access.

| Before | After |
| --- | --- |
| <img
src="https://github.com/user-attachments/assets/5926b595-6a2d-4382-83e5-89329c009159"
alt="Before: full access prompt over a &quot;Could not save image&quot;
message" width="300"> | <img
src="https://github.com/user-attachments/assets/3b797c3e-43c4-4766-950b-8bef415ae2e0"
alt="After: &quot;Saved to Photos&quot; message" width="300"> |

Before:


https://github.com/user-attachments/assets/e4f88b29-cabc-4c43-9967-d8481e434551

After:


https://github.com/user-attachments/assets/ca3631a5-c988-4082-898a-426867788051

### Cause

`photo_manager`'s `saveImage` returns the saved asset, so its iOS code
fetches the new asset back after writing it. PhotoKit does not let an
add-only app fetch assets: the fetch makes iOS show the full-access
prompt and comes back empty, and the plugin reports an error for a write
that succeeded. The latest release (3.12.0) has the same code.

On iOS the image is now written by a small native saver
(`PhotoLibrarySaver`) that creates the asset and reports the result of
that write, without reading the library. Android keeps using
`photo_manager`, and the permission request is unchanged on both
platforms.

### Regressions

None expected.

- The write is the same PhotoKit creation request the plugin made, with
the same original filename, so saved images are unchanged.
- Real failures still show "Could not save image": a denied permission,
a failed download and a failed write all still surface.
- Android and the rest of the app's photo library use (the composer's
photo picker) are untouched.

### Validation

- Added test: the image actions journey saves on iOS with a photo
library that grants add-only access and rejects every read, and expects
"Saved to Photos", one write with the downloaded bytes and filename, and
an add-only permission request. A failed write then shows "Could not
save image". It fails without the fix.
- Full mobile suite and the iOS Runner unit tests pass.
- Full-app run on an iOS 27 simulator, on a fresh install with no photo
permission, comparing this branch with unmodified `main`:
- `main`: first save adds the image, shows "Could not save image" and
the full-access prompt; a second save after **Keep Add Only** adds
another copy and shows the error again.
- This branch: first and second saves each add one image and show "Saved
to Photos", with no full-access prompt, and only add permission is
granted afterwards.
- This branch, other paths: **Don't Allow** shows "Could not save image"
and saves nothing; saving with full access already granted works;
**Share image** still opens the share sheet.
- Not covered: a physical device, and Android (its code path is
unchanged).

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: judge <7615ec4b7ddf99f0bb48e913297f99f8f772d289a1c9ef54e1d906dd55a93ba8@buzz.block.builderlab.xyz>
2026-11-18 07:17:27 -08:00
Sanket Kanjalkar
493cb4cc13 perf(db): stop per-id planning of wide #e reads (#9591)
Thread pages fetch the reactions, edits and deletions of ~200 ids at
once. Until a pooled connection has run that `#e` read about five times,
Postgres plans it with the values: ~12 ms per plan (one estimate per id
per partition) against ~2 ms to run it.
Past 8 ids the arrays now go through a scalar subquery, so planning is
one estimate (~1.5 ms) and still uses the tags GIN index; narrower reads
are unchanged.
On an 830-reply local thread, one viewer's full scan drops from 119 to
59 ms p50; with 50 viewers p50 holds at 242 ms, p99 drops from 664 to
413 ms, and the read's planning time falls from 13 s to 0.6 s per
minute.

---------

Signed-off-by: Sanket Kanjalkar <sanketk@squareup.com>
2026-11-17 22:47:57 -08:00
Helen Tian
bc3afbb293 [buzz] fix(ci): link relay image indexes to their source (#9637)
The relay image index includes the qualified Git revision. Add the
source repository URL beside it so OCI registry clients and deployment
tools can link the image to the exact source commit.

The manifest assembly step derives the URL from GitHub Actions' server
and repository variables. The release workflow contract checks that the
index includes both the source and revision annotations.

Signed-off-by: Helen Tian <htian@squareup.com>
2026-11-18 14:41:24 +11:00
Tom Brow
25b58ab98f feat(push-gateway): verify Android Key Attestation (#9562)
## What and why

Ticket 3 of the Android push plan ([design PR
#9555](https://github.com/block/buzz/pull/9555)). The gateway now
verifies Android Key Attestation at enrollment instead of rejecting
every Android chain, and rate limits signed installation calls per
attested key.

Stacked on [#9560](https://github.com/block/buzz/pull/9560) (Android
enrollment and FCM wakes). This PR's base is that branch; it will be
retargeted once that merges.

- **Chain.** It must end at a configured Google attestation root
(Google's [published hardware
roots](https://developer.android.com/privacy-and-security/security-key-attestation#root_certificate)
are built in, pinned by public key), with valid signatures and issuer
links, CA issuers above the attestation key certificate, and no SHA-1
signatures. The attestation key certificate itself is exempt from the CA
flags, because some factory keyboxes issue it with CA:FALSE and
digitalSignature only (Google's Sony Xperia 10 III sample); a Keystore
leaf still cannot act as an issuer, since the extension is refused above
the leaf. Validity is enforced for Remote Key Provisioning chains;
Google tells verifiers to keep trusting the long-expired factory chains,
which the revocation list covers instead. The attestation extension must
be in the leaf and nowhere else. The leaf key must be EC P-256; it
becomes the installation's signing key.
- **KeyDescription.** Attestation and KeyMint security levels must be
TrustedEnvironment or StrongBox. The challenge must equal SHA-256 of the
enrollment transcript. Key properties (generated, EC, P-256, sign-only)
and the root of trust come only from the hardware-enforced list. The
bootloader must be locked, and the boot state Verified, or SelfSigned
with a verified boot key on an operator-configured list. The application
id (the one software-enforced value) must name exactly the configured
package with a configured signing digest.
- **Revocation.** A background task fetches Google's status list at
startup and then on its cache lifetime (5 minutes to 1 day), with a 30
second timeout, an 8 MiB size cap, capped exponential backoff and
jitter. Any REVOKED or SUSPENDED serial in the chain is rejected. With
no list yet, or a list older than the grace period, enrollment fails
closed. Enrollment reads an in-memory snapshot and never waits on a
fetch.
- **Rate limit.** Signed installation calls (delegate, revoke
delegation, rotate endpoint, revoke installation, on both platforms) are
limited per attested key. A call is counted only after its signature
verifies, so forged requests cannot spend another installation's
allowance. Counters are in memory per replica, bounded to 100,000 keys.
- **Dependencies.** None added. `x509-parser` gains its `verify-aws`
feature, which uses the `aws-lc-rs` the crate already depends on.

## Configuration

All optional; Android stays off unless the ticket 2 settings are
present. Documented in `docs/push-gateway-deployment.md` and
`.env.example` with example values only, and passed through
`deploy/charts/buzz-push-gateway` (disabled by default, schema-checked,
covered by `tests/runtime-options.sh`).

- `BUZZ_PUSH_ANDROID_BOOT_KEY_DIGESTS`: SHA-256 digests of verified boot
keys accepted with a SelfSigned boot state. Empty by default, so a
default gateway accepts stock Android only.
- `BUZZ_PUSH_ANDROID_ATTESTATION_ROOTS_PATH`: PEM bundle replacing the
built-in roots, for a reviewed root rollout. In the chart,
`android.attestationRoots.secretName` and `secretKey` mount it from a
Secret; an empty name keeps the built-in roots.
- `BUZZ_PUSH_ANDROID_REVOCATION_GRACE_SECONDS`: default 604800 (7 days),
minimum 3600.
- `BUZZ_PUSH_SIGNED_CALL_WINDOW_SECONDS` and
`BUZZ_PUSH_SIGNED_CALL_MAX_CALLS`: defaults 60 and 30.

## Tests

- `cargo test -p buzz-push-gateway` (all pass, 18 ignored), `cargo fmt
--all --check`, `cargo clippy -p buzz-push-gateway --all-targets -- -D
warnings`, and the chart tests (`render.sh`, `release-contract.sh`).
- Key Attestation chains are generated in the tests with a test root
injected as the configured root, and run through the production
verifier. One table rejects: unlocked bootloader, Unverified, Failed,
SelfSigned with an unlisted key, boot key only in the software list (two
variants), key properties only in the software list, extra key purposes,
wrong curve, wrong package, two packages, wrong signing digest, wrong
challenge, software-backed key (two variants), unknown root, forged leaf
signature, expired provisioned intermediate, extension repeated above
the leaf, non-P-256 leaf, a CA:FALSE certificate issuing the attestation
key certificate. Another accepts Verified with any boot key, SelfSigned
with a listed key, StrongBox and TrustedEnvironment, an expired factory
intermediate, and a CA:FALSE, digitalSignature attestation key
certificate. Revoked leaf, intermediate and root, a missing list and a
stale list are rejected. The status list parser and refresh (backoff,
cap, keeping the last list through failures) run against a scripted fake
source; no test touches the network.
- The per-key rate limit runs through the public router: forged calls do
not spend the allowance, the fourth authentic call is refused whatever
its kind, and another installation is unaffected.
- Break check: disabling the locked-bootloader guard and the rate limit
turned `rejected_attestations` and the rate limit test red; restored.

## Not here

The app side (ticket 7) generates the Keystore key and sends the chain.
The end to end run on a physical Android phone against a test gateway is
also still to do.

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
2026-11-17 19:18:35 -08:00
Will Pfleger
b769d5bee8 fix(relay): remove an owner's agents with the owner (#9575)
## What this changes

When someone is removed from a community, their agents' live sessions
already closed, but the agents kept their own membership rows and could
reconnect as members. This PR removes those agents with their owner.

- **Cascade.** `delete_member_with_acceptances` locks and deletes the
target, then locks and deletes the `join_policy_acceptances` and
`relay_members` rows of every member of the same community whose
`users.agent_owner_pubkey` is the target and whose role is not `owner`.
All of it runs in the same transaction, before the roster snapshot is
written. Admin removal (kind 9031), self-leave and `buzz-admin
remove-member` all go through it. An agent goes with its owner whatever
its role, so an admin who removes a member also removes that member's
admin-role agent. A direct 9031 target is still limited to `member` for
admins.
- **Owner recording.** The relay records a verified NIP-OA owner on
every admitted sign-in, whatever the relay mode or `allow_nip_oa_auth`:
on WebSocket AUTH, and for HTTP in the shared admission step after the
denial checks, so `/events`, `/query`, `/count` and member POSTs all
record it in one place. Before, it recorded only on open relays, so on
closed relays the cascade and owner bans missed agents added directly. A
request refused before recording writes nothing. Once the owner-signed
tag is verified and the first admission checks pass, the relay may
record the owner even if a final check, a cancellation or a token
revocation then refuses the sign-in. The record still can't be changed.
Over HTTP, a different stored owner refuses the request with 403 (invite
creation keeps its `invite_owner_mismatch` code), and storage trouble
refuses it with 503. A recorded owner can also manage the agent (channel
management, channel-add policy, invites).
- **CLI.** `buzz-admin remove-member` publishes clusterwide disconnects
(`ConnControl::DisconnectPubkey`) for the target and its recorded agents
on every run, including when the member is already gone. If publication
fails or no relay server is subscribed, it exits 6 after the removal
commits. Rerunning the same command retries the disconnect.
- **Spec.** NIP-FI states the rule.

## Rollout limit

An agent is covered only if its owner was recorded before the owner is
removed. An agent whose owner was removed before the agent signed in
with a NIP-OA tag after deploy, or an agent that never signs in with
one, stays a member and needs a manual removal. The relay holds no proof
of ownership for those agents, so there is nothing to backfill.

Supersedes #6098 and #6078.

---------

Signed-off-by: Will Pfleger <wpfleger@block.xyz>
Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
2026-11-17 20:35:33 -05:00
Logan Johnson
4bf7d8a9b0 relay: refuse a reaction or deletion whose h names another channel (#9006)
## Summary

A reaction, or a deletion that targets a message, belongs to the target
message's channel. The relay works out that channel from the target and
stores the event there. But every read and every live delivery matches
the event's own channel (`h`) tags. So if a client puts a *different*
channel in the `h` tag, the event is stored in one channel and only ever
matches another:

- No one ever receives it.
- It still takes a slot when a client asks for "the latest N events" of
the real channel. A catch-up can then return fewer events than exist
while it looks complete, because the relay removes the stray event after
it applies the limit. This is one of the known gaps in
https://github.com/block/buzz-app/pull/2206.

The relay now refuses such an event. The rule:

| Event's `h` tags | Before | After |
|---|---|---|
| none | accepted | accepted |
| include the target's channel | accepted | accepted |
| only other channels | accepted, never delivered | refused |

The refusal uses the same "target not found" text as the existing
refusals for these kinds. So it tells the sender nothing about where the
target is.

No first-party client sends a mismatched `h`. buzz-app uses the target
message's channel, and desktop, mobile and the SDK send no `h` on
reactions. So no current client is affected.

### Details

- The check covers kind:7 reactions and kind:5 deletions that name their
target with an `e` tag. These are the two kinds whose channel comes from
a target. A kind:5 that names an addressable event (`a` tag) is not
affected.
- The check runs only when the target is in a channel, so a reaction to
a global event keeps any `h`. A tag must be the channel's UUID exactly
as the relay writes it (lowercase, hyphenated), the same way `#h`
filters match.
- The check runs after the token, membership and archive checks. If it
ran first, it would skip their database reads, and the response time
could tell someone who cannot read a private channel whether a guessed
`h` names the channel that holds a message.
- Events already stored with a stray `h` are not changed. They can still
take a slot under the limit.
- NOSTR.md now says that an optional `#h` on these kinds must name the
target's channel. It also says kind:5 takes its channel from its `#e`
target (the old text said it used `#h`).

### Related issue
None found. Follow-up to the known gaps listed in
https://github.com/block/buzz-app/pull/2206.

### Testing
- New `reaction_and_deletion_h_must_name_the_target_channel` test, as a
member of the target's channel. A reaction whose `h` names only another
channel is refused and not stored. A reaction with no `h`, or with both
channels, is accepted, and so is a reaction with any `h` on a global
event. A deletion of that reaction is refused and not stored with
another channel's `h`. It is accepted with the target's `h` or with no
`h`. A non-member's wrong guess still reaches the membership check. On a
private channel, a right guess and a wrong guess both end at the same
membership denial.
- I removed the check, and the test failed. I also moved it back before
the membership check, and the test failed.
- On a local relay over WebSocket: the same refusals and acceptances,
with the same messages, and a reaction to a global event keeps its `h`.

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



Human test: Logan asked to take this to team review without a separate
hand test (2026-11-17).

buzz-review-completed

Signed-off-by: Logan Johnson <loganj@squareup.com>
Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
2026-11-17 20:03:02 -05:00
Luke Tornquist
3876720c34 buzz-db: drop the five single-table guard triggers (BUZZ-318 phase 2) (#9398)
> [!NOTE]
> **Rollout:** #8320 (app guards + catalog expand) is deployed, so the
hold is lifted. With `autoMigrate=true`, `0096` runs at startup under a
5s lock timeout, and a failure stops startup. With
`BUZZ_AUTO_MIGRATE=false`, deploy this binary first and then run
`buzz-admin migrate`. Both orders are safe because the expand tolerates
the objects being present or absent.

## What

The required stop for `0096` is in
`docs/trigger-retirement-deployment.md` (from #9622): a relay build at
or after #8320 (`ec778bff`). A build older than that needs the tombstone
trigger at startup and readiness.

Migration `0096_drop_single_table_guards.sql` drops five triggers and
their functions. #8320 moved each invariant into the application
writers:

| Trigger (table) | Function |
|---|---|
| `trg_channels_community_id_immutable` (channels) |
`channels_community_id_immutable()` |
| `communities_deletion_tombstone` (communities) |
`enforce_community_tombstone()` |
| `community_deletion_request_retargeting_guard`
(community_deletion_requests) |
`prevent_community_deletion_request_retargeting()` |
| `community_deletion_approval_removal_guard`
(community_deletion_approvals) |
`prevent_community_deletion_approval_removal()` |
| `community_deletion_manifest_keys_guard`
(community_deletion_manifest_keys) |
`protect_community_deletion_manifest_keys()` |

Desired state (`schema/`) drops the five functions and four trigger
files, plus the channels trigger declaration. The universal write fence
on `channels` stays. Both boot paths stay catalog-equivalent: the
pgschema-vs-migration parity check now also compares columns, key and FK
shapes, and the remaining triggers on all five tables.

Executor GUCs stay because `assert_community_write_allowed` still reads
them through the universal write fence. `transition_community` and every
phase-1 app guard are byte-identical to #8320.
`scripts/reconcile-schema-after-pgschema.sql` has no entries for these
objects.

## Tests

- #8320's six `single_table_guard_*_without_trigger` PG tests no longer
need to disable a trigger. They are now plain app-path tests with the
same assertions.
- New per-test regressions for the desired-template and migration boot
paths assert that none of the ten objects exist, including disabled
triggers and function overloads.
- Deleted assertions that only exercised raw SQL against the triggers:
retarget, rewrite and approval mutation, frozen-manifest rewrite, and
tombstone DELETE. The app-path coverage for each remains.
- The expand regression in #8320 migrates through `0086`, validates
serving, readiness and the deletion lifecycle, drops the five guards,
then validates again.
- Rebased onto main `b568d9bf` after #8696 took `0095`; renumbered to
`0096`. Blox gate at `7bda1f45`: fmt, clippy and buzz-db `--lib` pass;
the PostgreSQL lane ran 219 tests, all pass.
- Gate at `c8bc061c` (on main `051dd2d7`, then numbered `0095`, #9622
folded in): on Blox, `cargo fmt --check`, clippy and the buzz-db `--lib`
tests pass. The PostgreSQL lane (migrations, single-table guards, floor
retirement, fence and deletion) ran 208 tests: all pass.
- Earlier gate at `0840ba49`: CI was green, and the Blox PostgreSQL lane
passed 840 of 841 (the one failure, `media_reference_full_query_plans`,
is a timing check that fails the same way on main on that host).
- The rebase updates main's fence-retirement tests to expect the
tombstone trigger gone.

## What got simpler

Ten database behavior objects and nine desired-state files are gone
(about 150 lines). Each rule has a single owner, the application writer.

buzz-review-completed

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

---------

Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-17 22:30:49 +00:00
Luke Tornquist
44cdd9feef push-gateway: lock expired installations before reaping (#9627)
## What

The push gateway reaper deletes expired delegations and then expired
installations in two statements. A delegation writer
(`upsert_delegation`) that holds the installation lock can commit a new
child between them. With the foreign key, the installation delete then
fails, and the reap transaction rolls back.

This PR locks the expired installations with `FOR UPDATE` first, as
every authority mutation does. It then deletes their delegations and the
installations by id. A writer that was holding the lock commits first,
and the delete sees its child. A later writer finds the parent gone and
is rejected.

No schema change. This is the code half of #9610. The gateway image with
this change must run everywhere before the delegation foreign key is
dropped.

## Tests

Blox at `20b66f8f`: fmt, clippy, and the push-gateway PostgreSQL tests
(15/15) pass.

- `reaper_deletes_delegation_committed_while_it_waits`: a writer holds
the installation lock and inserts a child. The reaper starts and waits.
The writer commits. The reaper deletes both rows.
- `delegation_for_missing_installation_is_rejected`: `upsert_delegation`
for an unknown installation returns `Rejected` and writes nothing.

## What got simpler

The reaper now uses the same lock order as every other authority write.
The child delete no longer needs a correlated subquery.

buzz-review-completed

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

Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:17:57 -05:00
Logan Johnson
b568d9bf95 Retire the 0032 roster trigger in migration 0095 (#8696)
## Summary
Migration 0095 drops the 0032 channel roster trigger
(`trg_events_guard_channel_roster_snapshot`) and its function
(`guard_channel_roster_snapshot()`).

The trigger repeats a check that the relay already does in Rust. Every
kind:39002 roster writer checks the roster against the channel's
membership before it saves it (#8316). Since #8611, no relay requires
the trigger at startup. This PR is the last step of the trigger
retirement sequence in `docs/database.md`.

This PR was split out of #8494 so the migration can roll out by itself.
A relay from this PR does not change how it stores or publishes roles,
and it has no new startup check. It serves correctly whether or not 0095
has run. #8494 stacks on this PR and must not merge until 0095 has run
in every environment.

## Details
- **Migration 0095.** `DROP TRIGGER` and `DROP FUNCTION`, with
`lock_timeout = '1s'` and `statement_timeout = '5s'` as in 0049. `DROP
TRIGGER` takes `ACCESS EXCLUSIVE` on each `events` partition in turn, so
event reads and writes block while it runs. A timeout rolls it back with
no change, and it can be retried.
- **Desired-state schema.**
`schema/functions/guard_channel_roster_snapshot.sql` is removed. This
was the last trigger on `events`, so `schema/triggers/events.sql` and
its include go too, as do the pre-attach trigger drops in
`scripts/reconcile-schema-after-pgschema.sql`.
- **Operator guide.** #8326 added
`docs/trigger-retirement-deployment.md` for migrations 0089–0091. (0092
from #9365 and 0093 from #9560 drop nothing; 0094 from #9598 drops two
plain SQL functions and has its own section there.) This PR adds 0095 to
it: its row, the two ways an older relay fails, the migrate check, and
the parent trigger a pgschema deployment must drop first. The Helm chart
README names the required stop and points to that guide.
- **Tests.** Tests that compared the trigger with the Rust check, or
that disabled the trigger first, now test the Rust check alone. Tests
that only exercised the trigger against a simulated pre-#8316 writer are
removed. The 0075 invite upgrade test now migrates to 0075 exactly.

## Rollout
**Required stop: the stop build in
`docs/trigger-retirement-deployment.md`** (a relay build at or after
`68785206`, the merge of #8325). That build contains #8316 (the app-side
roster check) and #8611 (no startup trigger check), so it covers 0095
too. `relay-v0.3.0` contains #8316 and #8611 but not #8325, so it is no
longer enough on its own: any build with 0095 also has 0089–0091.
Without the stop, an untagged `main` build between 0032 and #8611
refuses to start once the trigger is gone, and a relay without #8316 can
save stale kind:39002 snapshots (`docs/database.md` Rule 5).

**Merge gate.** Every push to main publishes relay `:main` images, and
the Helm chart defaults to `migrate.autoMigrate=true`. Do not merge this
PR until the stop build or later runs on every serving and rollback
target. That is the same gate #8326 had for 0089–0091.

After that, either way works:
- With `autoMigrate=true`, the first relay from this PR applies 0095 at
startup.
- With `autoMigrate=false`, run `buzz-admin migrate` when convenient.
Relays from this PR serve with or without 0095.

As with every new migration, an older binary with auto-migration on
refuses a database that has 0095 (sqlx `VersionMissing`). A rollback
past this release needs auto-migration off (`docs/database.md`).

## What happens next
#8494 computes the `member`/`bot` label at read time. The 0032 trigger
compares labels with the stored role exactly, so it would refuse those
rosters. #8494 adds a startup check that refuses to serve while the
trigger is installed. Merge it only after 0095 has run everywhere.

### Testing
- `migration_0095_retires_the_roster_trigger`: on a database migrated
through 0094, the trigger and function are installed. After the
remaining migrations, both are gone, and a raw kind:39002 insert that
does not match membership is accepted. It fails if 0095 does not drop
them.
- `embedded_migrator_contains_consolidated_initial_schema` pins 95
migrations and the 0095 statements, and checks that the desired-state
schema no longer installs the function.
-
`migration_schema_desired_pgschema_reconcile_matches_populated_upgrade`:
its fixture drops each retired parent trigger before pgschema runs
(pgschema drops partition copies before the parent, which PostgreSQL
refuses with 2BP01). It now drops the roster trigger too.
- Locally at this head: `cargo check`, `cargo fmt --check`, and 245/245
buzz-db unit tests pass; 760/764 buzz-db Postgres tests pass. The four
`event_follow_up_contract` tests fail the same way on `main` locally and
pass in CI. CI runs clippy and the full PostgreSQL lane.

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

---------

Signed-off-by: Logan Johnson <loganj@squareup.com>
Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:56:50 -05:00
Ian Oberst
c01d3292a1 fix(db): hard-delete superseded relay-signed lists (#9586)
## Why

The relay republishes its own lists in full on every change:
- the NIP-43 membership list (kind 13534)
- the NIP-IA archived list (13535)
- NIP-29 group state (39000 metadata, 39001 admins, 39002 members)

Each write soft-deletes the previous head. No reader returns a
soft-deleted row, so each retired copy is dead weight in `events` and
its indexes. On the deployments we measured, these retired copies are
about 40–65% of monthly `events` growth. The NIP-33 path already
hard-deletes superseded NIP-RS read state and mesh status in the
replacing transaction. This PR applies the same rule to the relay-owned
lists.

## What

When a write supersedes a head of kind 13534, 13535, 39000, 39001, or
39002, it deletes the old head instead of soft-deleting it. The delete
runs in the same transaction, under the same scope and lock as before.
The change applies on the 3 paths the relay uses to write these kinds:

- `replace_addressable_event_under_lock` (13535, 39000, 39001, including
`buzz-admin` writes through `replace_addressable_event`). It gates on
the new `hard_deletes_superseded(kind)`. Other kinds on this path (0, 3,
10002, …) keep the soft delete.
- `LockedMemberSnapshot::replace_member_event` (39002).
- `write_nip43_membership_snapshot` (13534).

All 3 paths build their head read and supersede statement with one
function, `replacement_sql(in_channel, hard_delete)`, keyed by
`hard_deletes_superseded(kind)`.

Kind 13535 is now relay-only: ingest rejects a client-submitted 13535
with `restricted: relay-only kind`, as it already does for 13534. NIP-IA
defines 13535 as relay-signed, and every relay, desktop, CLI, and mobile
reader filters on the relay's pubkey. No client in this repository
publishes it.

The 39000–39002 paths already use `superseded_with_mentions_sql!`, so
the old head's mention rows are deleted with it, as before.

The gate checks the kind, not the signer, and every supersede is scoped
to the event's own pubkey. A client-signed 39000–39002 is routed to the
NIP-33 path, which keeps the soft delete. Channel deletion
(`soft_delete_discovery_events`) retires the live heads without a
replacement and still soft-deletes them.

This PR has no migration and no schema change.

## Why this is safe

- **Readers:** relay reads of these kinds filter on `deleted_at IS
NULL`, so a retired head was already invisible. One reader includes
soft-deleted rows: the admin event preview (`get_event_preview`). It
will now report a superseded roster id as absent instead of deleted. A
moderation report against an old version of a channel's metadata (for
example, a name it had before a rename) will show no target content. An
operator can no longer look up an old roster or membership list by id to
audit past membership. `docs/admin/README.md` now documents this for
`GET /api/admin/v1/events/{id}`.
- **Operator repair:** when `buzz-admin`'s group-state reconcile
overwrites a 39000–39002 head, the old row is gone, so an operator can
no longer restore it with `UPDATE … SET deleted_at = NULL`. The relay
rebuilds these lists from `channels` and `channel_members`, so no source
data is lost.
- **Replays:** while the coordinate has a live head, a replay of a
deleted head's id is still rejected, because its `created_at` does not
beat the live head's. With no live head (after channel deletion, for
example), the deleted row no longer makes the replay a duplicate. Only
the relay can submit these events: ingest requires the event's signer to
be the authenticated pubkey, 13534 is relay-only, and the relay's
writers sign a new event on every attempt. The existing tests for
soft-deleted replays seed their own rows and do not change.
- **13534 id uniqueness:** the writer still takes `max(created_at)` over
every stored list. The live head is always the newest, so the next
list's `created_at` still moves past every earlier one.
- **13535 strict stamps (NIP-IA, #9476):** each new archived list is
stamped past the live head, which the writer reads behind the
replacement lock. It never reads retired rows, so deleting them does not
change the next `created_at`.
- **Database objects:** no foreign key references `events`, and none of
these kinds is a push kind. The DELETE runs in the same admitted
community write transaction as the old UPDATE. The only trigger left on
`events` is the BEFORE INSERT kind 39002 roster guard
(`guard_channel_roster_snapshot`), and a DELETE does not fire it.
- **Rolling deploy (docs/database.md Rule 7):** old pods keep
soft-deleting and new pods delete. Both leave exactly one live head per
coordinate, under the same locks.

## Follow-up

Rows that are already soft-deleted stay. Rule 3 does not allow a
migration to delete them. A separate PR will add a
`scripts/maintenance/` repair script: bounded batches, the
community-deletion lock, and a validation query. An operator runs it
after this change is fully rolled out.

Not in this PR: the relay-signed NIP-DV DM visibility snapshot (kind
30622, `publish_dm_visibility_snapshot`) is written on the NIP-33 path
and still soft-deletes its superseded heads. We will measure its share
of `events` growth before we change it.

## QA focus

- **Each roster write keeps exactly one stored row.** Create a channel,
then add and remove members, change roles, and edit the metadata. For
each of 39000, 39001, and 39002, the channel must have exactly one
`events` row (live), not one live row plus retired ones. Do the same for
13534 (relay membership add, remove, and role change) and 13535 (`agents
archive` and unarchive).
- **Other kinds still soft-delete.** Replace a kind 0 profile or kind 3
contact list. The old row must stay, with `deleted_at` set.
- **Mention rows.** After a 39002 or 13535 replacement, `event_mentions`
has no rows for the deleted head's id.
- **Admin event preview.** Opening the id of a replaced roster now shows
the event as absent instead of deleted. Check that this is acceptable in
the admin UI, including a report filed against a channel's metadata
before a rename.
- **13535 `since` cache.** Archive and unarchive several times,
including at the same time. Each new list has a `created_at` later than
the one before. A mobile client that asks `since` its list's
`created_at` + 1 gets the newer list.
- **Client 13535 is rejected.** Publishing a kind 13535 signed by a user
key returns `restricted: relay-only kind`. Archive and unarchive (kinds
9035 and 9036) still work, and the relay still publishes its own 13535.
- **Channel deletion.** Deleting a channel still soft-deletes its live
39000–39002 heads. This path is unchanged.
- **Mixed-version rollout.** With an old and a new relay on one
database, each coordinate keeps exactly one live head. Rows that old
pods soft-deleted stay until the follow-up script runs.
- **Existing soft-deleted rows are not touched.** The disk-space gain
shows only in growth after deploy. The follow-up script cleans up the
backlog.

## Tests

- `only_relay_owned_lists_hard_delete_their_superseded_heads`: checks
the kind set, including the neighbours 13533, 13536, 38999, and 39003,
and negative kinds.
- `superseded_heads_drop_their_mention_rows` (Postgres) now expects the
old head to be gone for the 39002 member snapshot, 13535 (global), and
39000 (in a channel). A kind 3 contact list on the same addressable path
is the control: it must stay soft-deleted.
- `replacement_channel_predicate_is_an_index_condition` (Postgres) now
builds its statements with `replacement_sql`, the same function
production uses, for all 4 scope and retire-mode combinations. Before,
it checked hand-copied SQL. It checks that each `DELETE` seeks by
`channel_id` on every populated partition, as the `UPDATE` does.
- The 39002 and 13534 writers take their statements from
`replacement_sql` and `hard_deletes_superseded`, so the index-condition
test covers each statement production runs.
- `nip_ia_archived_list_is_relay_only` (buzz-core): 13535 is relay-only,
and the 9035 and 9036 requests are not.
- `test_client_submitted_nip_ia_archive_snapshots_are_rejected`
(buzz-test-client e2e, against a running relay): a client-signed 13535
is rejected with `restricted: relay-only kind` over both WebSocket and
HTTP. It shares a helper with the existing 13534 test. Against a relay
built without the 13535 gate, it fails at the WebSocket assertion. The
Relay E2E step in `.github/workflows/_ci-relay.yml` now selects it, next
to the 13534 test.
- `late_owner_link_closes_ownerless_agent_sockets_on_owner_revoke`
(buzz-relay, Postgres) copies selected tables into a private schema. The
13534 writer's supersede now also deletes the old list's
`event_mentions` rows, so the fixture copies `event_mentions` too.
- `every_membership_write_commits_its_list` (Postgres): after each
membership writer runs, the community stores exactly one kind 13534 row.
- `concurrent_archival_publishers_stamp_strictly_increasing_snapshots`
(buzz-relay, Postgres, from #9476) counted the 16 stored kind 13535
rows, superseded ones included. It now pins the head an hour ahead and
asserts that the coordinate stores exactly one row, at the pinned
`created_at` + 16 s. That holds only if each of the 16 publishers stored
exactly one snapshot, one second past the head it replaced. A
same-second replacement leaves the row short of + 16 s, and a publisher
that runs out of attempts still fails its `expect`.
- `a_publisher_that_read_before_an_edit_cannot_replace_it` (buzz-relay,
Postgres) counted retired kind 39000 rows to prove that each publisher
stores a new second. It now asserts that the coordinate stores exactly
one row, at the pinned `created_at` + 2 s. The mutation it guards
against (taking the live `created_at` before the lock) leaves the head
at + 1 s, so the test still catches it.

Commands run:

- `cargo clippy -p buzz-core -p buzz-db -p buzz-relay --all-targets --
-D warnings`
- `cargo test -p buzz-core --lib`
- `cargo nextest run -p buzz-relay --lib`
- `cargo test -p buzz-test-client --test e2e_relay -- --ignored` for the
13534 and 13535 rejection tests, against a local relay built from this
branch
- `cargo test -p buzz-db --lib`
- `cargo test -p buzz-db --test observability_source`
- `scripts/postgres-test-run.sh -p buzz-db -p buzz-relay --lib --tests`
(the CI PostgreSQL lane, run locally)

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

Signed-off-by: Ian Oberst <ioberst@block.xyz>
Co-authored-by: Ian Oberst <ioberst@block.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 13:51:18 -08:00
ravarora2
8b6bc9beb5 Add community-scoped user and agent profile cleanup (#9580)
## Summary

Content, account and media cleanup leave profile records behind. Add
`buzz-admin user-deletions profile-batches` to preview or delete those
records in one community. Preview is the default; explicit `--delete`
applies bounded, retryable transactions.

Every run and retry discovers the human’s current direct agents in that
community. Ownership elsewhere cannot authorize deletion here. If Alice
owns an agent in A but Bob owns it in B, deleting Alice in B preserves
that agent. Each write batch locks and rechecks ownership. All profile
data is removed before identity rows, so an interrupted run resumes
without saved agent keys. The command no longer accepts
`--agent-pubkey`.

The handler removes profile/configuration events and projections,
rebuilds shared archive snapshots with valid signatures, and finally
removes identity rows. Repository announcements/state (30617/30618) and
name mappings remain intact without blocking identity removal; other
authored content still requires prior cleanup. Unresolved dependencies,
changed sources, untrusted signers or excessive plans stop deletion.
This includes historical `replaced-by` references in archive requests
and deltas, even after unarchive removes the current archive row. See
[operator instructions and verification steps](docs/profile-cleanup.md).

Writers must be stopped. Coordinator integration, online admission
fencing, media objects, client caches and final account-erasure
verification remain separate. The command always reports
`account_erasure_complete: false`.

### Related issue

Fixes #9576. Continues the standalone handler pattern from #9363
(content) and #9364 (account). This is an independent PR against main.

### Testing

The latest correction adds a PostgreSQL regression that runs content
cleanup followed by profile preview/delete/retry for human and agent
repository owners. It checks unchanged repository events, mentions, name
mappings and other-community data, and verifies ordinary content still
blocks profile deletion. The merge of main brings in `buzz-deletion
--lib` coverage in the CI unit lane and its fallback, covering the
preview-default parser test without duplicate runs. Account, content,
media and profile command dispatch are all preserved. The
archive-history documentation also now distinguishes planning errors
from printed blockers.

The latest main merge includes the shared dependency-policy correction
from #9609 and the content cleanup lock fix from #9615. On `54bd50299`,
PostgreSQL CI passed 1647 tests and failed 18 because content cleanup
still called the retired SQL lock-key function; this also blocked the
new content→profile regression. The merged upstream fix uses the
existing Rust-built key for both the cleanup lock and the test blocker.
Local test suites and hooks remain skipped at the owner’s request. CI
and review of the updated head are pending. The results below apply to
earlier revisions.

At `92aa9c216`, exercised the rebuilt `buzz-admin` against signed
archive/unarchive events stored in disposable PostgreSQL:

- For kinds 9035 and 8002, test a historical `replaced-by` reference to
the human and then to their owned agent after unarchive.
- Run `profile-batches --pubkey <human> --community <A> --relay-pubkey
<relay>` in preview and `--delete` modes. Both refuse the unresolved
reference; full table dumps remain unchanged.
- Keep that history only in community B. Cleanup in A succeeds,
preserves B, and selects zero work on retry.
- Delete the archive subject in B. Its history is removed while the
replacement identities remain intact.

All four scenarios passed. These are signed database fixtures exercised
through the real CLI; they do not claim live relay admission. The
correction also merges main and preserves content, media and profile
command dispatch.

The initial full database run passed 880/881 tests: the new request
fixture lost its required self-`p` tag during signing. Commit
`ff6689386` preserves that tag; all ten profile regressions now pass.
Further local checks and pre-push hooks were skipped at the owner’s
explicit request. The full corrected database suite has not been rerun;
GitHub CI will validate the new head. At `ff6689386`, the production
code matched the CLI-tested revision; the repository-retention
correction above is newer.

Previous ownership validation follows:

At `090d2a1cf`, exercised the rebuilt `buzz-admin` binary against a
disposable PostgreSQL fixture:

- Run `user-deletions profile-batches --pubkey <human> --community <A>`:
preview left table exports unchanged and selected four profile/identity
mutations.
- Repeat with `--delete --batch-size 2`: all four mutations committed;
retry selected zero work.
- Use the same human and agent keys in another community, with the agent
owned by someone else: only the human was selected, and the agent
remained intact.

This fixture uses placeholder profile signatures and validates
database/CLI behavior. It does not claim live signed-event admission.
The earlier live relay and Desktop results below cover the previous
revision.

Independent agent review covered the previous ownership correction. A
later review found the historical replacement-reference bug; the
historical-reference correction addresses that finding. Fresh review of
this revision is still required. Human command verification has not been
recorded; it is not claimed by the agent-run checks. Follow the local
verification steps in `docs/profile-cleanup.md`; preview must leave data
unchanged, deletion must preserve other-community records, and retry
must select zero work.

<details>
<summary>Historical validation at fdf8a8363, before the ownership
correction</summary>

These records are retained from the earlier PR description. They do not
validate the current revision. The saved-agent-key retry below describes
the old interface, which this update removes.

- `cargo test -p buzz-db -p buzz-deletion -p buzz-admin`: passed at
`fdf8a8363` (298 tests, with PostgreSQL tests in the separate lane).
- `cargo clippy -p buzz-db -p buzz-deletion -p buzz-admin --all-targets
-- -D warnings`: passed.
- Full PostgreSQL lane for those three packages: **814/818 passed**,
including all five new profile tests. Four unchanged infrastructure
tests failed: reader-pool startup, a `postgres://`-only test given a
`postgresql://` URL, a one-second partition-lock timing assertion (1.55
seconds), and size-one matcher pool startup. The URL spelling has been
corrected for future runs; the full lane has not yet been rerun. The run
experienced heavy host contention.
- Actual `buzz-admin` command against a separate disposable SQL fixture:
default preview, `--print-only`, and `--read-only` left all table
exports unchanged; `--delete` removed four selected rows;
survivor/second-community data remained; retry selected zero rows. This
is database/CLI evidence, not live relay acceptance.
- Workspace Rust clippy and desktop static checks passed. `just ci`
initially stopped at mobile formatting because the fresh worktree lacked
Flutter package configuration; dependencies were installed and the retry
remains incomplete. The long-running local pre-push run was stopped to
publish the draft at the author’s request; incomplete gates are not
claimed as passing.
- Isolated live relay at `fdf8a8363`: 22 signed client events accepted
across two communities; WebSocket authentication established four
agent-owner links. All three preview forms left all 67 public tables
unchanged. `--delete --batch-size 2` removed eight selected source
events, four mention rows, one archive row and two identity rows, and
inserted one independently verified survivor-only archive snapshot. All
other rows matched exactly; retry selected zero work.
- Eight refusal cases left every table unchanged. A real process kill
after a committed batch, followed by retry with saved agent keys,
produced the exact expected result. Separate signed SQL fixtures covered
kind 30382, verified heads and historical kind 30179; these do not claim
live issuer-backed admission.
- Independent restart checks passed: target profiles stayed absent from
events, search and NIP-05; the other community was preserved; the
surviving user could publish and read a profile update. A separate
replay clone confirmed the boundary: replaying the original target
profile recreated its user row, and a fresh profile was accepted too.
Permanent erasure requires external admission/write fencing.
- Native Desktop experiment: relay/admin `fdf8a8363`, `buzz-app`
`859c9953a` with isolated app storage and a local TLS configuration.
Seed a survivor-owned conversation, open Alice and her agent's profiles,
then run `profile-batches --delete --batch-size 2` while app and relay
remain running. Preview selected 17 mutations across nine batches
without changing any of 67 tables. Deletion removed ten source events,
four associated mention rows and two users, then inserted one validly
signed survivor-only archive snapshot. Every other row, including eight
survivor events and community B, matched exactly. Retry did zero work.
- Desktop observations: fresh signed relay reads returned no target
profiles/events/NIP-05 in A; B and the survivor conversation remained
readable. Bob updated his profile through the API and sent a reply
through the native composer, with signed relay readback and visible
receipt. Cached target details remained in the open profile panel,
reopened search and after an app-page reload/reconnect. This does not
erase client caches or prove safety under concurrent target writes; the
stopped-writer contract remains.
- At that earlier revision, the PR was draft pending human command
verification. Agent testing does not satisfy the repository's
human-testing requirement, and this command does not certify online
erasure.

</details>

Generated with Codex

---------

Signed-off-by: Ravneet Arora <rarora@squareup.com>
Co-authored-by: dessert <7d616e7e143e5d408159614dccff1371350a1c1bd36c8de838a45ece5aca0aca@buzz.block.builderlab.xyz>
Co-authored-by: maincourse <37ce551b493d4a998caf030929c47bce0b6a0e43f1178b3a63c4151d7c16b76e@buzz.block.builderlab.xyz>
2026-11-17 21:47:12 +00:00
Wes
051dd2d7aa fix(sdk): timestamp channel messages with millisecond offsets (#9548)
Kind-9 messages sent through the SDK or `buzz messages send` omit the
`ms` tag, so clients break same-second ties by event ID. Capture one
clock reading in the shared message builder and use it for both
`created_at` and the canonical 0–999 millisecond offset, including
direct and nested replies.

Validation: both new regressions failed before the fix; the full CLI
suite (691 tests) and SDK suite (335 tests) pass. The SDK test checks
that the timestamp is pinned before signing; the CLI test captures and
verifies signed HTTP submissions for roots and both reply depths. The
built CLI also sent direct and nested replies through a managed signer
to a live relay; readback confirmed one canonical `ms` tag and correct
thread tags on both. Client ordering and human testing remain pending;
keep this PR draft.

To test manually, run `cargo build -p buzz-cli`, then send several
kind-9 messages with `target/debug/buzz messages send --channel
<channel> --content <text>` and direct/nested replies using `--reply-to
<event-id>`. Inspect their raw events: each should carry exactly one
canonical `ms` value, and a client that honors `ms` should display
same-second sends in timestamp order.

Related: #9541 updates mobile display ordering to consume these offsets.
No duplicate producer fix found in the open PR/issue search.

Repository-wide validation: `just ci` passed Rust/Tauri Clippy and
formatting, then failed mobile analysis at
`mobile/test/features/search/search_channels_journey_test.dart:933`:
`_RenamingSession.subscribeWithStatus` omits the base method's
`resumeSince` parameter. Mobile files are unchanged from the base
commit. This unrelated failure remains outside this fix.

The first push hook run failed the existing WebSocket throttle test
`a_throttled_sign_in_reconnects_with_fresh_evidence` (connection reset
during sign-in); a subsequent full CLI rerun and the complete normal
push-hook retry passed without source changes. The test uses a
kind-20001 event and does not call the changed builder. All required
push hooks passed.

Signed-off-by: Rocket <0c41329ade659e01801116549bc617351689892a382bc864a1186dc9191293a7@buzz.block.builderlab.xyz>
Co-authored-by: Rocket <0c41329ade659e01801116549bc617351689892a382bc864a1186dc9191293a7@buzz.block.builderlab.xyz>
2026-11-17 14:19:27 -07:00
Luke Tornquist
3bd121bc15 Check product_feedback's community in the writing transaction (#9608)
## Summary

Third app-side step of retiring the database foreign keys (after #9399
and #9404). After this, every reference the drop migrations will remove
is checked in application code.

- **`product_feedback -> communities`:** `product_feedback::insert` now
runs in a transaction. It locks the community row `FOR KEY SHARE` and
returns `NotFound` when the row is missing. This is the same guarantee
the foreign key gives. Any lifecycle state still qualifies.
`docs/database.md` says provenance-only tables stay writable while their
community is being deleted, and the purge clears their provenance.
- **Reader tolerance:** `ProductFeedbackRecord.community_id` is now
`Option<Uuid>`. The purge sets `community_id = NULL`, and `list` (used
by `buzz-admin list-product-feedback`) failed to decode those rows. The
JSON output shows `null` for them.
- **One home for reference checks:** `require_workflow` and
`require_workflow_run` move from `store/workflow.rs` into
`store/reference_check.rs`. The workflow owner and channel checks now
reuse `require_user` and `require_optional_channel`, so two duplicate
helpers are gone. A new `require_community` joins them.
- **Stale comments:** comments that justified behavior by the foreign
keys now say what holds both before and after the drop. Touched: the
purge order (`deletion.rs`), `command_executor.rs`'s `ensure_user`, the
`set_agent_owner` doc, the NIP-43 snapshot lock note
(`relay_members.rs`), `attach_scheduled_workflow_run`, and one workflow
deletion test.

## Writers and readers checked (RPR #2)

`product_feedback.community_id` writers:
- `store/product_feedback.rs` `insert`: the only insert. It is now
checked.
- `store/deletion.rs` `purge_postgres`: sets the column to `NULL`. No
check is needed.
- `store/relay_admin_actions.rs` status update: does not touch
`community_id`.

Readers:
- `product_feedback::list`: fixed to accept `NULL`.
- `store/admin_moderation.rs` inbox queries: already `LEFT JOIN` and
accept `NULL`.

## Tests

All three tests drop `product_feedback -> communities` in the per-test
database first, so a pass proves the application check and not the
constraint.

- `insert_rejects_missing_community_without_foreign_key`: a community
that never existed gets `NotFound` and no row. A fenced community still
accepts feedback. An active one accepts it, and a replay returns the
same row.
- `insert_key_share_locks_community_without_foreign_key`: an insert
waits while another transaction holds the community `FOR UPDATE`, then
proceeds.
- `list_returns_rows_with_cleared_provenance`: a row with `community_id
= NULL` is listed with `community_id: None`.

## Not in this PR

- The foreign key drop migrations. They come after this PR is deployed
(`docs/database.md` expand/contract).
- Nothing in the database stops `DELETE FROM communities` on an active
community once the community foreign keys are gone. The tombstone
trigger rejects it only for inactive communities. Production never
hard-deletes communities. This is decided with the drop migrations,
since a trigger change conflicts with the no-new-triggers rule.

## What got simpler

All in-transaction reference checks now live in one module. Two
duplicate helpers were removed. `store/workflow.rs` loses about 80
lines.

buzz-review-completed

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

---------

Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
2026-11-17 16:10:58 -05:00
Luke Tornquist
0a05330740 buzz-db: stop calling the dropped lock-key function in SQL (#9615)
## Summary

Main's user content cleanup still calls the SQL function
`community_deletion_lock_key`. Migration `0094` (#9598) drops it. On any
database at `0094`, every user-deletion content batch fails with `42883
function community_deletion_lock_key(uuid) does not exist`.

#9363 added this caller after #9396 moved the key to Rust. This PR binds
the Rust-built key with `hashtextextended($1, 0)`, as every other caller
does.

- `content_batches/execute.rs`: the batch's exclusive advisory lock uses
the Rust key.
- `content_batches/safety_postgres_tests.rs`: the test blocker takes the
same lock the same way.
- `docs/trigger-retirement-deployment.md`: builds from #9363 up to this
PR are not valid stops before `0094`.

Rebased onto main `e894d75d`. The renumber and the `update_channel`
test-call fixes this PR first carried are already on main through #9616,
so they are gone from this PR.

Deployed relays are unaffected: the deployed build predates #9363.

## Tests

The 17 `user_deletion::content_batches` PostgreSQL tests fail on main at
`0094` with the error above. This PR makes them pass.

## What got simpler

One fewer SQL-side copy of the lock key. Every caller now builds the key
in Rust.

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

Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
mobile-v1.5.0-rc.2
2026-11-17 20:31:39 +00:00
ravarora2
8fb0de8d53 Clean up account records and refresh member lists (#9364)
## Summary

Add bounded, resumable cleanup for a user’s account records and their
current direct agents in each selected community. Preview prints the
proposed changes without writing; deletion uses the same selectors
through the command and workflow handler.

Each run and retry discovers agent ownership again. An agent owned by
Alice in one community and Bob in another is cleaned only in Alice’s
community. Ownership changes stop the current run, and ownership rows
remain available for retries and later handlers.

Membership removal rebuilds and signs the current channel lists and
community roster in the same transaction as each removal. A failed
roster write rolls back that membership removal. The command requires
the existing relay signing key when channel or community memberships are
present, including users with no channel memberships. Preview does not
require a key.

The relay, account cleanup and admin reconciliation share the kind
39001/39002 tag builders in `buzz-db`. They preserve the existing
identity tags, roster order and role positions. Regular unit-test runs
now include `buzz-deletion` through both nextest and the Cargo fallback.

**Channel ownership policy:** deletion may remove the last channel
owner, including when the human and their agents are all owners. The
channel, messages and surviving members remain. A surviving admin can
manage the channel and grant ownership. If no owner or admin remains,
members can continue normal use, but management recovery requires
operator intervention on request. Cleanup does not require a channel
ownership handoff or assign a replacement owner. The separate
community-owner restriction remains.

The content handler now on main advances to account cleanup before the
remaining agent stage. Content and account workflow progress goes to
stderr so stdout remains one JSON inspection document. The direct
account command retains NDJSON stdout. Nullable attribution updates use
explicit table and SET clauses so the source-policy guard can inspect
them.

The handler covers credentials, memberships, read progress, supported
personal events and their copies, feedback, and explicit global
listener/database-role cleanup. It retains shared records and historical
signed lists. Scope files select the human and communities; saved agent
keys do not authorize deletion.

This remains an offline operator feature: stop relay and external
writers before deletion. It does not revoke already-connected sessions.
Coordinator integration, remaining handlers and final erasure
verification are separate; results always report
`account_erasure_complete: false`. The real account workflow still stops
at an unimplemented successor.

### Related issue

Replaces the account scope of #9354 and #9355 with one focused PR. Those
earlier PRs remain intact for reference. Agent cleanup belongs within
the business handlers; this change does not integrate the historical
standalone agent stage in #8959.

### Testing

Exercised the real preview and delete commands in an isolated local
relay/database with Alice disconnected and Bob’s desktop app open.
Preview left the normalized database dump unchanged. Deletion checks
covered all 101 tables and all 30 affected channels; 168 newly signed
list events verified. Bob refreshed the member dialog and saw Bob, B1
and Carol, then successfully sent and read a message. A1’s membership in
the community where Bob owns it remained intact.

The live CLI and desktop evidence above predates the latest follow-up.
Independent end-to-end checks at `d45759df2` also verified unchanged
preview data, signed channel/community lists after deletion, signing-key
preflight, and workflow JSON stdout. The shared-builder follow-up was
source-reviewed and formatted; local builds, tests and commit/push hooks
were skipped at the author’s request. Validation of the new revision and
a repeat of the signed-list end-to-end check are pending. Human testing
remains pending.

For human verification, use an isolated database and its relay signing
key. Preview a community-only member, confirm no writes, then delete and
verify the current kind 13534 roster omits them. Run an approved
account-stage fixture with `user-deletions run <id> --delete
--next-step`; the entire stdout must parse as one JSON document, with
batch progress on stderr.

Generated with Codex

---------

Signed-off-by: Ravneet Arora <rarora@squareup.com>
Signed-off-by: soup <757a365d4ee72aedf003a39cd856b16b49a3b940a42fe00402b8f80fbc40e730@buzz.block.builderlab.xyz>
Co-authored-by: soup <757a365d4ee72aedf003a39cd856b16b49a3b940a42fe00402b8f80fbc40e730@buzz.block.builderlab.xyz>
Co-authored-by: maincourse <37ce551b493d4a998caf030929c47bce0b6a0e43f1178b3a63c4151d7c16b76e@buzz.block.builderlab.xyz>
2026-11-17 15:11:25 -05:00
Tom Brow
a26eacde49 perf(mobile): save own thread interest once per unread catch-up (#9614)
iOS was killing the app with watchdog terminations (`0x8BADF00D`,
"scene-update watchdog transgression" and "Failed to terminate
gracefully") because the main thread spent 5 to 10 seconds in unread
catch-up.

Symbolicated reports from a 1.4.0-rc.1 user all point at the same stack:
`UnreadCatchUp._catchUpUnreadEvents` →
`ChannelsNotifier._writeThreadInterestStores` → `jsonEncode` /
`SharedPreferences.setString`. For every self-authored event in a
catch-up batch whose thread was new to the interest sets, the notifier
re-encoded **both** whole root-id sets and wrote both to
SharedPreferences. That is quadratic in the batch: a fresh sign-in,
whose catch-up returns many of the user's own messages, ran thousands of
growing encodes and platform-channel writes on the main thread.

Now the catch-up adds the whole batch to the in-memory sets and saves
once if anything changed. The live single-event path is unchanged (one
write per new thread).

### Regressions

None expected. The persisted keys, format and contents are identical;
only the number of intermediate writes changes. The storage contract is
unchanged: saves were and still are fire-and-forget `setString` calls,
so neither version guarantees durability before a process kill. A kill
before the save lands now loses the whole batch rather than a prefix of
it; a later catch-up can re-add those threads only while they are still
after the channel's read timestamp and within the catch-up window.

### Validation

- **Writes per catch-up**, 50 own messages across 50 threads: 50 writes
per key before, 1 after (new test).
- Added test: `unread catch-up saves own thread interest once per batch`
(channels_provider_thread_interest_cases.dart). It checks the saved sets
and the write count; it fails on the old code.
- Full mobile check and test suite pass.

- Automated full-app run on an iOS simulator (PR head build, signed in
to a real community): cold launch and unread catch-up saved both
thread-interest sets; background and foreground; Activity rows and
unread dots render; opened a thread and sent a reply, and the
participation set grew by one (live path still saves). No errors in the
app log.

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
2026-11-17 15:01:13 -05:00
Luke Tornquist
e894d75d26 buzz-db: fix main (renumber the function drop to 0094, update_channel test call) (#9616)
## Summary

Main has two migrations numbered `0093`:

- `0093_push_gateway_installation_platform.sql` from #9560
- `0093_drop_plain_sql_functions.sql` from #9598

The file names differ, so GitHub showed no conflict between the PRs.
sqlx applies the first version-93 migration and then rejects the second
as a changed migration 93. Every migrate run on main fails, including
relay startup with auto-migration on.

This PR moves #9598's migration to `0094`:

- `git mv migrations/0093_drop_plain_sql_functions.sql
migrations/0094_drop_plain_sql_functions.sql`. The SQL is unchanged.
- `embedded_migrator_contains_consolidated_initial_schema` now expects
94 migrations, with the function drop at version 94.
- The Postgres test is renamed to
`migration_0094_drops_plain_sql_functions`. It finds the migration by
description, so its logic is unchanged.
- `docs/trigger-retirement-deployment.md` now names `0094`.

#9560's `0093` keeps its number. It reached main first and may already
be applied on deployments that auto-migrate.

## Second break on main: `update_channel` call sites

Main's buzz-db lib tests also stopped compiling. #9581 added a `sender`
argument to `update_channel`, and #8320's cross-community test
(`deletion.rs`) landed in parallel with the old three-argument call.
This PR passes the channel creator as the sender. The test only renames
an open channel, so the private-to-open rule does not apply.

## Deployments

No deployment has applied #9598's `0093`: no image built from main after
#9598 has rolled out yet. A database that applied #9560's `0093` applies
`0094` next. Do not promote any image built from `4e8f8365` (the #9598
merge) or later until this PR merges.

## What got simpler

Nothing. This is a renumber and a test call fix only.

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

---------

Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 19:28:05 +00:00
morgmart
f158fdd9a1 feat(relay): name the agent whose add policy refuses a DM (#9601)
## Problem

When an agent's add policy refuses a DM open or add (from #9125), the
refusal says only that an agent refused. The person can't tell which
agent blocked it, so they don't know whose owner to ask.

## Change

The DM refusal now ends with `(agent <hex pubkey>)` for the first agent
refused, in the order the request named them. For example:

`forbidden: policy:owner_only — only the agent owner can add this agent
(agent 3f9a…)`

The prefix is unchanged, so existing clients that match on
`policy:owner_only` or `policy:nobody` keep working. Desktop and mobile
follow-ups will show the agent's name.

## Tests

- `adding_an_agent_follows_its_add_policy` asserts the full refusal
including the agent.
- `opening_with_several_agents_follows_their_add_policy` adds a second
refusing agent and checks the first one named is reported.
- DM Postgres tests: 297/297 passed. Clippy is clean.

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

Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com>
Co-authored-by: Carl <c217fe6b9d958f41c3a5e030dccc7f626775a923089cb6491305eade75ea1f1b@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 11:26:25 -08:00
Luke Tornquist
4e8f836576 buzz-db: drop the community_deletion_lock_key and profile_name_fields functions (contract) (#9598)
## Summary

Phase 2 of retiring the two remaining plain SQL functions. Phase 1 moved
their work into the relay:

- #9396 builds the community deletion lock key in Rust
(`deletion::community_deletion_lock_key`, locked with
`hashtextextended($1, 0)`).
- #9397 reads profile names with inline SQL (`PROFILE_NAME_FIELDS` in
`buzz-search`).

No relay at or after #9397's merge (`279a31da`) calls either function.
This PR drops them:

- **Migration 0093** runs `DROP FUNCTION
community_deletion_lock_key(UUID)` and `DROP FUNCTION
profile_name_fields(TEXT)` under a 5s `lock_timeout`, with no `IF
EXISTS` and no `CASCADE`. If anything still depends on a function, the
migration fails instead. Migrations 0029 and 0064 stay frozen. No
database function calls either one any more: 0090 dropped the fence
functions, which were the only SQL callers of the lock key.
- **Desired state:** removes both `schema/functions/` files and their
`schema.sql` includes. Both boot paths stay catalog-equivalent
(`admin_schema_parity_between_desired_state_and_migrations`).
- **Tests:**
- New `migration_0093_drops_plain_sql_functions`. It migrates to 0092,
checks that both functions exist and that serving and deletion catalog
validation pass, then runs 0093 and checks that both functions are gone
and that validation still passes. This covers new code on either side of
the drop.
- The migration listing test pins 0093's statements and that it has no
`CASCADE`.
- `desired_state_catalog_has_no_universal_fence_and_still_boots` now
asserts that both functions are absent.
- Replaces the Rust-vs-SQL lock key parity test with
`community_deletion_lock_key_bytes_are_fixed`, a unit test that maps
fixed UUIDs (nil, max, and one with hex letters) to their exact keys.
Older replicas and the repair-script key in `docs/database.md` build the
same string, so a changed prefix or UUID format must fail a test.
- Removes two relay test-schema wrappers (`bridge.rs`, `ingest.rs`) that
forwarded `community_deletion_lock_key` to `public`. Writers no longer
call it, and the wrapper's `CREATE FUNCTION` would fail once the
function is gone.
- **Docs:** `docs/trigger-retirement-deployment.md` gets a `0093`
section with the required stop.

## Deploy gate

**Required stop:** any relay build at or after `279a31da` (#9397's
merge, which follows #9396). `relay-v0.3.0` does not contain it. A relay
older than that which still serves after 0093 fails every write and
deletion that takes the community deletion lock, with `42883
community_deletion_lock_key(uuid) does not exist`, and its profile name
search fails with `42883 profile_name_fields(text) does not exist`. 0093
takes no table locks and needs no cleanup.

Migration number: #8696 and #9398 also propose `0093`. Whichever lands
second renumbers.

## Review-Proven Rules

- **RPR #2 (every path):** I checked every reference on `main` and at
the stop build `279a31da`. At both, only test code reads either
function: no boot, readiness, catalog or runtime query depends on them.
Serving and deletion catalog validation pass before and after 0093, in
the new test.
- **RPR #3 (falsifiable):** removing the `profile_name_fields` drop from
0093 turns `migration_0093_drops_plain_sql_functions` red.
- **RPR #3 (lock key bytes):** a changed prefix, `.simple()` UUID
formatting, or uppercase formatting each turns
`community_deletion_lock_key_bytes_are_fixed` red.

## What got simpler

Two database functions, their desired-state files, a cross-language
parity test and two test-only SQL wrappers are gone. After this PR, the
only functions left in `schema/functions/` are trigger functions.

## Validation

Blox gate at `95ac71c8`:

- `cargo fmt --all --check`, and `cargo clippy -p buzz-db -p buzz-relay
--all-targets -D warnings`.
- `buzz-db --lib` unit tests: 216/216, including the migration listing
test.
- `buzz-db` Postgres tests (`migration::`, `deletion::`,
`nip_fi_binding::` postgres_tests): 130/130. These include
`migration_0093_drops_plain_sql_functions`,
`admin_schema_parity_between_desired_state_and_migrations` and
`deletion_surface_parity_between_migration_0029_and_schema_sql`.
- `buzz-search` `profile_names*` Postgres tests: 4/4, on a fully
migrated database where `profile_name_fields` no longer exists.
- The two relay tests whose test-schema wrapper this PR removes: 2/2.
- Must-fail check: with the `profile_name_fields` drop removed from
0093, `migration_0093_drops_plain_sql_functions` fails.

Second Blox gate at `e1b5513a` (the lock key vector test):

- `cargo fmt --all --check`, and `cargo clippy -p buzz-db --all-targets
-D warnings`.
- `buzz-db --lib` unit tests: 217/217.
- Must-fail checks: a changed prefix, `.simple()` and uppercase UUID
formatting each fail `community_deletion_lock_key_bytes_are_fixed`.

The first gate run found that
`deletion_surface_parity_between_migration_0029_and_schema_sql` still
expected `community_deletion_lock_key` in `schema.sql`. The second
commit fixes that.

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



buzz-review-completed

---------

Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 13:44:33 -05:00
Luke Tornquist
66b463fb2f fix(deps): clear chrono, humantime and zip advisories from the dependency policy (#9609)
## Summary

main's `Security` check (`cargo-deny check`) fails on six new
advisories:

- RUSTSEC-2026-0545, 0546, 0547, 0548: zip 8.6.0 (fix in zip >= 9.0.5).
- RUSTSEC-2026-0543: chrono is unmaintained.
- RUSTSEC-2026-0542: humantime is unmaintained (it wraps chrono).

This PR adds ignore entries with reasons. It changes only `deny.toml`.

## Why ignore and not upgrade

**zip.** zip 8 reaches the graph only through the examples-only
`buzz-mesh-smoke` crate, via mesh-llm v0.76.2. mesh-llm builds zip with
only the `deflate` feature. It reads archives through `ZipArchive` and
copies entries by hand. It never calls `extract`, never decrypts AES
entries (`aes-crypto` is off), never enables `legacy-zip`, and never
uses `ZipStreamReader`. None of the affected code paths run.

mesh-llm v0.79.0 ships zip 9.0.5. But that release removes the `client`
feature of `mesh-llm-sdk`, which `buzz-mesh-smoke` and desktop use. A
bump needs an SDK migration in both places. That is out of scope for a
red-main fix.

The new IDs join the existing zip block. Its note said the fix was in
"unreleased mesh-llm#2471". That is stale, so the note now names the
release and the migration it needs.

**chrono / humantime.** Both are unmaintained, not vulnerable. Neither
has a maintained release. chrono is a direct workspace dependency of
most crates. humantime comes only through `buzz-mesh-smoke` → mesh-llm →
hf-xet → xet-runtime. Removing them needs a migration to `time` or
`jiff`.

## What got simpler

Nothing could. The new ignores are the smallest change that makes the
check pass. Identified debt:

- The mesh-llm SDK migration to v0.79+ would delete all eight zip
ignores.
- A chrono → `time`/`jiff` migration would delete both unmaintained
ignores.

## Test plan

- [x] `cargo-deny check` at this tree: `advisories ok, bans ok, licenses
ok, sources ok` (exit 0).
- [x] `git diff --check` clean.

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



buzz-review-completed

Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
mobile-v1.5.0-rc.1
2026-11-17 13:00:06 -05:00
Tom Brow
026b203c64 docs: define mobile diagnostic reporting (#9600)
## Summary

Records the vocabulary, the two hard-to-reverse decisions and the spec
for diagnostic reporting in the mobile app, before any code is written.
Nothing here changes behavior.

- `CONTEXT.md`: two new terms. **Diagnostic reporting** is sending
crash, error and performance data from a mobile installation to a
reporting destination. A **reporting destination** is where a build
sends it, chosen at build time by whoever distributes the build.
- [ADR
0007](https://github.com/block/buzz/blob/tomb/mobile-diagnostic-reporting-docs/docs/adr/0007-diagnostic-reporting-follows-the-destination.md):
a build reports if, and only if, it was given a reporting destination,
whatever kind of build it is. It also lists what a report may and may
never carry.
- [ADR
0008](https://github.com/block/buzz/blob/tomb/mobile-diagnostic-reporting-docs/docs/adr/0008-sentry-for-mobile-diagnostic-reporting.md):
the app reports through the Sentry Flutter SDK, with the comparison
against Datadog and Bugsnag.
-
[`docs/mobile-diagnostic-reporting.md`](https://github.com/block/buzz/blob/tomb/mobile-diagnostic-reporting-docs/docs/mobile-diagnostic-reporting.md):
the spec for step one. It covers crashes, uncaught errors, error reports
for unexpected protocol and decoding failures, and networking
measurements by backend and endpoint, all through one reporting module.
It sits beside the existing mobile push suppression spec.

The term avoids "telemetry" because the repository already uses that
word for agent session streams and relay rollout signals.

### Related issue

N/A. The Swift Package Manager move that ADR 0008 depends on is #9597.

### Regressions

Documentation only. No code, configuration or build changes.

### Validation

Checked that every link in the four files resolves within the branch,
and that the new glossary anchors match the links that point to them.

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: judge <7615ec4b7ddf99f0bb48e913297f99f8f772d289a1c9ef54e1d906dd55a93ba8@buzz.block.builderlab.xyz>
2026-11-17 09:40:06 -08:00
Tom Brow
148585c804 build(mobile): link iOS plugins through Swift Package Manager (#9597)
## Summary

The iOS app stops opting out of Flutter's Swift Package Manager
integration. The 19 iOS plugins that ship a Swift package are now linked
through it. The three that don't (`google_mlkit_commons`,
`google_mlkit_selfie_segmentation` and `open_filex`) keep installing
through CocoaPods, which Flutter supports side by side.

Why now:

- CocoaPods is winding down: its spec repo [becomes read-only on
December 2, 2026](https://blog.cocoapods.org/CocoaPods-Specs-Repo/), and
plugin releases have started to ship as Swift packages only. Staying
opted out pins those plugins at their last CocoaPods release.
- The opt-out dates from the Flutter 3.47 upgrade (#8419), which kept
the existing CocoaPods integration. With it removed, the app builds and
runs as before.

What is in the diff:

- `pubspec.yaml`: the opt-out is removed.
- `project.pbxproj` and `Runner.xcscheme`: the edits Flutter's own tool
makes on the first build with the integration on (a local reference to
its generated plugin package, and a scheme pre-action that prepares the
Flutter framework). They are committed so a build does not dirty the
tree.
- `Podfile.lock`: only the three CocoaPods plugins and their
dependencies remain.

No Dart code, plugin version or remote Swift package changes. All 19
packages resolve to local paths in the pub cache, so `Package.resolved`
is untouched and builds fetch nothing new.

### Related issue

N/A. No existing issue or PR for this was found.

### Regressions

- **App behavior:** the same plugin code at the same versions. The 19
plugins are linked statically into the app binary instead of embedded as
dynamic frameworks, which leaves fewer libraries to load at launch and a
slightly smaller app (numbers below). One resource bundle is lost; see
the second accepted tradeoff.
- **Extensions:** the notification service extension links no plugins,
so it is unchanged.
- **Build and release:** CocoaPods is still required for the three
remaining plugins, so the Podfile, its post-install steps and the
release tooling are unchanged. The first build after this change spends
about 17 extra seconds adding the integration.
- **Accepted tradeoff, build warning:** Flutter now prints a warning
naming the three plugins without Swift packages. It goes away when those
plugins add support or are replaced.
- **Accepted tradeoff, one privacy manifest dropped:** the app no longer
bundles `app_badge_plus`'s privacy manifest, and Xcode prints `Invalid
Resource 'Resources': File not found` for it. Version 1.2.10's Swift
package looks for `Resources` under its source directory, but the
manifest sits at the package root, so the Swift package bundles nothing
where the podspec bundled it. This is harmless: that manifest declares
only UserDefaults access, and the plugin's single source file never
touches UserDefaults. The other 16 plugin privacy manifests are still in
the release app. Fixing it means a plugin bump, which is left out of
this PR.
- **Android:** unaffected.

### Validation

Unsigned release build, this branch against unmodified `main`:

| | `main` | This branch |
| --- | --- | --- |
| App size | 87.0 MB | 85.6 MB |
| Embedded frameworks | 31 | 12 |

Focused existing validation: the three iOS steps CI runs (simulator
debug build, the 116 native `RunnerTests`, and the unsigned release
build) pass locally.

Full-app run on an iOS 27 simulator (iPhone 17 Pro), driven by an agent,
with the debug build from this branch installed over an existing
signed-in install:

- The app stayed signed in and loaded its channel list and message
history (keychain, preferences and local storage plugins).
- Photo library picker, attaching a photo, and sending a video, which
uploaded and played back.
- Image viewer, the share sheet, and saving an image to Photos.
- The file picker, and the camera and microphone permission prompts.
- A link in a message opened in the browser, and a `buzz://` deep link
reached the app.

Two failures showed up and both reproduce identically on unmodified
`main` on the same simulator, so neither comes from this change: a
recorded voice note is empty because the host Mac has no microphone, and
saving an image adds it to Photos but then reports "Could not save
image".

Limits: no physical device run. Camera capture, QR scanning, selfie
segmentation and biometric prompts cannot be exercised on a simulator.
Voice note playback was not exercised.

Human testing is waived for this PR under the author's standing policy
for mobile changes; the agent-driven run above stands in for it.

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: judge <7615ec4b7ddf99f0bb48e913297f99f8f772d289a1c9ef54e1d906dd55a93ba8@buzz.block.builderlab.xyz>
2026-11-17 10:11:28 -07:00
Tom Brow
6b4a398829 feat(push-gateway): enroll Android installations and send FCM wakes (#9560)
## What and why

Ticket 2 of the Android push plan ([design PR
#9555](https://github.com/block/buzz/pull/9555)). The gateway now
enrolls Android installations and wakes them through FCM, next to the
existing iOS path.

Builds on [#9557](https://github.com/block/buzz/pull/9557)
(platform-neutral `/v1/deliveries` route), now merged.

- **Platform.** The enrollment request has no platform field. The
gateway derives it from which attestation is present (App Attest object
or Android attestation chain) and records it in a new
`push_gateway_installations.platform` column (`ios` or `android`). It
lives only in gateway state; the relay never sees it.
- **Android enrollment transcript.** Key Attestation fixes the challenge
at key generation, so the client signs nothing at enrollment and sends
no `key_id`. The attestation challenge must equal SHA-256 of a canonical
JSON transcript under domain `buzz.push.enroll.android.v1` with `v`,
`audience`, `challenge_id`, `challenge`, `endpoint`, `endpoint_epoch`
and `expires_at`. The gateway derives the key id as SHA-256 of the
attested 65-byte uncompressed P-256 key. A request whose `key_id`
presence doesn't match its platform gets 400. The iOS transcript
(`buzz.push.enroll.v1`) is unchanged.
- **Signed calls.** iOS keeps App Attest assertions. After enrollment,
an Android installation signs every call (delegate, revoke delegation,
rotate endpoint, revoke installation) with its attested Keystore key:
ECDSA P-256, DER, over the same transcript bytes iOS signs. High-S
signatures are accepted since Keystore does not normalize. There is no
counter; the single-use challenge inside the transcript is the replay
protection.
- **FCM sender.** HTTP v1, high priority, data-only, compiled-in payload
(no relay-supplied bytes), one constant collapse key, TTL from the
delivery expiry. OAuth access tokens come from the service account key
(RS256 JWT bearer). Outcomes map onto the existing delivery outcome
classes and metrics (`push_gateway_fcm_*`).
- **Token refresh.** A cached token keeps serving until it expires. Once
it is due for refresh, one background task fetches a new one, so a wake
never waits on a refresh while a valid token exists. A failed fetch
keeps the current token and backs off 5 s before the next attempt. Only
a cold cache (no unexpired token) makes a wake wait on the token
request, single-flighted. A 401 discards the cached token only if it is
still the one FCM refused, so a late 401 can't drop a newer token.
- **Retries.** 429 and `QUOTA_EXCEEDED` retry after at least 60 s (FCM's
hint if longer). 500, 502, 503 and 504 retry.
- **Attestation seam.** Android Key Attestation verification sits behind
a trait. Tests use a test-only verifier compiled under `cfg(test)`, so
production configuration cannot select it. The production verifier fails
closed: a gateway configured for Android starts but rejects every
Android enrollment until ticket 3.
- **Migration.** Expand-only `ADD COLUMN platform TEXT NOT NULL DEFAULT
'ios' CHECK (...)`: the deployed gateway's inserts stay valid and
existing rows become iOS. `SET LOCAL lock_timeout` (5 s) and
`statement_timeout` (30 s) bound the table lock wait and the CHECK
validation scan. No triggers, functions, foreign keys or backfills.
Mirrored as gateway `0007` and relay `0093` plus `schema/tables/public`,
per docs/database.md.

## Configuration

All four are optional and must be supplied together (a partial set fails
startup). Documented in `docs/push-gateway-deployment.md` and
`.env.example` with example values only.

- `BUZZ_PUSH_ANDROID_PACKAGE_NAME`
- `BUZZ_PUSH_ANDROID_SIGNING_CERT_DIGESTS`
- `BUZZ_PUSH_FCM_PROJECT_ID`
- `BUZZ_PUSH_FCM_SERVICE_ACCOUNT_PATH`

## Tests

- `cargo test -p buzz-push-gateway` (92 passed, 18 ignored; 94 passed
with `personal-dev-app-attest`; iOS rows unchanged), `cargo fmt
--check`, `cargo clippy -p buzz-push-gateway -p buzz-db --all-targets --
-D warnings`.
- New HTTP tests with a fake FCM sender: Android enroll, delegate,
deliver, rotate endpoint and revoke; signed-call rows for wrong key,
altered transcript and reused challenge; platform derivation and bad
attestations.
- Postgres (ignored, run locally): gateway migration test (existing and
old-gateway inserts become `ios`, bad value rejected); relay
`admin_schema_parity_between_desired_state_and_migrations` now covers
`push_gateway_installations` columns, indexes and constraints; the
`runtime::migration::postgres_tests` set passes single-threaded.
- Break check: making signature verification always succeed turned two
tests red (the signed-call rejection rows and the signature unit test);
restored.
- Token cache tests against a local fake token endpoint with a
controlled clock: a due refresh keeps serving the valid token even when
it fails; a late 401 does not discard a refreshed token; a queued
background refresh honors a foreground failure's backoff. The FCM
response table covers 429 with and without an error body, and 502/504
HTML pages.
- Android enrollment rows: `key_id` present on Android (400), wrong
transcript binding, a 65-byte non-point key, an over-long chain, and
exact replay.
- Break checks for every new guard (no background refresh, blocking
while due, failure dropping the token, unconditional 401 clear, no quota
floor, no 502/504 retry, the queued-refresh backoff check, Android
requiring `key_id`, skipping the P-256 point check): each turned at
least one test red; restored.

## Not here (ticket 3)

Real Key Attestation verification (Google roots, revocation list, boot
state, boot-key list, app identity). Per-key rate limiting is also left
for ticket 3, since it did not fall out of this change. The Helm chart
does not pass the Android settings yet.

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
2026-11-17 10:11:17 -07:00
Tom Brow
ff652ed06c perf(mobile): cache and animate custom emoji in the iOS picker (#9479)
The iOS emoji picker's custom emoji downloaded again every time the
picker opened, and animated emoji showed only their first frame.

Now each custom emoji downloads once per install and plays its
animation:

- The native picker gets image bytes from Flutter through the same path
as the rest of the app's images: the in-memory custom emoji cache, then
the persistent media disk cache, then one download through the shared
media HTTP client. Relay media is cached as immutable.
- Swift decodes every frame (no Swift-side cache) and shows the image in
a `UIImageView`, since SwiftUI `Image` draws only the first frame of an
animated `UIImage`. With Reduce Motion on, it shows the first frame,
following the setting live.
- At most four picker downloads run at once, and an emoji scrolled off
screen before its turn never starts. Emoji already saved on disk skip
the queue, so reopening a large set stays instant.
- A picker load joins any download of the same image already in flight
elsewhere in the app. A saved copy that fails to decode is evicted and
downloaded again, and only bytes that decoded are kept in memory.
- Swift decodes at most four emoji at once, including ones from cached
bytes. An emoji whose cell scrolls away gives up its place and stops
decoding between frames, and a cell that leaves the screen keeps only
its first frame.
- Each animation frame keeps its own delay. UIKit spaces animated frames
evenly, so a frame repeats for its share of the loop, and a GIF that
holds its last frame for 3 s still does.

### Why it refetched

The native picker loaded images itself with `URLSession.shared` and an
`NSCache` keyed on the whole request. Every request carried a freshly
signed media auth header, so the key never matched and nothing was
cached on disk.

### Validation

Relay media downloads for the 48 custom emoji matching "nod" (local
relay, iPhone 17 Pro simulator):

| Step | main | this PR |
| --- | --- | --- |
| First open | 48 | 48 |
| Leave and re-enter the channel, reopen | 48 | 0 |
| Relaunch the app, reopen | 48 | 0 |
| Reinstall the app, reopen | not measured | 0 |

Before (main): every reopen downloads again, and animated emoji are
still.


https://github.com/user-attachments/assets/7a43dd6a-61e0-495d-abed-6c11f7d4f965

After (this PR): reopening shows cached emoji immediately, and animated
emoji play.


https://github.com/user-attachments/assets/bf45a5c0-77ef-4501-8843-6f42e15de389

Automated app run: signed in to a local relay, opened a channel,
long-pressed a message, opened the full picker, searched, closed, left
and re-entered the channel, reopened, relaunched and reopened. Repeated
on the final head (359fdc8) with a warm cache: 0 downloads across open,
re-entering the channel and relaunch, all emoji rendered. The run used
the simulator only; device and hosted-relay behavior were not exercised.

Added tests:

- `media_disk_cache_test.dart`: encoded bytes for a native surface
download once, survive a relaunch, and bytes that never decode are not
saved.
- `emoji_picker_test.dart`: the native sheet's `mediaBytes` call returns
authorized bytes, a second call makes no request, and a cancelled call
fails.
- `emoji_picker_test.dart`: at most four loads run at once, a queued
load cancelled before it starts never downloads, and a saved emoji
doesn't wait for a slot.
- `media_disk_cache_test.dart`: a damaged saved copy (including a
truncated PNG) is evicted and downloaded again.
- `media_image_test.dart`: encoded-bytes requests share one download
with simultaneous image loads, and only decoded bytes reach observers.

- `NativeMessageImageLoaderTests.swift`: a GIF with uneven delays keeps
each frame's share, a cancelled decode returns nothing, and the decode
gate admits four in order and drops a cancelled waiter.

Removed `NativeEmojiRedirectPolicyTests` and the native concurrency test
along with the Swift loader they covered.

### Regressions

- Network: fewer requests. Cold loads keep the old picker's
four-at-a-time limit, so on a slow HTTP/1.1 origin queued requests don't
time out waiting for a connection. Downloads use the shared media HTTP
client, the same one other app images use, which on iOS now runs over
HTTP/2 since [#8897 iOS
HTTP/2](https://github.com/block/buzz/pull/8897).
- Memory: the picker keeps no image cache of its own. Each view decodes,
downsampled to 84 px and at most four at a time, from bytes Flutter
already holds in memory or on disk.
- Disk: emoji go into the existing 250 MB LRU media cache.

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-17 09:04:38 -08:00
Tom Brow
1059d81fc2 fix(ios): end each bold or strikethrough run at its first closing marker (#9559)
Bold and strikethrough runs in iOS push notification bodies now end at
their first closing marker, so a message with two bold runs on one line
shows both without their markers.

Before, the run's optional group was greedy and stretched to the last
marker on the line:

| Message | Before | After |
| --- | --- | --- |
| `option **A** or option **B**` | `option A** or option **B` | `option
A or option B` |
| `~~x~~ and ~~y~~` | `x~~ and ~~y` | `x and y` |
| `**😀** and **b**` | `😀** and **b` | `😀 and b` |

The fix makes that group lazy (`(?:.*?\S)??`). Found while reviewing the
Dart port in [#9556 Dart notification
body](https://github.com/block/buzz/pull/9556), which must match these
fixtures. That PR takes the same pattern once this one lands.

### Validation

- Added tests: three shared rows in
`test-fixtures/notification-body.json`, one per row above. All three
fail with the old pattern.
- All 70 BuzzPushKit tests pass on macOS, including the other 36 fixture
rows, which are unchanged.

### Regressions

None expected. The pattern still needs non-space characters right inside
both markers and still stays on one line. It now stops at the first
closing marker where before it reached for the last one. The output
changes only where a one-character run is followed by the same marker
later on the line, for example `**a** costs 2**3`, which was `a** costs
23` and is now `a costs 2**3`. Worst-case time for unclosed markers is
unchanged (measured during review of the Dart port).

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
2026-11-17 12:04:04 -05:00