Skip to content

Loryth Knowledge Base -- Development Roadmap

Field Value
Service loryth-kb
Stack Python 3.13+ / FastAPI / PostgreSQL 17 / RabbitMQ 4 / MinIO
Target user Individual or small-team knowledge worker
Scale ~2 000 documents per user over 6 months
Status Pre-v1 development

1. Overview

The Loryth Knowledge Base service provides a structured, version-controlled repository for Markdown documents and binary assets. Users organise content in a folder hierarchy, navigate links between documents, search across a space, and synchronise subtrees to a local filesystem for offline editing.

This roadmap breaks development into seven milestones. Each milestone produces a working, tested increment that can be demonstrated and deployed independently.


2. Architecture at a Glance

                  +-----------+
                  |  FastAPI   |  (loryth-kb API)
                  +-----+-----+
                        |
        +-------+-------+-------+-------+
        |       |               |       |
   PostgreSQL  MinIO        RabbitMQ  loryth-kb worker
   (entries,   (asset       (domain    (async event
    revisions,  blobs)       events)    handlers)
    links,
    search,
    sync roots)

Key domain tables (already migrated)

Table Purpose
entry Folder / document / asset tree node
document_revision Append-only Markdown snapshots
asset_revision Append-only binary file snapshots
document_link Directed links with backlink support
sync_root Sync configuration per user/space

3. Milestones

M1 -- Core CRUD + Folder Tree (Weeks 1--2)

Goal: Establish the foundational data model and API surface so that every later milestone can build on reliable entry management.

Work item Detail
Entry CRUD Create, read, update, delete for folders, documents, and assets
Folder hierarchy parent_id navigation, listing children, breadcrumb path resolution
Cycle prevention Ancestor walk on move/reparent; reject if the target is a descendant
Document revisions Create initial revision on document creation; create new revision on update; list revisions; get revision content
Asset revisions Create initial revision with upload; upload new revision for existing asset
Slug generation Auto-generate URL-safe slugs from entry names; enforce sibling uniqueness per (space_id, parent_id, name)
Migration scripts v01 through v03 (entry, document_revision, asset_revision)
API tests Happy-path and error-case tests for every endpoint using testcontainers

Definition of Done

  • A user can create, read, update, and delete entries of all three types.
  • Folder tree can be navigated (list children, resolve path).
  • Document and asset revisions are created on every content change.
  • All tests pass.

Dependencies: None (foundation milestone).


M2 -- Version History + Restore (Weeks 3--4)

Goal: Make the full revision timeline browsable and allow restoring a document to any previous revision.

Work item Detail
Revision list endpoint Paginated list of revisions per entry with metadata (author, timestamp, byte_size, content_hash)
Get specific revision Retrieve the body of any historical revision by revision_number
Restore to revision Create a new revision whose body is copied from a previous one; increment revision_number
Revision diff support v1: return both revisions in a single response so the client can compute the diff; no server-side diffing
Asset revision listing Same paginated list for asset revisions (storage_key, mime_type, byte_size)
Content hash verification On revision creation, compute SHA-256 of the body/blob and persist as content_hash; expose verification endpoint

Definition of Done

  • Full revision history is browsable for both documents and assets.
  • Restore creates a new revision with the old content.
  • Content hashes are computed and stored for every revision.
  • Tests cover restore round-trip and hash verification.

Dependencies: M1.


Goal: Automatically extract links from Markdown content, maintain a link table, and expose queries for backlinks and the knowledge graph.

Work item Detail
Link extraction Parse kb:// URIs from Markdown body on every revision save; store in document_link table
kb:// URI scheme Format: kb://<space_id>/<entry_uuid>[#anchor]; resolve to target_entry_id at extraction time
Backlink queries GET /entries/{entry_id}/backlinks -- all documents that link to this entry
Outgoing link queries GET /entries/{entry_id}/links -- all links originating from this document
Link graph endpoint GET /spaces/{space_id}/graph -- returns all links in the space as {nodes, edges} for client-side rendering
Broken link detection Links whose target_entry_id IS NULL (target not found or deleted); queryable via filter on link endpoints
Re-extraction on save Replace all links for the source document on every revision save (delete + re-insert)

Definition of Done

  • Links are auto-extracted from Markdown body when a document revision is saved.
  • Backlinks and outgoing links are queryable.
  • Graph endpoint returns the full link topology for a space.
  • Broken links are detectable.
  • Tests cover extraction edge cases (multiple links, anchors, broken targets).

Dependencies: M1.


M4 -- Full-Text Search (Weeks 5--6)

Goal: Provide fast, filtered full-text search over document content and entry metadata using PostgreSQL's built-in text search.

