feat(core): tags and types are names, one type per page implying a tag

Tags no longer have pages. A page has at most one type, which implies a
tag of the same name. Tags are stored sorted. Adds rename_tag and
remove_tag. Schema v6 turns tag pages into notes and trims types to the
first one. History exports synapse-type:: and reads the old forms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Opus 5.5 committed 2026-10-26 03:33:17 +01:00
1 parent 39e7e43071
commit e2ed9054c6
11 files changed
+373 -328

No files matched your search

+11 -10
View File
@@ -17,12 +17,12 @@ pub fn new_id() -> Uuid {
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PageKind {
/// Also what the retired `tag` kind of schema v5 reads as (tags no longer have pages).
#[default]
#[serde(alias = "tag")]
Note,
Hub,
Template,
/// A topic page: notes point at it from their `tags`.
Tag,
}
impl PageKind {
@@ -31,7 +31,6 @@ impl PageKind {
PageKind::Note => "note",
PageKind::Hub => "hub",
PageKind::Template => "template",
PageKind::Tag => "tag",
}
}
/// Unknown values read as notes.
@@ -39,7 +38,6 @@ impl PageKind {
match s {
"hub" => PageKind::Hub,
"template" => PageKind::Template,
"tag" => PageKind::Tag,
_ => PageKind::Note,
}
}
@@ -66,11 +64,13 @@ pub struct Page {
/// pages no longer hubs); readers ignore those.
#[serde(default)]
pub hubs: Vec<PageId>,
/// Titles of the tag pages ([`PageKind::Tag`]) this page is filed under, any number; see
/// `tags`. Always in step with the tag pages (created on first use).
/// Tag names this page is filed under, any number (names only: tags have no pages); see
/// `tags`. Its types count as tags too without being listed here.
#[serde(default)]
pub tags: Vec<String>,
/// What kind of thing this is ("persona", "lugar"...): plain names, not pages; see `types`.
/// What kind of thing this is ("persona", "lugar"...): a name, not a page; see `types`.
/// Holds zero or one entry (a list only for compatibility with older replicas: readers
/// use the first, see [`Page::page_type`]). The type implies a tag of the same name.
#[serde(default)]
pub types: Vec<String>,
}
@@ -79,15 +79,16 @@ impl Page {
pub fn is_journal(&self) -> bool {
self.journal_date.is_some()
}
/// The page's single type, if any.
pub fn page_type(&self) -> Option<&str> {
self.types.first().map(String::as_str)
}
pub fn is_hub(&self) -> bool {
self.kind == PageKind::Hub
}
pub fn is_template(&self) -> bool {
self.kind == PageKind::Template
}
pub fn is_tag(&self) -> bool {
self.kind == PageKind::Tag
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+22 -3
View File
@@ -1,6 +1,6 @@
use rusqlite::OptionalExtension;
pub const VERSION: i64 = 5;
pub const VERSION: i64 = 6;
pub const SCHEMA: &str = r#"
CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
@@ -116,11 +116,18 @@ CREATE TABLE IF NOT EXISTS ops (
);
"#;
/// Rebuilds the `page_tags` index from every page's `tags` column.
/// Rebuilds the `page_tags` index from every page's `tags` column and first type (the type
/// implies a tag of the same name).
pub fn rebuild_page_tags(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
conn.execute("DELETE FROM page_tags", [])?;
let rows: Vec<(String, String)> = {
let mut st = conn.prepare("SELECT id, tags FROM pages WHERE tags != '[]'")?;
let mut st = conn.prepare(
"SELECT id, json_group_array(value) FROM (
SELECT pages.id AS id, j.value AS value FROM pages, json_each(pages.tags) j
UNION ALL
SELECT pages.id AS id, j.value AS value FROM pages, json_each(pages.types) j WHERE j.key = 0
) GROUP BY id",
)?;
st.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?
.collect::<rusqlite::Result<_>>()?
};
@@ -192,6 +199,18 @@ pub fn migrate(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
if version.is_some_and(|v| v < 4) {
rebuild_page_tags(conn)?;
}
if version.is_some_and(|v| v < 6) {
// v6: tags and types are names only, one type per page. Old tag pages become plain notes (title,
// outline and links kept); their members keep the name in `tags`.
conn.execute("UPDATE pages SET kind='note' WHERE kind='tag'", [])?;
// A page has one type: keep the first of several.
conn.execute(
"UPDATE pages SET types = json_array(json_extract(types, '$[0]'))
WHERE json_array_length(types) > 1",
[],
)?;
rebuild_page_tags(conn)?;
}
conn.execute(
"INSERT OR REPLACE INTO meta(key, value) VALUES ('schema', ?1)",
[VERSION.to_string()],
+4 -11
View File
@@ -82,7 +82,6 @@ impl Graph {
dir,
now_override: Cell::new(None),
};
graph.repair_tag_pages()?;
Ok(graph)
}
@@ -358,12 +357,9 @@ impl Graph {
st.query_map([&old_key], |r| r.get(0))?
.collect::<std::result::Result<_, _>>()?
};
let old_title = std::mem::replace(&mut page.title, new_title.to_string());
page.title = new_title.to_string();
page.updated_at = self.now_ms();
self.write_page(&page, &self.tick())?;
if page.is_tag() {
self.retitle_tag(&old_title, new_title)?;
}
for bid in referencing {
if let Some(mut b) = self.get_block(parse_id(&bid)?)? {
let rewritten = parse::rewrite_refs(&b.content, &old_key, new_title);
@@ -411,11 +407,6 @@ impl Graph {
pub(crate) fn delete_page_rows(&self, id: PageId) -> Result<()> {
// Members of a deleted hub leave it (each member page is rewritten and logged).
self.drop_hub_from_members(id)?;
if let Some(p) = self.get_page(id)?
&& p.is_tag()
{
self.drop_tag_from_members(&p.title)?;
}
let ids: Vec<String> = {
let mut st = self
.conn
@@ -1222,7 +1213,9 @@ impl Graph {
)?;
let id = p.id.to_string();
self.exec("DELETE FROM page_tags WHERE page_id=?1", [&id])?;
for t in &p.tags {
// The type implies a tag of the same name, so the index covers both (a page has one
// type: older replicas may sync more, and only the first counts).
for t in p.tags.iter().chain(p.types.iter().take(1)) {
self.exec(
"INSERT OR IGNORE INTO page_tags(page_id, tag_key) VALUES (?1, ?2)",
params![id, title_key(t)],
+122 -115
View File
@@ -1,27 +1,26 @@
//! Tags: topic pages ("neurociencia", "finanzas") that notes are filed under.
//! Tags: topic names ("neurociencia", "finanzas") that notes are filed under.
//!
//! A tag is a page of kind [`PageKind::Tag`]: it has an outline, backlinks and a place in the
//! graph like any note. A page lists the titles of its tag pages in [`Page::tags`] (synced
//! with the page, last writer wins), any number of them, and a derived `page_tags` index
//! answers "which pages have this tag". Tagging with a title that has no page creates the tag
//! page; tagging with an existing note turns that note into a tag page. Renaming or deleting
//! a tag page keeps its members in step. Names compare case-insensitively ([`title_key`]).
//! What a page *is* ("persona", "lugar") is a different, name-only mechanism: see `types`.
//! A tag is only a name: it has no page. A page lists its tags in [`Page::tags`] (synced with
//! the page, last writer wins), any number of them. Its type ([`Page::types`], at most one) implies a tag of
//! the same name without being stored twice, and a derived `page_tags` index (tags and types,
//! one row per page and [`title_key`]) answers "which pages have this tag". Names compare
//! case-insensitively. What a page *is* ("persona", "lugar") is the name-only mechanism in
//! `types`.
use crate::error::{Error, Result};
use crate::model::{NewPage, Page, PageId, PageKind, title_key};
use crate::model::{Page, PageId, title_key};
use crate::store::{Graph, parse_id};
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
/// Longest tag (or type) name, in characters.
pub const MAX_TAG_CHARS: usize = 48;
/// A tag with the number of pages filed under it (tag pages with no members count 0).
/// A tag with the number of pages filed under it (explicitly or through a type).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TagInfo {
pub name: String,
pub count: u32,
/// Part of the seeded suggestions (types only; tag pages are never seeded).
/// Part of the seeded suggestions (types only).
pub suggested: bool,
}
@@ -33,34 +32,14 @@ pub fn normalize_tag(raw: &str) -> Option<String> {
}
impl Graph {
/// The tag page called `name`, created (or made out of a note of that name) on demand.
fn ensure_tag_page(&self, name: &str) -> Result<Page> {
if let Some(mut p) = self.page_by_title(name)? {
return match p.kind {
PageKind::Tag => Ok(p),
PageKind::Note if !p.is_journal() => {
p.kind = PageKind::Tag;
p.updated_at = self.now_ms();
self.write_page(&p, &self.tick())?;
Ok(p)
}
_ => Err(Error::Invalid(format!(
"{name:?} is a hub, template or journal and cannot be a tag"
))),
};
}
self.create_page_kind_tx(NewPage::titled(name), PageKind::Tag, String::new())
}
/// Replaces the tags of `page` (names cleaned, duplicates dropped case-insensitively,
/// order kept; each becomes the title of a tag page). Journals, templates and tag pages
/// cannot be tagged, nor can a page be tagged with itself.
/// kept sorted by [`title_key`]). Journals and templates cannot be tagged.
pub fn set_page_tags(&self, page: PageId, tags: Vec<String>) -> Result<Page> {
let tx = self.tx()?;
let mut p = self
.get_page(page)?
.ok_or_else(|| Error::NotFound(page.to_string()))?;
let mut wanted: Vec<String> = Vec::with_capacity(tags.len());
let mut next: Vec<String> = Vec::with_capacity(tags.len());
for raw in tags {
let Some(t) = normalize_tag(&raw) else {
continue;
@@ -70,22 +49,16 @@ impl Graph {
"tag {t:?} is longer than {MAX_TAG_CHARS} characters"
)));
}
if !wanted.iter().any(|x| title_key(x) == title_key(&t)) {
wanted.push(t);
if !next.iter().any(|x| title_key(x) == title_key(&t)) {
next.push(t);
}
}
if (p.is_journal() || p.is_template() || p.is_tag()) && !wanted.is_empty() {
next.sort_by_cached_key(|t| title_key(t));
if (p.is_journal() || p.is_template()) && !next.is_empty() {
return Err(Error::Invalid(
"journals, templates and tag pages cannot have tags".into(),
"journals and templates cannot have tags".into(),
));
}
if wanted.iter().any(|t| title_key(t) == title_key(&p.title)) {
return Err(Error::Invalid("a page cannot be its own tag".into()));
}
let mut next = Vec::with_capacity(wanted.len());
for t in wanted {
next.push(self.ensure_tag_page(&t)?.title);
}
if next == p.tags {
tx.commit()?;
return Ok(p);
@@ -107,7 +80,8 @@ impl Graph {
self.set_page_tags(page, tags)
}
/// Removes a tag (no-op when the page does not have it). The tag page stays.
/// Removes an explicit tag (no-op when the page does not list it; a type of the same name
/// keeps implying it).
pub fn remove_page_tag(&self, page: PageId, tag: &str) -> Result<Page> {
let p = self
.get_page(page)?
@@ -117,7 +91,7 @@ impl Graph {
self.set_page_tags(page, tags)
}
/// Pages carrying `tag`, most recently updated first.
/// Pages carrying `tag` (listed or implied by a type), most recently updated first.
pub fn pages_with_tag(&self, tag: &str) -> Result<Vec<PageId>> {
let mut st = self.conn().prepare_cached(
"SELECT p.id FROM page_tags t JOIN pages p ON p.id = t.page_id
@@ -127,39 +101,63 @@ impl Graph {
rows.map(|r| parse_id(&r?)).collect()
}
/// Tags of every tagged page, as stored.
/// Tags of every tagged page: the listed ones, then the type if not already among them
/// (each type implies a tag), names as stored.
pub fn all_page_tags(&self) -> Result<HashMap<PageId, Vec<String>>> {
let mut st = self
.conn()
.prepare_cached("SELECT id, tags FROM pages WHERE tags != '[]'")?;
let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
let mut st = self.conn().prepare_cached(
"SELECT id, tags, types FROM pages WHERE tags != '[]' OR types != '[]'",
)?;
let rows = st.query_map([], |r| {
Ok((
r.get::<_, String>(0)?,
r.get::<_, String>(1)?,
r.get::<_, String>(2)?,
))
})?;
let mut out = HashMap::new();
for row in rows {
let (id, tags) = row?;
out.insert(
parse_id(&id)?,
serde_json::from_str(&tags).unwrap_or_default(),
);
let (id, tags, types) = row?;
let mut all: Vec<String> = serde_json::from_str(&tags).unwrap_or_default();
let types: Vec<String> = serde_json::from_str(&types).unwrap_or_default();
for t in types.into_iter().take(1) {
if !all.iter().any(|x| title_key(x) == title_key(&t)) {
all.push(t);
}
}
out.insert(parse_id(&id)?, all);
}
Ok(out)
}
/// Every tag page with the number of pages under it: most used first, then by name.
/// Every tag in use, listed or implied by a type: spelling of its first page, with its page
/// count. Most used first, then by name.
pub fn tag_catalog(&self) -> Result<Vec<TagInfo>> {
let mut st = self.conn().prepare_cached(
"SELECT p.title, (SELECT COUNT(*) FROM page_tags t WHERE t.tag_key = p.title_key)
FROM pages p WHERE p.kind = 'tag'",
"SELECT tags, types FROM pages WHERE tags != '[]' OR types != '[]'
ORDER BY created_at, id",
)?;
let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, u32>(1)?)))?;
let mut out = Vec::new();
let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
let mut used: HashMap<String, (String, u32)> = HashMap::new();
for row in rows {
let (name, count) = row?;
out.push(TagInfo {
let (tags, types) = row?;
let tags: Vec<String> = serde_json::from_str(&tags).unwrap_or_default();
let types: Vec<String> = serde_json::from_str(&types).unwrap_or_default();
let mut seen = HashSet::new();
for t in tags.into_iter().chain(types.into_iter().take(1)) {
let key = title_key(&t);
if seen.insert(key.clone()) {
used.entry(key).or_insert((t, 0)).1 += 1;
}
}
}
let mut out: Vec<TagInfo> = used
.into_values()
.map(|(name, count)| TagInfo {
name,
count,
suggested: false,
});
}
})
.collect();
out.sort_by(|a, b| {
b.count
.cmp(&a.count)
@@ -168,59 +166,68 @@ impl Graph {
Ok(out)
}
/// A tag page was renamed: its members now list the new title.
pub(crate) fn retitle_tag(&self, old: &str, new: &str) -> Result<()> {
for id in self.pages_with_tag(old)? {
if let Some(mut p) = self.get_page(id)? {
let key = title_key(old);
for t in &mut p.tags {
if title_key(t) == key {
*t = new.to_string();
}
}
self.write_page(&p, &self.tick())?;
}
}
Ok(())
}
/// A tag page was deleted: its members stop listing it.
pub(crate) fn drop_tag_from_members(&self, title: &str) -> Result<()> {
let key = title_key(title);
for id in self.pages_with_tag(title)? {
if let Some(mut p) = self.get_page(id)? {
p.tags.retain(|t| title_key(t) != key);
self.write_page(&p, &self.tick())?;
}
}
Ok(())
}
/// Databases from before tag pages (or snapshots of them) list tags that have no page:
/// create the missing pages, keeping the spelling first used.
pub(crate) fn repair_tag_pages(&self) -> Result<()> {
let missing: Vec<String> = {
let mut st = self.conn().prepare_cached(
"SELECT DISTINCT tag_key FROM page_tags
WHERE tag_key NOT IN (SELECT title_key FROM pages)",
)?;
st.query_map([], |r| r.get(0))?
.collect::<std::result::Result<_, _>>()?
};
if missing.is_empty() {
return Ok(());
/// Renames a tag everywhere: in the `tags` and `types` of every page carrying it (one
/// transaction; each page is rewritten and logged, so it syncs). When a page already lists
/// `new`, the two merge. Returns the number of pages changed.
pub fn rename_tag(&self, old: &str, new: &str) -> Result<usize> {
let new = normalize_tag(new).ok_or_else(|| Error::Invalid("empty tag name".into()))?;
if new.chars().count() > MAX_TAG_CHARS {
return Err(Error::Invalid(format!(
"tag {new:?} is longer than {MAX_TAG_CHARS} characters"
)));
}
let key = title_key(old);
let tx = self.tx()?;
let mut done = std::collections::HashSet::new();
for (_, tags) in self.all_page_tags()? {
for t in tags {
let key = title_key(&t);
if missing.contains(&key) && done.insert(key) {
self.ensure_tag_page(&t)?;
}
let mut changed = 0;
for id in self.pages_with_tag(old)? {
let Some(mut p) = self.get_page(id)? else {
continue;
};
let (tags, types) = (p.tags.clone(), p.types.clone());
p.tags = rename_in(&p.tags, &key, &new);
p.tags.sort_by_cached_key(|t| title_key(t));
p.types = rename_in(&p.types, &key, &new);
if p.tags != tags || p.types != types {
p.updated_at = self.now_ms();
self.write_page(&p, &self.tick())?;
changed += 1;
}
}
tx.commit()?;
Ok(())
Ok(changed)
}
/// Removes the explicit tag `name` from every page (types of that name stay, and keep
/// implying it). Returns the number of pages changed.
pub fn remove_tag(&self, name: &str) -> Result<usize> {
let key = title_key(name);
let tx = self.tx()?;
let mut changed = 0;
for id in self.pages_with_tag(name)? {
let Some(mut p) = self.get_page(id)? else {
continue;
};
let before = p.tags.len();
p.tags.retain(|t| title_key(t) != key);
if p.tags.len() != before {
p.updated_at = self.now_ms();
self.write_page(&p, &self.tick())?;
changed += 1;
}
}
tx.commit()?;
Ok(changed)
}
}
/// `names` with the entries matching `key` replaced by `new` (later duplicates dropped).
fn rename_in(names: &[String], key: &str, new: &str) -> Vec<String> {
let mut out: Vec<String> = Vec::with_capacity(names.len());
for n in names {
let n = if title_key(n) == key { new } else { n };
if !out.iter().any(|x| title_key(x) == title_key(n)) {
out.push(n.to_string());
}
}
out
}
+19 -54
View File
@@ -1,7 +1,7 @@
//! Types: what kind of thing a page is ("persona", "lugar", "empresa").
//! Types: what kind of thing a page is, one per page ("persona", "lugar", "empresa").
//!
//! Types are plain names from a small vocabulary, not pages: a page carries its own list
//! ([`Page::types`], synced with the page, last writer wins). Topics are a different
//! Types are plain names from a small vocabulary, not pages: a page carries its own
//! ([`Page::types`], at most one name, kept as a list for compatibility; synced with the page, last writer wins). Topics are a different
//! mechanism: see `tags`.
use crate::error::{Error, Result};
@@ -12,47 +12,36 @@ use std::collections::HashMap;
/// Types offered in pickers before they are used anywhere (the seed of the vocabulary).
pub const SUGGESTED_TYPES: [&str; 10] = [
"persona",
"lugar",
"empresa",
"software",
"sueño",
"concepto",
"idea",
"evento",
"recurso",
"persona", "lugar", "empresa", "software", "sueño", "concepto", "idea", "evento", "recurso",
"receta",
];
impl Graph {
/// Replaces the types of `page` (names cleaned, duplicates dropped case-insensitively,
/// order kept). Journals and templates cannot be typed.
pub fn set_page_types(&self, page: PageId, types: Vec<String>) -> Result<Page> {
/// Sets the single type of `page` (name cleaned), or clears it with `None`. Journals and
/// templates cannot be typed. The type is stored as a list of zero or one name.
pub fn set_page_type(&self, page: PageId, ty: Option<&str>) -> Result<Page> {
let tx = self.tx()?;
let mut p = self
.get_page(page)?
.ok_or_else(|| Error::NotFound(page.to_string()))?;
let mut next: Vec<String> = Vec::with_capacity(types.len());
for raw in types {
let Some(t) = normalize_tag(&raw) else {
continue;
};
if t.chars().count() > MAX_TAG_CHARS {
return Err(Error::Invalid(format!(
"type {t:?} is longer than {MAX_TAG_CHARS} characters"
)));
let next: Vec<String> = match ty.and_then(normalize_tag) {
Some(t) => {
if t.chars().count() > MAX_TAG_CHARS {
return Err(Error::Invalid(format!(
"type {t:?} is longer than {MAX_TAG_CHARS} characters"
)));
}
vec![t]
}
if !next.iter().any(|x| title_key(x) == title_key(&t)) {
next.push(t);
}
}
None => Vec::new(),
};
if next == p.types {
tx.commit()?;
return Ok(p);
}
if (p.is_journal() || p.is_template()) && !next.is_empty() {
return Err(Error::Invalid(
"journals and templates cannot have types".into(),
"journals and templates cannot have a type".into(),
));
}
p.types = next;
@@ -62,30 +51,6 @@ impl Graph {
Ok(p)
}
/// Adds a type (no-op when the page already has it).
pub fn add_page_type(&self, page: PageId, ty: &str) -> Result<Page> {
let p = self
.get_page(page)?
.ok_or_else(|| Error::NotFound(page.to_string()))?;
let mut types = p.types;
types.push(ty.to_string());
self.set_page_types(page, types)
}
/// Removes a type (no-op when the page does not have it).
pub fn remove_page_type(&self, page: PageId, ty: &str) -> Result<Page> {
let p = self
.get_page(page)?
.ok_or_else(|| Error::NotFound(page.to_string()))?;
let key = title_key(ty);
let types = p
.types
.into_iter()
.filter(|t| title_key(t) != key)
.collect();
self.set_page_types(page, types)
}
/// The vocabulary: every type in use (spelling of its first page) plus the suggestions not
/// used yet. Used types first by count then name, then unused suggestions in seed order.
pub fn type_catalog(&self) -> Result<Vec<TagInfo>> {
@@ -96,7 +61,7 @@ impl Graph {
let mut used: HashMap<String, (String, u32)> = HashMap::new();
for row in rows {
let types: Vec<String> = serde_json::from_str(&row?).unwrap_or_default();
for t in types {
for t in types.into_iter().take(1) {
used.entry(title_key(&t)).or_insert((t, 0)).1 += 1;
}
}
+151 -99
View File
@@ -506,7 +506,7 @@ fn old_ops_and_v2_databases_load() {
r.get(0)
})
.unwrap();
assert_eq!(schema, "5");
assert_eq!(schema, "6");
let p = g.get_page(id).unwrap().unwrap();
assert_eq!((p.kind, p.title.as_str()), (PageKind::Note, "Legacy"));
let h = g.create_hub("New hub", "").unwrap();
@@ -626,25 +626,22 @@ fn converting_to_a_hub_creates_a_template_and_back_removes_it() {
}
#[test]
fn tags_are_pages_many_per_page() {
fn tags_are_names_many_per_page_kept_sorted() {
let (_d, g) = graph();
let a = page(&g, "Rust", &["x"]);
let b = page(&g, "Madrid", &["y"]);
let pages_before = g.list_pages(true, 100, 0).unwrap().len();
g.add_page_tag(a, " #Tecnología ").unwrap();
g.add_page_tag(a, "herramientas").unwrap();
g.add_page_tag(a, "TECNOLOGÍA").unwrap(); // same tag, other case
g.add_page_tag(a, "Álgebra").unwrap();
g.add_page_tag(b, "Tecnología").unwrap();
assert_eq!(
g.get_page(a).unwrap().unwrap().tags,
["Tecnología", "herramientas"]
);
// The first use creates the tag page; it is an ordinary page of kind tag.
let tp = g.page_by_title("tecnología").unwrap().unwrap();
assert_eq!(tp.kind, PageKind::Tag);
assert_eq!(tp.title, "Tecnología");
g.insert_block(tp.id, Placement::LastChildOf(None), "About tech")
.unwrap();
let tags = g.get_page(a).unwrap().unwrap().tags;
assert_eq!(tags, ["herramientas", "Tecnología", "Álgebra"]);
// Tags never become pages.
assert_eq!(g.list_pages(true, 100, 0).unwrap().len(), pages_before);
assert!(g.page_by_title("tecnología").unwrap().is_none());
assert_eq!(
g.pages_with_tag("tecnologia").unwrap().len(),
@@ -659,19 +656,14 @@ fn tags_are_pages_many_per_page() {
let cat = g.tag_catalog().unwrap();
assert_eq!((cat[0].name.as_str(), cat[0].count), ("Tecnología", 2));
assert_eq!((cat[1].name.as_str(), cat[1].count), ("herramientas", 1));
assert_eq!(cat.len(), 2, "no seeded tags: tags are pages you create");
assert_eq!(cat.len(), 3, "no seeded tags");
g.remove_page_tag(a, "TECNOLOGÍA").unwrap();
assert_eq!(g.pages_with_tag("Tecnología").unwrap(), [b]);
assert!(
g.page_by_title("Tecnología").unwrap().is_some(),
"the tag page stays"
);
g.set_page_tags(a, vec![]).unwrap();
assert!(g.get_page(a).unwrap().unwrap().tags.is_empty());
// Rules.
// Rules. A page may carry a tag equal to its own title.
let j = g
.journal(chrono::NaiveDate::from_ymd_opt(2026, 1, 2).unwrap())
.unwrap();
@@ -680,127 +672,187 @@ fn tags_are_pages_many_per_page() {
let t = g.hub_template(h).unwrap();
assert!(invalid(g.add_page_tag(t, "x")));
assert!(invalid(g.add_page_tag(a, &"x".repeat(49))));
assert!(invalid(g.add_page_tag(a, "H")), "a hub cannot be a tag");
assert!(invalid(g.add_page_tag(a, "Rust")), "not its own tag");
assert!(
invalid(g.add_page_tag(tp.id, "x")),
"tag pages are not tagged"
);
g.add_page_tag(a, "Rust").unwrap();
g.remove_page_tag(a, "Rust").unwrap();
g.add_page_tag(a, " ").unwrap(); // blank: ignored
assert!(g.get_page(a).unwrap().unwrap().tags.is_empty());
// Deleting a tagged page drops it from the index.
g.delete_page(b).unwrap();
assert!(g.pages_with_tag("Tecnología").unwrap().is_empty());
}
#[test]
fn a_note_becomes_a_tag_page_when_used_as_a_tag() {
fn a_page_with_a_tag_title_is_untouched_by_tagging() {
let (_d, g) = graph();
let n = page(&g, "Neurociencia", &["brains", "memory"]);
let other = page(&g, "Plasticidad", &["x"]);
g.add_page_tag(other, "neurociencia").unwrap();
let p = g.get_page(n).unwrap().unwrap();
assert_eq!(p.kind, PageKind::Tag);
assert_eq!(texts(&g, n).len(), 2, "its content is kept");
assert_eq!(g.get_page(other).unwrap().unwrap().tags, ["Neurociencia"]);
assert_eq!(g.get_page(n).unwrap().unwrap().kind, PageKind::Note);
assert_eq!(texts(&g, n).len(), 2);
assert_eq!(g.get_page(other).unwrap().unwrap().tags, ["neurociencia"]);
g.rename_page(n, "Cerebro").unwrap();
assert_eq!(g.get_page(other).unwrap().unwrap().tags, ["neurociencia"]);
}
#[test]
fn renaming_or_deleting_a_tag_page_keeps_members_in_step() {
let (_d, g) = graph();
let a = page(&g, "A", &["x"]);
let b = page(&g, "B", &["y"]);
g.add_page_tag(a, "web").unwrap();
g.add_page_tag(b, "Web").unwrap();
g.add_page_tag(b, "otro").unwrap();
let tag = g.page_by_title("web").unwrap().unwrap().id;
g.rename_page(tag, "Sitios web").unwrap();
assert_eq!(g.get_page(a).unwrap().unwrap().tags, ["Sitios web"]);
assert_eq!(g.get_page(b).unwrap().unwrap().tags, ["Sitios web", "otro"]);
assert_eq!(g.pages_with_tag("Sitios web").unwrap().len(), 2);
assert!(g.pages_with_tag("web").unwrap().is_empty());
g.delete_page(tag).unwrap();
assert!(g.get_page(a).unwrap().unwrap().tags.is_empty());
assert_eq!(g.get_page(b).unwrap().unwrap().tags, ["otro"]);
}
#[test]
fn tags_without_a_page_get_one_when_the_graph_opens() {
let dir = tempfile::tempdir().unwrap();
let id = {
let g = Graph::open(dir.path()).unwrap();
let id = page(&g, "Old", &["x"]);
g.add_page_tag(id, "Idea").unwrap();
// Simulate a pre-v5 database: the tag exists only on the note.
let tag = g.page_by_title("Idea").unwrap().unwrap().id;
g.conn()
.execute("DELETE FROM pages WHERE id=?1", [tag.to_string()])
.unwrap();
id
};
let g = Graph::open(dir.path()).unwrap();
let tag = g.page_by_title("idea").unwrap().unwrap();
assert_eq!((tag.kind, tag.title.as_str()), (PageKind::Tag, "Idea"));
assert_eq!(g.pages_with_tag("Idea").unwrap(), [id]);
}
#[test]
fn types_are_names_many_per_page_with_a_seeded_vocabulary() {
fn a_page_has_one_type_that_implies_a_tag() {
let (_d, g) = graph();
let a = page(&g, "Ana", &["x"]);
let b = page(&g, "Madrid", &["y"]);
let pages_before = g.list_pages(true, 100, 0).unwrap().len();
g.add_page_type(a, " Persona ").unwrap();
g.add_page_type(a, "cliente").unwrap();
g.add_page_type(a, "PERSONA").unwrap();
g.add_page_type(b, "lugar").unwrap();
assert_eq!(
g.get_page(a).unwrap().unwrap().types,
["Persona", "cliente"]
);
// Types never become pages.
g.set_page_type(a, Some(" Persona ")).unwrap();
g.set_page_type(b, Some("lugar")).unwrap();
assert_eq!(g.get_page(a).unwrap().unwrap().types, ["Persona"]);
assert_eq!(g.get_page(a).unwrap().unwrap().page_type(), Some("Persona"));
// Changing replaces; types never become pages.
g.set_page_type(a, Some("empresa")).unwrap();
assert_eq!(g.get_page(a).unwrap().unwrap().types, ["empresa"]);
assert_eq!(g.list_pages(true, 100, 0).unwrap().len(), pages_before);
assert!(g.page_by_title("persona").unwrap().is_none());
let cat = g.type_catalog().unwrap();
assert!(cat.iter().any(|t| t.name == "Persona" && t.count == 1));
let names: Vec<&str> = cat.iter().map(|t| t.name.as_str()).collect();
assert!(names.contains(&"empresa"), "unused suggestions are listed");
// The type counts as a tag of the same name, once even when also listed.
assert_eq!(g.pages_with_tag("EMPRESA").unwrap(), [a]);
g.add_page_tag(a, "Empresa").unwrap();
g.add_page_tag(a, "web").unwrap();
let cat = g.tag_catalog().unwrap();
let count = |n: &str| {
cat.iter()
.find(|t| t.name.to_lowercase() == n)
.map(|t| t.count)
};
assert_eq!(
names
.iter()
.filter(|n| n.to_lowercase() == "persona")
.count(),
1
count("empresa"),
Some(1),
"explicit + implicit counted once"
);
assert_eq!(count("lugar"), Some(1));
assert_eq!(count("web"), Some(1));
assert_eq!(g.all_page_tags().unwrap()[&a].len(), 2);
g.remove_page_type(a, "persona").unwrap();
assert_eq!(g.get_page(a).unwrap().unwrap().types, ["cliente"]);
// Removing the type removes the implicit tag; the explicit one stays.
g.set_page_type(a, None).unwrap();
assert_eq!(g.pages_with_tag("empresa").unwrap(), [a]);
g.remove_page_tag(a, "empresa").unwrap();
assert!(g.pages_with_tag("empresa").unwrap().is_empty());
g.set_page_type(b, None).unwrap();
assert!(g.pages_with_tag("lugar").unwrap().is_empty());
let cat = g.type_catalog().unwrap();
assert!(cat.iter().any(|t| t.name == "empresa" && t.suggested));
let j = g
.journal(chrono::NaiveDate::from_ymd_opt(2026, 1, 2).unwrap())
.unwrap();
assert!(invalid(g.add_page_type(j.id, "x")));
assert!(invalid(g.set_page_type(j.id, Some("x"))));
}
#[test]
fn tags_sync_with_the_page() {
fn renaming_and_removing_tags_cover_tags_and_types() {
let (_d, g) = graph();
let a = page(&g, "A", &["x"]);
let b = page(&g, "B", &["y"]);
let c = page(&g, "C", &["z"]);
g.add_page_tag(a, "web").unwrap();
g.add_page_tag(b, "Web").unwrap();
g.add_page_tag(b, "otro").unwrap();
g.set_page_type(c, Some("WEB")).unwrap();
assert_eq!(g.rename_tag("web", "Sitios web").unwrap(), 3);
assert_eq!(g.get_page(a).unwrap().unwrap().tags, ["Sitios web"]);
assert_eq!(g.get_page(b).unwrap().unwrap().tags, ["otro", "Sitios web"]);
assert_eq!(g.get_page(c).unwrap().unwrap().types, ["Sitios web"]);
assert_eq!(g.pages_with_tag("Sitios web").unwrap().len(), 3);
assert!(g.pages_with_tag("web").unwrap().is_empty());
assert!(invalid(g.rename_tag("otro", " # ")));
// Removing drops the explicit tag everywhere and leaves types alone.
assert_eq!(g.remove_tag("sitios web").unwrap(), 2);
assert!(g.get_page(a).unwrap().unwrap().tags.is_empty());
assert_eq!(g.get_page(b).unwrap().unwrap().tags, ["otro"]);
assert_eq!(g.pages_with_tag("Sitios web").unwrap(), [c]);
}
#[test]
fn v5_databases_turn_tag_pages_into_notes() {
let dir = tempfile::tempdir().unwrap();
let (tag, member) = {
let g = Graph::open(dir.path()).unwrap();
let member = page(&g, "Member", &["see [[Idea]]"]);
let tag = page(&g, "Idea", &["about ideas"]);
g.add_page_tag(member, "Idea").unwrap();
g.set_page_type(member, Some("persona")).unwrap();
// Simulate schema v5: the tag page has kind 'tag', the member two types.
g.conn()
.execute("UPDATE pages SET kind='tag' WHERE id=?1", [tag.to_string()])
.unwrap();
g.conn()
.execute(
"UPDATE pages SET types='[\"persona\",\"lugar\"]' WHERE id=?1",
[member.to_string()],
)
.unwrap();
g.conn()
.execute("UPDATE meta SET value='5' WHERE key='schema'", [])
.unwrap();
g.conn().execute("DELETE FROM page_tags", []).unwrap();
(tag, member)
};
let g = Graph::open(dir.path()).unwrap();
let t = g.get_page(tag).unwrap().unwrap();
assert_eq!((t.kind, t.title.as_str()), (PageKind::Note, "Idea"));
assert_eq!(texts(&g, tag), [(0, "about ideas".to_string())]);
assert_eq!(g.get_page(member).unwrap().unwrap().types, ["persona"]);
assert_eq!(g.pages_with_tag("idea").unwrap(), [member]);
assert_eq!(g.pages_with_tag("persona").unwrap(), [member]);
assert!(g.pages_with_tag("lugar").unwrap().is_empty());
}
#[test]
fn ops_from_old_replicas_degrade_tag_pages_to_notes() {
let id = synapse_core::new_id();
let op: Op = serde_json::from_value(json!({
"type": "upsert_page",
"page": {"id": id, "title": "Idea", "journal_date": null, "origin_journal": null,
"properties": {}, "created_at": 1, "updated_at": 2, "kind": "tag",
"tags": [], "types": ["a", "b"]}
}))
.unwrap();
let (_d, g) = graph();
assert!(
g.apply_remote("0000000000003-00000-oldactor0001", &op)
.unwrap()
);
let p = g.get_page(id).unwrap().unwrap();
assert_eq!(p.kind, PageKind::Note);
assert_eq!(g.pages_with_tag("a").unwrap(), [id]);
assert!(
g.pages_with_tag("b").unwrap().is_empty(),
"only the first type counts"
);
}
#[test]
fn tags_and_type_sync_with_the_page() {
let (_a, a) = graph();
let (_b, b) = graph();
let p = page(&a, "Note", &["x"]);
a.add_page_tag(p, "idea").unwrap();
a.add_page_tag(p, "proyecto").unwrap();
a.add_page_type(p, "concepto").unwrap();
a.add_page_tag(p, "idea").unwrap();
a.set_page_type(p, Some("concepto")).unwrap();
ship(&a, &b, 0);
let q = b.get_page(p).unwrap().unwrap();
assert_eq!(q.tags, ["idea", "proyecto"]);
assert_eq!(q.types, ["concepto"]);
assert_eq!(b.pages_with_tag("IDEA").unwrap(), [p]);
// The tag pages travel with it.
assert_eq!(b.pages_with_tag("concepto").unwrap(), [p]);
assert!(
b.page_by_title("idea").unwrap().is_none(),
"no tag pages travel"
);
b.rename_tag("idea", "ocurrencia").unwrap();
ship(&b, &a, 0);
assert_eq!(
b.page_by_title("idea").unwrap().unwrap().kind,
PageKind::Tag
a.get_page(p).unwrap().unwrap().tags,
["ocurrencia", "proyecto"]
);
}
+5 -8
View File
@@ -23,7 +23,9 @@ pub const DESCRIPTION_PROP: &str = "synapse-description";
/// Page property listing the titles of the hubs a page belongs to (JSON array).
pub const HUBS_PROP: &str = "synapse-hubs";
pub const TAGS_PROP: &str = "synapse-tags";
/// Page property with the type names (`synapse-types:: persona, lugar`).
/// Page property with the page's type (`synapse-type:: persona`).
pub const TYPE_PROP: &str = "synapse-type";
/// Retired list form of the type, still read on restore (the first entry wins).
pub const TYPES_PROP: &str = "synapse-types";
/// Encodes a page title as a file name ("triple-lowbar" format: `/` becomes `___`,
@@ -185,8 +187,6 @@ pub fn render_page(graph: &Graph, page: &Page, referenced: &HashSet<BlockId>) ->
props.remove("alias");
if page.is_hub() {
props.insert(KIND_PROP.into(), Value::String("hub".into()));
} else if page.is_tag() {
props.insert(KIND_PROP.into(), Value::String("tag".into()));
}
if !page.description.is_empty() {
props.insert(
@@ -209,11 +209,8 @@ pub fn render_page(graph: &Graph, page: &Page, referenced: &HashSet<BlockId>) ->
Value::Array(page.tags.iter().cloned().map(Value::String).collect()),
);
}
if !page.types.is_empty() {
props.insert(
TYPES_PROP.into(),
Value::Array(page.types.iter().cloned().map(Value::String).collect()),
);
if let Some(t) = page.page_type() {
props.insert(TYPE_PROP.into(), Value::String(t.to_string()));
}
let mut list = sorted_props(&props);
let aliases = graph.aliases_of(page.id)?;
+15 -16
View File
@@ -1,6 +1,8 @@
//! Parser for the Markdown files produced by [`crate::export`] (and plain outline pages).
use crate::export::{DESCRIPTION_PROP, HUBS_PROP, KIND_PROP, TAGS_PROP, TYPES_PROP, parse_value};
use crate::export::{
DESCRIPTION_PROP, HUBS_PROP, KIND_PROP, TAGS_PROP, TYPE_PROP, TYPES_PROP, parse_value,
};
use serde_json::Value;
use synapse_core::{BlockId, Properties, parse::property_split};
@@ -21,15 +23,13 @@ pub struct ParsedPage {
pub aliases: Vec<String>,
/// `synapse-kind:: hub`.
pub is_hub: bool,
/// `synapse-kind:: tag`.
pub is_tag: bool,
/// `synapse-description::`.
pub description: String,
/// Titles from `synapse-hubs::`.
pub hubs: Vec<String>,
/// Tag page titles from `synapse-tags::`.
/// Tag names from `synapse-tags::`.
pub tags: Vec<String>,
/// Names from `synapse-types::`.
/// The type from `synapse-type::` (or the first of the old `synapse-types::`): 0 or 1 name.
pub types: Vec<String>,
pub blocks: Vec<ParsedBlock>,
}
@@ -120,7 +120,6 @@ pub fn parse_page(text: &str) -> ParsedPage {
let kind = page.properties.remove(KIND_PROP);
page.is_hub = matches!(&kind, Some(Value::String(k)) if k == "hub");
page.is_tag = matches!(&kind, Some(Value::String(k)) if k == "tag");
page.description = match page.properties.remove(DESCRIPTION_PROP) {
Some(Value::String(d)) => d,
Some(other) => other.to_string(),
@@ -148,17 +147,17 @@ pub fn parse_page(text: &str) -> ParsedPage {
Some(Value::String(s)) => vec![s],
_ => Vec::new(),
};
page.types = match page.properties.remove(TYPES_PROP) {
Some(Value::Array(items)) => items
.into_iter()
.filter_map(|v| match v {
Value::String(s) => Some(s),
_ => None,
})
.collect(),
Some(Value::String(s)) => vec![s],
_ => Vec::new(),
let old_types = page.properties.remove(TYPES_PROP);
let ty = match (page.properties.remove(TYPE_PROP), old_types) {
(Some(Value::String(s)), _) => Some(s),
(_, Some(Value::Array(items))) => items.into_iter().find_map(|v| match v {
Value::String(s) => Some(s),
_ => None,
}),
(_, Some(Value::String(s))) => Some(s),
_ => None,
};
page.types = ty.into_iter().filter(|s| !s.trim().is_empty()).collect();
for raw in raws {
let mut lines = raw.lines;
-4
View File
@@ -53,7 +53,6 @@ fn atomic<T>(graph: &Graph, f: impl FnOnce() -> Result<T>) -> Result<T> {
struct Plan {
page: PageId,
is_hub: bool,
is_tag: bool,
description: String,
/// Titles of the hubs the page belongs to.
hubs: Vec<String>,
@@ -172,7 +171,6 @@ fn plan(graph: &Graph, title: &str, parsed: &ParsedPage, steal: bool) -> Result<
Ok(Plan {
page: page.id,
is_hub: parsed.is_hub,
is_tag: parsed.is_tag,
description: parsed.description.clone(),
hubs: parsed.hubs.clone(),
tags: parsed.tags.clone(),
@@ -223,8 +221,6 @@ fn apply_kind(graph: &Graph, plan: &Plan) -> Result<bool> {
};
let kind = if plan.is_hub {
PageKind::Hub
} else if plan.is_tag {
PageKind::Tag
} else {
PageKind::Note
};
+23 -7
View File
@@ -348,25 +348,25 @@ fn tags_round_trip_through_snapshots() {
let note = add(&g, "Note", &["body"]);
g.add_page_tag(note.id, "tecnología").unwrap();
g.add_page_tag(note.id, "idea").unwrap();
g.add_page_type(note.id, "concepto").unwrap();
g.set_page_type(note.id, Some("concepto")).unwrap();
let s1 = h.snapshot(&g, T0 + 500).unwrap().unwrap();
let tag_md = h.page_at(&s1.id, "idea").unwrap().unwrap();
assert!(tag_md.contains("synapse-kind:: tag"), "{tag_md}");
assert!(h.page_at(&s1.id, "idea").unwrap().is_none());
let md = h.page_at(&s1.id, "Note").unwrap().unwrap();
assert!(
md.contains(r#"synapse-tags:: ["tecnología","idea"]"#),
md.contains(r#"synapse-tags:: ["idea","tecnología"]"#),
"{md}"
);
assert!(md.contains("synapse-type:: concepto"), "{md}");
at(&g, T0 + 1000);
g.set_page_tags(note.id, vec![]).unwrap();
g.set_page_types(note.id, vec![]).unwrap();
g.set_page_type(note.id, None).unwrap();
h.restore_graph(&g, &s1.id, T0 + 2000).unwrap();
assert_eq!(g.get_page(note.id).unwrap().unwrap().types, ["concepto"]);
assert!(g.page_by_title("idea").unwrap().unwrap().is_tag());
assert!(g.page_by_title("idea").unwrap().is_none());
assert_eq!(
g.get_page(note.id).unwrap().unwrap().tags,
["tecnología", "idea"]
["idea", "tecnología"]
);
assert_eq!(g.pages_with_tag("idea").unwrap(), [note.id]);
}
@@ -446,3 +446,19 @@ fn hubs_round_trip_kind_description_and_memberships() {
);
}
}
#[test]
fn old_tag_kind_exports_parse_as_plain_notes() {
let parsed = synapse_history::parse::parse_page("synapse-kind:: tag\n\n- body\n");
assert!(!parsed.is_hub);
assert!(!parsed.properties.contains_key("synapse-kind"));
}
#[test]
fn old_types_list_restores_its_first_entry() {
let parsed =
synapse_history::parse::parse_page("synapse-types:: [\"persona\",\"lugar\"]\n\n- x\n");
assert_eq!(parsed.types, ["persona"]);
let parsed = synapse_history::parse::parse_page("synapse-type:: lugar\n\n- x\n");
assert_eq!(parsed.types, ["lugar"]);
}