diff --git a/doc/2026-11-08T06-25-00Z_design_tag_scope/2026-11-08T06-25-00Z_design_tag_scope.md b/doc/2026-11-08T06-25-00Z_design_tag_scope/2026-11-08T06-25-00Z_design_tag_scope.md new file mode 100644 index 0000000000..eecec6f057 --- /dev/null +++ b/doc/2026-11-08T06-25-00Z_design_tag_scope/2026-11-08T06-25-00Z_design_tag_scope.md @@ -0,0 +1,68 @@ +# Tag scope: local-only vs shared claims (#1793) + +## 2026-11-08T06-25-00Z Design: tag scopes for pkgs/id + +### Request + +Issue #1793 bullet 2: tags (and petnames) can be scoped local-only or +shared, chosen at create/edit time, honoured by replication, and +existing tags can be reviewed and organised by scope. Bullet 1 (file +origin in listings) landed separately in PR #5191; this record covers +only the scope work, implemented in PR #7344. + +### Design approach + +- `TagScope` (`shared` | `local`) is carried on every live `Claim`, + defaulting to `shared`, so already-landed claims decode and behave + exactly as before. No migration reclassifies an existing claim. +- The signed `tag.set` wire form is untouched: no field is added, so + v1 event IDs and encodings are unchanged and a shared claim is + replicated exactly as it was before scopes existed. + +### Persistence boundary + +- Shared claims live in the signed event store, as before. +- Local claims live in a separate store beside the event store + (`local-claims.jsonl`, rewritten atomically). A local claim is never + signed and never enters the event store, so it never enters the + range-sync set and cannot reach another node. A test pins the sync + set unchanged across a local set/clear. + +### Publication behaviour + +- `tags_on`, `search` and the review listing merge shared and local + claims; every row carries its scope, so the two kinds are never + silently conflated. +- CLI: `id claim set --scope local|shared` selects scope at create + time; `id claim scope SUBJECT NAME SCOPE` moves a claim between + scopes; `id claim review` lists every visible claim with its scope. + +### Scope-conversion trade-offs + +- Moving shared → local copies the claim into the local store and + then clears only this node's own shared claims, by claim ID, so + another author's same-named claims are untouched. +- Moving local → shared publishes only this node's own local claims + (filtered by author) under its signing key, and then removes only + its own local originals. Publishing another identity's local claims + — possible when two identities share one `--event-store` with + different data directories — would leak claims their owner chose to + keep private; the author filter is the guard, and it matches the + shared → local direction. +- A move changes where a claim lives, never its name or value. + +### Petnames + +Petnames were already viewer-private by construction (local journal, +shown only to the owning account, never replicated). No scope choice +was added for them; existing tests pin the private behaviour. + +--- + +## 2026-11-08T06-25-00Z Update: record created during review + +This record was written when PR #7344's Codex review flagged its +absence (pkgs/id/AGENTS.md requires the record for new commands, a +new persistent store, and scope-conversion semantics). It documents +the design as implemented in that PR, plus the author-filter guard +for local → shared conversion added in the same review round. diff --git a/pkgs/id/src/aliases.rs b/pkgs/id/src/aliases.rs index e7814be786..6bcd2b3964 100644 --- a/pkgs/id/src/aliases.rs +++ b/pkgs/id/src/aliases.rs @@ -186,6 +186,7 @@ mod tests { subject, name: name.to_owned(), value: value.map(str::to_owned), + scope: crate::tag_claims::TagScope::Shared, } } diff --git a/pkgs/id/src/cli.rs b/pkgs/id/src/cli.rs index e02891a1f7..85c00a1adf 100644 --- a/pkgs/id/src/cli.rs +++ b/pkgs/id/src/cli.rs @@ -2646,6 +2646,9 @@ pub enum ClaimCommand { name: String, /// The tag value. Without one, the tag is bare. value: Option, + /// Whether the claim is shared with peers or stays on this node. + #[arg(long, value_enum, default_value = "shared")] + scope: ClaimScope, }, /// Clear the live claims with this name on a subject, whoever set them. Clear { @@ -2661,6 +2664,18 @@ pub enum ClaimCommand { /// The tag value to match as a whole. Without one, any value and a bare tag match. value: Option, }, + /// Change the scope of this node's claims with this name on a subject. + Scope { + /// The subject's event ID. + subject: String, + /// The tag name. + name: String, + /// The target scope. + #[arg(value_enum)] + scope: ClaimScope, + }, + /// Review every live claim visible to this node, with its scope. + Review, /// List the live claims on a subject. List { /// The subject's event ID. @@ -2668,6 +2683,16 @@ pub enum ClaimCommand { }, } +/// Where a tag claim lives: shared with peers, or on this node only (#1793). +#[derive(ValueEnum, Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ClaimScope { + /// Published to the shared claim set and replicated, the v1 default. + #[default] + Shared, + /// Kept on this node only; never published or synced. + Local, +} + /// Subcommands for `id tag`. /// /// Manage metadata tags (key/value pairs) attached to files. diff --git a/pkgs/id/src/commands/claim.rs b/pkgs/id/src/commands/claim.rs index 3a1dbd5c5c..3eec801f84 100644 --- a/pkgs/id/src/commands/claim.rs +++ b/pkgs/id/src/commands/claim.rs @@ -16,11 +16,11 @@ use anyhow::Result; use p2panda_core::Hash; use serde_json::{Value, json}; -use crate::cli::ClaimCommand; +use crate::cli::{ClaimCommand, ClaimScope}; use crate::commands::doc::{open_events, print_action, print_rows}; use crate::commands::group::hex; use crate::groups::log::hash_from_hex; -use crate::tag_claims::Claim; +use crate::tag_claims::{Claim, TagScope}; /// Prints a `set` line for a claim just recorded. pub(super) fn print_set(json: bool, subject: Hash, name: &str, value: Option<&str>, event: Hash) { @@ -42,6 +42,7 @@ fn claim_fields(claim: &Claim) -> Vec<(&'static str, Value)> { fields.push(("value", json!(value))); } fields.push(("author", json!(hex(&claim.author)))); + fields.push(("scope", json!(claim.scope.as_str()))); fields.push(("event", json!(claim.id.to_hex()))); fields } @@ -59,10 +60,24 @@ pub async fn cmd_claim(path: Option, json: bool, command: ClaimCommand) subject, name, value, + scope, } => { let subject = hash_from_hex(&subject)?; - let event = events.set_tag(subject, &name, value.as_deref())?; - print_set(json, subject, &name, value.as_deref(), event); + let scope = match scope { + ClaimScope::Shared => TagScope::Shared, + ClaimScope::Local => TagScope::Local, + }; + let claim = events.set_tag_scoped(subject, &name, value.as_deref(), scope)?; + let mut fields = vec![ + ("subject", json!(subject.to_hex())), + ("name", json!(name)), + ("scope", json!(scope.as_str())), + ("event", json!(claim.to_hex())), + ]; + if let Some(value) = value { + fields.push(("value", json!(value))); + } + print_action(json, "set", fields); } ClaimCommand::Clear { subject, name } => { let subject = hash_from_hex(&subject)?; @@ -87,6 +102,36 @@ pub async fn cmd_claim(path: Option, json: bool, command: ClaimCommand) .collect(); print_rows(json, &rows); } + ClaimCommand::Scope { + subject, + name, + scope, + } => { + let subject = hash_from_hex(&subject)?; + let scope = match scope { + ClaimScope::Shared => TagScope::Shared, + ClaimScope::Local => TagScope::Local, + }; + let moved = events.set_tag_scope(subject, &name, scope)?; + print_action( + json, + "scope", + vec![ + ("subject", json!(subject.to_hex())), + ("name", json!(name)), + ("scope", json!(scope.as_str())), + ("moved", json!(moved)), + ], + ); + } + ClaimCommand::Review => { + let rows: Vec> = events + .review_tags()? + .iter() + .map(claim_fields) + .collect(); + print_rows(json, &rows); + } ClaimCommand::List { subject } => { let subject = hash_from_hex(&subject)?; let rows: Vec> = diff --git a/pkgs/id/src/lib.rs b/pkgs/id/src/lib.rs index 2c36181059..45fec319ee 100644 --- a/pkgs/id/src/lib.rs +++ b/pkgs/id/src/lib.rs @@ -205,6 +205,7 @@ pub mod invites; pub mod issuer_rotation; pub(crate) mod key_envelope; pub mod local; +pub mod local_claims; pub mod local_events; pub mod log_sync; mod peer_announcement; diff --git a/pkgs/id/src/local_claims.rs b/pkgs/id/src/local_claims.rs new file mode 100644 index 0000000000..6807484c94 --- /dev/null +++ b/pkgs/id/src/local_claims.rs @@ -0,0 +1,387 @@ +//! The node's own local-only tag claims (#1793, issue #1793 bullet 2). +//! +//! A tag claim's scope says where it lives. A shared claim is a signed `tag.set` event in the +//! event store ([`crate::tag_claims`]): it is in the sync set, so every peer receives it. A +//! **local** claim is the opposite in exactly one respect — it is never signed into the event +//! store, so it is never in the sync set and never reaches another node. It is kept here, in a +//! JSON file beside the event store, and only this node reads it. +//! +//! The file is append-only in effect: a claim is a line, and a `tag.clear` of a local claim +//! removes its line. Rewriting the file is atomic (write a temporary file, then rename), so a +//! crash mid-write leaves either the old file or the new one, never a torn one. +//! +//! Local claims are deliberately not events: their IDs are content-derived +//! ([`LocalClaim::id_for`]) and carry no signature, because there is no second node to convince. +//! That is the whole point of the scope — a claim that must never leave the node must not be +//! something the node could accidentally publish. + +use std::collections::BTreeMap; +use std::io::Write as _; +use std::path::{Path, PathBuf}; + +use p2panda_core::Hash; +use serde::{Deserialize, Serialize}; + +use crate::tag_claims::{LocalClaim, TagError, TagScope, check_text, MAX_NAME_BYTES, MAX_VALUE_BYTES}; +use crate::waiting::AuthorKey; + +/// The file local claims live in, under the event store's directory. +pub const FILE_NAME: &str = "local-claims.jsonl"; + +/// One line of the local claim file. +#[derive(Debug, Serialize, Deserialize)] +struct Line { + /// The claim's ID, hex. + id: String, + /// The author's key, hex. + author: String, + /// The subject, hex. + subject: String, + /// The tag name. + name: String, + /// The tag value, if any. + #[serde(default, skip_serializing_if = "Option::is_none")] + value: Option, +} + +/// The node's local-only claims, keyed by claim ID. +/// +/// # Errors +/// +/// Every method that reads or writes the file returns an [`std::io::Error`] when the file cannot +/// be read or written, and the file's own parse errors surface as `InvalidData`. +#[derive(Debug, Default)] +pub struct LocalClaims { + /// The file the claims are persisted in. + path: PathBuf, + /// The claims, by ID, in ID order so the file is deterministic. + claims: BTreeMap<[u8; 32], LocalClaim>, +} + +impl LocalClaims { + /// Opens the local claim store in `dir`, reading `local-claims.jsonl` if it exists. A missing + /// file is an empty store. + /// + /// # Errors + /// + /// Fails if the directory cannot be created, the file cannot be read, or a line is not a + /// well-formed claim. + pub fn open(dir: &Path) -> std::io::Result { + std::fs::create_dir_all(dir)?; + let path = dir.join(FILE_NAME); + let mut claims = BTreeMap::new(); + if path.exists() { + let text = std::fs::read_to_string(&path)?; + for (number, line) in text.lines().enumerate() { + if line.trim().is_empty() { + continue; + } + let parsed: Line = serde_json::from_str(line).map_err(|err| { + std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("{} line {}: {err}", path.display(), number + 1), + ) + })?; + let claim = parsed.into_claim().map_err(|err| { + std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("{} line {}: {err}", path.display(), number + 1), + ) + })?; + claims.insert(*claim.id.as_bytes(), claim); + } + } + Ok(Self { path, claims }) + } + + /// The path of the file the claims are persisted in. + #[must_use] + pub fn path(&self) -> &Path { + &self.path + } + + /// Every local claim, in ID order. + #[must_use] + pub fn claims(&self) -> Vec { + self.claims.values().cloned().collect() + } + + /// The local claims on `subject`, in ID order. + #[must_use] + pub fn on_subject(&self, subject: &Hash) -> Vec { + self.claims + .values() + .filter(|claim| claim.subject == *subject) + .cloned() + .collect() + } + + /// The local claims named `name`, and with `value` if given, on any subject, in ID order. + #[must_use] + pub fn matching(&self, name: &str, value: Option<&str>) -> Vec { + self.claims + .values() + .filter(|claim| claim.name == name && value.is_none_or(|want| claim.value.as_deref() == Some(want))) + .cloned() + .collect() + } + + /// Records a local claim: `name` (and `value`) on `subject`, authored by `author`. The claim's + /// ID is derived from its content, so recording the same claim twice is a no-op that returns + /// the same ID. The file is rewritten atomically. + /// + /// # Errors + /// + /// Fails if the name or value breaks its limit or the NFC rule, or the file cannot be written. + pub fn set( + &mut self, + author: &AuthorKey, + subject: Hash, + name: &str, + value: Option<&str>, + ) -> std::io::Result { + check_text("name", name, 1, MAX_NAME_BYTES) + .and_then(|()| match value { + Some(text) => check_text("value", text, 0, MAX_VALUE_BYTES), + None => Ok(()), + }) + .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidInput, err.to_string()))?; + let id = LocalClaim::id_for(author, &subject, name, value); + let claim = LocalClaim { + id, + author: *author, + subject, + name: name.to_owned(), + value: value.map(str::to_owned), + }; + self.claims.insert(*id.as_bytes(), claim); + self.persist()?; + Ok(id) + } + + /// Removes the local claims named `name` on `subject` that `author` recorded. Returns the + /// number removed; zero means nothing was removed. The file is rewritten atomically. + /// + /// Only the recording author's own local claims are removed: a local claim has no other + /// author on this node, and a clear from anyone else has no meaning here. + /// + /// # Errors + /// + /// Fails if the file cannot be written. + pub fn clear(&mut self, author: &AuthorKey, subject: Hash, name: &str) -> std::io::Result { + let before = self.claims.len(); + self.claims.retain(|_, claim| { + !(claim.subject == subject && claim.name == name && claim.author == *author) + }); + let removed = before - self.claims.len(); + if removed > 0 { + self.persist()?; + } + Ok(removed) + } + + /// Rewrites the file atomically: a temporary file in the same directory, then a rename. + fn persist(&self) -> std::io::Result<()> { + let temporary = self.path.with_extension("jsonl.tmp"); + let mut file = std::fs::File::create(&temporary)?; + for claim in self.claims.values() { + let line = Line { + id: claim.id.to_hex(), + author: hex(&claim.author), + subject: claim.subject.to_hex(), + name: claim.name.clone(), + value: claim.value.clone(), + }; + let text = serde_json::to_string(&line) + .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err))?; + writeln!(file, "{text}")?; + } + file.sync_all()?; + drop(file); + std::fs::rename(&temporary, &self.path) + } +} + +impl Line { + /// Parses the line into a claim, checking that its ID is the one its content derives. + fn into_claim(self) -> Result { + let id = hash_from_hex(&self.id).map_err(|err| format!("id: {err}"))?; + let author = author_from_hex(&self.author).map_err(|err| format!("author: {err}"))?; + let subject = hash_from_hex(&self.subject).map_err(|err| format!("subject: {err}"))?; + let derived = LocalClaim::id_for(&author, &subject, &self.name, self.value.as_deref()); + if derived != id { + return Err(format!( + "the claim ID {} is not the one its content derives ({})", + self.id, + derived.to_hex() + )); + } + Ok(LocalClaim { + id, + author, + subject, + name: self.name, + value: self.value, + }) + } +} + +/// Parses a 32-byte hash from hex. +fn hash_from_hex(text: &str) -> Result { + let bytes = hex_bytes(text)?; + let array: [u8; 32] = bytes + .try_into() + .map_err(|_| format!("{text:?} is not 32 bytes"))?; + Ok(Hash::from_bytes(array)) +} + +/// Parses a 32-byte author key from hex. +fn author_from_hex(text: &str) -> Result { + let bytes = hex_bytes(text)?; + bytes + .try_into() + .map_err(|_| format!("{text:?} is not 32 bytes")) +} + +/// Decodes lowercase or uppercase hex, two digits per byte. +fn hex_bytes(text: &str) -> Result, String> { + if !text.len().is_multiple_of(2) { + return Err(format!("{text:?} has an odd number of hex digits")); + } + (0..text.len()) + .step_by(2) + .map(|index| { + u8::from_str_radix(&text[index..index + 2], 16) + .map_err(|_| format!("{text:?} is not hex")) + }) + .collect() +} + +/// Lowercase hex of a byte string. +fn hex(bytes: &[u8]) -> String { + use std::fmt::Write as _; + let mut text = String::with_capacity(bytes.len() * 2); + for byte in bytes { + let _ = write!(text, "{byte:02x}"); + } + text +} + +/// The scope a claim name records, if the name carries one. This is the create/edit surface's +/// shorthand: a name written `local:NAME` is a local claim named `NAME`, and any other name is a +/// shared claim. It is a convenience for the CLI only; the scope is stored as a field, never as +/// part of the name. +#[must_use] +pub fn split_scope_prefix(name: &str) -> (TagScope, &str) { + match name.strip_prefix("local:") { + Some(rest) if !rest.is_empty() => (TagScope::Local, rest), + _ => (TagScope::Shared, name), + } +} + +/// The error a scope prefix with an empty name produces, for the CLI to report. +#[must_use] +pub fn scope_prefix_error(name: &str) -> Option { + if name == "local:" { + return Some(TagError::Field( + "a local claim needs a name after \"local:\"".to_owned(), + )); + } + None +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + + fn author(n: u8) -> AuthorKey { + [n; 32] + } + + fn subject(n: u8) -> Hash { + Hash::from_bytes([n; 32]) + } + + fn temp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "id-local-claims-{name}-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn test_a_local_claim_survives_reopening_and_is_not_a_shared_claim() { + let dir = temp_dir("roundtrip"); + let id = { + let mut store = LocalClaims::open(&dir).unwrap(); + store.set(&author(1), subject(2), "city", Some("Oslo")).unwrap() + }; + let store = LocalClaims::open(&dir).unwrap(); + let claims = store.on_subject(&subject(2)); + assert_eq!(claims.len(), 1); + assert_eq!(claims[0].id, id); + assert_eq!(claims[0].as_claim().scope, TagScope::Local); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn test_recording_the_same_local_claim_twice_is_a_no_op() { + let dir = temp_dir("idempotent"); + let mut store = LocalClaims::open(&dir).unwrap(); + let first = store.set(&author(1), subject(2), "city", None).unwrap(); + let second = store.set(&author(1), subject(2), "city", None).unwrap(); + assert_eq!(first, second); + assert_eq!(store.claims().len(), 1); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn test_a_local_claim_id_separates_name_and_value_boundaries() { + let a = LocalClaim::id_for(&author(1), &subject(2), "a", Some("bc")); + let b = LocalClaim::id_for(&author(1), &subject(2), "ab", Some("c")); + let bare = LocalClaim::id_for(&author(1), &subject(2), "abc", None); + assert_ne!(a, b); + assert_ne!(a, bare); + } + + #[test] + fn test_a_clear_removes_only_the_authors_claims_of_that_name() { + let dir = temp_dir("clear"); + let mut store = LocalClaims::open(&dir).unwrap(); + store.set(&author(1), subject(2), "city", None).unwrap(); + store.set(&author(1), subject(2), "other", None).unwrap(); + assert_eq!(store.clear(&author(9), subject(2), "city").unwrap(), 0); + assert_eq!(store.clear(&author(1), subject(2), "city").unwrap(), 1); + assert_eq!(store.claims().len(), 1); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn test_a_tampered_line_is_refused_on_open() { + let dir = temp_dir("tamper"); + { + let mut store = LocalClaims::open(&dir).unwrap(); + store.set(&author(1), subject(2), "city", None).unwrap(); + } + let path = dir.join(FILE_NAME); + let text = std::fs::read_to_string(&path).unwrap(); + std::fs::write(&path, text.replace("\"city\"", "\"town\"")).unwrap(); + assert!(LocalClaims::open(&dir).is_err()); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn test_the_scope_prefix_selects_a_local_claim() { + assert_eq!(split_scope_prefix("local:city"), (TagScope::Local, "city")); + assert_eq!(split_scope_prefix("city"), (TagScope::Shared, "city")); + assert_eq!(split_scope_prefix("local:"), (TagScope::Shared, "local:")); + assert!(scope_prefix_error("local:").is_some()); + } +} diff --git a/pkgs/id/src/local_events.rs b/pkgs/id/src/local_events.rs index 12e955c884..cfa5728b40 100644 --- a/pkgs/id/src/local_events.rs +++ b/pkgs/id/src/local_events.rs @@ -29,7 +29,10 @@ use crate::notes::{ REVISE_KIND as NOTE_REVISE_KIND, check_note_op, fold_notes, }; use crate::search::{Hit, ValueMatch, search_store}; -use crate::tag_claims::{CLEAR_KIND, Claim, MAX_CLEAR_CLAIMS, SET_KIND, TagOp, check_op}; +use crate::local_claims::LocalClaims; +use crate::tag_claims::{ + CLEAR_KIND, Claim, LocalClaim, MAX_CLEAR_CLAIMS, SET_KIND, TagOp, TagScope, check_op, +}; use crate::waiting::{AuthorKey, WaitingLimits}; /// The directory the event store lives in, under the data directory, unless `--event-store` names @@ -213,6 +216,8 @@ fn fold_remote_notes( #[derive(Debug)] pub struct LocalEvents { store: EventStore, + /// The node's own local-only claims (#1793): never signed, never synced. + local: LocalClaims, key: SigningKey, } @@ -225,7 +230,8 @@ impl LocalEvents { pub fn open(dir: &Path, key: SigningKey) -> Result { std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?; let store = EventStore::open(dir, WaitingLimits::default(), now_ms())?; - Ok(Self { store, key }) + let local = LocalClaims::open(dir).context("open the local claim store")?; + Ok(Self { store, local, key }) } /// Runs one range-sync session over `conn` against this node's store: the session @@ -297,16 +303,130 @@ impl LocalEvents { /// Sets the tag `name` on `subject`, with `value` if given. The new claim's ID is the event's. /// + /// The claim is shared: it is signed into the event store and published to peers, exactly as + /// before scopes existed. Use [`LocalEvents::set_tag_scoped`] to choose the scope. + /// /// # Errors /// /// Fails if the name or value is refused, or the store cannot record the event. pub fn set_tag(&mut self, subject: Hash, name: &str, value: Option<&str>) -> Result { - let op = TagOp::Set { - subject, - name: name.to_owned(), - value: value.map(str::to_owned), - }; - self.record(SET_KIND, Some(op), None, None, None, &[]) + self.set_tag_scoped(subject, name, value, TagScope::Shared) + } + + /// Sets the tag `name` on `subject`, with `value` if given, at the chosen `scope` (#1793). + /// + /// A [`TagScope::Shared`] claim is a signed `tag.set` event, exactly as [`LocalEvents::set_tag`] + /// records it, and its ID is the event's. A [`TagScope::Local`] claim is never signed and never + /// enters the event store, so it never reaches another node; its ID is derived from its content + /// ([`crate::tag_claims::LocalClaim::id_for`]). Both kinds are returned by + /// [`LocalEvents::tags_on`], [`LocalEvents::search`] and [`LocalEvents::review_tags`], each + /// carrying its scope. + /// + /// # Errors + /// + /// Fails if the name or value is refused, or the store cannot record the event (shared) or + /// write the local claim file (local). + pub fn set_tag_scoped( + &mut self, + subject: Hash, + name: &str, + value: Option<&str>, + scope: TagScope, + ) -> Result { + match scope { + TagScope::Local => Ok(self.local.set(&self.author(), subject, name, value)?), + TagScope::Shared => { + let op = TagOp::Set { + subject, + name: name.to_owned(), + value: value.map(str::to_owned), + }; + self.record(SET_KIND, Some(op), None, None, None, &[]) + } + } + } + + /// Changes the scope of every live claim named `name` on `subject` that this node authored. + /// + /// Moving a claim to [`TagScope::Local`] records a local claim and then clears the shared one; + /// moving it to [`TagScope::Shared`] records a shared claim and then removes the local one. The + /// claim keeps its name and value, so the move changes only where it lives. Claims authored by + /// another node are not touched: this node cannot rewrite another node's signed claim, and a + /// local claim is this node's own by construction. + /// + /// Returns the number of claims moved. + /// + /// # Errors + /// + /// Fails if the store cannot be read or written, or the local claim file cannot be written. + pub fn set_tag_scope( + &mut self, + subject: Hash, + name: &str, + scope: TagScope, + ) -> Result { + let me = self.author(); + let mut moved = 0; + let shared: Vec = self + .store + .tag_claims()? + .into_iter() + .filter(|claim| { + claim.subject == subject && claim.name == name && claim.author == me + }) + .collect(); + match scope { + TagScope::Local => { + for claim in &shared { + self.local + .set(&me, subject, &claim.name, claim.value.as_deref())?; + moved += 1; + } + if !shared.is_empty() { + self.clear_claim_ids(&shared.iter().map(|claim| claim.id).collect::>())?; + } + } + TagScope::Shared => { + let local = self.local.on_subject(&subject); + for claim in local + .iter() + .filter(|claim| claim.name == name && claim.author == me) + { + self.set_tag(subject, &claim.name, claim.value.as_deref())?; + moved += 1; + } + if moved > 0 { + self.local.clear(&me, subject, name)?; + } + } + } + Ok(moved) + } + + /// Clears only the named claim IDs, in batches that fit the wire limit. Used by scope moves + /// so changing this node's scope cannot accidentally clear another author's claims with the + /// same name. + fn clear_claim_ids(&mut self, claims: &[Hash]) -> Result<()> { + let author = self.author(); + let required: Vec = self + .frontier()? + .into_iter() + .find(|head| head.author == author) + .map(|head| vec![head.event]) + .unwrap_or_default(); + for group in claims.chunks(MAX_CLEAR_CLAIMS) { + self.record( + CLEAR_KIND, + Some(TagOp::Clear { + claims: group.to_vec(), + }), + None, + None, + None, + &required, + )?; + } + Ok(()) } /// Clears every live claim named `name` on `subject`, whoever set it, by recording @@ -335,6 +455,16 @@ impl LocalEvents { /// /// Fails if no live claim matches, or the store cannot record an event. pub fn clear_tag(&mut self, subject: Hash, name: &str) -> Result<(usize, Hash)> { + // Local claims are this node's own and are removed from the local store; shared claims + // are cleared by `tag.clear` events, as before (#1793). + let local_ids: Vec = self + .local + .on_subject(&subject) + .into_iter() + .filter(|claim| claim.name == name) + .map(|claim| claim.id) + .collect(); + let removed_local = self.local.clear(&self.author(), subject, name)?; let claims: Vec = self .store .tag_claims()? @@ -342,9 +472,15 @@ impl LocalEvents { .filter(|claim| claim.subject == subject && claim.name == name) .collect(); if claims.is_empty() { + if removed_local > 0 { + // Nothing shared to clear: the local claims are gone, and the last local claim's + // ID stands in for the event ID a shared clear would have returned. + let last = local_ids.last().copied().unwrap_or(subject); + return Ok((removed_local, last)); + } bail!("no live claim on {} is named {name}", subject.to_hex()); } - let count = claims.len(); + let count = claims.len() + removed_local; // The current head of each author, for the required tier of each sub-clear. let heads: HashMap = self .frontier()? @@ -411,12 +547,28 @@ impl LocalEvents { /// /// Fails if the store cannot be read. pub fn tags_on(&self, subject: Hash) -> Result> { - Ok(self + let mut claims: Vec = self .store .tag_claims()? .into_iter() .filter(|claim| claim.subject == subject) - .collect()) + .collect(); + claims.extend(self.local.on_subject(&subject).iter().map(LocalClaim::as_claim)); + claims.sort_by_key(|claim| *claim.id.as_bytes()); + Ok(claims) + } + + /// Every live claim this node can see — shared and local — for the review listing (#1793), + /// sorted by scope then claim ID, so the local-only claims are reviewable on their own. + /// + /// # Errors + /// + /// Fails if the store cannot be read. + pub fn review_tags(&self) -> Result> { + let mut claims = self.store.tag_claims()?; + claims.extend(self.local.claims().iter().map(LocalClaim::as_claim)); + claims.sort_by_key(|claim| (claim.scope == TagScope::Local, *claim.id.as_bytes())); + Ok(claims) } /// The live claims that match `name`, and `value` if given, as [`crate::search`] returns them. @@ -426,7 +578,20 @@ impl LocalEvents { /// Fails if the store cannot be read. pub fn search(&self, name: &str, value: Option<&str>) -> Result> { let matching = value.map_or(ValueMatch::Any, ValueMatch::Exact); - Ok(search_store(&self.store, name, matching)?) + let mut hits = search_store(&self.store, name, matching)?; + // Local claims are this node's own, so they are part of this node's search answer (#1793). + // They are folded in per subject, so a subject with both kinds reports one hit. + for claim in self.local.matching(name, value) { + let entry = claim.as_claim(); + match hits.iter_mut().find(|hit| hit.subject == claim.subject) { + Some(hit) => hit.claims.push(entry), + None => hits.push(Hit { + subject: claim.subject, + claims: vec![entry], + }), + } + } + Ok(hits) } /// Creates a note with `content` as its first content. The returned ID is the note's @@ -796,6 +961,7 @@ fn entry_of(event: &Event) -> Option { subject, name, value, + .. }), _, _, @@ -1210,6 +1376,99 @@ mod tests { assert_eq!(events.tags_on(published.id).unwrap().len(), 3); } + #[test] + fn test_local_claim_is_reviewable_but_never_enters_the_shared_store() { + let (_dir, mut events) = open_events(); + let subject = publish_subject(&mut events); + let before = events.store.sync_entries().unwrap(); + + let id = events + .set_tag_scoped(subject, "city", Some("Oslo"), TagScope::Local) + .unwrap(); + + let visible = events.tags_on(subject).unwrap(); + assert_eq!(visible.len(), 1); + assert_eq!(visible[0].id, id); + assert_eq!(visible[0].scope, TagScope::Local); + assert!(events.store.tag_claims().unwrap().is_empty()); + assert_eq!(events.store.sync_entries().unwrap(), before); + assert_eq!(events.review_tags().unwrap(), visible); + assert_eq!(events.search("city", Some("Oslo")).unwrap()[0].claims, visible); + } + + #[test] + fn test_scope_edit_moves_a_local_claim_to_shared_and_back() { + let (_dir, mut events) = open_events(); + let subject = publish_subject(&mut events); + let local_id = events + .set_tag_scoped(subject, "city", Some("Oslo"), TagScope::Local) + .unwrap(); + + assert_eq!(events.set_tag_scope(subject, "city", TagScope::Shared).unwrap(), 1); + let shared = events.tags_on(subject).unwrap(); + assert_eq!(shared.len(), 1); + assert_eq!(shared[0].scope, TagScope::Shared); + assert_ne!(shared[0].id, local_id); + assert!(events.local.claims().is_empty()); + assert_eq!(events.store.tag_claims().unwrap(), shared); + + assert_eq!(events.set_tag_scope(subject, "city", TagScope::Local).unwrap(), 1); + let local = events.tags_on(subject).unwrap(); + assert_eq!(local.len(), 1); + assert_eq!(local[0].scope, TagScope::Local); + assert!(events.store.tag_claims().unwrap().is_empty()); + } + + #[test] + fn test_scope_edit_to_shared_publishes_only_own_local_claims() { + // Two identities can share one event store with different data + // directories; the local store merged into this view can therefore + // hold another author's local-only claims. Moving a tag to shared + // must publish only this node's own claims and leave the foreign + // local claim unpublished and intact (Codex review, PR #7344). + let (_dir, mut events) = open_events(); + let subject = publish_subject(&mut events); + events + .set_tag_scoped(subject, "city", Some("Oslo"), TagScope::Local) + .unwrap(); + let foreign: AuthorKey = [9; 32]; + events + .local + .set(&foreign, subject, "city", Some("Bergen")) + .unwrap(); + + assert_eq!( + events + .set_tag_scope(subject, "city", TagScope::Shared) + .unwrap(), + 1 + ); + + let shared = events.store.tag_claims().unwrap(); + assert_eq!(shared.len(), 1); + assert_eq!(shared[0].value.as_deref(), Some("Oslo")); + let remaining = events.local.claims(); + assert_eq!(remaining.len(), 1); + assert_eq!(remaining[0].author, foreign); + assert_eq!(remaining[0].value.as_deref(), Some("Bergen")); + } + + #[test] + fn test_clear_tag_removes_local_claims_without_signing_a_clear() { + let (_dir, mut events) = open_events(); + let subject = publish_subject(&mut events); + let before = events.store.sync_entries().unwrap(); + events + .set_tag_scoped(subject, "city", Some("Oslo"), TagScope::Local) + .unwrap(); + + let (count, _) = events.clear_tag(subject, "city").unwrap(); + + assert_eq!(count, 1); + assert!(events.tags_on(subject).unwrap().is_empty()); + assert_eq!(events.store.sync_entries().unwrap(), before); + } + fn open_events() -> (tempfile::TempDir, LocalEvents) { let dir = tempfile::tempdir().unwrap(); let events = LocalEvents::open(dir.path(), SigningKey::from_bytes(&[7; 32])).unwrap(); diff --git a/pkgs/id/src/tag_claims.rs b/pkgs/id/src/tag_claims.rs index 33c9a902de..7d6d421ece 100644 --- a/pkgs/id/src/tag_claims.rs +++ b/pkgs/id/src/tag_claims.rs @@ -53,6 +53,51 @@ pub const MAX_VALUE_BYTES: usize = 512; /// The most claims one `tag.clear` may name. The header decoder declares arrays at most 512 long. pub const MAX_CLEAR_CLAIMS: usize = 256; +/// Where a tag claim lives: on this node only, or in the shared claim set (#1793). +/// +/// The scope is part of the signed claim, so it is honoured by every replica that folds the +/// event. [`TagScope::Shared`] is the v1 behaviour and is the default, so a claim recorded +/// without a scope choice means exactly what it meant before scopes existed: it is published +/// into the shared claim set and visible to every node. [`TagScope::Local`] is a claim that +/// stays on the node that recorded it — it is not published, not synced, and not visible to +/// other nodes. Nothing about already-landed claims changes: they decode as `Shared`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum TagScope { + /// The claim is published into the shared claim set and replicated to other nodes. + #[default] + Shared, + /// The claim stays on this node only: never published, never replicated, never visible + /// to another node. + Local, +} + +impl TagScope { + /// The scope's name, as the CLI and the review listing print it. + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Shared => "shared", + Self::Local => "local", + } + } + + /// Parses a scope name. Accepts `shared` and `local`, case-insensitively. + /// + /// # Errors + /// + /// Returns a [`TagError::Field`] naming the accepted values for anything else. + pub fn parse(text: &str) -> Result { + match text.to_ascii_lowercase().as_str() { + "shared" => Ok(Self::Shared), + "local" => Ok(Self::Local), + _ => Err(TagError::Field(format!( + "the scope is {text:?}, it must be \"shared\" or \"local\"" + ))), + } + } +} + /// What a tag event does. The kind of the event says which form the operation takes. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum TagOp { @@ -96,6 +141,67 @@ pub struct Claim { pub name: String, /// The tag value, if any. pub value: Option, + /// Where the claim lives: shared, or this node only (#1793). + pub scope: TagScope, +} + +/// A local-only claim, as the node's own local claim store holds it (#1793). +/// +/// A local claim is never signed into the event store, so it is never in the sync set and never +/// reaches another node. Its ID is derived from its content and author, so it is stable across +/// reads and can be named by a local clear. It carries the same `author`/`subject`/`name`/`value` +/// shape as a shared [`Claim`], with [`TagScope::Local`] as its scope. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LocalClaim { + /// The claim's ID, derived from the author, subject, name and value. + pub id: Hash, + /// The key that recorded the claim. + pub author: AuthorKey, + /// The subject the claim is about. + pub subject: Hash, + /// The tag name. + pub name: String, + /// The tag value, if any. + pub value: Option, +} + +impl LocalClaim { + /// The claim's ID: the BLAKE3 hash of the author, subject, name and value, domain-separated + /// from any signed event so a local claim ID can never collide with a `tag.set` event ID. + /// `value` is length-prefixed, so `("a", Some("bc"))` and `("ab", Some("c"))` differ. + #[must_use] + pub fn id_for(author: &AuthorKey, subject: &Hash, name: &str, value: Option<&str>) -> Hash { + let mut hasher = blake3::Hasher::new(); + hasher.update(b"id.local-claim.v1\0"); + hasher.update(author); + hasher.update(subject.as_bytes()); + hasher.update(&(name.len() as u64).to_be_bytes()); + hasher.update(name.as_bytes()); + match value { + Some(text) => { + hasher.update(&[1]); + hasher.update(&(text.len() as u64).to_be_bytes()); + hasher.update(text.as_bytes()); + } + None => { + hasher.update(&[0]); + } + } + Hash::from_bytes(*hasher.finalize().as_bytes()) + } + + /// This claim as a [`Claim`], with [`TagScope::Local`]. + #[must_use] + pub fn as_claim(&self) -> Claim { + Claim { + id: self.id, + author: self.author, + subject: self.subject, + name: self.name.clone(), + value: self.value.clone(), + scope: TagScope::Local, + } + } } /// Why a tag operation was refused. @@ -160,7 +266,7 @@ pub fn check_op(kind: &str, op: &TagOp) -> Result<(), TagError> { } /// Checks a text field: its byte length is in `min..=max`, and it is NFC. -fn check_text(field: &str, text: &str, min: usize, max: usize) -> Result<(), TagError> { +pub(crate) fn check_text(field: &str, text: &str, min: usize, max: usize) -> Result<(), TagError> { let length = text.len(); if !(min..=max).contains(&length) { return Err(TagError::Field(format!( @@ -209,12 +315,7 @@ pub fn live_claims(applied: &[Applied], parents: &HashMap>) -> V let mut sets: BTreeMap<[u8; 32], Claim> = BTreeMap::new(); let mut removed: HashSet = HashSet::new(); for event in by_id.values().copied() { - if let TagOp::Set { - subject, - name, - value, - } = &event.op - { + if let TagOp::Set { subject, name, value } = &event.op { sets.insert( *event.id.as_bytes(), Claim { @@ -223,6 +324,7 @@ pub fn live_claims(applied: &[Applied], parents: &HashMap>) -> V subject: *subject, name: name.clone(), value: value.clone(), + scope: TagScope::Shared, }, ); } @@ -379,6 +481,7 @@ pub fn compacted_claims(applied: &[Applied], parents: &HashMap>) subject: *subject, name: name.clone(), value: value.clone(), + scope: TagScope::Shared, }), TagOp::Clear { .. } => None, }) diff --git a/pkgs/id/src/tag_index.rs b/pkgs/id/src/tag_index.rs index 714a205f69..233b7377d6 100644 --- a/pkgs/id/src/tag_index.rs +++ b/pkgs/id/src/tag_index.rs @@ -19,7 +19,7 @@ use std::collections::BTreeMap; use p2panda_core::Hash; -use crate::tag_claims::Claim; +use crate::tag_claims::{Claim, TagScope}; use crate::tuple::TupleEncoder; use crate::waiting::AuthorKey; @@ -34,6 +34,8 @@ pub struct Entry { pub name: String, /// The tag value, or `None` for a bare tag. pub value: Option, + /// Where the claim lives: shared, or this node only (#1793). + pub scope: TagScope, /// The claim's ID. pub claim: Hash, } @@ -59,6 +61,7 @@ impl TagIndex { author: claim.author, name: claim.name.clone(), value: claim.value.clone(), + scope: claim.scope, claim: claim.id, }; alpha.insert(alpha_key(&entry), entry.clone()); @@ -245,6 +248,7 @@ mod tests { subject: Hash::from_bytes([subject; 32]), name: name.to_owned(), value: value.map(str::to_owned), + scope: TagScope::Shared, } } @@ -276,6 +280,7 @@ mod tests { subject: Hash::from_bytes([subject; 32]), name: name.to_owned(), value: value.map(str::to_owned), + scope: TagScope::Shared, } } diff --git a/pkgs/id/tests/tag_index.rs b/pkgs/id/tests/tag_index.rs index 8e2a1cad1e..7bee9e7925 100644 --- a/pkgs/id/tests/tag_index.rs +++ b/pkgs/id/tests/tag_index.rs @@ -37,6 +37,7 @@ fn claim(n: usize, subject: Hash, name: &str, value: Option<&str>) -> Claim { subject, name: name.to_owned(), value: value.map(str::to_owned), + scope: id::tag_claims::TagScope::Shared, } }