Files
Greg ShuflinandClaude Opus 5.5 5fcc9bb7a4 artifacts: a singleton keeps its id across edits
A singleton artifact's id names its lineage, not its version. Every save
used to mint a fresh v4 id (Artifact::new), and the singleton upsert
adopted it. Peers address the value by that id: their stub, their holder
evidence and their artifact-sync fetch. A peer that stubbed a note body
before an edit landed in the same wall-clock second never had its stub
replaced, since stamps cross the wire in whole seconds. It then fetched
an id that no longer existed, marked the seed as not holding it, and
showed the note as on no node at all. That is the TODO.md 'note body
written after creation' bug that just seed-node reproduces.

- ArtifactStore::set_singleton is the local-edit entry point. It reuses
  the held id, else the id a peer announced, else a fresh one. It refuses
  a CRDT value held here only as a stub.
- Every singleton writer goes through it: notes, humans, clippings,
  reading position, listen progress, latest-read child, thumbnails and
  primary content.
- crdt_merged merges only within one lineage. Another id is a separate
  CRDT document, and the newer one replaces the older by LWW, the same
  rule tombstones follow.
- abandon_absent_body remains the one place that starts a new lineage.
- list_artifact_stubs and list_all_artifact_stubs no longer drop a stub
  whose id matches a held value. That filter only worked while each
  version had its own id; with stable ids it would hide every peer's
  newer version from the fetcher. A stub is outstanding by construction:
  it is recorded only when not redundant and cleared when a value lands.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 04:04:48 -08:00

65 KiB
Raw Permalink Blame History

Data Model

Terminology

Term Meaning
Node A running instance of the software on one device (phone, desktop, server, etc.)
Modality The specific program a human uses to run a node — CLI, TUI, desktop GUI, or Android app. Different doors onto the same node, not a distinct data concept
Document A piece of structured data in the tree — the core unit of the data model
Property Small infrastructure metadata attached to a Document; eagerly synced; always locally present
Artifact User data or content attached to a Document; may be absent locally. Its value lives inline in SQLite or, for blob-backed kinds, in the blob store
Blob store Content-addressed storage tier for large, immutable bytes; blob-backed Artifact values point into it via BlobRef
Edge A typed, directed relationship between two Documents, orthogonal to tree hierarchy

The distinction between Property and Artifact is conceptual, not about size. A Property is data the system needs to display and organize documents at all times — titles, tags, immutable facts about origin. An Artifact is data representing the user's engagement with or the actual content of the document — note body, reading position, the PDF bytes themselves. Some Artifact kinds are blob-backed: the artifact row keeps its UUID identity and merge semantics, but its value is a small BlobRef pointer and the actual bytes live in the content-addressed blob store. "Blob" names a storage tier, not a distinct entity.

Properties have a restricted set of merge strategies (LastWriteWins, SetUnion, Immutable) that are simple enough to apply without coordination. Artifacts reconcile two versions of the same artifact with LastWriteWins, Immutable, or Crdt (the last requiring the full operation log); set-like semantics — a document holding many artifacts of one kind, with additions and deletions — are handled structurally by collection kinds and tombstones (see Artifact below), not by a per-value merge strategy. Blob-backed artifacts need no content-level merge: content addressing means a change produces a new hash, so the pointer merges like any other value — a LastWriteWins swap for singleton kinds, immutable members plus tombstones for Attachment.


Core Types

Document

The fundamental tree node. Has no inline content of its own — all content lives in Properties and Artifacts.

Document {
    id:           Uuid            -- stable identity, never changes
    doc_type:     DocumentType    -- determines valid properties and merge strategies
    parent_id:    Option<Uuid>    -- tree parent; None for root documents
    vault_id:     VaultId         -- which vault's key encrypts this document's properties and blob content keys
    created_at:   Timestamp
    modified_at:  Timestamp
    origin_node:  NodeId          -- which Node first created this document
}

The tree structure provides: ownership semantics (deleting a feed deletes its episodes), UI hierarchy, and navigation. It is not the only kind of relationship — see Edges.

Property

Infrastructure metadata attached to a Document. Small, typed, eagerly synced to all Nodes, always locally present once the document is known.

Property {
    id:           Uuid
    document_id:  Uuid
    kind:         PropertyKind    -- schema tag; determines type and merge strategy
    value:        PropertyValue   -- typed, not stringly-typed
    modified_at:  Timestamp
    origin_node:  NodeId
}

Each PropertyKind has a declared MergeStrategy:

MergeStrategy =
    | LastWriteWins    -- title, rss_url, updated_at
    | SetUnion         -- tags
    | Immutable        -- pub_date, stream_url, origin_node

Properties deliberately exclude Crdt — that merge strategy requires the full operation log and belongs on Artifacts. The sync engine dispatches on MergeStrategy, not on document type.

Each DocumentType declares its full expected set of PropertyKinds. A node that knows about a document but is missing one of its required Properties treats that as a sync error and will re-request the Property on the next peer connection.

Removing a Property

A Property can be cleared, and the clearing propagates — ADR 0043 has the design. Two granularities, one rule, the same rule the document, artifact and edge tombstones already follow: a strictly newer write beats a removal; an equal-or-older one loses to it.

  • The whole row. DocumentStore::remove_property records a tombstone keyed by (document_id, kind) and drops the row. Both write paths consult it, so a peer that still holds the property cannot put it back by re-announcing it. Keyed by the pair, not by the Property's id, because that id is local — a sync receive keeps whatever id the receiving node's row already had, so the pair is the only identity every node agrees on.
  • One element of a SetUnion property. Each element carries its own added_at and removed_at in property_set_elements, and that table — not the properties row — is the authoritative state for those kinds. The row is a materialized view: the present elements, sorted, with modified_at set to the newest stamp anything about the property carries, and no row at all once nothing is present. A row tombstone acts as a floor under every element, so clearing a whole tag set and re-adding one tag both work.

The asymmetry worth remembering: a local write states the whole set (an element it does not mention is removed), while a sync receive of a bare value only ever records adds — an element a peer does not mention may be one it removed or one it never had, and a value alone cannot tell you which. That is why removals travel as element records rather than as values.

Note what this does not change: absence is still how "unset" is represented, for a SetUnion kind as for any other. Clearing the last tag deletes the row rather than storing an empty list, and no PropertyKind grows a sentinel value.

Property vs. Artifact: what actually decides which one

The Terminology table's distinction — "needed to display/organize a Document at all times" vs. "user engagement or content, may be absent" — is about what a field is for, not how narrowly it's named. A field scoped to one DocumentType (PodcastEpisodeGuid) is not automatically Artifact material just because no other type shares it, and a broadly-useful name is not automatically Property material just because it sounds generic.

The actual test: would a node missing this value be in an error state that should trigger a re-request on next sync, or is absence a normal, non-error "not yet synced" / "user hasn't engaged with this yet" state? PodcastEpisodeGuid is the publisher's id for an episode, and half of what its document id is derived from — infrastructure needed before the user ever opens the episode, and an "immutable fact about origin" in exactly the sense the Terminology table already calls out. It stays a Property despite being type-specific.