Work item Detail
Search index table/column Add a tsvector column (or materialised projection) combining entry.name, document_revision.title, and document_revision.body
GIN index Create a GIN index on the tsvector column for fast lookup
Search API GET /spaces/{space_id}/search?q=... with filters: entry_type, parent_id, tags (future), and pagination
Relevance ranking Use ts_rank for ordering results; return a score field in the response
Index rebuild on revision events Listen for DocumentRevisionCreated events via RabbitMQ; update the search projection asynchronously
Migration New migration script for tsvector column and GIN index

Definition of Done

  • Search returns relevant documents for a given query string.
  • Filters narrow results correctly.
  • Index is automatically updated when revisions are created.
  • Pagination works.
  • Tests cover basic ranking, filters, and empty-result cases.

Dependencies: M1, M3 (link context may be included in search later).


M5 -- Sync Engine -- Foundation (Weeks 7--9)

Goal: Allow exporting a space subtree to a local folder and importing it back, preserving identity via frontmatter IDs.

Work item Detail
SyncRoot CRUD Create, read, update, delete sync root configurations (sync_root table)
Sync manifest generation Walk the entry tree for a given scope; produce a flat manifest mapping entry UUIDs to relative file paths
Export (platform to local) Generate Markdown files with YAML frontmatter (id, title, parent, tags); convert kb:// links to relative file paths; write assets to disk
Import (local to platform) Read local Markdown files; parse frontmatter to resolve or create entries; convert relative links back to kb:// URIs; upload assets to MinIO
Frontmatter ID persistence Assign a stable uuid in frontmatter on first export; use it to match files on re-import
Partial sync via scope_entry_ids scope_entry_ids (JSONB) limits sync to a subtree; entries outside scope are ignored
Link conversion kb:// URIs are converted to relative paths on export; relative paths are resolved back to kb:// on import

Definition of Done

  • A user can export a space subtree to a local folder structure.
  • Re-importing the folder recreates the same entries with matching UUIDs.
  • Links are converted in both directions.
  • Partial sync respects scope boundaries.
  • Tests cover round-trip export/import fidelity.

Dependencies: M1, M2 (revision restore mechanics), M3 (link conversion).


M6 -- Sync Engine -- Bidirectional + Conflicts (Weeks 9--11)

Goal: Support true two-way sync with automatic conflict detection and a clear resolution workflow.

Work item Detail
Change detection Compare content_hash of local files against last_sync_hash on the sync root and the latest platform revision hash
Three-way comparison Base = last_sync_hash, local = file hash, remote = latest revision hash; classify as local-only, remote-only, or conflict
Conflict resolution workflow Surface conflicts via API; user chooses keep_local, keep_remote, or manual_merge; resolution creates a new revision
Rename/move detection Match by frontmatter id rather than file path; detect renames and moves
Out-of-scope link handling Links pointing outside the sync scope are preserved as kb:// URIs in the local file (not converted to paths)
Sync locking Set sync_root.status = 'syncing' during an active sync; reject concurrent sync requests; timeout after configurable duration
Status transitions idle -> syncing -> idle on success; idle -> syncing -> conflict when conflicts detected; idle -> syncing -> error on failure

Definition of Done

  • Bidirectional sync detects local-only, remote-only, and conflicting changes.
  • Conflict resolution via the three options works end-to-end.
  • Renames and moves are detected by frontmatter ID.
  • Out-of-scope links are handled gracefully.
  • Concurrent sync requests are rejected.
  • Tests cover all change classification scenarios and conflict resolution paths.

Dependencies: M5.


M7 -- Production Hardening (Weeks 11--13)

Goal: Prepare the service for production deployment with authentication, observability, and operational tooling.

Work item Detail
Auth integration Enforce SpaceRole checks (reader / editor) on all endpoints; integrate with platform auth (JWT validation)
Rate limiting Per-user rate limits on write endpoints; configurable via environment variables
Error handling Consistent error response schema; map domain exceptions to HTTP status codes; never leak internal details
Structured logging JSON-formatted logs with request_id, user_id, space_id; use Python structlog or stdlib logging with JSON formatter
Metrics Expose Prometheus-compatible /metrics endpoint; track request latency, revision counts, sync durations, search query times
Health checks GET /healthz (liveness) and GET /readyz (readiness: DB, RabbitMQ, MinIO connectivity)
Performance testing Load test at target scale (2 000 docs, 100 revisions each); verify search latency < 200ms p95; verify sync of 500-doc subtree < 30s
API documentation Review and complete OpenAPI schema descriptions; add request/response examples
Migration safety Verify all migrations are idempotent; add a migration version check to the health endpoint

Definition of Done

  • All endpoints require valid authentication and enforce role-based access.
  • Rate limits are active.
  • Structured logs are emitted on every request.
  • Metrics endpoint is functional.
  • Health checks pass in staging.
  • Performance targets are met at design scale.
  • OpenAPI docs are complete and accurate.

Dependencies: M1--M6.


4. Milestone Dependency Graph

