Skip to content

Domain Requirements v1 -- Loryth Knowledge Base

Meta Value
Status Draft
Version 1.0
Date 2026-02-14
Service loryth-kb
Platform Loryth (multi-tenant)

Service Context

The Loryth Knowledge Base (KB) is a service within the Loryth multi-tenant platform that lets users store, organize, and navigate Markdown documents and binary assets (PDF, PNG, JPEG, etc.) inside a hierarchical folder tree.

Tenancy and Ownership

Every entity in the KB belongs to exactly one Space. A space_id is mandatory on all root-level aggregates and is immutable after creation. Spaces are provisioned by the upstream IAM service; the KB service treats them as an opaque foreign reference.

Roles

Users interact with a Space in one of two roles:

Role Capabilities
reader View the folder tree, read documents and assets, browse revision history, view link graph.
editor All reader capabilities plus create, update, move, rename, and delete entries and sync roots.

Role resolution is performed by the IAM service. The KB service receives the resolved role via a request-scoped context (e.g., JWT claims or gateway header).

Core Capabilities

  1. Hierarchical storage -- folders, documents, and assets organized in a tree.
  2. Version history -- append-only revisions for documents and assets.
  3. Links and backlinks -- internal references extracted from Markdown, with a navigable graph view.
  4. Full-text search -- PostgreSQL tsvector-backed search over document content.
  5. Two-way partial sync -- synchronize a subtree of the KB with a local folder on the user's machine.

1. Ubiquitous Language Glossary

Term Definition
Space The top-level tenant boundary. Every KB entity belongs to exactly one Space. Spaces are created and managed by the IAM service; the KB service references them by space_id.
Entry The fundamental node in the KB tree. An Entry is one of three types: Folder, Document, or Asset. Entries form a self-referencing hierarchy via parent_id.
Folder An Entry whose entry_type is folder. Folders contain other Entries (Folders, Documents, or Assets) but have no content of their own.
Document An Entry whose entry_type is document. Its content is stored as a series of DocumentRevisions. The latest revision represents the current state.
Asset An Entry whose entry_type is asset. Binary files (PDF, PNG, JPEG, etc.) whose content is stored in an object store, referenced through AssetRevisions.
Revision A generic term for an immutable snapshot of content. Revisions are append-only; you cannot edit or delete a revision. Restoring previous content means creating a new revision with the old content.
DocumentRevision A specific revision of a Document. Contains the Markdown body, title, frontmatter, content hash, and authorship metadata.
AssetRevision A specific revision of an Asset. Contains a storage_key pointing to the binary blob in the object store, along with MIME type, byte size, content hash, and authorship metadata.
SyncRoot A configured synchronization relationship between a subtree of the KB and a local folder on a user's machine. Defines direction (push, pull, or bidirectional) and an optional scope.
SyncScope The set of folder Entry IDs (scope_entry_ids) that limits which parts of the KB tree are included in a given SyncRoot. When empty or null, the entire Space is in scope.
SyncManifest A point-in-time snapshot of file paths, content hashes, and revision numbers used to compute the delta between the local folder and the remote KB tree during a sync operation. Derived at sync time, not stored durably.
DocumentLink A directional reference from one Document to another Entry, extracted from Markdown link syntax. Stored persistently to support backlink queries and graph views.
Backlink The inverse view of a DocumentLink. Given an Entry, its backlinks are all DocumentLinks where it appears as the target_entry_id.
Canonical URI A stable, internal identifier for an Entry used inside Markdown links. Format: kb://doc/<UUID> for documents, kb://asset/<UUID> for assets. Canonical URIs survive renames and moves.
Frontmatter A JSON object (jsonb) attached to a DocumentRevision. Stores structured metadata (tags, aliases, custom properties) that lives alongside the Markdown body.
Content Hash A SHA-256 digest of the content body (for documents) or the binary blob (for assets). Used for deduplication checks and sync conflict detection.
EntryType An enumeration with three values: folder, document, asset. Stored on every Entry and immutable after creation.
SpaceRole An enumeration with two values: reader, editor. Resolved externally by the IAM service and passed into the KB service per request.
Link Graph The directed graph formed by all DocumentLinks within a Space. Nodes are Entries; edges are links. Used to render the graph view in the UI.
Search Index A PostgreSQL full-text search index (tsvector) maintained as a projection over DocumentRevision content. Supports ranked, filtered queries within a Space.