Human already demonstrates the correct split in shipped code: the shared PropertyKind::Title is a Property (the display name needed to show a list item immediately), while HumanFullName, HumanNickname, HumanBirthDate, HumanGender are all Artifacts — not because their names are more specific than the title, but because they're richer content whose absence before the rest of a Human's profile syncs is a normal, non-error state. Use this pairing — one lightweight always-present Property plus optional richer Artifacts — as the template when a new type is tempted to put everything in one bucket or the other.

A third question sits behind that one: should this be its own kind at all? Four Human Artifact kinds are gone, retired into two generic ones in rust/lib/src/documents/facts.rs, both usable by any DocumentType:

HumanJob, HumanReligion          -> ArtifactKind::Fact      (a key with one value)
HumanPet, HumanWebPresence       -> ArtifactKind::ListFact  (a key with several)

A kind per attribute someone once wanted to record has no end, and ArtifactKind is a closed enum synced across nodes, so key-as-data is how a user-extensible field set is possible at all. Reach for a fact unless the value needs structure the code will actually dispatch on, or merge semantics neither kind offers.

That last clause is the hard constraint, and it is also why two generic kinds rather than one holding a Vec: merge_strategy() takes only the kind, so a list living in a single row would reconcile last-write-wins over the whole list, and two nodes each adding a pet would lose one. A row per member — id derived from (key, value) — converges to the union instead. A third kind is the right move for anything neither rule fits (a counter that should sum, say), not a flag inside an existing one.

ContactMethod is the one promotion back out of facts so far, and it shows what "actually dispatch on" means: phone numbers and links lived as ListFacts keyed "phone"/"twitter" until something needed to render a working tel: link, which requires knowing a number from a handle. A string key cannot carry that — "twitter", "x" and "X" are three keys and one thing, and nothing rejects "twiter". The test is whether code branches on it, not whether the data feels important; a Discord handle, which nothing dispatches on, is still ContactProtocol::Other with no link rather than a new variant.

Note the two kinds are a storage distinction, not a presentational one. A UI should show one list of facts; facts::list_all_facts merges them, and facts::add_fact_value picks the kind, promoting a key from single- to multi-valued when a second value arrives. Making the user choose between "fact" and "list fact" would be leaking the merge rule into the interface.

Generalizing a PropertyKind across Document Types

Whether to give several DocumentTypes their own PropertyKind (ImageTitle, NoteTitle, ...) or to share one generic kind (Title) is decided by one test: do all current consumers agree on both PropertyValue type and MergeStrategy? merge_strategy() dispatches on PropertyKind alone, with no DocumentType parameter — so a shared kind can only carry one merge strategy, period.

