Files
synchronicity/docs/document-materialization.md
Greg ShuflinandClaude Opus 5.5 bb88bdacce
Build Debug APK / build (push) Failing after 2m37s
lib: a node-bearing record hands back its NodePubkey, not hex
DelegationCert, RegistryMember, PeerNode and RevocationRecord each kept
their own node_id_hex, and two of them a node_short_id that cut the key
with no ellipsis. Each now has one typed accessor — node(), or
revoked_node() on a revocation — and callers say .to_hex() or
.short_id() on what it returns, so a shortened node id goes through
copy::short_id like every other. The NodePubkey(x.node_pubkey) wrappers
at call sites fold into the same accessor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 15:54:11 -07:00

15 KiB

Document Materialization (Filesystem Export / Mount)

Status

A notebook-only static export shipped as a first cut (NotebookManager::manifest_to_disk, CLI syn notebook manifest <id> <path>) and is being replaced by the generalized, decided design below: a single syn docs materialize <document_id> command, implemented in rust/lib/src/documents/materialize.rs, reusing the original walk/slugify logic rather than duplicating it. See "Decided design" for the concrete command shape and scope.

The one-shot batch write itself (no daemon, no watcher, nothing FUSE-like) was already the right shape and carries over unchanged: "read-only" means we never read the exported files back in — a user can freely edit the exported files and those edits are silently ignored on the next materialize run (which unconditionally overwrites), though see "Decided design" below for making that non-enforcement slightly less silent (read-only file permissions).

Motivation

Urbit's %clay lets you |mount %desk to get a live view of a desk's files on the host filesystem, edit them with any tool, then |commit to feed edits back in. We want the analogous thing for Synchronicity documents: point a tool like Obsidian, VS Code, or ls at a directory and see/browse/edit personal documents as ordinary files, without the app needing to reimplement a text editor, a PDF viewer, etc.

Question 1: Can every DocumentType be standardized to a file?

There's no single serializer today — and there shouldn't be one function, because documents fall into three genuinely different shapes. docs/data-model.md's "Document has no inline content of its own — all content lives in Properties, Artifacts, or BlobRefs" means "the file for a document" is really "whichever of those three actually holds the content," and that's a per-DocumentType fact:

DocumentType Content lives in Materialization strategy Conversion needed?
Collection nothing (pure container) directory, no file of its own none
Note Artifact(NoteBody) — already String + TextFormat write .md/.typ/.txt text file none — already the shipped case
Pdf BlobRef(PrimaryContent), application/pdf the blob's plaintext bytes are the PDF file none — pure passthrough
Image BlobRef(PrimaryContent) blob bytes are already image/* none — passthrough
MusicTrack BlobRef(PrimaryContent) audio blob bytes already the audio file none — passthrough
PodcastEpisode BlobRef(PrimaryContent) audio (optional — lazily downloaded, see data-model.md's sync model) passthrough if present, else skip (blob may not be locally available) none — passthrough
Comic ordered Image children, each its own BlobRef either a directory of page images, or reconstitute a .cbz (data-model.md already flags .cbz export as "not yet implemented") zip packing, if we want single-file .cbz output rather than a page directory
PodcastFeed only Properties (rss_url, title, ...), no content blob of its own directory of episode files + a synthesized sidecar (e.g. _feed.md or .json) since the directory alone doesn't carry the feed metadata new: needs a Property→text renderer
Human only Artifacts (HumanFullName, HumanNickname, HumanPet, ...), no content blob synthesized file, e.g. vCard or a rendered .md profile new: needs a renderer

The pattern: documents whose primary content is a BlobRef(PrimaryContent) need zero format conversion — the blob's decrypted plaintext already is the right file format, we just need to name it. Documents whose content is a small Artifact (Note today) need a trivial text projection, which already exists for NoteBody. Only the metadata-only types (PodcastFeed, Human) need a genuinely new "render Properties/Artifacts as a synthesized file" step, and neither is in scope for the notebook PoC.

Proposed extension point for generalizing past Notebooks (not needed for the notebook-only case, since it only ever contains Collection/Note per create_notebook/create_note):

enum MaterializedContent {
    /// Directory; recurse into children. (Collection)
    Directory,
    /// Render this Artifact's value to a text file with the given extension. (Note)
    Text { content: String, extension: &'static str },
    /// Copy/link the given blob's decrypted plaintext bytes verbatim. (Pdf, Image,
    /// MusicTrack, PodcastEpisode, Comic pages)
    BlobPassthrough { blob_hash: BlobHash, extension: &'static str },
    /// No local content to materialize yet (e.g. an episode blob not downloaded).
    Unavailable,
}

fn materialize_content(doc_type: &DocumentType, ...) -> Option<MaterializedContent>

dispatching on DocumentType, so a new type added to the enum in the future gets an explicit decision here rather than silently falling through.

Question 2: What mechanism should do the materializing? (FUSE?)

Worth correcting a premise: Urbit's |mount is not a FUSE virtual filesystem. %clay writes real files onto the host filesystem under <pier>/<desk>/, and the runtime uses a plain file-change watcher (inotify/kqueue via libuv) to notice edits and feed them back in via |commit. It's a sync, not a virtual view — much closer to what manifest_to_disk already does than to a FUSE mount. That matches "however Urbit did it is probably fine" well: the shipped one-shot exporter is already the right shape; it just needs a watcher added later for the write-back direction, not a filesystem driver.

Static export (current) + file watcher (Urbit-style) FUSE mount
Mechanism batch write, on demand batch write + notify-crate watcher feeding edits back as artifact writes kernel-level virtual filesystem, lazy reads/writes intercepted live
Cross-platform story trivial — just files, works identically on Android app storage, desktop, anywhere the app can already write same, plus a background watcher thread/process Linux (fuser) and macOS (macFUSE) only without extra work; Windows needs WinFsp/Dokan; Android has no general-app-accessible FUSE API (system-level only) — a real blocker for a phone node
Disk usage for blob-backed docs duplicate bytes unless we symlink (blob store path → human-readable name in the export dir); symlinks have their own portability gaps (Windows needs dev mode/admin, Android scoped storage may forbid them in shared storage) same none — content is read lazily straight from the blob store, no duplication ever
Live view no — must re-run manifest to see new documents yes, for both directions yes, natively
Implementation cost already done moderate — watcher + a way to map an edited path back to (DocumentID, ArtifactKind), needs the manifest/mapping file below high — a long-running privileged daemon, real filesystem semantics (permissions, partial writes, readdir on huge trees), CRDT-vs-POSIX-write reconciliation
Needed for the notebook PoC yes no no

Decision: don't reach for FUSE. Keep the static-export model as the backbone; when write-back is eventually built, model it on %clay's explicit |commit rather than a live-watching daemon — the user should run a command to feed disk edits back in, not have edits silently and continuously absorbed. FUSE stays a possible additional mechanism much later, specifically for large blob-backed libraries where duplicating bytes via export is wasteful — not something to build now, and even then Linux/macOS/desktop-only (Android has no general-app FUSE access, so the static-export path remains necessary there regardless).

  1. Phase 1 (done): generalize the one-shot exporter into syn docs materialize, read-only, Collection/Note only — see "Decided design" below.
  2. Phase 2 (in progress — MusicTrack/Pdf done, Image/PodcastEpisode/Comic not yet): extend dispatch to blob-backed types (Pdf, Image, MusicTrack, PodcastEpisode, Comic pages). MusicTrack and Pdf share one code path (materialize_primary_content_child in materialize.rs) since both are a bare ArtifactKind::PrimaryContent blob with nothing else to render — the only per-type difference is the extension, resolved from the FileType property recorded at import. Shipped as a plain decrypt-and-copy passthrough (BlobStore::load then fs::write) rather than a symlink into the blob store — simpler, no per-platform symlink caveats (Windows dev mode/admin, Android scoped storage), and consistent with how Note content is already written. The symlink-vs-copy tradeoff noted below is still open for remaining Phase 2 types if the disk-duplication cost becomes a real problem.
  3. Phase 3 (write mode): a manual, |commit-style command — not a background watcher — that reads the materialized files back and writes them into the store. Scoped to Note first (an unambiguous "overwrite the artifact" semantics); needs the manifest sidecar below to map an edited/renamed path back to a DocumentID.
  4. FUSE: deferred indefinitely; revisit only if a large media library makes phase 2's disk duplication genuinely painful.

Decided design: syn docs materialize

Replaces syn notebook manifest entirely (removed, along with NotebookCmd::Manifest and NotebookManager::manifest_to_disk); the underlying slugify/walk logic is reused, not duplicated, by moving it into a new rust/lib/src/documents/materialize.rs module that generalizes it to walk from an arbitrary DocumentID, not just a CollectionRole::Notebook root. Lives under the docs CLI verb (the existing DocsCmd/AgentId::Documents surface) since materialization is a property of the document tree in general, not notebooks specifically.

syn docs materialize <DOCUMENT_ID> --path <PATH> [--write]
  • <DOCUMENT_ID> — any document. If its type isn't (yet) supported, fail immediately with a clear error naming the type (materializing an Image document is not yet supported (only Collection, Note, MusicTrack, and Pdf are supported)) rather than a silent no-op or a generic failure.
  • --path <PATH> — the exact target location, not a parent to nest a title-derived directory under (unlike the old manifest_to_disk, which always nested one level under the notebook's own slugified name). For a Collection root, PATH is the directory that gets populated directly; for a lone Note root, PATH is the exact file to write.
  • --write — present in the flag surface now for forward compatibility, but since only read-only export is being built in this pass, passing it fails fast with a clear "write mode is not yet implemented" error rather than pretending to support it.

Scope for now: Collection (→ directory, recurse), Note (→ .md/.typ/.txt file, by TextFormat), and MusicTrack/Pdf (→ audio/PDF file, decrypted blob passthrough, extension from the FileType property recorded at import — Pdf import was updated to record it too, matching Image/MusicTrack/Comic) are materializable. A MusicTrack or Pdf whose content blob hasn't finished syncing to this node (DocumentAvailability::Partial, e.g. a Stream-policy track never fully fetched — see docs/sync-management.md phase 6) is skipped rather than erroring the whole run, same as an unsupported type. A Collection subtree that contains an unsupported child type (e.g. a picture-album Collection full of Images, or a manga Collection full of Comics) does not abort the whole run — that child is skipped and reported in the summary output, so the rest of a mixed tree still materializes. This is a deliberate asymmetry from the root-type check: the root type is a hard precondition (you asked to materialize this, and it can't be done at all), whereas an unsupported descendant is a partial-support situation the rest of a large tree shouldn't be held hostage to.

Filename disambiguation: ad hoc, no need to over-engineer — the first sibling to claim a slugified name keeps it bare; any later sibling that collides gets -<short document ID> appended (before the extension, for notes), first-seen order, using the same 8-character prefix as copy::short_id, without its ellipsis. Not stable across re-runs if sibling order or titles change (a different document could claim the bare name next time), which is fine for a stateless, always-overwrite exporter — and unlike a numeric counter, the suffix that does get used is at least always unambiguous and traceable back to one document.

Read-only enforcement: exported files are chmod'd read-only (fs::Permissions:: set_readonly(true), portable across Unix/Windows) after writing, so an accidental edit fails visibly instead of silently vanishing on the next materialize run. Directories are left writable (removing this bit is one of the things a future --write/commit flow will need to do anyway).

Supporting design: a manifest sidecar for path ↔ DocumentID

materialize today is stateless: paths are recomputed from titles on every run and unconditionally overwritten, which is fine as long as nothing needs to map an edited file back to a document. Write-back (phase 3 above) breaks that assumption — once files can be renamed or moved by the user in their own file manager, title-based path recomputation alone can no longer identify which document a given file corresponds to.

Proposed: write a sidecar (e.g. .syn-manifest.json at the root of each exported tree) recording { document_id, relative_path, content_hash_or_modified_at } per exported file. Not needed for the current read-only, always-overwrite case; needed as soon as a --write/ commit command exists. This is the same class of problem %clay solves by keeping its own notion of desk/path mapping rather than trusting the host filesystem's paths as identity.

Open questions / non-goals for now

  • PodcastFeed / Human sidecar rendering (a synthesized metadata file for Property/Artifact-only types) is real design work of its own — deferred; not needed for notebooks or for blob-backed types.
  • Symlink vs. copy policy for blob passthrough needs a per-platform decision (Android scoped storage and Windows both complicate symlinks) — deferred to phase 2.
  • The manual commit command's exact shape (syn docs commit <path>? a mode of materialize itself?) is deferred to phase 3, once read-only generalization has shipped and the manifest sidecar format is designed.
  • GUI affordance: today this is CLI-only. An "Export to folder..." action in the notebook screen is a small follow-up, not before.