M1  (Core CRUD + Folder Tree)
 |
 +---> M2  (Version History + Restore)
 |      |
 +---> M3  (Links + Backlinks + Graph View)
 |      |
 +------+---> M4  (Full-Text Search)
 |      |
 +------+---> M5  (Sync Engine - Foundation)
               |
               +---> M6  (Sync Engine - Bidirectional)
                      |
M1--M6 ---------------+---> M7  (Production Hardening)

5. Iteration Plan

Principle Detail
Iteration length 1--2 weeks
Deliverable Each iteration produces a working, deployable increment
Testing Tests are written alongside features, not as a separate phase; target >80% line coverage on new code
Documentation API schemas and migration scripts updated within the milestone that introduces them
Review cadence Code review before merge; milestone demo at the end of each milestone
Branch strategy Feature branches off main; squash-merge on completion

Suggested iteration breakdown

Iteration Weeks Milestone Focus
I1 1--2 M1 Entry CRUD, folder tree, revisions
I2 3--4 M2 Version history, restore, hash verification
I3 4--5 M3 Link extraction, backlinks, graph
I4 5--6 M4 Full-text search, index projection
I5 7--8 M5 (1/2) SyncRoot CRUD, manifest, export
I6 8--9 M5 (2/2) Import, frontmatter IDs, partial scope
I7 9--10 M6 (1/2) Change detection, three-way comparison
I8 10--11 M6 (2/2) Conflict resolution, rename detection
I9 11--12 M7 (1/2) Auth, rate limiting, error handling
I10 12--13 M7 (2/2) Observability, perf testing, API docs

6. Risk Register

# Risk Impact Probability Mitigation
R1 Sync conflict resolution UX complexity High Medium Start with the three simple resolution options (keep_local, keep_remote, manual_merge). Defer smart three-way merge algorithms to a post-v1 iteration.
R2 Full-text search performance at scale Medium Low PostgreSQL FTS with GIN indexes is well-proven at this scale. Add result pagination from day one. If latency degrades, migrate to a dedicated search engine (e.g. Meilisearch) behind the same API contract.
R3 Link extraction edge cases Medium Medium Start with regex-based kb:// URI extraction. Build a comprehensive test suite covering nested links, escaped brackets, code blocks, and malformed URIs. Move to a proper Markdown AST parser if false positives become a problem.
R4 Cycle detection performance on deep trees Low Low Ancestor walk is O(depth) and tree depth is practically bounded (rarely >10 levels). If needed, add a path materialised column (ltree) for constant-time ancestry checks.
R5 Asset storage costs growing with revisions Medium Low Content-addressed deduplication via content_hash prevents storing identical blobs. Add lifecycle policies on MinIO to archive or delete orphaned objects.
R6 Partial sync scope changes during active sync High Medium Lock the sync root (status = 'syncing') for the duration of an active sync operation. Reject scope mutations while locked. Queue scope changes and apply them before the next sync run.
R7 Migration backwards compatibility Medium Low All migrations are additive (new tables/columns). Avoid destructive migrations. Test migration scripts against a snapshot of production data before deploying.
R8 RabbitMQ message loss affecting search index Medium Low Use publisher confirms and consumer acknowledgements. The search index can be fully rebuilt from the revision table as a recovery mechanism.

7. Technical Decisions and Constraints

Decision Rationale
PostgreSQL FTS over dedicated search engine Sufficient for ~2 000 docs per user; avoids operational overhead of a separate service
Append-only revisions (no in-place update) Simplifies version history, restore, and sync conflict detection; storage cost is acceptable at target scale
kb:// URI scheme for internal links Decouples link identity from file path or URL; survives renames and moves
Content-addressed hashing (SHA-256) Enables cheap change detection for sync; supports deduplication for assets
JSONB for scope_entry_ids and frontmatter Flexible schema for evolving sync scope and document metadata without migrations
RabbitMQ for async events Existing platform infrastructure; search index updates and future event consumers (notifications, webhooks)
MinIO for asset storage S3-compatible; content-addressed keys enable dedup; lifecycle policies for cost control

8. Future Work (Post-v1)

These items are explicitly out of scope for the initial release but are tracked for future planning.

Feature Description Prerequisite
Semantic search Vector embeddings (pgvector) for similarity search alongside keyword FTS M4
Real-time collaborative editing WebSocket-based CRDT or OT for concurrent document editing M1, M2
Fine-grained ACL Per-entry permissions beyond space-level Reader/Editor roles M7
Document templates Pre-defined Markdown templates for common document types (meeting notes, ADRs, runbooks) M1
Webhooks / external integrations Notify external systems on document events (create, update, delete) M7
Comments and annotations Inline comments on document sections; threaded discussions M1, M3
Smart three-way merge Automatic line-level merge for non-conflicting concurrent edits during sync M6
Cross-space links kb:// links that reference entries in a different space M3
Trash / soft delete Move deleted entries to a trash folder with a retention period before permanent deletion M1
Export formats PDF, DOCX, and HTML export of documents and folders M1, M2