Title mostly passes: every title-bearing type uses LastWriteWins — except PodcastEpisodeTitle, which is Immutable (an episode's title comes from the RSS feed once and is never user-renamed). That one exception is why PodcastEpisodeTitle should stay its own kind even if every other *Title collapses into one PropertyKind::Title — not because episodes are conceptually special, but because it is the one consumer that fails the test. Order/OrderTotal (above) pass the test cleanly with no exceptions, which is why they were introduced as generic kinds from the start rather than per-type variants.

Don't generalize a kind pre-emptively just because its name looks reusable — MergeStrategy divergence for even one consumer is reason enough to keep it (or split it further), and a kind that's currently unique to one DocumentType (PodcastEpisodeGuid) doesn't need a generic name just in case something else wants it later.

Ordering of Children

Some parent/child relationships need a stable, user-correctable sequence among siblings (comic pages, eventually music-album tracks) rather than the tree's default created_at ordering, which is neither meaningful (creation order is an implementation detail of the importer) nor guaranteed distinct (there is no secondary tiebreaker on created_at today). Two PropertyKinds exist for this, shared across every DocumentType that needs them rather than duplicated per type:

PropertyKind::Order       -- u32, LastWriteWins; this child's position among its
                              ordered siblings
PropertyKind::OrderTotal  -- u32, LastWriteWins; set on the *parent* at import,
                              the expected count of ordered children

A child with no Order property is not part of the sequence at all (e.g. a raw ComicInfo.xml sidecar kept as a child of a Comic for provenance) — absence, not a sentinel value, is what marks "unordered." OrderTotal mirrors the same "announce before fully synced" idea BlobRef already uses: a node can know a Comic should have 22 ordered children before all 22 have individually synced in, and render "14 of 22" rather than waiting for the last one to arrive.

OrderTotal is LastWriteWins, not Immutable: the expected count is only fixed for the lifetime of the document if the child set itself never changes after import, and nothing guarantees that (a comic can gain or lose a page later). An Immutable OrderTotal would mean the first value written wins forever — write_property's INSERT OR IGNORE path — so any later attempt to correct the count after adding or removing a child would be silently dropped, leaving completeness checks (comic_availability and friends) comparing the actual child set against a permanently stale expectation. LastWriteWins lets whoever changes the child set re-announce the new total. This accepts the same race Order already accepts: two nodes independently changing the child set before syncing with each other can leave OrderTotal reflecting only one of the two changes until the next sync resolves it — an eventually-consistent progress hint, not a value anything hard-depends on being correct mid-sync, consistent with the decentralization argument in "Property Invariants" below.

Neither Order nor OrderTotal is enforced to be contiguous or unique by the storage layer — see "Property Invariants" below.

Where an agent's properties are read and written

Property reading and writing for an agent belongs in lib/src/agents/<agent>.rs, which returns a shared struct — podcast::PodcastFeed, podcast::StoredEpisode, comics::ComicMetadata. Every consumer (lib/src/ffi, gui-app, tui-app, syn-daemon) maps that struct into its own view types and names no PropertyKind of its own. The one thing that legitimately lives per-modality is the generic property inspector/editor, which formats or edits an arbitrary PropertyValue without knowing which kind it belongs to.

The rule is not tidiness. When the projection was duplicated instead, the two copies drifted, and a track imported on Android reached the library with no artist, no album and no tag-scan stamp, because only the desktop copy read the file's tags.

Adding an agent, an FFI method, or a daemon command is the moment to re-check it:

grep -rn "PropertyKind::" rust/gui-app/src rust/tui-app/src rust/syn-daemon/src \
    rust/lib/src/ffi

should turn up nothing outside #[cfg(test)] fixtures.

Property Invariants (open question)

MergeStrategy answers one question: given two versions of the same property on the same document, which one wins. It does not answer a different question that matters once properties start expressing facts about relationships between sibling documents — e.g. "no two children of the same parent should carry the same Order value." That is a structural invariant across multiple documents' properties, not a merge conflict on one.

No storage-layer mechanism can guarantee this kind of invariant in a decentralized system: a local uniqueness constraint only protects a single node's own writes, and does nothing to stop two nodes from independently producing colliding values before they have synced with each other — by the time the collision is visible, both writes have already happened on different machines, and rejecting one at insert time is not possible without violating the "accept what a peer tells you" contract sync depends on. This mirrors why a missing required Property is already documented as a sync error to be re-requested rather than something prevented outright — partial or inconsistent states are expected to exist transiently and are resolved by detection and re-sync, not by being made unrepresentable.

The proposed approach, not yet implemented: give PropertyKind a second declared trait alongside merge_strategy():

enum PropertyInvariant {
    None,
    UniqueAmongSiblings,   -- no two children of the same parent may share a value
}

A generic, advisory checker — run opportunistically (e.g. when listing a parent's children, or as an explicit "verify library" action), never on every write or read — walks this declared table and surfaces violations for any PropertyKind that opts in, rather than each feature growing bespoke validation code. Consistent with the decentralization argument above, this checker only ever detects and reports; it must never auto-repair on read, since a silent local "fix" is itself a new write that can conflict with a peer's independent, equally valid view of the same structure. Repair, if ever implemented, should be an explicit, visible user- or agent-triggered action.

PropertyKind::Order is the first candidate for UniqueAmongSiblings.

Clearing a Property from the UI (open question)

DocumentStore::remove_property exists and propagates correctly, but nothing user-facing calls it — every removal today comes from an agent re-reading its source (the music scanner clearing a tag the file no longer carries). What the affordance should be is undecided, and there are real questions under it:

  • Which kinds may be cleared at all. Absence is meaningful for most, but not all: an Immutable kind is a fact fixed at creation, and clearing one leaves it unwritable by anything that isn't strictly newer than the removal — which for a value nobody rewrites means permanently gone. A kind a DocumentType declares as required is worse: its absence is defined as a sync error to re-request, so clearing it locally asks every peer to send it back.
  • Where it lives. The generic property inspector is the only per-modality surface that handles an arbitrary PropertyValue without knowing its kind (see "Where an agent's properties are read and written"), so it is the natural home — but a per-agent editor showing a field the agent itself owns may want its own wording for the same act.
  • Whether clearing a set is one affordance or two. For a SetUnion kind, removing one element and clearing the whole property are different acts with different tombstones, and a UI that offers only the second makes the first reachable solely by editing the value.

The model imposes nothing here: a UI that never clears anything is a coherent product decision, and this stays open until there is a case that wants it.

Artifact

User data or content attached to a Document. Stored as a typed value in SQLite; for blob-backed kinds the stored value is a BlobRef pointer into the blob store (see "Blob-backed Artifacts and the Blob Store" below). An Artifact may be absent on a node without being a sync error — absence means "not yet synced" and the UI should reflect that gracefully.

Artifact {
    id:           Uuid
    document_id:  Uuid
    value:        ArtifactValue  -- typed; stored as BLOB in SQLite for future encryption
    modified_at:  Timestamp
    origin_node:  NodeId
}

An Artifact has no role field: its classifier is its ArtifactValue variant, surfaced as an ArtifactKind (NoteBody, ListenProgress, ReadingPosition, Bookmarks, …). The variant already names what the data is, so a separate tag would be redundant. Opaque file bytes are classified the same way: PrimaryContent, Thumbnail, and Attachment are value variants whose payload is a BlobRef pointer — see "Blob-backed Artifacts and the Blob Store" below.

Each ArtifactKind declares a MergeStrategy for reconciling two versions of the same artifact:

MergeStrategy =
    | Immutable        -- value set once, never changes
    | LastWriteWins    -- reading position, listen progress
    | Crdt             -- note body (a Loro document; see ADR 0030)

Crdt is a bare variant, not Crdt(CrdtKind): one library and one shape (text) are in play, and enumerating hypothetical CRDT flavors would be generality with no second case to justify it.

Each ArtifactKind also has an Arity:

Arity =
    | Singleton    -- at most one per document (note body, reading position)
    | Collection   -- potentially many per document (bookmarks, annotations)

Each ArtifactKind also declares a Storage tier — Inline (value bytes in SQLite) or BlobStore (value is a BlobRef pointer) — read off the kind the same way as arity() and merge_strategy(); see "Blob-backed Artifacts and the Blob Store" below.

Artifacts are addressed by their stable id. A Singleton kind additionally enforces that (document_id, kind) is unique — one Artifact per kind — via a partial unique index. A singleton's id names its lineage, not its version: every edit, on any node, keeps it (ArtifactStore::set_singleton), because a peer's stub, its record of which nodes hold the value, and its fetch all name the value by that id. Only starting a note over (abandon_absent_body) begins a new lineage under a new id, and two lineages of one CRDT value are never merged — the newer replaces the older. A Collection kind holds many members per document, one artifact row each (e.g. Bookmark(Bookmark)), distinguished by id. Deleting a collection member records an ArtifactTombstone (by id) rather than a bare row removal, so the deletion propagates and an equal-or-older version cannot resurrect from a peer — the same delete-intent idea as Purge (see "Removing a Document vs. Purging"), at sub-document granularity. A strictly newer re-add of the same id wins over the tombstone. There is no separate "have" flag; presence is determined by whether the row exists.

Derived ids, and why they must be frozen

A Collection member's id is its identity across nodes. Where two nodes can independently record the same member — the same wikilink, the same quick fact, the same person at the same dinner, the same phone number — the id cannot be a fresh v4 or the pair syncs into two rows that differ only by id and every list built on them doubles. The (from_id, to_id, kind) and (document_id, kind) uniqueness constraints do not save you: sync inserts by id.

The fix is a UUIDv5 derived from the member's identifying content — derived_edge_id, fact_id, list_fact_member_id, contact_method_id. All of them, and every derived document id too (music artists and albums, agent settings, anchors, podcast episodes), go through the one helper in documents::derived_id: a caller names a Domain and the parts of its key, and never sees the namespace, the separator, or Uuid::new_v5. That is not tidiness. Two derivations that agree on UUIDv5 and disagree on the separator, or on whether the key was case-folded first, produce two ids just as surely as two different algorithms would — and there is nothing to notice, because each side is internally consistent. Adding a derived id means adding a Domain variant; there is nowhere else it could be written.

What matters is the constraint that comes with it:

A derived id must be a pure function of stored bytes, and its derivation is frozen forever. Never let it consult node-local configuration or any table that ships with a dependency.

Two ways that goes wrong, both silent:

  • Node-dependent input. If normalization consulted the node's locale, 555-0143 would derive one id on a node defaulting to US and another on one defaulting to GB. Two rows, never reconciled.
  • Version-dependent input. Library metadata changes between releases. The same value normalizing differently after an upgrade moves the id: the old row is orphaned, and deleting it in the UI derives the new id and tombstones nothing.

So anything that needs world knowledge — phone-number regions, unicode folding tables, public-suffix lists — belongs at write time, not at compare time. Canonicalize the value as it is entered, store the canonical form, and derive the id from a trivial frozen rule over what was stored. Ambiguity then gets resolved once, visibly, where the user can correct it, instead of invisibly and differently on each node. ContactMethod is the worked example: E.164 conversion happens in the agent, and contact_method_id asks for nothing beyond the trim-and-case-fold that derived_id's folded applies.

Latest-read child

Some containers hold children the user works through one at a time — a manga series Collection and its Comic issues, eventually a PodcastFeed and its episodes — where "which one did I have open last" is worth recording without walking every child's own progress artifact (ReadingPosition, ListenProgress) to find whichever was touched most recently. ArtifactKind::LatestReadChild (Singleton, LastWriteWins) is a single artifact on the parent document naming the child last opened:

LatestReadChild { child_id: Uuid }

This passes the "Generalizing a PropertyKind" test above even though it's an Artifact, not a Property: every plausible consumer agrees on both the value shape (a bare child id) and the merge strategy, so one shared ArtifactKind serves all of them rather than a ComicLastTouchedIssue-style kind per container type.

It is deliberately general but not universal: nothing in the storage layer restricts which DocumentTypes use it, but nothing writes it automatically either. A container only gets one because the agent that owns it chooses to write one when the user opens a child — the same opt-in discipline agent-owned container types already use (a plain Collection of PDFs grouped by subject has no "last touched" semantics and simply never gets this artifact, the same way it is a Collection rather than a Notebook). Only the direct parent/child hop is recorded; a deeply nested manga series (series → "Volume N" → issue) needs one recorded hop per level to resolve all the way down to the actual last-read issue, not a single artifact that understands the whole chain.

Blob-backed Artifacts and the Blob Store

Large immutable content — the PDF bytes, an audio file, cover art — is still an Artifact; what distinguishes it is where the value's bytes live. Every ArtifactKind declares a storage tier alongside its arity and merge strategy:

Storage =
    | Inline       -- the ArtifactValue is stored directly in SQLite
    | BlobStore    -- the value is a BlobRef pointer; the bytes live in the
                      content-addressed blob store

A blob-backed artifact's value is a small pointer struct:

BlobRef {
    blob_hash:      Blake3Hash   -- BLAKE3(ciphertext); the blob store address
    plaintext_hash: Blake3Hash   -- used to re-derive the per-blob content key
    vault_id:       VaultId
    size_bytes:     u64
}

Three blob-backed kinds exist, replacing the former standalone Blob/BlobRole types:

PrimaryContent(BlobRef)   [Singleton]   [LastWriteWins]  -- the main file (PDF bytes, audio)
Thumbnail(BlobRef)        [Singleton]   [LastWriteWins]  -- a preview or cover image
Attachment(BlobRef)       [Collection]  [Immutable]      -- a supplementary file

There is deliberately no single generic "blob content" kind: arity and merge strategy diverge across the three (PrimaryContent/Thumbnail are LWW pointer swaps, Attachment members are immutable), and both dispatch on ArtifactKind alone — the same generalization test that keeps PodcastEpisodeTitle its own PropertyKind.

"Merging" a singleton blob-backed artifact means swapping the pointer — content addressing turns every content change into a new hash, so LastWriteWins on the pointer is the whole conflict story. Removing an Attachment member records an ArtifactTombstone like any other collection kind, which gives attachment deletion the same propagation semantics bookmarks already have.

Identity in the blob store is content — two Nodes that import the same file independently converge on the same hash and store one copy. Whether a Node holds a given blob's bytes locally is answered by querying the blob store directly — no have: bool flag is needed on the pointer; the artifact row (the pointer) is synced like any other artifact value, while the bytes may be absent.

Sync for blob bytes stays "do you have this hash? no? want it?" — nothing more. The pointer values are a few dozen bytes and sync eagerly with all other artifact values; only the bytes are subject to per-node content policy (see docs/sync-management.md).

The former blob_refs table merges into the artifacts table, and blob-backed kinds get history and tombstones from the same machinery as every other kind — the previously planned separate BlobRefHistory is subsumed by ArtifactHistory (see History section).

Edge

A typed, directed relationship between two Documents, separate from the parent/child tree. Stable under moves and renames (targets are IDs, not paths).

Edge {
    id:           Uuid
    from_id:      Uuid
    to_id:        Uuid
    kind:         EdgeKind      -- e.g. WikiLink, PlaylistMember, RelatedTo
    created_at:   Timestamp
    origin_node:  NodeId
}

The tree's parent/child relationship is NOT stored as an Edge — it lives on the Document itself. Edges are for everything else.

An Edge is created or deleted, never mutated in place, so its merge story is set union by id plus an EdgeTombstone — with a strictly newer re-add beating an older tombstone, exactly the rule ArtifactTombstone already uses. (from_id, to_id, kind) is additionally unique, which makes "assert this relationship exists" idempotent for an agent that re-derives the same graph on every build.

Edges sync: each one rides inside the DocumentRecord of its from_id document, alongside that document's properties and artifact refs, and mutating an edge bumps the from document's modified_at so incremental (since-filtered) syncs carry it. Because an edge's to_id is unconstrained — unlike parent_id, it can point at a document later in the same batch — received edges are applied in a deferred pass after every document in the batch exists. One still dangling after that is dropped and re-announced on the next sync.

EdgeKind today: WikiLink, PlaylistMember, RelatedTo, Attendee, ArtistAlbum, AlbumTrack.


Document Types

Derived documents

Most documents are imported (a PDF, an MP3) or authored (a note). A few are derived — generated by an agent from other documents' data — and DocumentType::is_derived() declares which. MusicArtist and MusicAlbum are the first, computed from music tags (see docs/music-library.md); the types exist but nothing writes them yet.

Derived documents are reproducible: delete them all, rebuild, and the same graph returns with the same ids, because the derivation assigns UUIDv5 ids from normalized keys rather than fresh v4s. Two nodes deriving independently therefore converge on one document instead of visible duplicates. Three consequences follow:

  • Hidden from general listings by default. SearchParams::include_derived defaults to false, so browsing documents isn't swamped by four hundred albums. Naming a derived type in document_types overrides it — an explicit ask is never second-guessed.
  • Never purged. A document tombstone is permanent (sync's resurrection guard skips a tombstoned id forever), so purging a deterministic id would poison it ensemble-wide and no node could re-derive it. purge_recursive refuses derived types; deletion goes through remove_document/delete_recursive, which leave no tombstone.
  • Fixed by rebuilding, not by migrating data.

Declared per type rather than per document because every case today is cleanly type-determined. The trigger to promote it to a Provenance field on Document is the first agent that derives documents of a type users also create by hand.

Collection

A pure organisational container with no agent semantics — an import-mirror folder, a comic series/volume grouping, a plain subfolder inside a notebook. No domain-specific properties.

Collection {}

A container that does carry agent semantics gets its own DocumentType instead of a Collection tagged with a role property. A role property is an immutable classifier, set at creation, that decides which agent interprets the document and how it is displayed — which is what DocumentType already means, and doing it with a property gives up exhaustiveness checking, indexed "list every X" queries, and the forced per-type decisions in materialize_content and friends. DocumentType::is_container() names the set of types that hold children and exist mainly to do so, so hierarchy walks don't hardcode Collection. See docs/music-library.md's "Retiring CollectionRole" for the full argument and the one capability it gives up (roles can be attached to an existing document; a type is fixed at creation).

Notebook

The root of a notes notebook (the Notes agent). A container, like Collection, but one the Notes agent owns: list_notebooks is a single indexed query on doc_type.

Notebook {
    properties:
        title:  String  [LastWriteWins]  -- Title kind (shared)
}

Children are Notes and plain Collections (arbitrarily nested).

Scrapbook

The root of a tree of clippings (the Clippings agent, ADR 0039). A container, like Notebook, owned by one agent: ClippingsManager::scrapbooks is a single indexed query on doc_type.

Scrapbook {
    properties:
        title:  String  [LastWriteWins]  -- Title kind (shared)
}

Children are Clippings. Every node has the default one, an anchor (Provenance::Anchor, deterministic id, never purged); any others are the user's. Which one captures land in is ClippingsDefaultRoot on the agent's settings document, not a property of the scrapbook.

Note

A markdown or Typst text note.

Note {
    properties:
        title:  String          [LastWriteWins]
        tags:   Set<String>     [SetUnion]
    artifacts:
        body:    String         [Crdt]           -- NoteBody kind (text + Loro snapshot)
        format:  TextFormat     [LastWriteWins]  -- NoteFormat kind
}

edges:
    WikiLink → other Documents

The note body is an Artifact rather than a Property: it is user content, not infrastructure metadata, and it requires Crdt merge semantics. Text notes are small enough that SQLite storage (Artifact) is appropriate; content-addressing (Blob) would add hash churn on every edit with no benefit.

The markup format is a separate artifact rather than a field of the body, because it is display state: it tells a renderer how to read the text and has no bearing on what the text is, so it has no business inside a content CRDT. Splitting it also decouples the two, which is what lets a node set a note's format while holding only a stub for its body. A body with no format artifact renders as markdown — a body can arrive before its format.

Event

Something that happened — a dinner, a phone call, a chance meeting, usually with other people but not necessarily — written up after the fact.

Event {
    properties:
        title:        String        [LastWriteWins]
        occurred_on:  PartialDate   [LastWriteWins]  -- OccurredOn kind
    artifacts:
        body:         String        [Crdt]           -- NoteBody kind, exactly as a Note's
}

edges:
    Attendee → Human        -- who was there
    WikiLink → other Documents

Structurally this is a Note with a date and a guest list, and that is the point of the DocumentType / Artifact split: nothing here needed a new artifact kind, only a new semantic type. What the type buys is the distinction Attendee exists to draw — a note whose body mentions someone is not a record of having seen them — so "when did I last see this person" is one indexed edge query rather than a guess over prose.

occurred_on is a Property, not an Artifact: it is what orders and filters the timeline, so a node that knows the event exists must know its date to place it at all, even before the write-up syncs. It is a PartialDate because "sometime in 2019" is a real answer.

PodcastFeed

PodcastFeed {
    properties:
        rss_url:         String     [LastWriteWins]  -- canonical; how the feed is found
        podcast_guid:    String     [LastWriteWins]  -- <podcast:guid>, optional
        title:           String     [LastWriteWins]
        description:     String     [LastWriteWins]
        author:          String     [LastWriteWins]
        updated_at:      Timestamp  [LastWriteWins]  -- newest episode, as of the last refresh
        cover_art_url:   String     [LastWriteWins]  -- the artwork the feed names
        cover_art_source: String    [LastWriteWins]  -- the address `artwork` came from
    blob-backed artifacts:
        artwork:         image/*    (optional)   -- Thumbnail kind
}

A refresh brings these up to date with the feed (podcast::adopt_snapshot), the address included: a feed that moves keeps its document, and so its episodes. Where cover_art_source differs from cover_art_url, the stored artwork is behind the feed's and is fetched again (podcast::cover_art).

Children of a PodcastFeed are PodcastEpisodes.

A feed is identified by its address, stored canonical (feeds::canonical_feed_url), and never by a directory's id for it — so changing or dropping a directory leaves every subscription, and every episode under it, where it was (docs/podcasts-from-rss.md §5). The document id itself stays a random v4, for the tombstone reason in docs/rss-reader.md §3.3: an unsubscribe must not make the address unsubscribable.

PodcastEpisode

PodcastEpisode {
    properties:
        guid:          String     [Immutable]  -- the item's <guid>; with the feed id, derives the document id
        title:         String     [Immutable]
        pub_date:      Timestamp  [Immutable]
        stream_url:    String     [Immutable]
        duration_secs: f64        [Immutable]
    artifacts:
        progress:      ListenState [LastWriteWins]  -- ListenProgress kind
    blob-backed artifacts:
        audio:         audio/*    (optional; user-initiated download)  -- PrimaryContent kind
}

ListenState = NotStarted | InProgress { position_secs: f64 } | Finished

progress is an Artifact because it is user engagement data, not infrastructure metadata. Its absence (before the user starts listening) is a normal state, not a sync error.

Pdf

Pdf {
    properties:
        title:            String  [LastWriteWins]
        file_type:        String  [Immutable]      -- FileType kind, always "pdf"
        page_count:       u32     [LastWriteWins]  -- PdfPageCount kind (optional; absent
                                                      when the document didn't parse at
                                                      import, never 0)
    artifacts:
        reading_position: ReadingPosition  [LastWriteWins]  -- ReadingPosition kind [Singleton]
        bookmarks:        [Bookmark]        [Collection]     -- Bookmarks kind       [Collection]
    blob-backed artifacts:
        content:          application/pdf  (required)  -- PrimaryContent kind
}

ReadingPosition { current_page: u32 }
Bookmark        { page: u32, label: Option<String> }

page_count is read from the document's own page tree at import (agents::pdf::read_metadata, ADR 0035) so a library row can say "12 pages" without opening the blob — which may not even be here. It is what the parser resolved, not necessarily what a renderer will: a viewer that has the document open takes the renderer's count instead. Absent means the bytes wouldn't parse (or predate the property); the library then falls back to when the document was added.

Reading position and bookmarks are separate artifacts. reading_position is a singleton merged LastWriteWins, so turning a page on one node no longer races a bookmark edit on another (the previous bundled ReadingState had exactly that flaw). bookmarks is a Collection kind: each bookmark is its own Bookmark(Bookmark) artifact row, added and removed independently. A removal records a tombstone (by artifact id) that propagates over sync, so a deleted bookmark does not resurrect from a peer that still holds it.

Comic

A comic or manga issue, imported from a .cbz/.cbr archive or a directory of page images. Unlike Collection (a plain organisational container with no domain-specific properties), Comic carries real metadata — it is shaped like PodcastFeed, not like a PictureAlbum-style Collection.

Comic {
    properties:
        display_title: String  [LastWriteWins]  -- Title kind (shared, generic — see
                                                     "Generalizing a PropertyKind" above);
                                                     resolves to series if present, else
                                                     issue_title, else the import fallback
        issue_title:   String  [LastWriteWins]  -- ComicIssueTitle kind (optional; the
                                                     issue's own <Title>, distinct from
                                                     display_title once series is set)
        series:        String  [LastWriteWins]  -- ComicSeries kind (optional; from ComicInfo.xml)
        number:        String  [LastWriteWins]  -- ComicNumber kind (optional)
        writer:        String  [LastWriteWins]  -- ComicWriter kind (optional)
        summary:       String  [LastWriteWins]  -- ComicSummary kind (optional)
        page_total:    u32     [LastWriteWins]  -- OrderTotal kind; set at import,
                                                     re-written if pages are later added/removed
        source_name:   String  [LastWriteWins]  -- SourceName kind (generic); the file or folder
                                                     name it was imported from — what a re-import
                                                     matches it by (ADR 0054)
        pages_hash:    String  [LastWriteWins]  -- ComicPagesHash kind; hash of the pages'
                                                     plaintext hashes in order — matches a renamed
                                                     file (ADR 0054)
    artifacts:
        reading_position: ReadingPosition  [LastWriteWins]  -- shared with Pdf
        bookmarks:        [Bookmark]        [Collection]     -- shared with Pdf
}

Children of a Comic are Image documents, one per page, each carrying an Order property (see "Ordering of Children" above) plus whatever per-page ComicInfo.xml <Pages><Page> fields were present, matched by the page's 0-based index (the same index as Order): ComicPageType (Text; the page's role, e.g. "FrontCover"/"Story"), ComicPageDoublePage (Bool; written only when true — absence, not a stored false, is the "no" state, the same idiom Order's absence already uses), and ComicPageBookmark (Text; a bookmark label from the archive itself, distinct from the reader's own Bookmarks artifact). ImageSize/Key/ImageWidth/ImageHeight are not captured — redundant with the blob's real size or the decoded image itself. A Comic may also hold a non-orderable child, e.g. a raw copy of the original ComicInfo.xml kept for provenance — such a child simply carries no Order property.

At import time, .cbz/.cbr archive bytes and standalone directories of NN.jpg-style images are both flattened into the same shape: a title, optional metadata, and an ordered list of page images. The archive/directory container itself is not retained — it is a transient import format, not something the document model needs to remember. Export (not yet implemented) would reverse this: walk the ordered Image children and their blob content back into a fresh .cbz.

Importing the same file again updates the Comic already standing for it rather than creating another: a sibling under the same parent with the same SourceName, or, for a file renamed on disk, with the same ComicPagesHash. Its properties are rewritten only where they differ, cleared where the file dropped them, and its pages are matched by position, so an unchanged page keeps its document. ADR 0054 has the identity rules and why neither derived ids nor paths would do.

A Comic's own parent_id may be None (a standalone issue, as above) or a Collection representing a manga series or "Volume N" grouping (see import_comic_tree, rust/lib/src/agents/comics.rs) — arbitrarily nested, since a Collection may itself parent further Collections. A chapter's number/order are both derived from its source directory or file name ("Chapter 10", "Vol.10 Ch.103.cbz", …), the number only when not already set from its own ComicInfo.xml. The digits after a dot are a sub-chapter, so Order is chapter × 1000 + part: a "Chapter 10.5" extra is read between chapters 10 and 11, and "Ch.8.10" after "Ch.8.9" (see comics::ChapterNumber). number keeps the digits as written — "51.10", which a float would have printed as "51.1". Collection's own "no domain-specific properties" rule above still holds for a series grouping level: it carries Title and, when parsed, Order (so "Volume 3" sorts correctly among its siblings) — nothing comic-specific.

A series/volume Collection records which issue was opened most recently via the shared LatestReadChild artifact (see "Latest-read child" under Artifact above) — written on the Collection itself, one hop per nesting level, whenever the gpui desktop reader opens one of its Comic children (rust/gui-app/src/agents/comics.rs's open_comic). This is the same opt-in mechanism a future PodcastFeed could use for "last-played episode"; it is not special-cased to comics, and a Collection with no such reading-order semantics (e.g. a plain folder of related PDFs) never gets one.

VideoClip

A video file, imported from MP4/MOV. Metadata is read from the container itself, not from any decoded frame — see agents::video::probe_metadata (re_mp4, pure Rust, no decoder). Decoding for playback is not implemented yet (see TODO.md).

VideoClip {
    properties:
        title:          String  [LastWriteWins]  -- Title kind (falls back to the file stem)
        file_type:      String  [Immutable]       -- FileType kind, e.g. "mp4"
        duration_secs:  f64     [LastWriteWins]  -- VideoDurationSecs kind (optional)
        width:          u32     [LastWriteWins]  -- VideoWidth kind (optional)
        height:         u32     [LastWriteWins]  -- VideoHeight kind (optional)
        codec:          String  [LastWriteWins]  -- VideoCodec kind (optional; the
                                                     container's own codec string, e.g.
                                                     "avc1.640028", shown as-is)
    blob-backed artifacts:
        content:        video/*  (required)  -- PrimaryContent kind
}

All four metadata properties are absent, rather than a sentinel, when the container couldn't be parsed or carried no video track — the file still imports (same resilience an untagged MusicTrack already has).

MusicArtist / MusicAlbum

Derived containers for the music library (see "Derived documents" above and docs/music-library.md for the full design). Both are root documents; their membership is expressed by Edges, not tree parenting, because an album can legitimately belong to more than one artist and a single parent_id cannot say so.

MusicArtist {
    properties:
        title:  String  [LastWriteWins]  -- Title kind
}

MusicAlbum {
    properties:
        title:   String  [LastWriteWins]  -- Title kind (the album name)
        artist:  String  [LastWriteWins]  -- MusicArtist kind, denormalized for display
        year:    u32     [LastWriteWins]  -- MusicYear kind (optional)
    blob-backed artifacts:
        cover:   image/*  (optional)      -- Thumbnail kind
}

edges:
    MusicArtist --ArtistAlbum--> MusicAlbum --AlbumTrack--> MusicTrack

Declared but not yet populated: the tag extraction and library build that create them are still to come.


History

Every Property change is appended to a history table, giving a complete audit log and enabling reconstruction of any past state without full event sourcing.

PropertyHistory {
    property_id:   Uuid
    value:         PropertyValue   -- the value *before* this change
    modified_at:   Timestamp
    origin_node:   NodeId
}

On every Property write: append the current value to PropertyHistory, then update Property. "What did this note look like last Tuesday?" is a query against this table, not a special-case feature.

Artifacts should have an analogous ArtifactHistory table, keyed by artifact id — which works uniformly for singleton kinds, for the individually-addressed members of a collection kind, and for blob-backed kinds, whose history rows preserve the previous BlobRef pointer so a document's earlier content is not silently unlinked when the pointer swaps (this subsumes the previously planned separate BlobRefHistory). This is the foundation for document-level version history.

Note on CRDT artifacts

For NoteBody, the CRDT op log is the history: the stored value is a full Loro snapshot, which carries the whole op log beside the materialized state, so ArtifactHistory for that kind would only duplicate it. "Scroll back through this note" therefore has its data already and needs only a UI. See ADR 0030 for what that retention costs (roughly 12x plaintext at 300 revisions) and the shallow-snapshot pressure valve if it stops being affordable.


Sync Model

Properties sync eagerly to all Nodes. The sync engine applies the declared MergeStrategy when conflicts arise. A node that is missing a required Property treats that as a sync error and re-requests it on the next peer connection.

Artifacts sync on-demand or lazily at the protocol level; the background scheduler (see docs/sync-management.md) chooses to fetch pending values eagerly, since values — including the BlobRef pointers of blob-backed kinds — are small. A node may know a document has a NoteBody or ListenProgress artifact without yet having its value. Absence is not an error. Each artifact is announced and fetched by its id, so the members of a collection kind sync individually; their deletions are announced as tombstones alongside the artifact refs and applied on receipt, removing the local member and propagating onward.

Blob bytes sync lazily. Blob-backed artifact values are small pointers and sync like any other artifact value, so a node knows what bytes should exist before holding any of them. The bytes themselves are fetched when the user opens content that requires them, or when the node's content policy wants them locally (see docs/sync-management.md). Whether a Node holds a given blob's bytes is answered by querying the blob store directly — no have: bool flag is needed on the pointer.

Local Document States

Because artifact values and blob bytes can lag behind the catalog, a document can exist on a node across a spectrum of completeness. The axes are independent — a node can have a note body value without having the PDF bytes, etc. — but the common progression is:

State Document row Properties Artifact values Blob bytes
Known (skeleton) ✓ ✗ ✗ ✗
Metadata synced ✓ ✓ ✗ ✗
Content available ✓ ✓ ✓ ✗
Locally available ✓ ✓ ✓ ✓ (some/all)

Skeleton is transient: a node just learned a document exists (e.g. from a peer announcement) and created the Document row, but has not yet synced anything else. Properties sync eagerly, so this state resolves automatically on the next peer connection.

Metadata synced is the resting state for a document that has been announced but whose artifact values and blob bytes have not arrived. Artifact refs — including those of blob-backed kinds — are synced alongside Properties, so the node knows what content should exist before any value or byte is fetched. Querying the blob store is the authoritative check for byte presence.

Content available means artifact values have been fetched (the note body is readable, blob pointers are populated) but blob bytes (the PDF file, audio) have not been downloaded yet. This is a normal state for text-centric documents.

Locally available means all Artifact values and desired Blob bytes are present. For many documents this means the user has explicitly requested a download.

Removing a Document vs. Purging

Two distinct operations exist with very different semantics:

Remove locally frees disk space without affecting the ensemble's awareness of the document. Blob bytes are deleted from the blob store, but the Document row, artifact rows (including their BlobRef pointers), and properties remain intact. The node_document_status entry transitions to Removed, and each dropped blob is written to content_release_log so that doc-sync can tell peers this node no longer holds it (see the Node Content Index below). Re-syncing with any peer that holds the document restores state 2, 3, or 4. This is always reversible.

Purge expresses intent to erase a document from the entire ensemble. It deletes the local Document row (cascading to properties, blob refs, and status rows) and broadcasts a signed delete intent to all known nodes. Other nodes may honor the purge, but cannot be compelled to in a decentralized system. This operation is not reliably reversible and should require explicit user confirmation.

Node Document Index

Each node maintains a node_document_status table — its local belief about which documents exist on which nodes in the ensemble. Each row records:

NodeDocumentRecord {
    document_id: Uuid
    node_pubkey: NodePubkey
    presence:    Present | Removed
    observed_at: Timestamp   -- local clock; remote clocks are never trusted
}

"Present" means the node's document row exists locally (any of the three states above). "Removed" means a remove-locally operation was performed. Absence of a row means no information has been received yet. The table FK-references documents: a node that learns about a document from a peer first creates a skeleton document row, then writes the Present status record. The skeleton contains enough structural data (id, type, parent, origin node) to satisfy the FK and populate the UI, even before properties or blobs have arrived.

Node Content Index

The document index answers "does this node know about the document?" It does not answer "can this node serve the content?" — a node can hold every artifact row and none of the bytes those rows point at, or hold a stub where an inline value should be. That second question gets its own table, node_content_status:

NodeContentRecord {
    node_pubkey: NodePubkey
    key:         Blob(BlobHash) | Artifact(Uuid)
    presence:    Present | Absent
    observed_at: Timestamp   -- local clock; remote clocks are never trusted
}

The key spans both storage tiers deliberately. Blob content is content-addressed, so possession is a property of the bytes and evidence gathered for one artifact answers for every artifact with the same hash. An inline value has no identity apart from the artifact row it lives in, so it is keyed by artifact id.

Absent is the node's own word that it does not hold the content; no row at all means we have not been told, which is a much weaker statement. Nothing here is second-hand: a row about node N exists because N itself said so — affirming possession during doc-sync, serving (or declining to serve) the content during blob-/artifact-sync, or announcing a release from its content_release_log. That is what makes a node authoritative about its own copy without a per-row provenance column. The local node is never recorded; its own possession is read from the blob store and the artifacts table, which cannot go stale.

See ADR 0029.


Security / Vault Model

Every Property, Artifact, and Blob is encrypted under an identifiable key at all times — there is no unencrypted state, only different levels of key protection. The unit of keying is the Vault.

Vault {
    id:         VaultId
    name:       String
    key_spec:   VaultKeySpec
}

VaultKeySpec =
    | EnsembleDerived(label: String, version: u32)
        -- KDF(ensemble_key, label, version); same on all nodes; version starts at 1
    | Passphrase(KdfParams)
        -- derived from user passphrase; never stored; not recoverable from ensemble key
    | SharedKey(...)
        -- reserved: for future sharing with other identities

Every Document carries a vault_id. The default vault uses EnsembleDerived("vault:default", 1) and is unlocked whenever the app is running. A "secrets" vault uses Passphrase and requires an additional passphrase even when the app is open — the cop-with-open-phone scenario. Because the secrets vault key is derived from a passphrase and never stored, it is not recoverable from the ensemble key alone; this is a deliberate tradeoff.

Default Vault Key Storage

Although the default vault key is derivable from the ensemble key, it is not re-derived on every boot. Instead:

  1. During ensemble creation or registration (the only window the ensemble key is in memory), the default vault key is derived via HKDF and immediately encrypted under a node-local wrapping key: HKDF-SHA256(node_key, "syn:vault-wrap:v1").
  2. The encrypted blob (nonce + ciphertext) is stored in the local VaultStore (a table in the node's SQLite database).
  3. On every subsequent startup, the node decrypts the vault key using its own key — no user interaction needed.

This design avoids storing the ensemble key longer than necessary, while still making the default vault immediately available on every boot without re-entry. The wrapping key is derived from the node key and never leaves the device.

Ensemble Key

The ensemble key is a human-memorizable seed phrase (analogous to a cryptocurrency wallet seed phrase) that is the single cross-node root of trust. It is used to:

  • Derive vault keys for EnsembleDerived vaults, identically on every node
  • Authenticate new node enrollment (a new node proves it was enrolled by someone who knew the phrase)

The ensemble key is designed to be treated as a high-value secret: memorized or stored with the same care as a wallet seed phrase. Rotation is possible but intentionally costly — it is an emergency operation for major security breaches, not a routine one. Node keys are easier to rotate (on-device decrypt/re-encrypt, then deactivate old node and activate new one with identical contents).

Node keys and anything derived solely from node keys never leave the device and never need to.

Vault Key Versioning and Rotation

EnsembleDerived vaults carry a version integer starting at 1. Every node stores its current version for each vault.

This is design, not code. default_vault() hard-codes version: 1 and the vault_keys table has no version column, so nothing below can happen yet. The gap is tracked in TODO.md under revocation phase 3c, which is what wants rotation first — a revoked device keeps its copy of the vault key until the key changes.

To rotate a vault key (emergency operation, e.g. suspected in-memory key compromise):

  1. Increment version on one node; re-derive the new vault key
  2. Re-encrypt all local blobs under new content keys — this is O(total blob storage) and is an intentionally expensive operation, not a routine one
  3. Manually instruct all other nodes to perform the same increment and re-encryption
  4. Any node still on the old version cannot participate in sync for that vault until upgraded; other nodes detect the version mismatch and alert the user

Version bumps must be human-confirmed on each node. A node must never automatically adopt a higher version advertised by a peer — a compromised node could otherwise push all nodes to an unused version and orphan their data. Version bump messages should be signed by the ensemble key to prevent a compromised node from advertising a spurious version.

The version integer is small and human-trackable by design. In normal operation it stays at 1 indefinitely.

Convergent Encryption for the Blob Store

The blob store uses convergent encryption to achieve both within-vault deduplication and cross-vault unlinkability:

content_key = KDF(vault_key, plaintext_hash)
ciphertext  = Encrypt(content_key, plaintext)
stored_hash = Blake3(ciphertext)

Properties of this scheme:

  • Within-vault deduplication: same plaintext + same vault → same content key → same ciphertext → same stored hash. Two nodes that independently import the same PDF into the same vault converge on one blob.
  • Cross-vault unlinkability: same plaintext + different vault → different content key → different ciphertext → different stored hash. A blob in the default vault and the same file in the secrets vault are not correlatable by hash.
  • Size leakage: blob size is still visible and provides weak correlation. Not worth mitigating for a personal single-user threat model.
  • Confirmation attack: an adversary who suspects you have a specific file can encrypt it under your known vault key and compare hashes. Acceptable for this threat model.

Because the content key is re-derivable as KDF(vault_key, plaintext_hash), it does not need to be stored separately. It may be cached in the BlobRef for performance.

Blob sync transfers (ciphertext, stored_hash). The receiving node derives the content key from its own copy of the vault key and the plaintext hash (obtained by decrypting). No key material travels with the blob in transit.

Organizational concerns (grouping, filtering, browsing) are handled by Collection Documents and the parent/child tree, plus tags on Documents. Vault is purely a security boundary, not an organizational one.

Tree structure visibility: a Document's existence and position in the tree (its parent_id) are stored under the same vault as the Document itself. A Node without the vault key cannot read the Document's properties or blob contents, but depending on implementation may still observe that some encrypted document exists at that tree position. Full structural hiding is a future concern.

Implementation note: Property and Artifact value columns in SQLite are typed as BLOB (not TEXT) so that adding at-rest encryption requires no schema migration. The VaultId type (vault::VaultId, a UUID newtype), the VaultStore, and blob content encryption (vault::BlobCipher, ADR 0028) are implemented. Encrypting Property and Artifact values under the vault key is the remaining step — until it lands, the vault boundary holds for blob bytes and nothing else, on disk or on the wire.


Prior Art Worth Studying

Most directly relevant

  • iroh-docs (https://iroh.computer) — CRDT key-value namespaces with blob references and sync, built on iroh. Already in use as transport layer. iroh-docs maps closely onto the Property + BlobRef model above and may be usable as the sync substrate.

  • Hypercore / Hyperbee (https://hypercore-protocol.org) — append-only log as primitive, Hyperbee for mutable key-value on top. Good reference for how to think about log-structured sync. Dat/Hypercore is the clearest prior art for "public-key-addressed mutable feeds."

  • Cap'n Proto (https://capnproto.org) — zero-copy typed serialization with capability fields and promises baked into the protocol. The schema model is a strong reference for how to express typed Properties with schema evolution. Level 3 CapTP (capability transport) is relevant to the long-term agent model.

Distributed OS / capability systems

  • Plan 9 / 9P — per-process namespaces, synthetic filesystems. Relevant for the agent model (each agent sees its own namespace). Not relevant for typing.

  • Google Fuchsia / FIDL + Zircon — capability handles as first-class kernel objects, typed IPC via FIDL. Best existing large-scale example of "no ambient authority" design. The Component Manifest model is worth reading for the long-term agent capabilities story.

  • Spritely / Goblins / OCapN (https://spritely.institute) — distributed object capability network. Christine Lemmer-Webber's work on CapTP is the most rigorous current thinking on how to pass capabilities between machines. Relevant for the eventual human-to-human sharing and AI agent story.

Data model inspiration

  • IPFS / IPLD (https://ipld.io) — content-addressed DAGs with typed codecs. IPLD's data model (nodes, links, schemas) is a strong reference for the Blob + typed-block model.

  • BeOS / Haiku BFS — typed extended attributes on files, filesystem queries. The closest prior art for "typed metadata as first-class, not a sidecar." Haiku's codebase is readable.

  • Unison (https://unison-lang.org) — content-addressed code and data; names are display only, identity is hash. Relevant for thinking about Document identity vs. naming.

  • Loro (https://loro.dev) — the CRDT library behind MergeStrategy::Crdt on Note bodies. Chosen over Automerge and yrs after measuring all three against this project's save shape; ADR 0030 records the numbers and the reasoning.

Less directly relevant but worth knowing

  • Nock / Hoon / Urbit — subject-oriented computing, event-sourced state. You already know the tradeoffs here. The Urbit model is the clearest prior art for the long-term "overlay OS with persistent agents" vision, warts and all.