2. Aggregates

2.1 Entry

The Entry aggregate is the root of the KB tree. It models folders, documents, and assets as a single polymorphic entity with a self-referencing parent pointer.

Field Type Constraints
id bigint (PK) Auto-generated surrogate key.
uuid uuid Unique, indexed. Used in APIs and canonical URIs.
space_id bigint (FK) Mandatory. Immutable after creation.
parent_id bigint (FK to entry.id) Nullable. NULL means root-level entry.
entry_type enum(folder,document,asset) Immutable after creation.
name text File/folder name. Unique within (space_id, parent_id).
slug text URL-safe version of name. Unique within (space_id, parent_id).
position integer Sort order among siblings. Defaults to 0.
description text Optional short description.
created_at timestamptz Set on creation, never updated.
updated_at timestamptz Updated on any mutation to the Entry itself.

Relationships:

  • A Folder Entry may have zero or more child Entries (folders, documents, or assets).
  • A Document Entry has one or more DocumentRevisions (at least one is created on document creation).
  • An Asset Entry has one or more AssetRevisions (at least one is created on asset creation).
  • An Entry's parent_id references another Entry that must be a Folder.

Lifecycle:

  1. Created via CreateFolder, CreateDocument, or CreateAsset.
  2. Can be moved (MoveEntry), renamed (RenameEntry), or deleted (DeleteEntry).
  3. Deletion is recursive for folders: all descendants are deleted.
  4. entry_type and space_id are immutable after creation.

2.2 DocumentRevision

An append-only log of document content snapshots. The latest revision (highest revision_number) represents the current state of the document.

Field Type Constraints
id bigint (PK) Auto-generated surrogate key.
uuid uuid Unique, indexed.
entry_id bigint (FK to entry) Must reference an Entry with entry_type = document.
revision_number integer Monotonically increasing per entry_id. Starts at 1.
title text Human-readable title. May differ from entry.name.
body text Markdown content.
frontmatter jsonb Structured metadata (tags, aliases, custom properties).
author_id bigint The user who created this revision.
content_hash text SHA-256 hex digest of body.
byte_size bigint Size of body in bytes (UTF-8 encoded).
created_at timestamptz Set on creation. Revisions are immutable once created.

Lifecycle:

  1. The first revision is created as part of CreateDocument.
  2. Subsequent revisions are appended via UpdateDocument.
  3. Restoring a previous revision (RestoreDocumentRevision) creates a new revision whose body and frontmatter are copied from the target revision.
  4. Revisions are never updated or deleted.

2.3 AssetRevision

An append-only log of asset binary snapshots. The actual binary data lives in an external object store; this aggregate stores the reference.

Field Type Constraints
id bigint (PK) Auto-generated surrogate key.
uuid uuid Unique, indexed.
entry_id bigint (FK to entry) Must reference an Entry with entry_type = asset.
revision_number integer Monotonically increasing per entry_id. Starts at 1.
storage_key text Object store key (e.g., S3 path) for the binary blob.
mime_type text IANA media type (e.g., application/pdf, image/png).
byte_size bigint Size of the binary blob in bytes.
content_hash text SHA-256 hex digest of the binary blob.
author_id bigint The user who uploaded this revision.
created_at timestamptz Set on creation. Revisions are immutable once created.

Lifecycle:

  1. The first revision is created as part of CreateAsset.
  2. Subsequent revisions are appended via UploadAssetRevision.
  3. Revisions are never updated or deleted. Old blobs may be garbage-collected by a separate retention policy (out of scope for v1 domain logic).

