constitution · epochs · watch · epoch 3

comparison

c_97611919bf0b (tommy-mor) vs c_e2ee16c7ada5 (tommy-mor)

download prompt · raw event · cmp_6dd23248578be2

council reasoning

~anthropic/claude-sonnet-latest · winner B · 60:40 · permalink

Side B is a coherent, testable identity refactor (splitting canonical_path/identity, making delegate optional, removing sigil-mangling in the reducer, plus new integration tests asserting rejection of '@') that fixes a real correctness/security concern in wire identity handling. Side A is a large mechanical rename (CanonicalItemUrl -> ItemId) that mostly shuffles code between files/modules without adding new capability, and even leaves an unfinished plan.md-driven refactor with fallback 'opaque' hacks that weaken the type safety it claims to add.

~x-ai/grok-latest · winner A · 3:1 · permalink

A replaces CanonicalItemUrl with a first-class ItemId across reducer maps, ranking, RPC, HTML routing, and types (new item_id/item_wire modules), which is a lasting core-domain design change. B’s split of path/identity helpers, no-@ wire form, and optional delegate improve API boundaries and module hygiene, but they are narrower contract/layering cleanups than A’s graph-wide identity migration.

openai/gpt-chat-latest · winner A · 4:1 · permalink

Side A introduces a new structural `ItemId` type, extracts shared wire-normalization into `item_wire`, and propagates the new identity model through reducer state, ranking, routing, HTML, RPC, and tests, replacing pervasive `CanonicalItemUrl` usage with a stronger abstraction. Side B usefully separates identity and path normalization into dedicated modules and cleans up API semantics around usernames/delegates, but it is primarily an architectural reorganization and wire-format adjustment rather than the broad foundational data-model change implemented in Side A.

sides

A — c_97611919bf0b (tommy-mor)

message

[3b3d5873] item refactor

diff preview

diff --git a/plan.md b/plan.md
deleted file mode 100644
index 00d6867a1e0ed144a16a020ea037f685ce646c73..0000000000000000000000000000000000000000
--- a/plan.md
+++ /dev/null
@@ -1,155 +0,0 @@
-# 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<String> (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<ItemId>` — 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<str>`** 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<str>`** 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/api/helpers.rs b/server/src/api/helpers.rs
index 1b291db83df7364a026f2e147e0a2

… preview truncated; 100,301 characters omitted

download full diff A

B — c_e2ee16c7ada5 (tommy-mor)

message

[80ad7753] refactor: split canonical_path and identity; strict wire identity without @

- Add canonical_path.rs (tag + item URL normalization) and identity.rs
  (parse_username/parse_agent; reject @ in API input).
- Slim events.rs to event types only; reducer applies no identity rewriting.
- JSON APIs return stored-form usernames and agent ids; HTML keeps @/@@ for display.
- Optional delegate on ingest; CLI and tests use naked uuid:rig:model.

Made-with: Cursor

diff preview

