You are a constitutional council ranking individual git commits for ownership allocation. Compare these two commits. Decide which contributed more lasting value to the project. Judge substance, not spectacle: - Prefer correct, lasting design and real bugfixes over churn, formatting, renames, or generated noise. - Prefer clarity and necessity over sheer line count. A small precise change can beat a large diffuse one. - Do not favor a side merely because its patch is longer or noisier. - Weight what the change does for the project, not the contributor's name. Return ONLY a JSON object: {"winner": "A" or "B", "ratio": "N:M", "explanation": "..."} The explanation must cite concrete differences in the patches (1-3 sentences). Side A — contributor: tommy-mor Side A — commit message: [1c914c6e] stage set Side A — unified diff (full patch): diff --git a/plan.md b/plan.md new file mode 100644 index 0000000000000000000000000000000000000000..00d6867a1e0ed144a16a020ea037f685ce646c73 --- /dev/null +++ b/plan.md @@ -0,0 +1,155 @@ +# Plan: `ItemId` + `RouteContext` (identity vs hrefs) + +This document is for **the next agent** to continue the refactor without re-deriving context from chat. It supersedes ad-hoc notes: treat it as the checklist of record until the work lands and this file is deleted or trimmed. + +## Goal + +- **Identity** (what lives in the reducer graph, votes, indexes) becomes a **structural `ItemId` enum** in `slug-types`, not a canonical `String` / `CanonicalItemUrl` newtype. +- **Presentation** (tilde / dash display, breadcrumbs) derives from `ItemId` via explicit methods, not string stripping. +- **Routing** (browser `href`s for public vs room) goes through **`RouteContext`** (started in `server/src/html/routing.rs`) so Maud/handlers do not stitch `/r/…` vs `/~` ad hoc. + +**Non-goals for v1 of the migration:** backward-compatible JSONL or dual-read of old canonical strings in the event log (project has accepted breaking changes). If you reintroduce compat, document it here. + +## Current state (as of this plan) + +- **`CanonicalItemUrl`** (`types/src/paths.rs`): newtype around `String`; `parse` / `parent` / `display_path` / `tilde_tail` / etc. Reducer `ContentState`, `VoteData`, ranking, RPC, search, garden, breadcrumbs all use it or `String` keys derived from it. +- **`ThreadNav`** (`server/src/html/forum/nav.rs`): encodes scope prefixes for threads and garden URLs; **`RouteContext`** now wraps `ThreadNav` (`server/src/html/routing.rs`, re-exported from `server/src/html/mod.rs`) but **most HTML still takes `&ThreadNav` directly** — migration incomplete. +- **URL normalization** lives in `types/src/url_normalize.rs` + `canonicalize_item` / `finalize_external_identity_url` in `paths.rs` (YouTube, sorted query params, room path `room_route_segment` in `paths.rs`). +- **Room HTTP paths** are `/r/{short}{slug}` (fused segment); wire **`room_id`** remains `short/slug` for RPC/events. + +## Target architecture + +### `ItemId` (types) + +Suggested shape (adjust after profiling `Ord` / `Hash` / serde size): + +```text +ItemId::Root — tilde ontology root (today `SLUG_TILDE_ONTOLOGY_ROOT`) +ItemId::Local { segments } — slug.social ~/… path as Vec (lowercase segments, non-empty for non-root) +ItemId::External { url: Url } — normalized `url::Url` (crate `url` already in `slug-types`) +``` + +**API surface (minimum):** + +- `ItemId::parse(&str) -> Option` — single entry from DSL / user input / legacy wire (internally may call `canonicalize_item` + structured split). +- `ItemId::to_wire_url(&self) -> String` — only for **external** boundaries if needed (HTTP fetch, rare assertions); avoid using as the primary key once maps use `ItemId`. +- `parent`, `display_path`, `tilde_tail` / `tilde_http_tail`, `tilde_segments`, `last_segment`, `normalized_storage` — port from `CanonicalItemUrl`. +- **`Ord` + `Hash` + `Eq`** stable for `BTreeSet` / `HashMap` (see `write_actor` scope-rank snapshots). +- **`Serialize` / `Deserialize`** — decide **tagged JSON** for any persisted or API-carried structs (e.g. `VoteData` in tests). If RPC must stay stringy for clients, use a **DTO layer** that converts `ItemId` ↔ wire at the boundary only. + +**Remove:** `CanonicalItemUrl` type and all `path_types::CanonicalItemUrl` / `slug_types::paths::CanonicalItemUrl` exports once call sites are migrated. **`Borrow`** on the old newtype goes away; update `nav!` / any code that assumed map keys borrowed as `str`. + +### `RouteContext` (server HTML) + +- **File:** `server/src/html/routing.rs` — **`RouteContext(ThreadNav)`** with `item_href`, `item_href_raw`, `thread_url`, `garden_root_url`, `room_url`, `From`/`Into` `ThreadNav`. +- **Direction:** new code and refactored Maud should take **`&RouteContext`** (or owned where appropriate) instead of `&ThreadNav` when building links. Long term, **`item_href(&ItemId)`** should not parse strings — it should pattern-match `ItemId` and append tilde tail or `/-/…` external tail using the same rules as today’s `ThreadNav::garden_item_url`. + +### Axum / garden routes + +- **No** single catch-all route (explicit decision): keep the existing router layout in `server/src/lib.rs`. +- Room routes stay **`/r/:room_key/...`** with `room_key` fused; parsing via `slug_types::room_id_from_route_segment` / `room_route_segment` in `paths.rs`. + +## Phased execution (recommended order) + +### Phase 0 — Preconditions (quick) + +1. Read **`AGENTS.md`** (UI contract, durability matrix, `RpcCommand` vs `HtmlUiAction`). +2. Run **`cargo test --workspace`** and **`./scripts/clj-test.sh`** on clean `main` before large diffs; repeat after each phase. + +### Phase 1 — `ItemId` in `slug-types` (no server yet) + +1. Add **`ItemId`** (new file e.g. `types/src/item_id.rs` **or** inline at bottom of `paths.rs` — see **Module cycle** below). +2. Implement **`ItemId::parse`** using existing **`canonicalize_item`** + normalization; port **`CanonicalItemUrl`** methods to **`ItemId`** with tests ported from `paths.rs` `#[cfg(test)] mod tests`. +3. **`GardenItemUrl::from_stored(&ItemId, room_wire)`** (and thread helpers) — build absolute hrefs from structure, not from re-parsing a canonical string. +4. **`TildeHttpPathTail::to_item_id`** (rename from `to_canonical`) / **`tilde_http_path_to_item_id`**. +5. **`TildeOntologyPath::from_stored(&ItemId)`**. +6. Export **`ItemId`** from **`types/src/lib.rs`**; update **`server/src/path_types.rs`** re-exports. +7. **Delete `CanonicalItemUrl`** and fix all **in-crate** references in `types` only until `cargo test` passes for `slug-types`. + +**Module cycle trap:** `item_id.rs` must not `use crate::paths::{...}` if `paths.rs` also imports `ItemId` for `GardenItemUrl` in the same module. **Fix one of:** + +- **A)** Put `ItemId` **inside `paths.rs`** below `canonicalize_item` / helpers (simplest, large file), or +- **B)** Split **`canonicalize_item`** (+ dash host helpers + `finalize_external_identity_url`) into **`types/src/item_wire.rs`**, then `paths.rs` + `item_id.rs` both depend on `item_wire` only (cleaner, more files). + +### Phase 2 — Reducer + ranking (server core) + +1. **`server/src/reducer.rs`**: `ContentState` / `GroupState` / **`VoteData`** — replace **`CanonicalItemUrl`** with **`ItemId`** on all maps, sets, deques, vectors. +2. **`apply_vote`**: normalize `a`/`b` via **`ItemId::parse`** or **`ItemId`**-aware logic (remove string round-trip). +3. **`apply_ingest_to_content`**: **`dsl`** still yields strings for item titles in statements; normalize to **`ItemId`** at ingest boundary via **`ItemId::parse`** once per item. +4. **`server/src/ranking.rs`**, **`server/src/scope_rank.rs`**, **`server/src/api/write_actor.rs`** (including **`BTreeSet`** ordering), **`server/src/api/validate.rs`**, **`server/src/api/helpers.rs`** — propagate **`ItemId`**. +5. **`server/tests/basic.rs`** and any reducer tests constructing **`VoteData`** — use **`ItemId::parse(...).unwrap()`** or helpers. + +### Phase 3 — RPC + search + external resolver + +1. **`server/src/api/rpc.rs`**: rank/pair/matchup/search payloads; today many paths use **`GardenItemUrl::from_storage_str(item.as_str(), …)`** — switch to **`ItemId`** + **`GardenItemUrl::from_stored(&item_id, …)`** (or equivalent). +2. **`server/src/html/search.rs`**: scoring uses item path strings — derive from **`ItemId::display_path`** / **`to_wire_url`** only at the scoring boundary if needed. +3. **`server/src/external_resolver.rs`**: take **`&ItemId`** or **`ItemId::external_url()`** instead of **`&CanonicalItemUrl`**. + +### Phase 4 — HTML / Maud + +1. **`ThreadNav::garden_item_url`**: overload or replace with **`garden_item_href(&self, item: &ItemId)`** (no `CanonicalItemUrl::parse` inside). +2. **`RouteContext`**: extend **`item_href(&ItemId)`**; migrate call sites from **`ThreadNav`** to **`RouteContext`** where only link-building is needed (keep **`ThreadNav`** where scope / auth helpers need the full struct). +3. **`server/src/html/garden.rs`**, **`breadcrumb_path.rs`**, **`forum/*`**, **`editor.rs`**: replace **`CanonicalItemUrl`** with **`ItemId`**; breadcrumbs should walk **`ItemId::parent`** without string `rsplit`. +4. **`types` JSON types** (`RankRow`, etc.): decide whether **`GardenItemUrl`** stays string for JSON or becomes a structured field; keep **one** wire format for the public API. + +### Phase 5 — Cleanup + docs + +1. Remove dead **`canonical_path`** / **`breadcrumb_path`** string logic if fully superseded. +2. Update **`AGENTS.md`** if durability, `POST /ui`, or command surfaces change. +3. Delete or shrink **`plan.md`** when done. + +## File / symbol checklist (non-exhaustive — grep-driven) + +Run periodically: + +```bash +rg "CanonicalItemUrl" -g'*.rs' +rg "path_types::CanonicalItemUrl" -g'*.rs' +rg "tilde_http_path_to_canonical" -g'*.rs' +``` + +**High-touch files (from prior exploration):** + +| Area | Files | +|------|--------| +| Types | `types/src/paths.rs`, `types/src/lib.rs`, `types/src/url_normalize.rs`, (optional) `types/src/item_id.rs`, `types/src/item_wire.rs` | +| Server re-exports | `server/src/path_types.rs`, `server/src/canonical_path.rs` | +| Reducer / ingest | `server/src/reducer.rs`, `server/src/dsl.rs` (parse output types if changed) | +| Ranking | `server/src/ranking.rs`, `server/src/scope_rank.rs` | +| Writer / RPC | `server/src/api/write_actor.rs`, `server/src/api/rpc.rs`, `server/src/api/helpers.rs`, `server/src/api/validate.rs` | +| HTML | `server/src/html/garden.rs`, `server/src/html/breadcrumb_path.rs`, `server/src/html/forum/nav.rs`, `server/src/html/routing.rs`, `server/src/html/search.rs`, `server/src/html/editor.rs`, `server/src/html/forum/ingest.rs`, … | +| Tests | `server/tests/basic.rs`, `server/tests/integration.rs`, `types/src/paths.rs` tests, Clojure under `test/` if URLs/assertions mention canonical shapes | + +## Events / JSONL + +- **`Ingest`** events store **`raw` DSL** only — no change required for item identity inside the event. +- If any future event type stores item ids as strings, migrate to **structured `ItemId` serde** or accept string only at the event boundary with immediate parse into **`ItemId`** on `apply_event`. + +## `nav!` macro (`server/src/paths.rs`) + +- Macros use **`keypath($key)`** with **`.clone()`** — **`ItemId`** must be **`Clone`** (already for enums). Remove any reliance on **`Borrow`** for map keys. + +## Testing gate + +After each phase: + +```bash +cargo test --workspace +./scripts/clj-test.sh +``` + +## Risks / gotchas + +1. **`Ord` on `ItemId`**: must match prior **`CanonicalItemUrl`** / `String` ordering wherever **`BTreeSet`** is used (e.g. deterministic scope-rank snapshots in **`write_actor`**). +2. **External `ItemId`**: **`Url`** equality / hashing — normalization is already centralized in **`url_normalize`**; ensure **`ItemId::parse`** always inserts normalized **`Url`** into **`External`**. +3. **Fake parent URLs** in garden (e.g. **`https://.`** for external root ranking): find all **`parse("https://.")`** style hacks and express as **`ItemId`** or a dedicated sentinel. +4. **Serde**: tests and any RPC clients that snapshot JSON may need expectation updates if **`VoteData`** shape changes. + +## Optional follow-ups (not blocking `ItemId`) + +- More **domain normalizers** in **`url_normalize.rs`** (e.g. `music.youtube.com`, Spotify, etc.). +- **Room wire** vs **HTTP segment** helpers already in **`paths.rs`** (`ROOM_SHORT_ID_LEN`, `room_route_segment`, `room_id_from_route_segment`). + +--- + +**End state criteria:** `rg CanonicalItemUrl` returns nothing; reducer maps use **`ItemId`**; HTML link generation for items goes through **`RouteContext` + `ItemId`**; tests and Kaocha green. diff --git a/server/src/html/mod.rs b/server/src/html/mod.rs index c3dccd03dc6da2a2f6f6fa828657e33a951884b1..668403a35c415e6f091362b28c63ac294057fb6d 100644 --- a/server/src/html/mod.rs +++ b/server/src/html/mod.rs @@ -15,6 +15,7 @@ mod breadcrumb_path; mod editor; mod forum; mod garden; +pub mod routing; mod search; pub mod ui_action; use breadcrumb_path::{ExternalOntologyPath, OntologyPath}; @@ -35,6 +36,7 @@ pub use garden::{ external_garden_index, external_ontology_path, garden_index, ontology_path, room_external_garden_index, room_external_ontology_path, room_garden_index, room_ontology_path, }; +pub use routing::RouteContext; pub use search::{search_page, search_results_fragment}; pub use forum::user_profile_page; pub use ui_action::{parse_html_ui_from_form, HtmlUiAction, HtmlUiParseError, UI_RPC_FIELD}; diff --git a/server/src/html/routing.rs b/server/src/html/routing.rs new file mode 100644 index 0000000000000000000000000000000000000000..13e9ae0cbe32d454e34a7737edf8234d2a558502 --- /dev/null +++ b/server/src/html/routing.rs @@ -0,0 +1,71 @@ +//! Scoped browser paths for HTML. **RouteContext** is the intended single place to build `href`s +//! given public vs room scope (the original blueprint name); today it wraps [`ThreadNav`]. +//! +//! Prefer `RouteContext::item_href` / [`RouteContext::thread_url`] in new Maud over stitching +//! `/r/…` vs `/~` manually. Call sites can migrate incrementally from passing `&ThreadNav`. + +use crate::path_types::CanonicalItemUrl; + +use super::forum::ThreadNav; + +#[derive(Clone)] +pub struct RouteContext(ThreadNav); + +impl RouteContext { + #[inline] + pub fn public() -> Self { + Self(ThreadNav::public()) + } + + #[inline] + pub fn from_room_id(room_id: &str) -> Option { + ThreadNav::from_room_id(room_id).map(Self) + } + + #[inline] + pub fn thread_nav(&self) -> &ThreadNav { + &self.0 + } + + #[inline] + pub fn into_thread_nav(self) -> ThreadNav { + self.0 + } + + /// Relative path for a stored canonical item in this scope’s garden. + pub fn item_href(&self, item: &CanonicalItemUrl) -> String { + self.0.garden_item_url(item.as_str()) + } + + /// Same as [`Self::item_href`] but parses `item` first (raw DSL / user paste). + pub fn item_href_raw(&self, item: &str) -> String { + self.0.garden_item_url(item) + } + + #[inline] + pub fn thread_url(&self, tag: &str) -> String { + self.0.thread_url(tag) + } + + #[inline] + pub fn garden_root_url(&self) -> &str { + self.0.garden_root_url() + } + + #[inline] + pub fn room_url(&self) -> &str { + self.0.room_url() + } +} + +impl From for RouteContext { + fn from(nav: ThreadNav) -> Self { + Self(nav) + } +} + +impl From for ThreadNav { + fn from(ctx: RouteContext) -> Self { + ctx.0 + } +} Side B — contributor: tommy-mor Side B — commit message: [c94456ff] Make feed catch-up stable and permission-aware Anchor implicit feeds to durable ingest order and cover multi-user private-room visibility so concurrent posts are not missed or leaked. Co-authored-by: Cursor Side B — unified diff (full patch): diff --git a/cli/src/main.rs b/cli/src/main.rs index abb5a55b49f60fe28fbfd4ec02715cb94ea0b4ec..c4f1494df3aedbd8b883aea6249579aa8336abfe 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -878,6 +878,30 @@ mod tests { "graph: 4 items, 3/6 pairs (50.0% density), 1 component, connected" ); } + + #[test] + fn feed_without_since_uses_logged_in_delegate_from_env() { + let key = "SLUG_DELEGATE"; + let previous = std::env::var_os(key); + let expected = "00000000-0000-0000-0000-0000000000ee:test:local/model"; + std::env::set_var(key, expected); + + let cli = Cli::try_parse_from(["slugsocial", "feed"]).expect("parse feed"); + + match previous { + Some(value) => std::env::set_var(key, value), + None => std::env::remove_var(key), + } + match cli.cmd { + Some(Command::Feed { + delegate, since, .. + }) => { + assert_eq!(delegate.as_deref(), Some(expected)); + assert!(since.is_none()); + } + _ => panic!("expected feed command"), + } + } } async fn run_scoped(base: &str, room: &str, sub: ScopedCmd) -> Result<()> { @@ -1626,7 +1650,15 @@ async fn run() -> Result<()> { } else { for p in &resp.posts { let ago = slug_types::timeago::timeago(now_ms, p.ts); - println!("", p.id, ago); + let thread_attr = p + .thread + .as_deref() + .map(|thread| format!(" thread=\"{thread}\"")) + .unwrap_or_default(); + println!( + "", + p.id, ago, p.room, thread_attr + ); print!("{}", p.body); if !p.body.ends_with('\n') { println!(); } println!(""); diff --git a/server/src/api/rpc.rs b/server/src/api/rpc.rs index afc4f95bef160c1e38ecff2c096d6440cd94e2b3..46d748f918d9b225acc4ecedfe5a1793089407b5 100644 --- a/server/src/api/rpc.rs +++ b/server/src/api/rpc.rs @@ -72,6 +72,80 @@ fn can_view_scope(reduced: &ReducerState, scope: &ScopeId, principal: Option<&st } } +/// Build a feed in durable ingest order. +/// +/// An implicit feed boundary is an ingest position, not only its millisecond timestamp. Two users +/// can post in the same millisecond, and wall-clock timestamps can move backwards during replay. +/// Explicit `since` remains a timestamp query for API compatibility, but scans the whole ordered +/// ledger rather than assuming timestamps are monotonic. +fn rpc_feed( + reduced: &ReducerState, + viewer: &str, + delegate: Option, + requested_since: Option, + implicit_anchor: Option<(usize, i64)>, + limit: usize, +) -> FeedResponse { + let since = requested_since.or_else(|| implicit_anchor.map(|(_, ts)| ts)); + let implicit_anchor_index = requested_since + .is_none() + .then(|| implicit_anchor.map(|(index, _)| index)) + .flatten(); + + let matching: Vec<&str> = reduced + .ingests_ordered + .iter() + .enumerate() + .rev() + .filter(|(index, id)| { + reduced.ingests_by_id.get(id.as_str()).is_some_and(|ing| { + match requested_since { + Some(cutoff) => ing.ts > cutoff, + None => implicit_anchor_index.is_none_or(|anchor| *index > anchor), + } + }) + }) + .map(|(_, id)| id.as_str()) + .filter(|id| { + reduced.ingests_by_id.get(*id).is_some_and(|ing| { + let scope = scope_from_room_wire(&ing.room_id); + can_view_scope(reduced, &scope, Some(viewer)) + }) + }) + .filter(|id| !reduced.redacted_posts.contains(*id)) + .collect(); + + let total = matching.len(); + let posts = matching + .into_iter() + .take(limit) + .filter_map(|id| reduced.ingests_by_id.get(id)) + .map(|ing| { + let scope = scope_from_room_wire(&ing.room_id); + let thread_post_index = reduced.try_thread_post_index_chronological( + &scope, + &ing.thread_tag, + &ing.id, + ); + FeedPost { + ts: ing.ts, + id: ing.id.clone(), + room: ing.room_id.clone(), + thread: Some(ing.thread_tag.clone()), + thread_post_index, + body: ing.raw.clone(), + } + }) + .collect(); + + FeedResponse { + delegate, + since, + posts, + total, + } +} + fn principal_from_optional_bearer(headers: &HeaderMap, reduced: &ReducerState) -> Result, RpcErr> { if headers.contains_key(axum::http::header::AUTHORIZATION) { verify_bearer_principal(headers, reduced) @@ -1506,60 +1580,27 @@ pub async fn handle_rpc_batch( Some("this delegate is not bound to your signed-in account".into()), ) } else { - let since_default = reduced + let implicit_anchor = reduced .ingests_ordered .iter() + .enumerate() .rev() - .filter_map(|id| reduced.ingests_by_id.get(id)) - .find(|ing| { - if ing.delegate.as_deref() != Some(delegate_stored.as_str()) { - return false; - } - let scope = scope_from_room_wire(&ing.room_id); - can_view_scope(&reduced, &scope, Some(viewer.as_str())) - }) - .map(|ing| ing.ts); - let since = since.or(since_default); - let cutoff = since.unwrap_or(0); - let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT); - let matching: Vec<&str> = reduced.ingests_ordered.iter().rev() - .map(|id| id.as_str()) - .take_while(|id| reduced.ingests_by_id.get(*id).is_some_and(|ing| ing.ts > cutoff)) - .filter(|id| { - reduced.ingests_by_id.get(*id).is_some_and(|ing| { - let scope = scope_from_room_wire(&ing.room_id); - can_view_scope(&reduced, &scope, Some(viewer.as_str())) + .find_map(|(index, id)| { + reduced.ingests_by_id.get(id).and_then(|ing| { + (ing.delegate.as_deref() + == Some(delegate_stored.as_str())) + .then_some((index, ing.ts)) }) - }) - .filter(|id| !reduced.redacted_posts.contains(*id)) - .collect(); - let total = matching.len(); - let posts: Vec = matching.into_iter() - .take(limit) - .filter_map(|id| reduced.ingests_by_id.get(id)) - .map(|ing| { - let scope = scope_from_room_wire(&ing.room_id); - let thread_post_index = reduced - .try_thread_post_index_chronological( - &scope, - &ing.thread_tag, - &ing.id, - ); - FeedPost { - ts: ing.ts, - id: ing.id.clone(), - thread: Some(ing.thread_tag.clone()), - thread_post_index, - body: ing.raw.clone(), - } - }) - .collect(); - line_ok(RpcResult::Feed(FeedResponse { - delegate: Some(delegate_stored), + }); + let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT); + line_ok(RpcResult::Feed(rpc_feed( + &reduced, + &viewer, + Some(delegate_stored), since, - posts, - total, - })) + implicit_anchor, + limit, + ))) }; drop(reduced); line @@ -1567,60 +1608,25 @@ pub async fn handle_rpc_batch( None => { // Session catch-up: last time *you* posted anything (delegate or not), so revisiting // an old chat with only a token still gets a sane cutoff. - let since_default = reduced + let implicit_anchor = reduced .ingests_ordered .iter() + .enumerate() .rev() - .filter_map(|id| reduced.ingests_by_id.get(id)) - .find(|ing| { - if ing.principal != viewer { - return false; - } - let scope = scope_from_room_wire(&ing.room_id); - can_view_scope(&reduced, &scope, Some(viewer.as_str())) - }) - .map(|ing| ing.ts); - let since = since.or(since_default); - let cutoff = since.unwrap_or(0); - let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT); - let matching: Vec<&str> = reduced.ingests_ordered.iter().rev() - .map(|id| id.as_str()) - .take_while(|id| reduced.ingests_by_id.get(*id).is_some_and(|ing| ing.ts > cutoff)) - .filter(|id| { - reduced.ingests_by_id.get(*id).is_some_and(|ing| { - let scope = scope_from_room_wire(&ing.room_id); - can_view_scope(&reduced, &scope, Some(viewer.as_str())) + .find_map(|(index, id)| { + reduced.ingests_by_id.get(id).and_then(|ing| { + (ing.principal == viewer).then_some((index, ing.ts)) }) - }) - .filter(|id| !reduced.redacted_posts.contains(*id)) - .collect(); - let total = matching.len(); - let posts: Vec = matching.into_iter() - .take(limit) - .filter_map(|id| reduced.ingests_by_id.get(id)) - .map(|ing| { - let scope = scope_from_room_wire(&ing.room_id); - let thread_post_index = reduced - .try_thread_post_index_chronological( - &scope, - &ing.thread_tag, - &ing.id, - ); - FeedPost { - ts: ing.ts, - id: ing.id.clone(), - thread: Some(ing.thread_tag.clone()), - thread_post_index, - body: ing.raw.clone(), - } - }) - .collect(); - let line = line_ok(RpcResult::Feed(FeedResponse { - delegate: None, + }); + let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT); + let line = line_ok(RpcResult::Feed(rpc_feed( + &reduced, + &viewer, + None, since, - posts, - total, - })); + implicit_anchor, + limit, + ))); drop(reduced); line } diff --git a/server/tests/integration_rooms.rs b/server/tests/integration_rooms.rs index a3b378267e090a016a7e663f103a0dd9f482690b..e623523ba352ce456674a399542c689505760b78 100644 --- a/server/tests/integration_rooms.rs +++ b/server/tests/integration_rooms.rs @@ -1,6 +1,9 @@ mod support; use slug_types::room_route_segment; +use slugsocial_server::events::{ + AgentBound, Event, GrantAdded, GrantRevoked, Ingest, RoomCreated, ThreadCapability, +}; use support::*; #[tokio::test] @@ -473,6 +476,247 @@ async fn test_feed_without_delegate_uses_principal_last_post_including_delegate( ); } +#[tokio::test] +async fn test_feed_uses_delegate_ingest_position_when_multi_user_timestamps_collide() { + let (addr, _tmp, _log, state, _handle) = create_test_server_with_state().await; + seed_test_identity(&state, "bob", "bobtok", "bobsecret").await; + let client = reqwest::Client::new(); + let alice_delegate = + "00000000-0000-0000-0000-0000000000c1:feedtest:local/alice-model"; + let bob_delegate = + "00000000-0000-0000-0000-0000000000c2:feedtest:local/bob-model"; + + { + let mut reduced = state.reduced.write().await; + for (agent, username) in [ + (alice_delegate, "testuser"), + (bob_delegate, "bob"), + ] { + reduced.apply_event(Event::AgentBound(AgentBound { + ts: 1, + agent: agent.to_string(), + username: username.to_string(), + })); + } + reduced.apply_event(Event::Ingest(Ingest { + ts: 100, + id: "alice-anchor".into(), + raw: "alice anchor".into(), + principal: "testuser".into(), + delegate: Some(alice_delegate.into()), + room_id: "public".into(), + thread_tag: "feed-order".into(), + })); + reduced.apply_event(Event::Ingest(Ingest { + ts: 100, + id: "bob-same-millisecond".into(), + raw: "bob same-millisecond change".into(), + principal: "bob".into(), + delegate: Some(bob_delegate.into()), + room_id: "public".into(), + thread_tag: "feed-order".into(), + })); + // Event-log order remains authoritative even if the wall clock moves backwards. + reduced.apply_event(Event::Ingest(Ingest { + ts: 99, + id: "bob-clock-rollback".into(), + raw: "bob change after clock rollback".into(), + principal: "bob".into(), + delegate: Some(bob_delegate.into()), + room_id: "public".into(), + thread_tag: "feed-order".into(), + })); + } + + let feed = rpc_batch( + &client, + addr, + Some(&test_bearer()), + serde_json::json!([{ + "GetFeed": { "delegate": alice_delegate, "limit": 20 } + }]), + ) + .await; + let posts = feed["results"][0]["result"]["Feed"]["posts"] + .as_array() + .unwrap(); + let ids: Vec<&str> = posts.iter().filter_map(|p| p["id"].as_str()).collect(); + assert_eq!( + ids, + ["bob-clock-rollback", "bob-same-millisecond"], + "implicit feed cutoff must use append position, not timestamp" + ); +} + +#[tokio::test] +async fn test_feed_multi_user_private_room_visibility_and_revoked_anchor_access() { + let (addr, _tmp, _log, state, _handle) = create_test_server_with_state().await; + seed_test_identity(&state, "bob", "bobtok", "bobsecret").await; + seed_test_identity(&state, "carol", "caroltok", "carolsecret").await; + let client = reqwest::Client::new(); + let alice_delegate = + "00000000-0000-0000-0000-0000000000d1:feedtest:local/alice-model"; + let bob_delegate = + "00000000-0000-0000-0000-0000000000d2:feedtest:local/bob-model"; + let room_alice = "alice01/alice-room"; + let room_bob = "bob0001/bob-room"; + + { + let mut reduced = state.reduced.write().await; + for (agent, username) in [ + (alice_delegate, "testuser"), + (bob_delegate, "bob"), + ] { + reduced.apply_event(Event::AgentBound(AgentBound { + ts: 1, + agent: agent.to_string(), + username: username.to_string(), + })); + } + for (room_id, slug, owner) in [ + (room_alice, "alice-room", "testuser"), + (room_bob, "bob-room", "bob"), + ] { + reduced.apply_event(Event::RoomCreated(RoomCreated { + ts: 2, + room_id: room_id.to_string(), + slug: slug.to_string(), + owner: owner.to_string(), + })); + reduced.apply_event(Event::GrantAdded(GrantAdded { + ts: 2, + room_id: room_id.to_string(), + username: owner.to_string(), + capabilities: vec![ThreadCapability::View], + granted_by: owner.to_string(), + })); + } + + let mut add_ingest = + |ts, id: &str, raw: &str, principal: &str, delegate: Option<&str>, room: &str| { + reduced.apply_event(Event::Ingest(Ingest { + ts, + id: id.into(), + raw: raw.into(), + principal: principal.into(), + delegate: delegate.map(str::to_string), + room_id: room.into(), + thread_tag: "feed-permissions".into(), + })); + }; + add_ingest(10, "prehistory", "must remain before alice anchor", "carol", None, "public"); + add_ingest( + 11, + "alice-private-anchor", + "alice last posted here", + "testuser", + Some(alice_delegate), + room_alice, + ); + add_ingest( + 12, + "bob-public-anchor", + "bob last posted here", + "bob", + Some(bob_delegate), + "public", + ); + add_ingest(13, "alice-room-change", "visible only to alice", "carol", None, room_alice); + add_ingest(14, "bob-room-change", "visible only to bob", "carol", None, room_bob); + add_ingest(15, "public-change", "visible to everyone", "carol", None, "public"); + + reduced.apply_event(Event::GrantRevoked(GrantRevoked { + ts: 16, + room_id: room_alice.into(), + username: "testuser".into(), + capabilities: vec![ThreadCapability::View], + revoked_by: "testuser".into(), + })); + } + + let alice_feed = rpc_batch( + &client, + addr, + Some(&test_bearer()), + serde_json::json!([{ + "GetFeed": { "delegate": alice_delegate, "limit": 20 } + }]), + ) + .await; + let alice_posts = alice_feed["results"][0]["result"]["Feed"]["posts"] + .as_array() + .unwrap(); + let alice_ids: Vec<&str> = alice_posts + .iter() + .filter_map(|p| p["id"].as_str()) + .collect(); + assert_eq!( + alice_ids, + ["public-change", "bob-public-anchor"], + "revoked private content must be hidden without moving the delegate anchor backwards" + ); + assert!(!alice_ids.contains(&"prehistory")); + assert!( + alice_posts + .iter() + .all(|post| post["room"].as_str() == Some("public")), + "private posts must not leak and every feed post must identify its room" + ); + + let bob_bearer = test_bearer_for("bobtok", "bobsecret"); + let bob_feed = rpc_batch( + &client, + addr, + Some(&bob_bearer), + serde_json::json!([{ + "GetFeed": { "delegate": bob_delegate, "limit": 20 } + }]), + ) + .await; + let bob_ids: Vec<&str> = bob_feed["results"][0]["result"]["Feed"]["posts"] + .as_array() + .unwrap() + .iter() + .filter_map(|p| p["id"].as_str()) + .collect(); + assert_eq!(bob_ids, ["public-change", "bob-room-change"]); + assert_eq!( + bob_feed["results"][0]["result"]["Feed"]["posts"][1]["room"], + room_bob + ); + + // Restoring View exposes only changes after the same stable delegate anchor. + { + let mut reduced = state.reduced.write().await; + reduced.apply_event(Event::GrantAdded(GrantAdded { + ts: 17, + room_id: room_alice.into(), + username: "testuser".into(), + capabilities: vec![ThreadCapability::View], + granted_by: "testuser".into(), + })); + } + let restored = rpc_batch( + &client, + addr, + Some(&test_bearer()), + serde_json::json!([{ + "GetFeed": { "delegate": alice_delegate, "limit": 20 } + }]), + ) + .await; + let restored_ids: Vec<&str> = restored["results"][0]["result"]["Feed"]["posts"] + .as_array() + .unwrap() + .iter() + .filter_map(|p| p["id"].as_str()) + .collect(); + assert_eq!( + restored_ids, + ["public-change", "alice-room-change", "bob-public-anchor"] + ); +} + #[tokio::test] async fn test_private_room_thread_urls_use_t_segment() { let (addr, _tmp, _log, _handle) = create_test_server().await; diff --git a/server/tests/support/mod.rs b/server/tests/support/mod.rs index 4a620eaa875e7a1145f2a4e82cc4ff2be21d5345..a4320e991763617c1a760efad4b621977e2b74d0 100644 --- a/server/tests/support/mod.rs +++ b/server/tests/support/mod.rs @@ -20,8 +20,10 @@ pub fn sha256_hex(s: &str) -> String { /// Fixed bearer for integration tests (`TokenIssued` seeded into reducer in `create_test_server`). pub fn test_bearer() -> String { - let token_id = "testtok"; - let secret = "secret"; + test_bearer_for("testtok", "secret") +} + +pub fn test_bearer_for(token_id: &str, secret: &str) -> String { format!("slug_{token_id}_{secret}") } @@ -71,19 +73,27 @@ pub async fn rpc_batch( } pub async fn seed_test_token(state: &AppState) { + seed_test_identity(state, "testuser", "testtok", "secret").await; +} + +/// Add a distinct principal and bearer to a running integration-test server. +pub async fn seed_test_identity( + state: &AppState, + username: &str, + token_id: &str, + secret: &str, +) { let registered = Event::UserRegistered(UserRegistered { ts: 0, - username: "testuser".to_string(), + username: username.to_string(), provider: "test".to_string(), - provider_id: "testuser".to_string(), + provider_id: username.to_string(), }); - let token_id = "testtok"; - let secret = "secret"; let salt = "salt"; let token_hash = sha256_hex(&format!("{salt}:{secret}")); let ev = Event::TokenIssued(TokenIssued { ts: 0, - username: "testuser".to_string(), + username: username.to_string(), token_id: token_id.to_string(), token_hash, salt: salt.to_string(), diff --git a/types/src/lib.rs b/types/src/lib.rs index 211493935d19582607f5c87fb492faf47bdc6f53..cd6f94c60a4e1c3bfbce13bc0404b803f5f57c6d 100644 --- a/types/src/lib.rs +++ b/types/src/lib.rs @@ -264,6 +264,9 @@ pub struct FeedResponse { pub struct FeedPost { pub ts: i64, pub id: String, + /// Permission scope containing the post: `"public"` or a private room id. + #[serde(default)] + pub room: String, /// Primary thread tag (without #), if the ingest declared one. #[serde(skip_serializing_if = "Option::is_none")] pub thread: Option,