A directional link extracted from the Markdown body of a Document, pointing to another Entry via its canonical URI.

Field Type Constraints
id bigint (PK) Auto-generated surrogate key.
uuid uuid Unique, indexed.
space_id bigint (FK) Must match the source entry's space_id.
source_entry_id bigint (FK to entry) Must reference an Entry with entry_type = document.
target_entry_id bigint (FK to entry) Nullable. NULL when the canonical URI cannot be resolved (broken link).
canonical_uri text The raw canonical URI as it appears in Markdown (e.g., kb://doc/<UUID>).
anchor text Optional fragment identifier (e.g., #section-heading).
context_text text Surrounding text snippet from the Markdown source for preview.

Lifecycle:

  1. Links are bulk-replaced on every ExtractLinks command: all existing links for a given source_entry_id are deleted and re-created from the current Markdown body.
  2. Links are deleted when the source Document Entry is deleted.
  3. Links with a target_entry_id of NULL represent broken links (the target does not exist or cannot be resolved).

2.5 SyncRoot

Represents a configured sync relationship between a user's local folder and a subtree of the KB.

Field Type Constraints
id bigint (PK) Auto-generated surrogate key.
uuid uuid Unique, indexed.
space_id bigint (FK) The Space this sync root operates within.
user_id bigint The user who owns this sync configuration.
name text Human-readable label for this sync root.
local_path text Absolute path on the user's local filesystem.
direction enum(push,pull,both) Sync direction: local-to-remote, remote-to-local, or bidirectional.
status enum(idle,syncing,error) Current operational status.
scope_entry_ids jsonb Array of folder Entry IDs that define the sync scope. NULL or empty means entire Space.
last_sync_hash text Hash of the last successfully synced manifest. Used for delta computation.
created_at timestamptz Set on creation.
updated_at timestamptz Updated on any mutation.

Lifecycle:

  1. Created via CreateSyncRoot.
  2. Scope can be narrowed or widened via UpdateSyncScope.
  3. Deleted via DeleteSyncRoot.
  4. status and last_sync_hash are updated by the sync engine during sync operations.

3. Invariants

3.1 Entry Invariants

ID Invariant
E-1 The parent chain must be acyclic. An Entry cannot be its own ancestor.
E-2 name must be unique within the tuple (space_id, parent_id).
E-3 slug must be unique within the tuple (space_id, parent_id).
E-4 If parent_id is not NULL, the referenced Entry must exist and must have entry_type = folder.
E-5 space_id is immutable after creation.
E-6 entry_type is immutable after creation.
E-7 A MoveEntry command must not create a cycle (i.e., the new parent must not be a descendant of the moved entry).
E-8 A MoveEntry command must keep the Entry within the same Space (space_id must match).

3.2 DocumentRevision Invariants

ID Invariant
DR-1 revision_number must be monotonically increasing per entry_id. Each new revision gets max(revision_number) + 1.
DR-2 content_hash must equal the SHA-256 hex digest of body.
DR-3 entry_id must reference an Entry with entry_type = document.
DR-4 Revisions are immutable once created. No updates or deletes are permitted.

3.3 AssetRevision Invariants

ID Invariant
AR-1 revision_number must be monotonically increasing per entry_id. Each new revision gets max(revision_number) + 1.
AR-2 entry_id must reference an Entry with entry_type = asset.
AR-3 Revisions are immutable once created. No updates or deletes are permitted.
AR-4 storage_key must be a non-empty string pointing to a valid object store location.
ID Invariant
DL-1 source_entry_id must reference an Entry with entry_type = document.
DL-2 space_id must match the space_id of the source Entry.
DL-3 If target_entry_id is not NULL, it must reference an existing Entry within the same Space.
DL-4 canonical_uri must conform to the format kb://doc/<UUID> or kb://asset/<UUID>.

3.5 SyncRoot Invariants

ID Invariant
SR-1 Every ID in scope_entry_ids must reference a valid Entry with entry_type = folder within the same Space.
SR-2 A user may not have two SyncRoots with the same local_path.
SR-3 direction must be one of push, pull, or both.

4. Commands (Write-Side)

All commands require the caller to have editor role in the target Space unless otherwise noted.

4.1 Entry Commands

CreateFolder

Parameter Type Required Notes
space_id bigint Yes Target Space.
name text Yes Must be unique within (space_id, parent_id).
parent_id bigint No NULL for root-level folder.
description text No Optional short description.

Emits: EntryCreatedEvent

CreateDocument

Parameter Type Required Notes
space_id bigint Yes Target Space.
name text Yes Must be unique within (space_id, parent_id).
body text Yes Markdown content for the initial revision.
author_id bigint Yes User creating the document.
parent_id bigint No NULL for root-level document.
title text No Defaults to name if omitted.
frontmatter jsonb No Structured metadata.

Side effects: Creates the Entry and the first DocumentRevision (revision_number = 1). Extracts links from body.

Emits: EntryCreatedEvent, DocumentRevisionCreatedEvent, LinkExtractedEvent

CreateAsset

Parameter Type Required Notes
space_id bigint Yes Target Space.
name text Yes Must be unique within (space_id, parent_id).
storage_key text Yes Object store key for the uploaded binary.
mime_type text Yes IANA media type.
byte_size bigint Yes Size in bytes.
content_hash text Yes SHA-256 hex digest of the binary.
author_id bigint Yes User uploading the asset.
parent_id bigint No NULL for root-level asset.

Side effects: Creates the Entry and the first AssetRevision (revision_number = 1).

Emits: EntryCreatedEvent, AssetRevisionCreatedEvent

MoveEntry

Parameter Type Required Notes
entry_id bigint Yes Entry to move.
new_parent_id bigint Yes Must be a folder in the same Space. NULL to move to root.
space_id bigint Yes Used to verify the move stays within the same Space.

Preconditions: Must not create a cycle (invariant E-7). Must stay within the same Space (invariant E-8). name must be unique at the destination.

Emits: EntryMovedEvent

RenameEntry

Parameter Type Required Notes
entry_id bigint Yes Entry to rename.
new_name text Yes Must be unique within (space_id, parent_id).

Side effects: Updates name, recomputes slug, updates updated_at.

Emits: EntryRenamedEvent

DeleteEntry

Parameter Type Required Notes
entry_id bigint Yes Entry to delete.

Side effects: Recursively deletes all descendant Entries (for folders). Deletes all associated revisions and links. Orphaned links (where target_entry_id pointed to a deleted entry) have their target_entry_id set to NULL.

Emits: EntryDeletedEvent (one per deleted entry)


4.2 Revision Commands

UpdateDocument

Parameter Type Required Notes
document_id bigint Yes Must reference an Entry with entry_type = document.
body text Yes New Markdown content.
author_id bigint Yes User making the edit.
title text No If omitted, carries forward from previous revision.
frontmatter jsonb No If omitted, carries forward from previous revision.

Side effects: Creates a new DocumentRevision with revision_number = max + 1. Re-extracts links from the new body.

Emits: DocumentRevisionCreatedEvent, LinkExtractedEvent

UploadAssetRevision

Parameter Type Required Notes
asset_id bigint Yes Must reference an Entry with entry_type = asset.
storage_key text Yes Object store key for the new binary.
mime_type text Yes IANA media type.
byte_size bigint Yes Size in bytes.
content_hash text Yes SHA-256 hex digest of the binary.
author_id bigint Yes User uploading the revision.

Side effects: Creates a new AssetRevision with revision_number = max + 1.

Emits: AssetRevisionCreatedEvent

RestoreDocumentRevision

Parameter Type Required Notes
document_id bigint Yes Must reference an Entry with entry_type = document.
revision_id bigint Yes The revision whose content should be restored. Must belong to the same document.
author_id bigint Yes User performing the restore.

Side effects: Creates a new DocumentRevision by copying body, title, and frontmatter from the specified revision. The new revision gets its own revision_number, content_hash, and created_at. Re-extracts links.

Emits: DocumentRevisionCreatedEvent, LinkExtractedEvent


Parameter Type Required Notes
source_entry_id bigint Yes Must reference a document Entry.
space_id bigint Yes Used for link resolution scope.
markdown_body text Yes The Markdown content to parse for links.

Side effects: Parses all canonical URIs (kb://doc/<UUID>, kb://asset/<UUID>) from markdown_body. Deletes all existing DocumentLinks for source_entry_id and inserts the newly extracted set. Resolves each canonical URI to a target_entry_id where possible; leaves it NULL for broken links.

Emits: LinkExtractedEvent


4.4 Sync Commands

CreateSyncRoot

Parameter Type Required Notes
space_id bigint Yes Target Space.
user_id bigint Yes Owner of the sync configuration.
name text Yes Human-readable label.
local_path text Yes Absolute path on the user's machine.
direction enum Yes One of push, pull, both.
scope_entry_ids jsonb No Array of folder Entry IDs. NULL for entire Space.

Emits: None (configuration only).

UpdateSyncScope

Parameter Type Required Notes
sync_root_id bigint Yes The SyncRoot to update.
scope_entry_ids jsonb Yes New array of folder Entry IDs. Empty array for entire Space.

Preconditions: All IDs in scope_entry_ids must satisfy invariant SR-1.

Emits: None (configuration only).

DeleteSyncRoot

Parameter Type Required Notes
sync_root_id bigint Yes The SyncRoot to delete.

Emits: None (configuration only).


5. Queries (Read-Side)

All queries require the caller to have at least reader role in the target Space.

Query Parameters Returns
GetEntry entry_id Single Entry with its metadata. Includes entry_type to allow the caller to fetch revisions.
ListRoots space_id All Entries where parent_id is NULL within the Space, ordered by position then name.
ListChildren folder_id, space_id All direct child Entries of the given folder, ordered by position then name.
GetDocumentContent document_id The latest DocumentRevision (highest revision_number) for the given document Entry.
ListDocumentRevisions document_id All DocumentRevisions for the given document, ordered by revision_number descending.
GetBacklinks entry_id All DocumentLinks where target_entry_id equals the given Entry ID.
GetOutgoingLinks entry_id All DocumentLinks where source_entry_id equals the given Entry ID.
GetLinkGraph space_id All DocumentLinks in the Space, returned as a list of edges (source_entry_id, target_entry_id, canonical_uri).
Search query, space_id, filters Ranked list of document Entries matching the full-text query. Filters may include parent_id, entry_type, and frontmatter predicates.
ListSyncRoots user_id, space_id All SyncRoots for the given user within the Space.
GetSyncRoot sync_root_id Single SyncRoot with all configuration fields.

6. Domain Events

All events include a timestamp field (ISO 8601) and an event_id (UUID) in addition to the fields listed below.

6.1 Entry Events

EntryCreatedEvent

Field Type Notes
space_id bigint The Space the entry belongs to.
entry_uuid uuid UUID of the created Entry.
entry_type enum folder, document, or asset.
name text Name of the entry.
parent_uuid uuid UUID of the parent Entry. NULL for root.

EntryMovedEvent

Field Type Notes
space_id bigint The Space the entry belongs to.
entry_uuid uuid UUID of the moved Entry.
old_parent_uuid uuid UUID of the previous parent. NULL if was root.
new_parent_uuid uuid UUID of the new parent. NULL if moved to root.

EntryRenamedEvent

Field Type Notes
space_id bigint The Space the entry belongs to.
entry_uuid uuid UUID of the renamed Entry.
old_name text Previous name.
new_name text New name.

EntryDeletedEvent

Field Type Notes
space_id bigint The Space the entry belonged to.
entry_uuid uuid UUID of the deleted Entry.
entry_type enum folder, document, or asset.

6.2 Revision Events

DocumentRevisionCreatedEvent

Field Type Notes
space_id bigint The Space the document belongs to.
document_uuid uuid UUID of the document Entry.
revision_uuid uuid UUID of the new DocumentRevision.
revision_number integer Sequence number of the new revision.

AssetRevisionCreatedEvent

Field Type Notes
space_id bigint The Space the asset belongs to.
asset_uuid uuid UUID of the asset Entry.
revision_uuid uuid UUID of the new AssetRevision.
revision_number integer Sequence number of the new revision.

LinkExtractedEvent

Field Type Notes
space_id bigint The Space the document belongs to.
source_document_uuid uuid UUID of the source document Entry.
target_uuids uuid[] Array of resolved target Entry UUIDs. Does not include broken links.

7. Projections

Projections are read-model updaters that consume domain events and maintain denormalized views optimized for specific query patterns.

7.1 SearchIndexProjection

Aspect Detail
Consumes DocumentRevisionCreatedEvent, EntryDeletedEvent
Maintains A PostgreSQL tsvector full-text index over document content.
Behavior On DocumentRevisionCreatedEvent: fetches the latest revision body and title, tokenizes them, and upserts the tsvector row keyed by entry_id. On EntryDeletedEvent (where entry_type = document): removes the corresponding tsvector row.
Used by Search query.

7.2 LinkGraphProjection

Aspect Detail
Consumes LinkExtractedEvent, EntryDeletedEvent
Maintains A materialized view of links and backlinks optimized for graph traversal.
Behavior On LinkExtractedEvent: replaces all outgoing edges for the source document with the newly extracted set. On EntryDeletedEvent: removes all edges where the deleted entry is either source or target; sets target_entry_id to NULL on edges that referenced the deleted entry as a target.
Used by GetBacklinks, GetOutgoingLinks, GetLinkGraph queries.

7.3 RecentActivityProjection

Aspect Detail
Consumes EntryCreatedEvent, EntryMovedEvent, EntryRenamedEvent, EntryDeletedEvent, DocumentRevisionCreatedEvent, AssetRevisionCreatedEvent
Maintains A time-ordered log of recent changes per Space, capped at a configurable limit (e.g., 200 entries per Space).
Behavior On any consumed event: inserts a summary record with the event type, entry UUID, entry name, actor, and timestamp. Trims older records beyond the cap.
Used by Activity feed UI within a Space.

7.4 SyncStatusProjection

Aspect Detail
Consumes EntryCreatedEvent, EntryMovedEvent, EntryRenamedEvent, EntryDeletedEvent, DocumentRevisionCreatedEvent, AssetRevisionCreatedEvent
Maintains A per-SyncRoot status record tracking whether the remote KB tree has diverged from the last sync point.
Behavior On any consumed event: checks whether the affected entry falls within the scope of any active SyncRoot. If so, marks the SyncRoot as stale (pending re-sync). Conflict detection happens at sync execution time, not in the projection.
Used by ListSyncRoots and GetSyncRoot queries (to surface staleness indicators in the UI).

8. Out of Scope for v1

The following capabilities are explicitly deferred to future versions:

Capability Rationale
Embedding / AI search (semantic) Requires a vector store and embedding pipeline. Deferred to v2 once the core document model is stable.
Real-time collaborative editing Requires CRDT or OT infrastructure. Documents are single-writer in v1; conflict resolution is last-write-wins.
Permissions beyond Reader/Editor Fine-grained ACLs (per-folder, per-document) add significant complexity. v1 uses Space-level roles only.
Comments / annotations on documents Requires a separate comment aggregate with threading and notification integration. Deferred to v2.
Document templates Pre-defined document structures (e.g., meeting notes, design docs). Deferred until usage patterns emerge.
Webhooks for external integrations Outbound event delivery to third-party systems. Deferred until the internal event model is proven stable.