diff --git a/cli/src/main.rs b/cli/src/main.rs
index 5ac8e289f2b7a366b5959d9338d02f9b546f408a..630c5dea1f78c0ec9bc53e6b96234a0dc75bb705 100644
--- a/cli/src/main.rs
+++ b/cli/src/main.rs
@@ -61,8 +61,8 @@ enum Command {
         /// Example: --before 2026-06-01
         #[arg(long, value_name = "DATE_OR_MS")]
         before: Option<String>,
-        /// Filter to posts from this actor (UUID prefix match).
-        /// Example: --actor 4d9d6173
+        /// Filter to posts from this principal username (prefix match, stored form).
+        /// Example: --actor alice
         #[arg(long, value_name = "PREFIX")]
         actor: Option<String>,
         /// Fetch a single post by its ingest ID (from --json output).
@@ -75,9 +75,8 @@ enum Command {
     ///
     /// SYNTAX:
     ///
-    /// Actor (required, once per document):
-    ///   @<uuid>:<rig>:<model>
-    ///   Example: @7a3b9c2d-1234-5678-90ab-cdef12345678:claudecode:anthropic/claude-sonnet
+    /// Identity: human comes from the bearer token; optional AI delegate from `--delegate`
+    /// (`uuid:rig:provider/model`). The document body is DSL only (items, votes, prose) — no `@` lines.
     ///
     /// Thread (required, once per document):
     ///   #thread-tag
@@ -109,7 +108,7 @@ enum Command {
     ///   Example: ~/python > ~/rust { Python's simpler syntax reduces learning curve. }
     ///
     /// Prose (optional, anywhere):
-    ///   Any line that doesn't start with @, #, or ~ is prose.
+    ///   Any line that doesn't start with # or ~ (or `http`) is prose.
     ///   Prose is displayed in thread context but does not affect rankings or items.
     ///   Use prose to write blog posts, reasoning, or notes within your ingest.
     ///
@@ -125,8 +124,7 @@ enum Command {
     /// EXAMPLES:
     ///
     ///   # From heredoc (recommended for agents)
-    ///   npx slugsocial ingest << 'EOF'
-    ///   @7a3b9c2d-1234-5678-90ab-cdef12345678:claudecode:anthropic/claude-sonnet
+    ///   npx slugsocial ingest --delegate '7a3b9c2d-1234-5678-90ab-cdef12345678:claudecode:anthropic/claude-sonnet' << 'EOF'
     ///   #languages: Python vs Rust for systems programming
     ///
     ///   ~/languages/python { A high-level language with simple syntax and rich ecosystem. }
@@ -153,14 +151,9 @@ enum Command {
         /// Thread identifier (public tag like "languages", without #).
         #[arg(long, env = "SLUG_THREAD", default_value = "public", value_name = "THREAD")]
         thread: String,
-        /// Agent delegate identity (request form), e.g. @@uuid:rig:provider/model
-        #[arg(
-            long,
-            env = "SLUG_DELEGATE",
-            default_value = "@@00000000-0000-0000-0000-000000000000:cli:local/dev",
-            value_name = "DELEGATE"
-        )]
-        delegate: String,
+        /// Agent delegate `uuid:rig:provider/model`. Omit for human-only ingests.
+        #[arg(long, env = "SLUG_DELEGATE", value_name = "DELEGATE")]
+        delegate: Option<String>,
         /// Output as JSON for agent parsing
         #[arg(long)]
         json: bool,
@@ -174,14 +167,9 @@ enum Command {
         /// Thread identifier (public tag like "languages", without #).
         #[arg(long, env = "SLUG_THREAD", default_value = "public", value_name = "THREAD")]
         thread: String,
-        /// Agent delegate identity (request form), e.g. @@uuid:rig:provider/model
-        #[arg(
-            long,
-            env = "SLUG_DELEGATE",
-            default_value = "@@00000000-0000-0000-0000-000000000000:cli:local/dev",
-            value_name = "DELEGATE"
-        )]
-        delegate: String,
+        /// Agent delegate `uuid:rig:provider/model`. Omit for human-only ingests.
+        #[arg(long, env = "SLUG_DELEGATE", value_name = "DELEGATE")]
+        delegate: Option<String>,
         /// Output as JSON for agent parsing
         #[arg(long)]
         json: bool,
@@ -193,10 +181,10 @@ enum Command {
     /// Useful for agents to catch up on activity after a context reset.
     ///
     /// Examples:
-    ///   npx slugsocial feed @<uuid>:<rig>:<model>
-    ///   npx slugsocial feed @<uuid>:<rig>:<model> --since 2026-01-01
+    ///   npx slugsocial feed tommy
+    ///   npx slugsocial feed tommy --since 2026-01-01
     Feed {
-        /// Actor identifier (@uuid:rig:model)
+        /// Principal username (stored form)
         #[arg(value_name = "ACTOR")]
         actor: String,
         /// Override the lower bound. Accepts Unix ms or YYYY-MM-DD.
@@ -455,7 +443,7 @@ fn print_rank_history_response(resp: &slug_types::RankHistoryResponse) {
             label,
         );
         for v in &e.caused_by {
-            println!("    {} {} {} {}", v.a, v.ratio, v.b, v.actor.as_deref().map(|a| format!("  (@{})", a)).unwrap_or_default());
+            println!("    {} {} {} {}", v.a, v.ratio, v.b, v.actor.as_deref().map(|a| format!("  ({})", a)).unwrap_or_default());
             if !v.body.is_empty() {
                 println!("      {}", v.body.lines().next().unwrap_or(&v.body).trim());
             }
@@ -1116,7 +1104,7 @@ async fn main() -> Result<()> {
             IdentityCmd::Start { rig, model, json } => {
                 let client = http_client()?;
                 let uuid = uuid::Uuid::new_v4().to_string();
-                let delegate = format!("@@{}:{}:{}", uuid, rig, model);
+                let delegate = format!("{uuid}:{rig}:{model}");
 
                 let start: PendingSessionStartResponse = expect_json(
                     client
diff --git a/server/src/api/auth.rs b/server/src/api/auth.rs
index cb0faa29b834931e2c2b2f5c174c875e2e2e9346..995ce4a61d29b024c399c656134f541ecfd880cf 100644
--- a/server/src/api/auth.rs
+++ b/server/src/api/auth.rs
@@ -12,10 +12,8 @@ use tokio::sync::RwLock;
 
 use crate::{
     api::helpers::{api_error, now_ms, sha256_hex},
-    events::{
-        canonicalize_username, validate_agent_format, validate_username,
-        Event, TokenIssued, UserRegistered,
-    },
+    events::{Event, TokenIssued, UserRegistered},
+    identity::{parse_agent, parse_username},
     html::{auth_complete_page, auth_signed_in_fragment, choose_username_error_fragment, choose_username_page},
     state::{AppState, PendingSession},
 };
@@ -77,9 +75,9 @@ fn verify_token(reduced: &crate::reducer::ReducerState, bearer: &str) -> Result<
     Ok(username)
 }
 
-fn issue_token_for_user(username: &str) -> (String, TokenIssued, String) {
-    // Returns: (bearer, event, canonical_username)
-    let canonical_user = canonicalize_username(username);
+/// `stored_username` must already be in persisted shape (lowercase slug, no `@`).
+fn issue_token_for_user(stored_username: &str) -> (String, TokenIssued) {
+    let username = stored_username.to_string();
     let token_id = {
         let mut id = String::new();
         let alphabet = b"abcdefghijklmnopqrstuvwxyz0123456789";
@@ -103,13 +101,13 @@ fn issue_token_for_user(username: &str) -> (String, TokenIssued, String) {
     let bearer = format!("slug_{token_id}_{secret}");
     let event = TokenIssued {
         ts: now_ms(),
-        username: canonical_user.clone(),
+        username: username.clone(),
         token_id,
         token_hash,
         salt,
         issued_via: "oauth".to_string(),
     };
-    (bearer, event, canonical_user)
+    (bearer, event)
 }
 
 #[derive(Debug, Deserialize)]
@@ -207,7 +205,7 @@ pub async fn get_auth_callback(Query(q): Query<AuthCallbackQuery>, State(state):
         s.provider = Some("google".to_string());
         s.provider_id = Some(sub.clone());
         if let Some(username) = existing {
-            let (bearer, token_event, canon_user) = issue_token_for_user(&username);
+            let (bearer, token_event) = issue_token_for_user(&username);
             // append token event
             let ev = Event::TokenIssued(token_event);
             if let Err(err) = state.event_log.append(&ev).await {
@@ -217,7 +215,7 @@ pub async fn get_auth_callback(Query(q): Query<AuthCallbackQuery>, State(state):
                 let mut reduced = reduced_arc.write().await;
                 reduced.apply_event(ev);
             }
-            s.complete = Some((canon_user, bearer));
+            s.complete = Some((username, bearer));
             return Redirect::temporary(&format!("{public_url}/auth/complete")).into_response();
         }
     }
@@ -251,9 +249,10 @@ pub async fn post_choose_username(
     State(state): State<AppState>,
     Form(form): Form<ChooseUsernameForm>,
 ) -> impl IntoResponse {
-    if let Err(msg) = validate_username(&form.username) {
-        return api_error(StatusCode::BAD_REQUEST, "invalid username", Some(msg)).into_response();
-    }
+    let canon_user = match parse_username(&form.username) {
+        Ok(u) => u,
+        Err(msg) => return api_error(StatusCode::BAD_REQUEST, "invalid username", Some(msg)).into_response(),
+    };
 
     let sessions = pending_sessions(&state);
     let (provider, provider_id, agent) = {
@@ -270,7 +269,7 @@ pub async fn post_choose_username(
         (provider, provider_id, s.agent.clone())
     };
 
-    if let Err(msg) = validate_agent_format(&agent) {
+    if let Err(msg) = parse_agent(&agent) {
         return api_error(StatusCode::BAD_REQUEST, "invalid agent format", Some(msg)).into_response();
     }
 
@@ -280,7 +279,7 @@ pub async fn post_choose_username(
     if reduced.users_by_provider.contains_key(&provider_key) {
         return api_error(StatusCode::CONFLICT, "provider already registered", None).into_response();
     }
-    if reduced.users_by_provider.values().any(|u| u == &canonicalize_username(&form.username)) {
+    if reduced.users_by_provider.values().any(|u| u == &canon_user) {
         drop(reduced);
         return choose_username_error_fragment(&form.session, "that username is taken — try another").into_response();
     }
@@ -288,12 +287,12 @@ pub async fn post_choose_username(
 
     let ur = Event::UserRegistered(UserRegistered {
         ts: now_ms(),
-        username: canonicalize_username(&form.username),
+        username: canon_user.clone(),
         provider: provider.to_lowercase(),
         provider_id: provider_id.clone(),
     });
 
-    let (bearer, ti, canon_user) = issue_token_for_user(&form.username);
+    let (bearer, ti) = issue_token_for_user(&canon_user);
     let ti_ev = Event::TokenIssued(ti);
 
     // Persist events.
@@ -325,15 +324,18 @@ pub async fn post_pending_session(
     State(state): State<AppState>,
     Json(req): Json<PendingSessionStartRequest>,
 ) -> impl IntoResponse {
-    if let Err(msg) = validate_agent_format(&req.agent) {
-        return api_error(StatusCode::BAD_REQUEST, "invalid agent format", Some(msg)).into_response();
-    }
+    let agent_naked = match parse_agent(&req.agent) {
+        Ok(a) => a,
+        Err(msg) => {
+            return api_error(StatusCode::BAD_REQUEST, "invalid agent format", Some(msg)).into_response();
+        }
+    };
     let session = format!("p_{}", uuid::Uuid::new_v4().simple());
     let public_url = std::env::var("SLUG_PUBLIC_URL").unwrap_or_else(|_| "http://127.0.0.1:8080".to_string());
     let login_url = format!("{public_url}/auth/login?session={}", urlencoding::encode(&session));
     let poll_url = format!("/api/v0/pending-session/{}", session);
     let s = PendingSession {
-        agent: req.agent.clone(),
+        agent: agent_naked,
         created_ts: now_ms(),
         provider: None,
         provider_id: None,
@@ -359,7 +361,7 @@ pub async fn get_pending_session(
         return api_error(StatusCode::NOT_FOUND, "unknown session", None).into_response();
     };
     let (complete, user, token) = match &s.complete {
-        Some((u, t)) => (true, Some(format!("@{}", u)), Some(t.clone())),
+        Some((u, t)) => (true, Some(u.clone()), Some(t.clone())),
         None => (false, None, None),
     };
     Json(PendingSessionPollResponse {
@@ -388,7 +390,7 @@ pub async fn get_whoami(State(state): State<AppState>, headers: HeaderMap) 

… preview truncated; 62,772 characters omitted

download full diff B

Hardlinks — judgments / attempts / prompt

prompt download

judgments

attempts

Prompt text is loaded only by the download route.