Skip to content

Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring

feat(docs): a real document space for the homelab

Pouzore6d338be13f7
diff --git a/backend/app/api/routes/designs.py b/backend/app/api/routes/designs.py
index c0018fd..3c7bda0 100644
--- a/backend/app/api/routes/designs.py
+++ b/backend/app/api/routes/designs.py
@@ -8,6 +8,7 @@ from app.api.deps import get_current_user
from app.db.database import get_db
from app.db.models import CanvasState, Design, Edge, Node, Rack, RackCable, RackDevice
from app.schemas.designs import DesignCopy, DesignCreate, DesignResponse, DesignUpdate
+from app.services.doc_links import unlink_documents
router = APIRouter()
@@ -233,6 +234,8 @@ async def delete_design(
for e in edges:
await db.delete(e)
nodes = (await db.execute(select(Node).where(Node.design_id == design_id))).scalars().all()
+ # Foreign keys are off, so orphan the documents by hand before the rows go.
+ await unlink_documents(db, node_ids=[n.id for n in nodes], design_ids=[design_id])
for n in nodes:
await db.delete(n)
await db.delete(design)
diff --git a/backend/app/api/routes/documents.py b/backend/app/api/routes/documents.py
new file mode 100644
index 0000000..2f9b63a
--- /dev/null
+++ b/backend/app/api/routes/documents.py
@@ -0,0 +1,581 @@
+"""Documents — the markdown documentation space.
+
+A document is either a page or a folder in the Library tree, or it describes one
+thing elsewhere in the app: a Device Inventory row, a piece of canvas furniture
+(a zone, a group), or a whole canvas. The tree the user navigates is *not* stored
+here: device documents are pivoted client-side by zone, subnet, type and so on,
+because every one of those groupings is derivable from data the frontend already
+holds and re-pivoting must be instant.
+
+The generated header is written once, at creation. Nothing in this module ever
+rewrites a body the user owns; `GET /blocks` hands the editor a freshly generated
+section on request, and `facts_snapshot` is what lets the UI say the device has
+moved on since the document was written.
+"""
+
+import re
+from datetime import datetime, timedelta, timezone
+from typing import Any
+
+from fastapi import APIRouter, Depends, HTTPException, Query
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.api.deps import get_current_user
+from app.db.database import get_db
+from app.db.models import Document, DocumentRevision, Edge, InventoryDevice, Node, Rack, RackDevice
+from app.schemas.documents import (
+ CoverageResponse,
+ DocumentCreate,
+ DocumentResponse,
+ DocumentSummary,
+ DocumentUpdate,
+ RevisionResponse,
+ RevisionSummary,
+ ScaffoldRequest,
+ ScaffoldResponse,
+ SearchHit,
+ SearchResponse,
+)
+from app.services import doc_search
+from app.services.doc_template import (
+ BLOCKS,
+ TEMPLATE_DEVICE,
+ facts_snapshot,
+ render_block,
+ render_device_document,
+ render_library_document,
+)
+from app.services.doc_tree import (
+ REVISION_LIMIT,
+ TREE_KINDS,
+ is_ancestor,
+ parse_frontmatter,
+ subtree_ids,
+ tags_from,
+ unique_slug,
+)
+
+router = APIRouter()
+
+# Node.type values that are canvas furniture. A zone or a group is documented
+# through its node; everything else is documented through its device.
+_FURNITURE_TYPES = {"group", "groupRect", "text"}
+
+_INTERVAL = re.compile(r"^\s*(\d+)\s*([dwmy])\s*$", re.IGNORECASE)
+_INTERVAL_DAYS = {"d": 1, "w": 7, "m": 30, "y": 365}
+
+
+def _now() -> datetime:
+ return datetime.now(timezone.utc)
+
+
+def _aware(value: datetime | None) -> datetime | None:
+ """SQLite hands back naive datetimes; compare them as UTC."""
+ if value is None:
+ return None
+ return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
+
+
+def _parse_interval(raw: Any) -> timedelta | None:
+ """`review_every: 6m` → 180 days. Anything unparseable means "never due"."""
+ match = _INTERVAL.match(str(raw or ""))
+ if not match:
+ return None
+ return timedelta(days=int(match.group(1)) * _INTERVAL_DAYS[match.group(2).lower()])
+
+
+def _apply_body(doc: Document, body: str) -> None:
+ """Store a body and refresh the frontmatter/tags cache from it.
+
+ The body is the source of truth — it is what exports to disk — so the two
+ JSON columns are only ever derived from it, never edited on their own.
+ """
+ doc.body = body
+ frontmatter = parse_frontmatter(body)
+ doc.frontmatter = frontmatter
+ doc.tags = tags_from(frontmatter)
+
+
+async def _record_revision(db: AsyncSession, doc: Document, reason: str) -> None:
+ """Snapshot the current body, then prune the document's oldest history."""
+ db.add(DocumentRevision(document_id=doc.id, title=doc.title, body=doc.body or "", reason=reason))
+ await db.flush()
+ stale = (
+ await db.execute(
+ select(DocumentRevision)
+ .where(DocumentRevision.document_id == doc.id)
+ .order_by(DocumentRevision.saved_at.desc(), DocumentRevision.id.desc())
+ .offset(REVISION_LIMIT)
+ )
+ ).scalars().all()
+ for revision in stale:
+ await db.delete(revision)
+
+
+async def _device_context(db: AsyncSession, device_id: str) -> dict[str, Any]:
+ """Zone, rack placement and canvas neighbours for a device.
+
+ All three are optional: a device may be on no canvas, in no rack and in no
+ zone, and the template drops those sections rather than printing them empty.
+ """
+ context: dict[str, Any] = {"zone_label": None, "rack": None, "connections": []}
+
+ node = (
+ await db.execute(select(Node).where(Node.device_id == device_id).order_by(Node.created_at))
+ ).scalars().first()
+ if node is not None:
+ parent_id = node.parent_id
+ seen: set[str] = set()
+ while parent_id and parent_id not in seen:
+ seen.add(parent_id)
+ parent = await db.get(Node, parent_id)
+ if parent is None:
+ break
+ if parent.type in _FURNITURE_TYPES:
+ context["zone_label"] = parent.label
+ break
+ parent_id = parent.parent_id
+
+ edges = (
+ await db.execute(select(Edge).where((Edge.source == node.id) | (Edge.target == node.id)))
+ ).scalars().all()
+ peer_ids = [e.target if e.source == node.id else e.source for e in edges]
+ if peer_ids:
+ peers = (await db.execute(select(Node.label).where(Node.id.in_(peer_ids)))).scalars().all()
+ context["connections"] = sorted({label for label in peers if label})
+
+ mount = (
+ await db.execute(select(RackDevice).where(RackDevice.device_id == device_id))
+ ).scalars().first()
+ if mount is not None:
+ rack = await db.get(Rack, mount.rack_id)
+ context["rack"] = {
+ "name": rack.name if rack else None,
+ "u_start": mount.u_start,
+ "u_height": mount.u_height,
+ "col_span": mount.col_span,
+ }
+ return context
+
+
+async def _scaffold_body(db: AsyncSession, doc: Document, template_id: str | None) -> None:
+ """Generate this document's initial body. Called once, at creation."""
+ if doc.device_id:
+ device = await db.get(InventoryDevice, doc.device_id)
+ if device is not None:
+ context = await _device_context(db, doc.device_id)
+ _apply_body(doc, render_device_document(device, **context))
+ doc.facts_snapshot = facts_snapshot(device)
+ doc.facts_synced_at = _now()
+ doc.template_id = TEMPLATE_DEVICE
+ return
+ _apply_body(doc, render_library_document(template_id or "blank", doc.title))
+ doc.template_id = template_id or "blank"
+
+
+# ── list / read ─────────────────────────────────────────────────────────────
+
+
[email protected]("", response_model=list[DocumentSummary])
+async def list_documents(
+ kind: str | None = Query(None, description="Filter to one document kind"),
+ parent_id: str | None = Query(None, description="Library children of this folder"),
+ device_id: str | None = Query(None, description="The document describing this device"),
+ tag: str | None = Query(None, description="Documents carrying this frontmatter tag"),
+ db: AsyncSession = Depends(get_db),
+ _: str = Depends(get_current_user),
+) -> list[DocumentSummary]:
+ query = select(Document)
+ if kind:
+ query = query.where(Document.kind == kind)
+ if parent_id:
+ query = query.where(Document.parent_id == parent_id)
+ if device_id:
+ query = query.where(Document.device_id == device_id)
+ docs = (await db.execute(query.order_by(Document.sort_order, Document.title))).scalars().all()
+ if tag:
+ wanted = tag.lower()
+ docs = [d for d in docs if any(str(t).lower() == wanted for t in (d.tags or []))]
+ return [DocumentSummary.model_validate(d) for d in docs]
+
+
[email protected]("/coverage", response_model=CoverageResponse)
+async def coverage(
+ db: AsyncSession = Depends(get_db),
+ _: str = Depends(get_current_user),
+) -> CoverageResponse:
+ """How much of the homelab is actually written down."""
+ devices = (
+ await db.execute(select(InventoryDevice).where(InventoryDevice.status != "hidden"))
+ ).scalars().all()
+ docs = (await db.execute(select(Document))).scalars().all()
+ by_device = {d.device_id: d for d in docs if d.device_id}
+
+ header_only = drifted = overdue = 0
+ now = _now()
+ for device in devices:
+ doc = by_device.get(device.id)
+ if doc is None:
+ continue
+ # Never edited since it was generated: the template is all there is.
+ if doc.edited_at is None and doc.reviewed_at is None:
+ header_only += 1
+ if doc.facts_snapshot and doc.facts_snapshot != facts_snapshot(device):
+ drifted += 1
+ interval = _parse_interval((doc.frontmatter or {}).get("review_every"))
+ since = _aware(doc.reviewed_at) or _aware(doc.created_at)
+ if interval and since and now - since > interval:
+ overdue += 1
+
+ documented = sum(1 for device in devices if device.id in by_device)
+ return CoverageResponse(
+ devices=len(devices),
+ documented=documented,
+ header_only=header_only,
+ missing=len(devices) - documented,
+ drifted=drifted,
+ overdue=overdue,
+ notes_unmigrated=sum(
+ 1 for device in devices if (device.notes or "").strip() and device.id not in by_device
+ ),
+ library_pages=sum(1 for d in docs if d.kind in TREE_KINDS),
+ )
+
+
[email protected]("/search", response_model=SearchResponse)
+async def search_documents(
+ q: str = Query(..., description="Full-text query"),
+ limit: int = Query(25, ge=1, le=100),
+ db: AsyncSession = Depends(get_db),
+ _: str = Depends(get_current_user),
+) -> SearchResponse:
+ engine, rows = await doc_search.search(db, q, limit)
+ if not rows:
+ return SearchResponse(engine=engine, hits=[])
+ docs = {
+ d.id: d
+ for d in (
+ await db.execute(select(Document).where(Document.id.in_([r["doc_id"] for r in rows])))
+ ).scalars().all()
+ }
+ hits = [
+ SearchHit(
+ doc_id=row["doc_id"],
+ title=docs[row["doc_id"]].title,
+ kind=docs[row["doc_id"]].kind,
+ snippet=row["snippet"] or "",
+ device_id=docs[row["doc_id"]].device_id,
+ )
+ for row in rows
+ if row["doc_id"] in docs
+ ]
+ return SearchResponse(engine=engine, hits=hits)
+
+
[email protected]("/blocks", response_model=dict)
+async def generated_block(
+ block: str = Query(..., description=f"One of {sorted(BLOCKS)}"),
+ device_id: str = Query(..., description="Device to read the facts from"),
+ db: AsyncSession = Depends(get_db),
+ _: str = Depends(get_current_user),
+) -> dict[str, str]:
+ """Render one generated section, for the editor's `/` insert menu.
+
+ This is the counterpart to generating the header only once: the user can
+ always pull a fresh block in, but nothing pushes one at them.
+ """
+ if block not in BLOCKS:
+ raise HTTPException(400, f"block must be one of {sorted(BLOCKS)}")
+ device = await db.get(InventoryDevice, device_id)
+ if not device:
+ raise HTTPException(404, "Device not found")
+ context = await _device_context(db, device_id) if block in {"rack", "network"} else {}
+ return {"block": block, "markdown": render_block(block, device, **context)}
+
+
[email protected]("/{document_id}", response_model=DocumentResponse)
+async def get_document(
+ document_id: str,
+ db: AsyncSession = Depends(get_db),
+ _: str = Depends(get_current_user),
+) -> DocumentResponse:
+ doc = await db.get(Document, document_id)
+ if not doc:
+ raise HTTPException(404, "Document not found")
+ return DocumentResponse.model_validate(doc)
+
+
[email protected]("/{document_id}/revisions", response_model=list[RevisionSummary])
+async def list_revisions(
+ document_id: str,
+ db: AsyncSession = Depends(get_db),
+ _: str = Depends(get_current_user),
+) -> list[RevisionSummary]:
+ doc = await db.get(Document, document_id)
+ if not doc:
+ raise HTTPException(404, "Document not found")
+ revisions = (
+ await db.execute(
+ select(DocumentRevision)
+ .where(DocumentRevision.document_id == document_id)
+ .order_by(DocumentRevision.saved_at.desc(), DocumentRevision.id.desc())
+ )
+ ).scalars().all()
+ return [
+ RevisionSummary(
+ id=r.id,
+ document_id=r.document_id,
+ title=r.title,
+ reason=r.reason,
+ saved_at=r.saved_at,
+ size=len(r.body or ""),
+ )
+ for r in revisions
+ ]
+
+
[email protected]("/revisions/{revision_id}", response_model=RevisionResponse)
+async def get_revision(
+ revision_id: str,
+ db: AsyncSession = Depends(get_db),
+ _: str = Depends(get_current_user),
+) -> RevisionResponse:
+ revision = await db.get(DocumentRevision, revision_id)
+ if not revision:
+ raise HTTPException(404, "Revision not found")
+ return RevisionResponse(
+ id=revision.id,
+ document_id=revision.document_id,
+ title=revision.title,
+ reason=revision.reason,
+ saved_at=revision.saved_at,
+ size=len(revision.body or ""),
+ body=revision.body or "",
+ )
+
+
+# ── write ───────────────────────────────────────────────────────────────────
+
+
[email protected]("", response_model=DocumentResponse, status_code=201)
+async def create_document(
+ body: DocumentCreate,
+ db: AsyncSession = Depends(get_db),
+ _: str = Depends(get_current_user),
+) -> DocumentResponse:
+ links = [body.device_id, body.node_id, body.design_id]
+ if sum(1 for link in links if link) > 1:
+ raise HTTPException(400, "A document describes at most one device, node or design")
+ if body.kind in TREE_KINDS and any(links):
+ raise HTTPException(400, "A page or folder cannot also describe a device, node or design")
+ if body.kind not in TREE_KINDS and not any(links):
+ raise HTTPException(400, f"A '{body.kind}' document must name what it describes")
+ if body.parent_id and body.kind not in TREE_KINDS:
+ raise HTTPException(400, "Only pages and folders live in the Library tree")
+
+ for link, model, what in (
+ (body.device_id, InventoryDevice, "Device"),
+ (body.node_id, Node, "Node"),
+ ):
+ if link and not await db.get(model, link):
+ raise HTTPException(404, f"{what} not found")
+ if body.parent_id and not await db.get(Document, body.parent_id):
+ raise HTTPException(404, "Parent folder not found")
+
+ for column, value in (
+ (Document.device_id, body.device_id),
+ (Document.node_id, body.node_id),
+ (Document.design_id, body.design_id),
+ ):
+ if value and (await db.execute(select(Document).where(column == value))).scalars().first():
+ raise HTTPException(409, "That already has a document")
+
+ doc = Document(
+ kind=body.kind,
+ title=body.title,
+ slug=await unique_slug(db, body.title, parent_id=body.parent_id),
+ icon=body.icon,
+ parent_id=body.parent_id,
+ device_id=body.device_id,
+ node_id=body.node_id,
+ design_id=body.design_id,
+ )
+ if body.body is not None:
+ _apply_body(doc, body.body)
+ doc.template_id = body.template_id
+ else:
+ await _scaffold_body(db, doc, body.template_id)
+
+ db.add(doc)
+ await db.flush()
+ await doc_search.index_document(db, doc)
+ await db.commit()
+ await db.refresh(doc)
+ return DocumentResponse.model_validate(doc)
+
+
[email protected]("/{document_id}", response_model=DocumentResponse)
+async def update_document(
+ document_id: str,
+ body: DocumentUpdate,
+ db: AsyncSession = Depends(get_db),
+ _: str = Depends(get_current_user),
+) -> DocumentResponse:
+ doc = await db.get(Document, document_id)
+ if not doc:
+ raise HTTPException(404, "Document not found")
+ sent = body.model_dump(exclude_unset=True)
+
+ if "parent_id" in sent:
+ parent_id = sent["parent_id"]
+ if doc.kind not in TREE_KINDS:
+ raise HTTPException(400, "Only pages and folders live in the Library tree")
+ if parent_id:
+ parent = await db.get(Document, parent_id)
+ if not parent:
+ raise HTTPException(404, "Parent folder not found")
+ if parent.kind != "folder":
+ raise HTTPException(400, "A document can only be filed under a folder")
+ if await is_ancestor(db, document_id, parent_id):
+ raise HTTPException(400, "A folder cannot be moved inside itself")
+ doc.parent_id = parent_id
+ doc.slug = await unique_slug(db, doc.title, parent_id=parent_id, exclude_id=doc.id)
+
+ if "body" in sent and sent["body"] is not None and sent["body"] != doc.body:
+ await _record_revision(db, doc, "edit")
+ _apply_body(doc, sent["body"])
+ doc.edited_at = _now()
+
+ if "title" in sent and sent["title"]:
+ doc.title = sent["title"]
+ doc.slug = await unique_slug(db, doc.title, parent_id=doc.parent_id, exclude_id=doc.id)
+ if "icon" in sent:
+ doc.icon = sent["icon"]
+ if "sort_order" in sent and sent["sort_order"] is not None:
+ doc.sort_order = sent["sort_order"]
+ if "starred" in sent and sent["starred"] is not None:
+ doc.starred = sent["starred"]
+ if sent.get("reviewed"):
+ doc.reviewed_at = _now()
+ if sent.get("resync_facts") and doc.device_id:
+ device = await db.get(InventoryDevice, doc.device_id)
+ if device is not None:
+ doc.facts_snapshot = facts_snapshot(device)
+ doc.facts_synced_at = _now()
+
+ await db.flush()
+ await doc_search.index_document(db, doc)
+ await db.commit()
+ await db.refresh(doc)
+ return DocumentResponse.model_validate(doc)
+
+
[email protected]("/{document_id}/revisions/{revision_id}/restore", response_model=DocumentResponse)
+async def restore_revision(
+ document_id: str,
+ revision_id: str,
+ db: AsyncSession = Depends(get_db),
+ _: str = Depends(get_current_user),
+) -> DocumentResponse:
+ doc = await db.get(Document, document_id)
+ if not doc:
+ raise HTTPException(404, "Document not found")
+ revision = await db.get(DocumentRevision, revision_id)
+ if not revision or revision.document_id != document_id:
+ raise HTTPException(404, "Revision not found")
+ # The body being replaced becomes history too, so a restore is undoable.
+ await _record_revision(db, doc, "restore")
+ _apply_body(doc, revision.body or "")
+ await db.flush()
+ await doc_search.index_document(db, doc)
+ await db.commit()
+ await db.refresh(doc)
+ return DocumentResponse.model_validate(doc)
+
+
[email protected]("/scaffold", response_model=ScaffoldResponse)
+async def scaffold_documents(
+ body: ScaffoldRequest,
+ db: AsyncSession = Depends(get_db),
+ _: str = Depends(get_current_user),
+) -> ScaffoldResponse:
+ """Create the device documents that do not exist yet.
+
+ This is the migration off `device_inventory.notes`: the old text is appended
+ verbatim under `## Notes` and the column is left untouched, so nothing is
+ lost and the move is repeatable.
+ """
+ query = select(InventoryDevice).where(InventoryDevice.status != "hidden")
+ if body.device_ids:
+ query = query.where(InventoryDevice.id.in_(body.device_ids))
+ devices = (await db.execute(query.order_by(InventoryDevice.discovered_at))).scalars().all()
+ existing = {
+ doc_id
+ for doc_id in (
+ await db.execute(select(Document.device_id).where(Document.device_id.is_not(None)))
+ ).scalars().all()
+ }
+
+ created: list[Document] = []
+ skipped = 0
+ for device in devices:
+ if device.id in existing:
+ skipped += 1
+ continue
+ if body.only_with_notes and not (device.notes or "").strip():
+ skipped += 1
+ continue
+ context = await _device_context(db, device.id)
+ doc = Document(
+ kind="device",
+ title=device.label or device.friendly_name or device.hostname or device.ip or "device",
+ slug="",
+ device_id=device.id,
+ template_id=TEMPLATE_DEVICE,
+ facts_snapshot=facts_snapshot(device),
+ facts_synced_at=_now(),
+ )
+ doc.slug = await unique_slug(db, doc.title, parent_id=None)
+ _apply_body(doc, render_device_document(device, **context))
+ db.add(doc)
+ await db.flush()
+ db.add(
+ DocumentRevision(
+ document_id=doc.id,
+ title=doc.title,
+ body=doc.body,
+ reason="migrate" if (device.notes or "").strip() else "scaffold",
+ )
+ )
+ await doc_search.index_document(db, doc)
+ created.append(doc)
+
+ await db.commit()
+ for doc in created:
+ await db.refresh(doc)
+ return ScaffoldResponse(created=[DocumentSummary.model_validate(d) for d in created], skipped=skipped)
+
+
[email protected]("/{document_id}", status_code=204)
+async def delete_document(
+ document_id: str,
+ db: AsyncSession = Depends(get_db),
+ _: str = Depends(get_current_user),
+) -> None:
+ doc = await db.get(Document, document_id)
+ if not doc:
+ raise HTTPException(404, "Document not found")
+ # SQLite does not always enforce the ON DELETE CASCADE, so walk the subtree
+ # by hand — a folder takes its children with it.
+ for doc_id in reversed(await subtree_ids(db, document_id)):
+ target = await db.get(Document, doc_id)
+ if target is None:
+ continue
+ for revision in (
+ await db.execute(select(DocumentRevision).where(DocumentRevision.document_id == doc_id))
+ ).scalars().all():
+ await db.delete(revision)
+ await doc_search.unindex_document(db, doc_id)
+ await db.delete(target)
+ await db.commit()
diff --git a/backend/app/api/routes/nodes.py b/backend/app/api/routes/nodes.py
index 2d5385b..4442c6c 100644
--- a/backend/app/api/routes/nodes.py
+++ b/backend/app/api/routes/nodes.py
@@ -8,6 +8,7 @@ from app.api.deps import get_current_user
from app.db.database import get_db
from app.db.models import Design, InventoryDevice, Node
from app.schemas.nodes import NodeCreate, NodeResponse, NodeUpdate
+from app.services.doc_links import unlink_documents
from app.services.inventory_sync import (
facts_from_payload,
facts_from_update,
@@ -178,5 +179,7 @@ async def delete_node(node_id: str, db: AsyncSession = Depends(get_db), _: str =
node = await db.get(Node, node_id)
if not node:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Node not found")
+ # Foreign keys are off, so the schema's ON DELETE SET NULL does not fire.
+ await unlink_documents(db, node_ids=[node_id])
await db.delete(node)
await db.commit()
diff --git a/backend/app/api/routes/scan.py b/backend/app/api/routes/scan.py
index a271d93..4bc4472 100644
--- a/backend/app/api/routes/scan.py
+++ b/backend/app/api/routes/scan.py
@@ -29,6 +29,7 @@ from app.schemas.scan import (
ScanRunResponse,
)
from app.services.discovery_sources import add_source
+from app.services.doc_links import unlink_documents
from app.services.inventory_sync import find_device_for, merge_properties, merge_services
from app.services.mac_utils import normalize_mac
from app.services.node_dedupe import dedupe_nodes_by_device, find_duplicate_node
@@ -532,6 +533,10 @@ async def clear_pending(
_: str = Depends(get_current_user),
) -> dict[str, int]:
from sqlalchemy import delete as sa_delete
+ pending_ids = (
+ await db.execute(select(InventoryDevice.id).where(InventoryDevice.status == "pending"))
+ ).scalars().all()
+ await unlink_documents(db, device_ids=list(pending_ids))
result = await db.execute(sa_delete(InventoryDevice).where(InventoryDevice.status == "pending"))
await db.commit()
return {"deleted": result.rowcount}
@@ -563,6 +568,7 @@ async def delete_pending(
if mounted:
raise HTTPException(status_code=409, detail="Device is mounted in a rack")
+ await unlink_documents(db, device_ids=[device.id])
await db.delete(device)
await db.commit()
return {"deleted": True}
@@ -1074,6 +1080,7 @@ async def ignore_device(
device = await db.get(InventoryDevice, device_id)
if not device:
raise HTTPException(status_code=404, detail="Device not found")
+ await unlink_documents(db, device_ids=[device.id])
await db.delete(device)
await db.commit()
return {"ignored": True}
diff --git a/backend/app/db/database.py b/backend/app/db/database.py
index 02e14ac..443dd67 100644
--- a/backend/app/db/database.py
+++ b/backend/app/db/database.py
@@ -17,6 +17,34 @@ from app.core.config import APP_VERSION, settings
logger = logging.getLogger(__name__)
+# DDL for the documents feature that `Base.metadata.create_all` cannot express:
+# a virtual table, and partial indexes. Shared with the test fixtures so the
+# suite runs against the same schema production boots with.
+DOCUMENT_DDL: tuple[tuple[str, str], ...] = (
+ (
+ "documents_fts.table",
+ "CREATE VIRTUAL TABLE IF NOT EXISTS documents_fts USING fts5("
+ "doc_id UNINDEXED, title, tags, body, "
+ "tokenize = 'unicode61 remove_diacritics 2')",
+ ),
+ (
+ "documents.device_id.unique",
+ "CREATE UNIQUE INDEX IF NOT EXISTS ux_documents_device "
+ "ON documents(device_id) WHERE device_id IS NOT NULL",
+ ),
+ (
+ "documents.node_id.unique",
+ "CREATE UNIQUE INDEX IF NOT EXISTS ux_documents_node "
+ "ON documents(node_id) WHERE node_id IS NOT NULL",
+ ),
+ (
+ "documents.design_id.unique",
+ "CREATE UNIQUE INDEX IF NOT EXISTS ux_documents_design "
+ "ON documents(design_id) WHERE design_id IS NOT NULL",
+ ),
+)
+
+
async def _try_migrate(conn: AsyncConnection, sql: str, *, label: str) -> None:
"""Run an idempotent migration statement, logging any error.
@@ -524,11 +552,18 @@ async def init_db() -> None:
):
await _try_migrate(conn, sql, label=label)
+ # Documents. The two tables come from create_all; only what create_all
+ # cannot express lives here — the FTS5 index and the partial uniques
+ # that keep one document per device / node / design.
+ for label, sql in DOCUMENT_DDL:
+ await _try_migrate(conn, sql, label=label)
+
await _backfill_node_devices()
await _drop_legacy_node_columns()
await _seed_node_views()
await _backfill_zone_size()
await _repair_self_parent_nodes()
+ await _reindex_documents_fts()
@@ -888,6 +923,47 @@ async def _repair_self_parent_nodes() -> None:
logger.warning("Repairing self-parented nodes failed: %s", exc)
+async def _reindex_documents_fts() -> None:
+ """Rebuild the document search index from the documents table.
+
+ The index is maintained on every write, so this only has to catch up the
+ rows a write path could not have seen: the first boot after the feature
+ lands, a restored backup, or a hand-edited database. Cheap enough to run on
+ every boot — it does nothing once the counts already match.
+
+ Never fatal: SQLite may be built without FTS5, in which case the search
+ endpoint falls back to LIKE and this is a no-op.
+ """
+ try:
+ async with engine.begin() as conn:
+ indexed = (await conn.exec_driver_sql("SELECT COUNT(*) FROM documents_fts")).scalar_one()
+ total = (await conn.exec_driver_sql("SELECT COUNT(*) FROM documents")).scalar_one()
+ if indexed == total:
+ return
+ await conn.exec_driver_sql("DELETE FROM documents_fts")
+ rows = (
+ await conn.exec_driver_sql("SELECT id, title, tags, body FROM documents")
+ ).fetchall()
+ for doc_id, title, tags, body in rows:
+ await conn.exec_driver_sql(
+ "INSERT INTO documents_fts (doc_id, title, tags, body) VALUES (?, ?, ?, ?)",
+ (doc_id, title or "", _tags_text(tags), body or ""),
+ )
+ logger.info("Reindexed %d document(s) for search", len(rows))
+ except Exception as exc: # pragma: no cover - defensive, boot must not die
+ logger.debug("Document search index not rebuilt: %s", exc)
+
+
+def _tags_text(raw: Any) -> str:
+ """Flatten a document's JSON tag list into a single indexable string."""
+ if isinstance(raw, str):
+ with suppress(ValueError):
+ raw = _json.loads(raw)
+ if isinstance(raw, list):
+ return " ".join(str(tag) for tag in raw)
+ return ""
+
+
async def get_db() -> AsyncGenerator[AsyncSession, None]:
async with AsyncSessionLocal() as session:
yield session
diff --git a/backend/app/db/models.py b/backend/app/db/models.py
index d45d14c..611f23f 100644
--- a/backend/app/db/models.py
+++ b/backend/app/db/models.py
@@ -324,3 +324,88 @@ class ScanRun(Base):
started_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now)
finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
error: Mapped[str | None] = mapped_column(Text)
+
+
+class Document(Base):
+ """One markdown document.
+
+ A document either stands alone in the Library tree (`kind` page/folder,
+ placed by `parent_id`) or describes exactly one thing on the other side of
+ an optional link: a Device Inventory row (`device_id`), a piece of canvas
+ furniture such as a zone or a group (`node_id`), or a whole canvas
+ (`design_id`). Only one of the three is ever set, and each is enforced
+ unique by a partial index created in `database.init_db`.
+
+ Every link is `SET NULL` and `title` is denormalized, so deleting a device
+ or a canvas never destroys what the user wrote — the document survives as
+ an orphan and can be re-linked or filed away.
+
+ `body` is the whole markdown file, YAML frontmatter included, so a document
+ exports to disk as-is. `frontmatter` and `tags` are a parsed cache of that
+ block, kept only so listings can filter without reading every body.
+ """
+
+ __tablename__ = "documents"
+
+ id: Mapped[str] = mapped_column(String, primary_key=True, default=_uuid)
+ kind: Mapped[str] = mapped_column(String, nullable=False, default="page")
+ title: Mapped[str] = mapped_column(String, nullable=False)
+ slug: Mapped[str] = mapped_column(String, nullable=False, index=True)
+ icon: Mapped[str | None] = mapped_column(String, nullable=True)
+
+ # Library tree. Folders are documents too, so an empty folder is possible
+ # and a folder can carry an index body. Only page/folder set this.
+ parent_id: Mapped[str | None] = mapped_column(
+ String, ForeignKey("documents.id", ondelete="CASCADE"), nullable=True, index=True
+ )
+ sort_order: Mapped[int] = mapped_column(Integer, default=0)
+
+ device_id: Mapped[str | None] = mapped_column(
+ String, ForeignKey("device_inventory.id", ondelete="SET NULL"), nullable=True, index=True
+ )
+ node_id: Mapped[str | None] = mapped_column(
+ String, ForeignKey("nodes.id", ondelete="SET NULL"), nullable=True, index=True
+ )
+ design_id: Mapped[str | None] = mapped_column(
+ String, ForeignKey("designs.id", ondelete="SET NULL"), nullable=True, index=True
+ )
+
+ body: Mapped[str] = mapped_column(Text, nullable=False, default="")
+ frontmatter: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict)
+ tags: Mapped[list[str]] = mapped_column(JSON, default=list)
+ starred: Mapped[bool] = mapped_column(Boolean, default=False)
+ template_id: Mapped[str | None] = mapped_column(String, nullable=True)
+
+ # The device facts as they read when this document was scaffolded or last
+ # reconciled. The header is generated once and then owned by the user, so
+ # this is what tells the UI the document has drifted from the device.
+ facts_snapshot: Mapped[dict[str, Any] | None] = mapped_column(JSON, nullable=True)
+ facts_synced_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
+ reviewed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
+ # Set the first time the body is edited by hand. NULL means the document is
+ # still only what the template generated — which is what the coverage view
+ # counts as "not really documented yet". A timestamp comparison cannot say
+ # this: created_at and updated_at are two separate clock reads on insert.
+ edited_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
+
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now)
+ updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now, onupdate=_now)
+
+
+class DocumentRevision(Base):
+ """A prior version of a document's body.
+
+ Written on every explicit save that actually changed the body, and pruned
+ to the most recent `REVISION_LIMIT` per document in the same transaction.
+ """
+
+ __tablename__ = "document_revisions"
+
+ id: Mapped[str] = mapped_column(String, primary_key=True, default=_uuid)
+ document_id: Mapped[str] = mapped_column(
+ String, ForeignKey("documents.id", ondelete="CASCADE"), nullable=False, index=True
+ )
+ title: Mapped[str] = mapped_column(String, nullable=False)
+ body: Mapped[str] = mapped_column(Text, nullable=False, default="")
+ reason: Mapped[str] = mapped_column(String, nullable=False, default="edit")
+ saved_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now)
diff --git a/backend/app/main.py b/backend/app/main.py
index addc14c..fe4b5b3 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -12,6 +12,7 @@ from app.api.routes import (
auth,
canvas,
designs,
+ documents,
edges,
liveview,
media,
@@ -93,6 +94,7 @@ app.include_router(zwave.router, prefix="/api/v1/zwave", tags=["zwave"])
app.include_router(proxmox.router, prefix="/api/v1/proxmox", tags=["proxmox"])
app.include_router(stats.router, prefix="/api/v1/stats", tags=["stats"])
app.include_router(media.router, prefix="/api/v1/media", tags=["media"])
+app.include_router(documents.router, prefix="/api/v1/documents", tags=["documents"])
@app.get("/api/v1/health")
diff --git a/backend/app/schemas/documents.py b/backend/app/schemas/documents.py
new file mode 100644
index 0000000..1b4dd6e
--- /dev/null
+++ b/backend/app/schemas/documents.py
@@ -0,0 +1,157 @@
+from datetime import datetime
+from typing import Any
+
+from pydantic import BaseModel, field_validator
+
+from app.services.doc_template import TEMPLATE_IDS
+from app.services.doc_tree import DOCUMENT_KINDS
+
+# Kept in sync with DocKind in frontend/src/documentation/types.ts.
+# "page" and "folder" live in the Library tree and carry a parent; "device",
+# "node" and "design" each point at exactly one thing elsewhere in the app and
+# are placed by that link instead, so the frontend can pivot them however the
+# user asks (by zone, subnet, type…) without the server storing a tree.
+DOC_KINDS = set(DOCUMENT_KINDS)
+
+
+class DocumentCreate(BaseModel):
+ kind: str = "page"
+ title: str
+ icon: str | None = None
+ parent_id: str | None = None
+ device_id: str | None = None
+ node_id: str | None = None
+ design_id: str | None = None
+ # Scaffolds the body when no body is supplied. "device" is implied for a
+ # device document and is the only template that reads the live facts.
+ template_id: str | None = None
+ body: str | None = None
+
+ @field_validator("kind")
+ @classmethod
+ def _known_kind(cls, v: str) -> str:
+ if v not in DOC_KINDS:
+ raise ValueError(f"kind must be one of {sorted(DOC_KINDS)}")
+ return v
+
+ @field_validator("template_id")
+ @classmethod
+ def _known_template(cls, v: str | None) -> str | None:
+ if v is not None and v not in TEMPLATE_IDS:
+ raise ValueError(f"template_id must be one of {sorted(TEMPLATE_IDS)}")
+ return v
+
+
+class DocumentUpdate(BaseModel):
+ title: str | None = None
+ icon: str | None = None
+ body: str | None = None
+ parent_id: str | None = None
+ sort_order: int | None = None
+ starred: bool | None = None
+ # Explicit: "I have re-read this and it is still true." Sent as a bare true
+ # rather than a timestamp so the server owns the clock.
+ reviewed: bool | None = None
+ # Accept the device's current facts as documented, clearing the drift
+ # banner without touching the body.
+ resync_facts: bool | None = None
+
+
+class DocumentSummary(BaseModel):
+ """Everything the tree needs. Never carries a body — listings stay small."""
+
+ id: str
+ kind: str
+ title: str
+ slug: str
+ icon: str | None = None
+ parent_id: str | None = None
+ sort_order: int = 0
+ device_id: str | None = None
+ node_id: str | None = None
+ design_id: str | None = None
+ tags: list[str] = []
+ # The parsed frontmatter travels with the summary so the tree can badge a
+ # document as due for review without fetching every body.
+ frontmatter: dict[str, Any] = {}
+ starred: bool = False
+ template_id: str | None = None
+ reviewed_at: datetime | None = None
+ edited_at: datetime | None = None
+ facts_synced_at: datetime | None = None
+ created_at: datetime
+ updated_at: datetime
+
+ model_config = {"from_attributes": True}
+
+
+class DocumentResponse(DocumentSummary):
+ body: str = ""
+ facts_snapshot: dict[str, Any] | None = None
+
+
+class RevisionSummary(BaseModel):
+ id: str
+ document_id: str
+ title: str
+ reason: str
+ saved_at: datetime
+ # Character count, so the history list can show how much changed without
+ # shipping every body.
+ size: int = 0
+
+ model_config = {"from_attributes": True}
+
+
+class RevisionResponse(RevisionSummary):
+ body: str = ""
+
+
+class SearchHit(BaseModel):
+ doc_id: str
+ title: str
+ kind: str
+ snippet: str
+ device_id: str | None = None
+
+
+class SearchResponse(BaseModel):
+ # "fts5" or "like" — the UI drops snippet highlighting on the fallback.
+ engine: str
+ hits: list[SearchHit]
+
+
+class ScaffoldRequest(BaseModel):
+ """Create the missing device documents.
+
+ Omitting `device_ids` means every approved device that has none, which is
+ the one-click migration off the old notes field.
+ """
+
+ device_ids: list[str] | None = None
+ template_id: str = "device"
+ # Only devices whose notes are not empty. What the migration banner sends.
+ only_with_notes: bool = False
+
+
+class ScaffoldResponse(BaseModel):
+ created: list[DocumentSummary]
+ skipped: int
+
+
+class DriftField(BaseModel):
+ field: str
+ documented: Any = None
+ current: Any = None
+
+
+class CoverageResponse(BaseModel):
+ devices: int
+ documented: int
+ # A document whose body is still only what the template generated.
+ header_only: int
+ missing: int
+ drifted: int
+ overdue: int
+ notes_unmigrated: int
+ library_pages: int
diff --git a/backend/app/services/doc_links.py b/backend/app/services/doc_links.py
new file mode 100644
index 0000000..0fbf2ca
--- /dev/null
+++ b/backend/app/services/doc_links.py
@@ -0,0 +1,40 @@
+"""Clear document links when the thing a document describes is deleted.
+
+The schema declares `ON DELETE SET NULL` on `documents.device_id`, `node_id` and
+`design_id`, but SQLite runs here with foreign keys off (see
+`api/routes/scan.py::delete_pending`), so nothing enforces it. Without this the
+column would keep naming a row that no longer exists and the document would look
+linked while resolving to nothing.
+
+Clearing rather than deleting is deliberate: the inventory outlives the canvas,
+and what the user wrote outlives both. The document survives as an orphan,
+keeping its denormalized `title`, and can be re-linked or filed into the Library.
+"""
+
+from collections.abc import Sequence
+
+from sqlalchemy import update
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.db.models import Document
+
+
+async def unlink_documents(
+ db: AsyncSession,
+ *,
+ device_ids: Sequence[str] | None = None,
+ node_ids: Sequence[str] | None = None,
+ design_ids: Sequence[str] | None = None,
+) -> None:
+ """Orphan every document pointing at any of the given rows.
+
+ Caller commits — this is meant to run inside the same transaction as the
+ delete it accompanies.
+ """
+ for column, ids in (
+ (Document.device_id, device_ids),
+ (Document.node_id, node_ids),
+ (Document.design_id, design_ids),
+ ):
+ if ids:
+ await db.execute(update(Document).where(column.in_(list(ids))).values({column: None}))
diff --git a/backend/app/services/doc_search.py b/backend/app/services/doc_search.py
new file mode 100644
index 0000000..24ec397
--- /dev/null
+++ b/backend/app/services/doc_search.py
@@ -0,0 +1,132 @@
+"""Full-text search over documents.
+
+SQLite's FTS5 module is not guaranteed: the LXC and Docker images ship whatever
+SQLite the base distribution built, and `database.py` already avoids depending
+on JSON1 for the same reason. So the index is best-effort — every write keeps it
+up to date when it exists, and `search` falls back to LIKE when it does not. The
+endpoint reports which engine answered so the UI can drop snippet highlighting.
+
+The index is maintained from Python rather than by triggers: the write paths are
+few, they are already inside a transaction, and a trigger would have to be kept
+in sync through `_try_migrate` forever.
+"""
+
+import logging
+from typing import Any
+
+from sqlalchemy import text
+from sqlalchemy.exc import OperationalError
+from sqlalchemy.ext.asyncio import AsyncSession
+
+logger = logging.getLogger(__name__)
+
+# Column positions inside documents_fts, for snippet().
+_BODY_COLUMN = 3
+
+_available: bool | None = None
+
+
+def reset_availability_cache() -> None:
+ """Forget the probed FTS5 state. Tests swap databases between cases."""
+ global _available
+ _available = None
+
+
+async def fts_available(db: AsyncSession) -> bool:
+ """Whether this SQLite build has FTS5 and the index table exists."""
+ global _available
+ if _available is None:
+ try:
+ await db.execute(text("SELECT doc_id FROM documents_fts LIMIT 1"))
+ _available = True
+ except OperationalError:
+ _available = False
+ logger.info("FTS5 unavailable — document search falls back to LIKE")
+ return _available
+
+
+def tags_text(tags: Any) -> str:
+ """Flatten a tag list into one indexable string."""
+ if isinstance(tags, list):
+ return " ".join(str(tag) for tag in tags)
+ return ""
+
+
+async def index_document(db: AsyncSession, doc: Any) -> None:
+ """Re-index one document. Safe to call when FTS5 is missing."""
+ if not await fts_available(db):
+ return
+ await unindex_document(db, doc.id)
+ await db.execute(
+ text("INSERT INTO documents_fts (doc_id, title, tags, body) VALUES (:i, :t, :g, :b)"),
+ {"i": doc.id, "t": doc.title or "", "g": tags_text(doc.tags), "b": doc.body or ""},
+ )
+
+
+async def unindex_document(db: AsyncSession, doc_id: str) -> None:
+ if not await fts_available(db):
+ return
+ await db.execute(text("DELETE FROM documents_fts WHERE doc_id = :i"), {"i": doc_id})
+
+
+def build_match_query(raw: str) -> str:
+ """Turn user input into an FTS5 MATCH expression.
+
+ Every term is quoted, so punctuation a user types (`192.168.1.1`, `nas-01`,
+ an unbalanced quote) is data rather than FTS5 syntax, and gets a prefix `*`
+ so typing half a word still matches.
+ """
+ terms = [term.replace('"', '""') for term in raw.split() if term.strip()]
+ return " AND ".join(f'"{term}"*' for term in terms)
+
+
+async def search(db: AsyncSession, query: str, limit: int = 25) -> tuple[str, list[dict[str, Any]]]:
+ """Return `(engine, hits)`; engine is "fts5" or "like"."""
+ query = query.strip()
+ if not query:
+ return ("fts5" if await fts_available(db) else "like", [])
+
+ if await fts_available(db):
+ match = build_match_query(query)
+ if not match:
+ return ("fts5", [])
+ try:
+ rows = (
+ await db.execute(
+ text(
+ "SELECT doc_id, "
+ f"snippet(documents_fts, {_BODY_COLUMN}, '<<', '>>', '…', 14) AS snip, "
+ "rank AS score "
+ "FROM documents_fts WHERE documents_fts MATCH :q "
+ "ORDER BY rank LIMIT :n"
+ ),
+ {"q": match, "n": limit},
+ )
+ ).fetchall()
+ return ("fts5", [{"doc_id": r[0], "snippet": r[1], "score": r[2]} for r in rows])
+ except OperationalError as exc:
+ # A malformed MATCH must degrade, never 500.
+ logger.debug("FTS query failed, falling back to LIKE: %s", exc)
+
+ like = f"%{query.lower()}%"
+ rows = (
+ await db.execute(
+ text(
+ "SELECT id, body FROM documents "
+ "WHERE lower(title) LIKE :q OR lower(body) LIKE :q "
+ "ORDER BY updated_at DESC LIMIT :n"
+ ),
+ {"q": like, "n": limit},
+ )
+ ).fetchall()
+ return ("like", [{"doc_id": r[0], "snippet": _excerpt(r[1] or "", query), "score": None} for r in rows])
+
+
+def _excerpt(body: str, query: str, width: int = 120) -> str:
+ """A LIKE-mode stand-in for snippet(): the text around the first match."""
+ at = body.lower().find(query.lower())
+ if at < 0:
+ return body[:width].strip()
+ start = max(0, at - width // 2)
+ end = min(len(body), at + len(query) + width // 2)
+ return ("…" if start else "") + body[start:end].strip() + ("…" if end < len(body) else "")
diff --git a/backend/app/services/doc_template.py b/backend/app/services/doc_template.py
new file mode 100644
index 0000000..7513f4c
--- /dev/null
+++ b/backend/app/services/doc_template.py
@@ -0,0 +1,489 @@
+"""Markdown scaffolding for documents.
+
+The header of a device document is generated **once**, when the document is
+created or migrated from the old `notes` field, and from then on it belongs to
+the user — nothing here ever rewrites a body that already exists. What keeps the
+document honest instead is `facts_snapshot`, which records the facts as they read
+at generation time so the UI can tell the user the device has moved on, and
+`render_block`, which lets them drop a freshly generated section back in from the
+editor's `/` menu whenever they want it.
+
+Every section is emitted even when its data is empty, with an italic prompt in
+place of the value. A blank section is the document telling the user what has not
+been written yet; omitting it would hide the gap.
+"""
+
+from collections.abc import Callable
+from datetime import date, datetime
+from typing import Any
+
+# Sections whose data is structural rather than descriptive: they are dropped
+# entirely rather than printed empty, because an unracked device has no rack
+# position to leave blank.
+_EMPTY = "—"
+_PROMPT = "_…_"
+
+TEMPLATE_DEVICE = "device"
+TEMPLATE_BLANK = "blank"
+TEMPLATE_RUNBOOK = "runbook"
+TEMPLATE_SERVICE = "service"
+TEMPLATE_NETWORK = "network"
+TEMPLATE_INCIDENT = "incident"
+TEMPLATE_PROCEDURE = "procedure"
+TEMPLATE_DECISION = "decision"
+TEMPLATE_ZONE = "zone"
+
+# Frontmatter carries a version from the first release: documents round-trip to
+# disk through export/import, so the on-disk shape is a compatibility surface.
+FRONTMATTER_VERSION = 1
+
+
+def cell(value: Any) -> str:
+ """Escape a value for a markdown table cell.
+
+ Mirrors `frontend/src/utils/exportMarkdown.ts`: backslash first, then pipe,
+ then collapse newlines so one field cannot break the row.
+ """
+ if value is None or value == "":
+ return _EMPTY
+ text = str(value).replace("\\", "\\\\").replace("|", "\\|")
+ return " ".join(text.split())
+
+
+def device_name(device: Any) -> str:
+ for attr in ("label", "friendly_name", "hostname", "ip"):
+ value = getattr(device, attr, None)
+ if value:
+ return str(value)
+ return "device"
+
+
+def device_type(device: Any) -> str | None:
+ return getattr(device, "type", None) or getattr(device, "suggested_type", None)
+
+
+def _fmt_date(value: Any) -> str:
+ if isinstance(value, datetime):
+ return value.date().isoformat()
+ if isinstance(value, date):
+ return value.isoformat()
+ return _EMPTY
+
+
+def _sources(device: Any) -> str:
+ sources = getattr(device, "discovery_sources", None) or []
+ if not sources:
+ single = getattr(device, "discovery_source", None)
+ sources = [single] if single else []
+ return ", ".join(str(s) for s in sources) if sources else _EMPTY
+
+
+def service_key(service: dict[str, Any]) -> str:
+ """The identity used everywhere else for a service: port|protocol|name."""
+ port = service.get("port")
+ protocol = service.get("protocol") or "tcp"
+ name = (service.get("service_name") or "").lower()
+ return f"{port if port is not None else ''}|{protocol}|{name}"
+
+
+# Ports that are definitely not HTTP. Mirrors NON_HTTP_PORTS in
+# `frontend/src/utils/serviceUrl.ts` — a service link printed in a document has
+# to be the same link the canvas offers, or the document is quietly wrong.
+_NON_HTTP_PORTS = frozenset(
+ {
+ 21, 23, 25, 53, 110, 143, 389, 445, 465, 514, 587, 636, 993, 995,
+ 1433, 3306, 5432, 5672, 6379, 9092, 11211, 27017, 27018,
+ }
+)
+
+
+def service_url(service: dict[str, Any], host: str | None) -> str | None:
+ """The browsable URL for a service, or None when there is not one.
+
+ Follows `getServiceUrl`: everything is HTTP unless the port says otherwise,
+ a host override wins over the device's address and hides the scanned port
+ (it usually names a reverse proxy), and UDP and SSH have no browser URL.
+ """
+ override = (service.get("host") or "").strip()
+ effective_host = override or host
+ if not effective_host or service.get("protocol") == "udp":
+ return None
+
+ scheme: str | None = None
+ hostname = effective_host.split(",")[0].strip()
+ for prefix in ("https://", "http://"):
+ if hostname.startswith(prefix):
+ scheme = prefix[:-3]
+ hostname = hostname[len(prefix):].rstrip("/")
+ break
+ if not hostname:
+ return None
+
+ port = service.get("port")
+ if port == 22 or (port is not None and port in _NON_HTTP_PORTS):
+ return None
+
+ name = (service.get("service_name") or "").lower()
+ if scheme is None:
+ secure = any(token in name for token in ("https", "ssl", "tls")) or port in (443, 8443)
+ scheme = "https" if secure else "http"
+
+ # A host override points at the public name; the scanned port is internal.
+ printed_port = "" if override else (f":{port}" if port is not None else "")
+ path = (service.get("path") or "").strip()
+ if path and not path.startswith("/"):
+ path = f"/{path}"
+ return f"{scheme}://{hostname}{printed_port}{path}"
+
+
+# ── generated blocks ────────────────────────────────────────────────────────
+
+
+def block_device_info(device: Any, **_: Any) -> str:
+ check = getattr(device, "check_method", None)
+ target = getattr(device, "check_target", None)
+ check_cell = f"`{check}` → `{target}`" if check and target else (f"`{check}`" if check else _EMPTY)
+ vendor = getattr(device, "vendor", None)
+ model = getattr(device, "model", None)
+ vendor_model = " / ".join(part for part in (vendor, model) if part) or _EMPTY
+ rows = [
+ ("Type", device_type(device)),
+ ("Vendor / Model", vendor_model),
+ ("Hostname", getattr(device, "hostname", None)),
+ ("IP", getattr(device, "ip", None)),
+ ("MAC", getattr(device, "mac", None)),
+ ("IEEE", getattr(device, "ieee_address", None)),
+ ("OS", getattr(device, "os", None)),
+ ("First discovered", f"{_fmt_date(getattr(device, 'discovered_at', None))} ({_sources(device)})"),
+ ("Status check", check_cell),
+ ]
+ lines = ["| | |", "|---|---|"]
+ lines += [f"| {label} | {cell(value)} |" for label, value in rows]
+ return "\n".join(lines)
+
+
+def block_hardware(device: Any, **_: Any) -> str:
+ cpu_model = getattr(device, "cpu_model", None)
+ cpu_count = getattr(device, "cpu_count", None)
+ if cpu_model and cpu_count:
+ cpu: Any = f"{cpu_model} ×{cpu_count}"
+ else:
+ cpu = cpu_model or (f"{cpu_count} cores" if cpu_count else None)
+ ram = getattr(device, "ram_gb", None)
+ disk = getattr(device, "disk_gb", None)
+ return "\n".join(
+ [
+ "| CPU | RAM | Disk |",
+ "|---|---|---|",
+ f"| {cell(cpu)} | {cell(f'{ram:g} GB' if ram else None)} | {cell(f'{disk:g} GB' if disk else None)} |",
+ ]
+ )
+
+
+def block_services(device: Any, **_: Any) -> str:
+ services = getattr(device, "services", None) or []
+ if not services:
+ return "_No service has been fingerprinted on this device yet._"
+ host = getattr(device, "ip", None) or getattr(device, "hostname", None)
+ sections: list[str] = []
+ for service in services:
+ if not isinstance(service, dict):
+ continue
+ name = service.get("service_name") or "Service"
+ port = service.get("port")
+ protocol = service.get("protocol") or "tcp"
+ heading = f"### {name}" + (f" — `{port}/{protocol}`" if port else "")
+ lines = [heading, ""]
+ url = service_url(service, host)
+ if url:
+ lines.append(f"- **URL** — <{url}>")
+ if service.get("category"):
+ lines.append(f"- **Category** — {service['category']}")
+ lines += [
+ f"- **Purpose** — {_PROMPT}",
+ f"- **Credentials** — {_PROMPT} _(where they are kept — never the secret itself)_",
+ f"- **Depends on** — {_PROMPT}",
+ ]
+ sections.append("\n".join(lines))
+ return "\n\n".join(sections)
+
+
+def block_properties(device: Any, **_: Any) -> str:
+ properties = getattr(device, "properties", None) or []
+ rows = [p for p in properties if isinstance(p, dict) and p.get("key")]
+ if not rows:
+ return ""
+ lines = ["| Key | Value |", "|---|---|"]
+ lines += [f"| {cell(p.get('key'))} | {cell(p.get('value'))} |" for p in rows]
+ return "\n".join(lines)
+
+
+def block_rack(device: Any, *, rack: dict[str, Any] | None = None, zone_label: str | None = None, **_: Any) -> str:
+ parts: list[str] = []
+ if rack and rack.get("name"):
+ u_start = rack.get("u_start")
+ u_height = rack.get("u_height") or 1
+ span = rack.get("col_span")
+ where = f"Rack **{rack['name']}**"
+ if u_start:
+ top = u_start + u_height - 1
+ where += f", U{u_start}" + (f"–U{top}" if top != u_start else "")
+ if span:
+ where += ", full width" if span >= 12 else f", {span}/12 wide"
+ parts.append(where + ".")
+ if zone_label:
+ parts.append(f"Zone **{zone_label}**.")
+ return " ".join(parts)
+
+
+def block_network(device: Any, *, connections: list[str] | None = None, **_: Any) -> str:
+ ip = getattr(device, "ip", None)
+ subnet = _guess_subnet(ip)
+ peers = ", ".join(f"`{peer}`" for peer in connections) if connections else _PROMPT
+ return "\n".join(
+ [
+ f"- **Subnet / VLAN** — {subnet or _PROMPT}",
+ f"- **Connected to** — {peers}",
+ f"- **DNS names** — {_PROMPT}",
+ f"- **Firewall / exposure** — {_PROMPT}",
+ f"- **Reverse proxy** — {_PROMPT}",
+ ]
+ )
+
+
+def _guess_subnet(ip: str | None) -> str | None:
+ """The /24 an IPv4 address sits in. Multi-IP fields keep the first token."""
+ if not ip:
+ return None
+ first = ip.split(",")[0].strip()
+ octets = first.split(".")
+ if len(octets) != 4 or not all(o.isdigit() for o in octets):
+ return None
+ return f"{octets[0]}.{octets[1]}.{octets[2]}.0/24"
+
+
+BLOCKS: dict[str, Callable[..., str]] = {
+ "device-info": block_device_info,
+ "hardware": block_hardware,
+ "services": block_services,
+ "properties": block_properties,
+ "rack": block_rack,
+ "network": block_network,
+}
+
+
+def render_block(name: str, device: Any, **context: Any) -> str:
+ render = BLOCKS.get(name)
+ if render is None:
+ raise ValueError(f"Unknown block: {name}")
+ return render(device, **context)
+
+
+# ── the device document ─────────────────────────────────────────────────────
+
+
+def facts_snapshot(device: Any) -> dict[str, Any]:
+ """The device facts a generated document depends on.
+
+ Compared against the live row to tell the user their document has drifted,
+ so it holds the fields the template actually prints and nothing else.
+ """
+ services = getattr(device, "services", None) or []
+ return {
+ "label": device_name(device),
+ "type": device_type(device),
+ "hostname": getattr(device, "hostname", None),
+ "ip": getattr(device, "ip", None),
+ "mac": getattr(device, "mac", None),
+ "ieee_address": getattr(device, "ieee_address", None),
+ "os": getattr(device, "os", None),
+ "vendor": getattr(device, "vendor", None),
+ "model": getattr(device, "model", None),
+ "cpu_count": getattr(device, "cpu_count", None),
+ "cpu_model": getattr(device, "cpu_model", None),
+ "ram_gb": getattr(device, "ram_gb", None),
+ "disk_gb": getattr(device, "disk_gb", None),
+ "check_method": getattr(device, "check_method", None),
+ "check_target": getattr(device, "check_target", None),
+ "services": sorted(service_key(s) for s in services if isinstance(s, dict)),
+ }
+
+
+def render_frontmatter(values: dict[str, Any]) -> str:
+ """A minimal YAML block.
+
+ Hand-rolled rather than `yaml.safe_dump` so key order is the order written
+ here — the frontmatter is read by humans at the top of every document.
+ """
+ lines = ["---"]
+ for key, value in values.items():
+ if value is None or value == "" or value == []:
+ continue
+ if isinstance(value, list):
+ lines.append(f"{key}: [{', '.join(str(v) for v in value)}]")
+ else:
+ lines.append(f"{key}: {value}")
+ lines.append("---")
+ return "\n".join(lines)
+
+
+def render_device_document(
+ device: Any,
+ *,
+ zone_label: str | None = None,
+ rack: dict[str, Any] | None = None,
+ connections: list[str] | None = None,
+ today: date | None = None,
+) -> str:
+ """The full skeleton for a device, old notes appended verbatim."""
+ today = today or date.today()
+ name = device_name(device)
+ notes = (getattr(device, "notes", None) or "").strip()
+
+ front = render_frontmatter(
+ {
+ "homelable": FRONTMATTER_VERSION,
+ "title": name,
+ "device": getattr(device, "id", None),
+ "type": device_type(device),
+ "tags": [],
+ "criticality": "medium",
+ "owner": "",
+ "review_every": "6m",
+ "created": today.isoformat(),
+ }
+ )
+
+ parts = [
+ front,
+ "",
+ f"# {name}",
+ "",
+ "> _One line: what this device is for. Replace this quote._",
+ "",
+ "## Device Information",
+ "",
+ block_device_info(device),
+ "",
+ "### Hardware",
+ "",
+ block_hardware(device),
+ "",
+ ]
+
+ location = block_rack(device, rack=rack, zone_label=zone_label)
+ if location:
+ parts += ["### Physical location", "", location, ""]
+
+ properties = block_properties(device)
+ if properties:
+ parts += ["### Properties", "", properties, ""]
+
+ parts += [
+ "## Services",
+ "",
+ block_services(device),
+ "",
+ "## Network",
+ "",
+ block_network(device, connections=connections),
+ "",
+ "## Configuration",
+ "",
+ "_How it is set up, where the config lives, what is not default, and what",
+ "would be needed to rebuild it from scratch._",
+ "",
+ "## Operations",
+ "",
+ "### Start / stop",
+ "",
+ _PROMPT,
+ "",
+ "### Backup",
+ "",
+ _PROMPT,
+ "",
+ "### Update procedure",
+ "",
+ _PROMPT,
+ "",
+ "### Monitoring and alerts",
+ "",
+ _PROMPT,
+ "",
+ "## Troubleshooting",
+ "",
+ "| Symptom | Likely cause | Fix |",
+ "|---|---|---|",
+ f"| {_PROMPT} | {_PROMPT} | {_PROMPT} |",
+ "",
+ "## Dependencies",
+ "",
+ f"- **Depends on** — {_PROMPT}",
+ f"- **Used by** — {_PROMPT}",
+ "",
+ "## Changelog",
+ "",
+ "| Date | Change |",
+ "|---|---|",
+ f"| {today.isoformat()} | Document created |",
+ "",
+ "## Notes",
+ "",
+ ]
+
+ if notes:
+ parts += [
+ f"<!-- Migrated verbatim from this device's Notes field on {today.isoformat()}. -->",
+ "",
+ notes,
+ "",
+ ]
+ else:
+ parts += ["_Anything worth remembering about this device._", ""]
+
+ return "\n".join(parts)
+
+
+# ── library templates ───────────────────────────────────────────────────────
+
+_LIBRARY_TEMPLATES: dict[str, tuple[str, list[str]]] = {
+ TEMPLATE_BLANK: ("", []),
+ TEMPLATE_RUNBOOK: (
+ "runbook",
+ ["Trigger", "Preconditions", "Steps", "Verification", "Rollback", "Escalation"],
+ ),
+ TEMPLATE_SERVICE: (
+ "service",
+ ["What it does", "Endpoints", "Components", "Configuration", "Backup", "Failure modes"],
+ ),
+ TEMPLATE_NETWORK: (
+ "network",
+ ["Topology", "Subnets and VLANs", "DHCP and DNS", "Routing", "Firewall zones", "Remote access"],
+ ),
+ TEMPLATE_INCIDENT: ("incident", ["Timeline", "Impact", "Root cause", "Fix", "What to change"]),
+ TEMPLATE_PROCEDURE: ("procedure", ["Goal", "Prerequisites", "Steps", "Verification"]),
+ TEMPLATE_DECISION: ("decision", ["Status", "Context", "Decision", "Consequences"]),
+ TEMPLATE_ZONE: ("zone", ["Purpose", "Members", "Addressing", "Access", "Notes"]),
+}
+
+TEMPLATE_IDS = frozenset({TEMPLATE_DEVICE, *_LIBRARY_TEMPLATES})
+
+
+def render_library_document(template_id: str, title: str, *, today: date | None = None) -> str:
+ """The skeleton for a page that is not about one device."""
+ today = today or date.today()
+ kind, headings = _LIBRARY_TEMPLATES.get(template_id, _LIBRARY_TEMPLATES[TEMPLATE_BLANK])
+ front = render_frontmatter(
+ {
+ "homelable": FRONTMATTER_VERSION,
+ "title": title,
+ "template": kind or None,
+ "tags": [],
+ "created": today.isoformat(),
+ }
+ )
+ parts = [front, "", f"# {title}", ""]
+ for heading in headings:
+ parts += [f"## {heading}", "", _PROMPT, ""]
+ return "\n".join(parts)
diff --git a/backend/app/services/doc_tree.py b/backend/app/services/doc_tree.py
new file mode 100644
index 0000000..138f5cf
--- /dev/null
+++ b/backend/app/services/doc_tree.py
@@ -0,0 +1,133 @@
+"""Placement and parsing helpers for documents.
+
+The Library is a real tree — a folder is a document with `kind='folder'`, so an
+empty folder exists and a folder can carry an index body. That makes three
+things this module owns: slugs that stay unique among siblings, a re-parent
+guard so the tree cannot be knotted into a cycle, and the subtree walk that
+`DELETE` needs because SQLite does not always enforce `ON DELETE CASCADE`
+(`api/routes/designs.py` unwinds its own deletes for the same reason).
+
+It also parses the YAML frontmatter out of a body. The body is the source of
+truth — it is what exports to disk — and `documents.frontmatter` / `documents.tags`
+are only a cache so a listing can filter without reading every body.
+"""
+
+import re
+from typing import Any
+
+import yaml
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.db.models import Document
+
+# A document is addressed by id; the slug is for readable URLs and export
+# filenames, so it only has to be filesystem- and URL-safe.
+_SLUG_STRIP = re.compile(r"[^a-z0-9]+")
+_FRONTMATTER = re.compile(r"\A---\s*\n(.*?)\n---\s*(?:\n|\Z)", re.DOTALL)
+
+DOCUMENT_KINDS = frozenset({"device", "node", "design", "page", "folder"})
+
+# Kinds that live in the Library tree and may therefore carry a parent.
+TREE_KINDS = frozenset({"page", "folder"})
+
+REVISION_LIMIT = 50
+
+
+def slugify(title: str) -> str:
+ slug = _SLUG_STRIP.sub("-", (title or "").strip().lower()).strip("-")
+ return slug[:80] or "untitled"
+
+
+async def unique_slug(db: AsyncSession, title: str, *, parent_id: str | None, exclude_id: str | None = None) -> str:
+ """A slug no sibling is already using."""
+ base = slugify(title)
+ sibling = Document.parent_id.is_(None) if parent_id is None else Document.parent_id == parent_id
+ query = select(Document.slug).where(sibling)
+ if exclude_id is not None:
+ query = query.where(Document.id != exclude_id)
+ taken = {row for row in (await db.execute(query)).scalars().all()}
+ if base not in taken:
+ return base
+ suffix = 2
+ while f"{base}-{suffix}" in taken:
+ suffix += 1
+ return f"{base}-{suffix}"
+
+
+def parse_frontmatter(body: str) -> dict[str, Any]:
+ """The YAML block at the top of a body, or `{}`.
+
+ Malformed YAML is not an error the user should be blocked by — they are
+ mid-edit. The cache simply stays empty until the block parses again.
+ """
+ match = _FRONTMATTER.match(body or "")
+ if not match:
+ return {}
+ try:
+ parsed = yaml.safe_load(match.group(1))
+ except yaml.YAMLError:
+ return {}
+ if not isinstance(parsed, dict):
+ return {}
+ return {str(key): _jsonable(value) for key, value in parsed.items()}
+
+
+def _jsonable(value: Any) -> Any:
+ """Coerce a parsed YAML value into something the JSON column can hold.
+
+ YAML resolves `created: 2026-09-05` to a `date` and `at: 10:30` to an int,
+ neither of which survives `json.dumps`. The cache is only ever read back for
+ filtering and display, so a string is the right shape — the body keeps the
+ literal the user typed either way.
+ """
+ if isinstance(value, str | int | float | bool) or value is None:
+ return value
+ if isinstance(value, list):
+ return [_jsonable(item) for item in value]
+ if isinstance(value, dict):
+ return {str(key): _jsonable(item) for key, item in value.items()}
+ return str(value)
+
+
+def tags_from(frontmatter: dict[str, Any]) -> list[str]:
+ raw = frontmatter.get("tags")
+ if isinstance(raw, str):
+ raw = [part.strip() for part in raw.split(",")]
+ if not isinstance(raw, list):
+ return []
+ return [str(tag).strip() for tag in raw if str(tag).strip()]
+
+
+async def is_ancestor(db: AsyncSession, candidate_id: str, of_id: str) -> bool:
+ """Whether `candidate_id` is `of_id` or sits above it.
+
+ Guards re-parenting: moving a folder inside its own subtree would orphan
+ everything under it. Mirrors the `_is_ancestor` guard the MCP zone tools use.
+ """
+ if candidate_id == of_id:
+ return True
+ seen: set[str] = set()
+ current: str | None = of_id
+ while current and current not in seen:
+ seen.add(current)
+ current = (await db.execute(select(Document.parent_id).where(Document.id == current))).scalar_one_or_none()
+ if current == candidate_id:
+ return True
+ return False
+
+
+async def subtree_ids(db: AsyncSession, root_id: str) -> list[str]:
+ """`root_id` plus every document beneath it, deepest last."""
+ collected = [root_id]
+ frontier = [root_id]
+ while frontier:
+ children = (
+ await db.execute(select(Document.id).where(Document.parent_id.in_(frontier)))
+ ).scalars().all()
+ children = [child for child in children if child not in collected]
+ if not children:
+ break
+ collected.extend(children)
+ frontier = children
+ return collected
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index 8729682..7f99a87 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -9,7 +9,7 @@ from httpx import ASGITransport, AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from app.core.security import hash_password
-from app.db.database import Base, get_db
+from app.db.database import DOCUMENT_DDL, Base, get_db
from app.main import app
TEST_DB_URL = "sqlite+aiosqlite:///:memory:"
@@ -28,6 +28,10 @@ async def db_session():
engine = create_async_engine(TEST_DB_URL)
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
+ # create_all cannot express the documents FTS5 table or its partial
+ # uniques; apply the same DDL init_db does so the suite matches boot.
+ for _label, sql in DOCUMENT_DDL:
+ await conn.exec_driver_sql(sql)
session_factory = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
# Background tasks open their own session through `AsyncSessionLocal` — the
# request-scoped `get_db` override does not reach them. Left alone they would
@@ -72,3 +76,13 @@ async def headers(client: AsyncClient):
"""Authenticated Bearer headers for the default admin test user."""
res = await client.post("/api/v1/auth/login", json={"username": "admin", "password": "admin"})
return {"Authorization": f"Bearer {res.json()['access_token']}"}
+
+
[email protected](autouse=True)
+def _reset_doc_search_probe():
+ """Forget whether FTS5 was available — each test gets a fresh database."""
+ from app.services import doc_search
+
+ doc_search.reset_availability_cache()
+ yield
+ doc_search.reset_availability_cache()
diff --git a/backend/tests/test_doc_search.py b/backend/tests/test_doc_search.py
new file mode 100644
index 0000000..24006db
--- /dev/null
+++ b/backend/tests/test_doc_search.py
@@ -0,0 +1,172 @@
+"""Search over documents, on both engines.
+
+FTS5 is not guaranteed by the SQLite build the LXC and Docker images ship, so
+the LIKE fallback is a supported path, not a safety net — it gets the same
+coverage as the index.
+"""
+
+from sqlalchemy import text
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.db.models import Document
+from app.services import doc_search
+
+
+def _doc(**kwargs) -> Document:
+ base = dict(kind="page", title="T", slug="t", body="", tags=[])
+ base.update(kwargs)
+ return Document(**base)
+
+
+async def _seed(db: AsyncSession) -> list[Document]:
+ docs = [
+ _doc(title="NAS", slug="nas", body="The Synology holds every backup.", tags=["storage"]),
+ _doc(title="Router", slug="router", body="Runs OPNsense on 192.168.1.1.", tags=["network"]),
+ _doc(title="VLAN plan", slug="vlan-plan", body="Guest traffic is isolated.", tags=["network"]),
+ ]
+ for doc in docs:
+ db.add(doc)
+ await db.flush()
+ await doc_search.index_document(db, doc)
+ await db.flush()
+ return docs
+
+
+# ── the MATCH expression ────────────────────────────────────────────────────
+
+
+def test_match_query_quotes_every_term_and_prefixes_it():
+ assert doc_search.build_match_query("nas backup") == '"nas"* AND "backup"*'
+
+
+def test_match_query_neutralises_punctuation_a_user_types():
+ # An IP and a lone quote are data, not FTS5 syntax.
+ assert doc_search.build_match_query("192.168.1.1") == '"192.168.1.1"*'
+ assert doc_search.build_match_query('a"b') == '"a""b"*'
+
+
+def test_match_query_of_whitespace_is_empty():
+ assert doc_search.build_match_query(" ") == ""
+
+
+def test_tags_text_flattens_a_list():
+ assert doc_search.tags_text(["a", "b"]) == "a b"
+ assert doc_search.tags_text(None) == ""
+
+
+# ── FTS5 ────────────────────────────────────────────────────────────────────
+
+
+async def test_fts_is_available_when_the_index_table_exists(db_session: AsyncSession):
+ assert await doc_search.fts_available(db_session) is True
+
+
+async def test_search_finds_a_word_that_is_only_in_a_body(db_session: AsyncSession):
+ await _seed(db_session)
+ engine, hits = await doc_search.search(db_session, "Synology")
+ assert engine == "fts5"
+ assert len(hits) == 1
+ assert "Synology" in hits[0]["snippet"]
+
+
+async def test_search_matches_a_prefix(db_session: AsyncSession):
+ await _seed(db_session)
+ _, hits = await doc_search.search(db_session, "OPNsen")
+ assert len(hits) == 1
+
+
+async def test_search_matches_a_title(db_session: AsyncSession):
+ await _seed(db_session)
+ _, hits = await doc_search.search(db_session, "VLAN")
+ assert len(hits) == 1
+
+
+async def test_search_matches_a_tag(db_session: AsyncSession):
+ await _seed(db_session)
+ _, hits = await doc_search.search(db_session, "network")
+ assert len(hits) == 2
+
+
+async def test_search_ands_its_terms(db_session: AsyncSession):
+ await _seed(db_session)
+ _, hits = await doc_search.search(db_session, "guest traffic")
+ assert len(hits) == 1
+ _, none = await doc_search.search(db_session, "guest Synology")
+ assert none == []
+
+
+async def test_search_of_an_empty_query_returns_nothing(db_session: AsyncSession):
+ await _seed(db_session)
+ _, hits = await doc_search.search(db_session, " ")
+ assert hits == []
+
+
+async def test_reindexing_replaces_the_previous_body(db_session: AsyncSession):
+ docs = await _seed(db_session)
+ docs[0].body = "Replaced entirely."
+ await doc_search.index_document(db_session, docs[0])
+ _, gone = await doc_search.search(db_session, "Synology")
+ assert gone == []
+ _, found = await doc_search.search(db_session, "Replaced")
+ assert len(found) == 1
+
+
+async def test_unindexing_removes_the_document(db_session: AsyncSession):
+ docs = await _seed(db_session)
+ await doc_search.unindex_document(db_session, docs[0].id)
+ _, hits = await doc_search.search(db_session, "Synology")
+ assert hits == []
+
+
+async def test_the_limit_is_honoured(db_session: AsyncSession):
+ for i in range(8):
+ doc = _doc(title=f"D{i}", slug=f"d{i}", body="shared word here")
+ db_session.add(doc)
+ await db_session.flush()
+ await doc_search.index_document(db_session, doc)
+ _, hits = await doc_search.search(db_session, "shared", limit=3)
+ assert len(hits) == 3
+
+
+# ── the LIKE fallback ───────────────────────────────────────────────────────
+
+
+async def test_search_falls_back_to_like_without_fts5(db_session: AsyncSession):
+ await _seed(db_session)
+ await db_session.execute(text("DROP TABLE documents_fts"))
+ doc_search.reset_availability_cache()
+
+ engine, hits = await doc_search.search(db_session, "Synology")
+ assert engine == "like"
+ assert len(hits) == 1
+ assert "Synology" in hits[0]["snippet"]
+
+
+async def test_indexing_is_a_no_op_without_fts5(db_session: AsyncSession):
+ await db_session.execute(text("DROP TABLE documents_fts"))
+ doc_search.reset_availability_cache()
+ doc = _doc(title="NAS", slug="nas", body="body")
+ db_session.add(doc)
+ await db_session.flush()
+ # Must not raise — writes carry on, only search degrades.
+ await doc_search.index_document(db_session, doc)
+ await doc_search.unindex_document(db_session, doc.id)
+
+
+async def test_like_fallback_is_case_insensitive(db_session: AsyncSession):
+ await _seed(db_session)
+ await db_session.execute(text("DROP TABLE documents_fts"))
+ doc_search.reset_availability_cache()
+ _, hits = await doc_search.search(db_session, "synology")
+ assert len(hits) == 1
+
+
+def test_excerpt_centres_on_the_match():
+ body = "x" * 200 + "needle" + "y" * 200
+ excerpt = doc_search._excerpt(body, "needle")
+ assert "needle" in excerpt
+ assert excerpt.startswith("…") and excerpt.endswith("…")
+
+
+def test_excerpt_falls_back_to_the_head_when_there_is_no_match():
+ assert doc_search._excerpt("short body", "absent") == "short body"
diff --git a/backend/tests/test_doc_template.py b/backend/tests/test_doc_template.py
new file mode 100644
index 0000000..c70af8d
--- /dev/null
+++ b/backend/tests/test_doc_template.py
@@ -0,0 +1,264 @@
+"""The generated skeleton. Written once, then owned by the user — so what it
+emits on day one is the whole contract."""
+
+from datetime import date, datetime, timezone
+from types import SimpleNamespace
+
+from app.services import doc_template as t
+
+
+def _device(**overrides):
+ base = dict(
+ id="dev-1",
+ label="nas-01",
+ friendly_name=None,
+ hostname="nas-01.lan",
+ ip="192.168.1.20",
+ mac="00:11:32:aa:bb:cc",
+ ieee_address=None,
+ os="DSM 7.2",
+ vendor="Synology",
+ model="DS920+",
+ type="nas",
+ suggested_type=None,
+ services=[
+ {"port": 5000, "protocol": "tcp", "service_name": "Synology DSM", "category": "management"},
+ {"port": 445, "protocol": "tcp", "service_name": "SMB"},
+ ],
+ properties=[{"key": "serial", "value": "20C0PDN", "icon": None, "visible": True}],
+ cpu_count=4,
+ cpu_model="Intel Celeron J4125",
+ ram_gb=20.0,
+ disk_gb=32000.0,
+ check_method="http",
+ check_target="http://192.168.1.20:5000",
+ discovery_source="arp",
+ discovery_sources=["arp", "mdns"],
+ discovered_at=datetime(2026, 3, 4, tzinfo=timezone.utc),
+ notes="",
+ )
+ base.update(overrides)
+ return SimpleNamespace(**base)
+
+
+# ── cells and names ─────────────────────────────────────────────────────────
+
+
+def test_cell_escapes_pipes_and_collapses_newlines():
+ assert t.cell("a|b") == r"a\|b"
+ assert t.cell("one\ntwo") == "one two"
+ assert t.cell(None) == "—"
+ assert t.cell("") == "—"
+
+
+def test_cell_escapes_backslash_before_pipe():
+ # Backslash first, or the escape of the pipe would itself be escaped.
+ assert t.cell(r"a\|b") == r"a\\\|b"
+
+
+def test_device_name_falls_back_through_label_hostname_ip():
+ assert t.device_name(_device()) == "nas-01"
+ assert t.device_name(_device(label=None)) == "nas-01.lan"
+ assert t.device_name(_device(label=None, hostname=None)) == "192.168.1.20"
+ assert t.device_name(_device(label=None, hostname=None, ip=None)) == "device"
+
+
+def test_device_type_prefers_curated_over_guessed():
+ assert t.device_type(_device(type="nas", suggested_type="server")) == "nas"
+ assert t.device_type(_device(type=None, suggested_type="server")) == "server"
+
+
+# ── blocks ──────────────────────────────────────────────────────────────────
+
+
+def test_device_info_block_reads_every_address():
+ md = t.block_device_info(_device())
+ assert "| Hostname | nas-01.lan |" in md
+ assert "| IP | 192.168.1.20 |" in md
+ assert "| Vendor / Model | Synology / DS920+ |" in md
+ assert "`http` → `http://192.168.1.20:5000`" in md
+ assert "(arp, mdns)" in md
+
+
+def test_device_info_block_prints_dashes_for_missing_facts():
+ md = t.block_device_info(_device(hostname=None, mac=None, os=None, vendor=None, model=None))
+ assert "| Hostname | — |" in md
+ assert "| Vendor / Model | — |" in md
+
+
+def test_hardware_block_joins_cpu_model_and_count():
+ assert "Intel Celeron J4125 ×4" in t.block_hardware(_device())
+ assert "20 GB" in t.block_hardware(_device())
+
+
+def test_hardware_block_handles_a_count_without_a_model():
+ assert "4 cores" in t.block_hardware(_device(cpu_model=None))
+
+
+def test_services_block_writes_one_section_per_service():
+ md = t.block_services(_device())
+ assert "### Synology DSM — `5000/tcp`" in md
+ assert "### SMB — `445/tcp`" in md
+ assert "**Category** — management" in md
+ # Prompts, not values — the user fills these in.
+ assert md.count("**Purpose**") == 2
+
+
+def test_services_block_says_so_when_nothing_was_fingerprinted():
+ assert "No service" in t.block_services(_device(services=[]))
+
+
+def test_services_block_never_invents_a_url_for_a_non_http_port():
+ md = t.block_services(_device(services=[{"port": 445, "protocol": "tcp", "service_name": "SMB"}]))
+ assert "**URL**" not in md
+
+
+def test_services_block_builds_an_http_url_from_the_device_ip():
+ assert "<http://192.168.1.20:5000>" in t.block_services(_device())
+
+
+def test_properties_block_is_empty_when_the_device_has_none():
+ assert t.block_properties(_device(properties=[])) == ""
+ assert "| serial | 20C0PDN |" in t.block_properties(_device())
+
+
+def test_rack_block_prints_the_span_of_units():
+ md = t.block_rack(_device(), rack={"name": "Rack-A", "u_start": 12, "u_height": 3, "col_span": 12})
+ assert md == "Rack **Rack-A**, U12–U14, full width."
+
+
+def test_rack_block_collapses_a_single_unit():
+ md = t.block_rack(_device(), rack={"name": "Rack-A", "u_start": 7, "u_height": 1, "col_span": 6})
+ assert "U7," in md and "–" not in md
+ assert "6/12 wide" in md
+
+
+def test_rack_block_is_empty_when_the_device_is_neither_racked_nor_zoned():
+ assert t.block_rack(_device()) == ""
+ assert t.block_rack(_device(), zone_label="Garage") == "Zone **Garage**."
+
+
+def test_network_block_guesses_the_slash_24_and_lists_peers():
+ md = t.block_network(_device(), connections=["switch-core", "router"])
+ assert "192.168.1.0/24" in md
+ assert "`switch-core`, `router`" in md
+
+
+def test_network_block_takes_the_first_ip_of_a_multi_ip_device():
+ assert "10.0.0.0/24" in t.block_network(_device(ip="10.0.0.5, 192.168.1.20"))
+
+
+def test_network_block_survives_a_device_with_no_ip():
+ assert "**Subnet / VLAN** — _…_" in t.block_network(_device(ip=None))
+
+
+def test_render_block_rejects_an_unknown_name():
+ try:
+ t.render_block("nope", _device())
+ except ValueError as exc:
+ assert "Unknown block" in str(exc)
+ else:
+ raise AssertionError("expected ValueError")
+
+
+# ── the whole document ──────────────────────────────────────────────────────
+
+
+def test_device_document_carries_every_section():
+ md = t.render_device_document(_device(), today=date(2026, 9, 5))
+ for heading in (
+ "## Device Information",
+ "### Hardware",
+ "## Services",
+ "## Network",
+ "## Configuration",
+ "## Operations",
+ "## Troubleshooting",
+ "## Dependencies",
+ "## Changelog",
+ "## Notes",
+ ):
+ assert heading in md, heading
+
+
+def test_device_document_opens_with_versioned_frontmatter():
+ md = t.render_device_document(_device(), today=date(2026, 9, 5))
+ assert md.startswith("---\n")
+ assert f"homelable: {t.FRONTMATTER_VERSION}" in md
+ assert "device: dev-1" in md
+ assert "created: 2026-09-05" in md
+ assert "review_every: 6m" in md
+
+
+def test_device_document_appends_old_notes_verbatim_with_provenance():
+ notes = "Runs the backups.\n\n Indented line kept as typed | with a pipe."
+ md = t.render_device_document(_device(notes=notes), today=date(2026, 9, 5))
+ assert "<!-- Migrated verbatim from this device's Notes field on 2026-09-05. -->" in md
+ assert notes.strip() in md
+
+
+def test_device_document_prompts_when_there_were_no_notes():
+ md = t.render_device_document(_device(notes=""))
+ assert "Migrated verbatim" not in md
+ assert "_Anything worth remembering about this device._" in md
+
+
+def test_device_document_drops_the_location_section_when_there_is_no_place():
+ assert "### Physical location" not in t.render_device_document(_device())
+ md = t.render_device_document(_device(), zone_label="Garage")
+ assert "### Physical location" in md
+
+
+def test_device_document_drops_the_properties_section_when_there_are_none():
+ assert "### Properties" not in t.render_device_document(_device(properties=[]))
+
+
+def test_device_document_of_a_bare_device_still_renders():
+ bare = SimpleNamespace(id="d", label=None, notes=None)
+ md = t.render_device_document(bare)
+ assert "# device" in md
+ assert "## Services" in md
+
+
+# ── library templates ───────────────────────────────────────────────────────
+
+
+def test_runbook_template_has_its_headings():
+ md = t.render_library_document(t.TEMPLATE_RUNBOOK, "Reboot the NAS", today=date(2026, 9, 5))
+ assert "# Reboot the NAS" in md
+ assert "## Rollback" in md
+ assert "template: runbook" in md
+
+
+def test_blank_template_is_just_a_title():
+ md = t.render_library_document(t.TEMPLATE_BLANK, "Scratch")
+ assert "# Scratch" in md
+ assert "##" not in md
+
+
+def test_unknown_template_falls_back_to_blank_rather_than_failing():
+ md = t.render_library_document("does-not-exist", "Scratch")
+ assert "# Scratch" in md
+
+
+def test_frontmatter_omits_empty_values():
+ rendered = t.render_frontmatter({"a": 1, "b": None, "c": "", "d": [], "e": ["x", "y"]})
+ assert rendered == "---\na: 1\ne: [x, y]\n---"
+
+
+# ── the drift snapshot ──────────────────────────────────────────────────────
+
+
+def test_facts_snapshot_keys_services_by_port_protocol_name():
+ snapshot = t.facts_snapshot(_device())
+ assert snapshot["services"] == ["445|tcp|smb", "5000|tcp|synology dsm"]
+
+
+def test_facts_snapshot_is_stable_when_services_are_reordered():
+ a = t.facts_snapshot(_device())
+ b = t.facts_snapshot(_device(services=list(reversed(_device().services))))
+ assert a == b
+
+
+def test_facts_snapshot_changes_when_the_ip_moves():
+ assert t.facts_snapshot(_device()) != t.facts_snapshot(_device(ip="192.168.1.21"))
diff --git a/backend/tests/test_doc_tree.py b/backend/tests/test_doc_tree.py
new file mode 100644
index 0000000..6264ae3
--- /dev/null
+++ b/backend/tests/test_doc_tree.py
@@ -0,0 +1,133 @@
+"""Slugs, frontmatter parsing, and the two tree guards."""
+
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.db.models import Document
+from app.services import doc_tree
+
+
+def _doc(**kwargs) -> Document:
+ base = dict(kind="folder", title="T", slug="t", body="")
+ base.update(kwargs)
+ return Document(**base)
+
+
+# ── slugs ───────────────────────────────────────────────────────────────────
+
+
+def test_slugify_lowercases_and_collapses_punctuation():
+ assert doc_tree.slugify("NAS-01 / main storage!") == "nas-01-main-storage"
+
+
+def test_slugify_of_nothing_is_untitled():
+ assert doc_tree.slugify("") == "untitled"
+ assert doc_tree.slugify(" ") == "untitled"
+ assert doc_tree.slugify("!!!") == "untitled"
+
+
+def test_slugify_truncates_a_long_title():
+ assert len(doc_tree.slugify("x" * 200)) == 80
+
+
+async def test_unique_slug_suffixes_a_taken_sibling(db_session: AsyncSession):
+ db_session.add(_doc(title="Network", slug="network"))
+ await db_session.flush()
+ assert await doc_tree.unique_slug(db_session, "Network", parent_id=None) == "network-2"
+
+
+async def test_unique_slug_keeps_counting_past_the_second(db_session: AsyncSession):
+ db_session.add(_doc(slug="network"))
+ db_session.add(_doc(slug="network-2"))
+ await db_session.flush()
+ assert await doc_tree.unique_slug(db_session, "Network", parent_id=None) == "network-3"
+
+
+async def test_unique_slug_only_looks_at_siblings(db_session: AsyncSession):
+ parent = _doc(title="Folder", slug="folder")
+ db_session.add(parent)
+ await db_session.flush()
+ db_session.add(_doc(slug="network", parent_id=parent.id))
+ await db_session.flush()
+ # Same slug, different parent — no clash.
+ assert await doc_tree.unique_slug(db_session, "Network", parent_id=None) == "network"
+
+
+async def test_unique_slug_ignores_the_document_being_renamed(db_session: AsyncSession):
+ doc = _doc(title="Network", slug="network")
+ db_session.add(doc)
+ await db_session.flush()
+ assert await doc_tree.unique_slug(db_session, "Network", parent_id=None, exclude_id=doc.id) == "network"
+
+
+# ── frontmatter ─────────────────────────────────────────────────────────────
+
+
+def test_parse_frontmatter_reads_the_leading_block():
+ body = "---\ntitle: NAS\ntags: [a, b]\n---\n\n# NAS\n"
+ assert doc_tree.parse_frontmatter(body) == {"title": "NAS", "tags": ["a", "b"]}
+
+
+def test_parse_frontmatter_ignores_a_block_that_is_not_first():
+ assert doc_tree.parse_frontmatter("# Title\n\n---\ntitle: NAS\n---\n") == {}
+
+
+def test_parse_frontmatter_of_malformed_yaml_is_empty_not_an_error():
+ # The user is mid-edit; the cache goes stale, the save does not fail.
+ assert doc_tree.parse_frontmatter("---\ntitle: [unclosed\n---\nbody") == {}
+
+
+def test_parse_frontmatter_of_a_non_mapping_is_empty():
+ assert doc_tree.parse_frontmatter("---\n- a\n- b\n---\n") == {}
+
+
+def test_parse_frontmatter_of_an_empty_body_is_empty():
+ assert doc_tree.parse_frontmatter("") == {}
+
+
+def test_tags_accepts_a_list_or_a_comma_string():
+ assert doc_tree.tags_from({"tags": ["a", " b "]}) == ["a", "b"]
+ assert doc_tree.tags_from({"tags": "a, b"}) == ["a", "b"]
+ assert doc_tree.tags_from({"tags": 7}) == []
+ assert doc_tree.tags_from({}) == []
+
+
+# ── tree guards ─────────────────────────────────────────────────────────────
+
+
+async def _chain(db_session: AsyncSession, depth: int) -> list[Document]:
+ docs: list[Document] = []
+ parent_id = None
+ for i in range(depth):
+ doc = _doc(title=f"L{i}", slug=f"l{i}", parent_id=parent_id)
+ db_session.add(doc)
+ await db_session.flush()
+ docs.append(doc)
+ parent_id = doc.id
+ return docs
+
+
+async def test_is_ancestor_walks_the_whole_chain(db_session: AsyncSession):
+ a, b, c = await _chain(db_session, 3)
+ assert await doc_tree.is_ancestor(db_session, a.id, c.id)
+ assert not await doc_tree.is_ancestor(db_session, c.id, a.id)
+
+
+async def test_a_document_is_its_own_ancestor(db_session: AsyncSession):
+ (a,) = await _chain(db_session, 1)
+ assert await doc_tree.is_ancestor(db_session, a.id, a.id)
+
+
+async def test_subtree_ids_collects_every_descendant(db_session: AsyncSession):
+ a, b, c = await _chain(db_session, 3)
+ sibling = _doc(title="S", slug="s", parent_id=a.id)
+ db_session.add(sibling)
+ await db_session.flush()
+ ids = await doc_tree.subtree_ids(db_session, a.id)
+ assert set(ids) == {a.id, b.id, c.id, sibling.id}
+ # Root first, so a caller deleting in reverse removes leaves first.
+ assert ids[0] == a.id
+
+
+async def test_subtree_ids_of_a_leaf_is_just_itself(db_session: AsyncSession):
+ (a,) = await _chain(db_session, 1)
+ assert await doc_tree.subtree_ids(db_session, a.id) == [a.id]
diff --git a/backend/tests/test_documents.py b/backend/tests/test_documents.py
new file mode 100644
index 0000000..142b635
--- /dev/null
+++ b/backend/tests/test_documents.py
@@ -0,0 +1,555 @@
+"""The documents API.
+
+Covers what the plan promises the user: a document per device generated once,
+a Library tree that cannot be knotted, history that survives a restore, and a
+document that outlives the device it describes.
+"""
+
+import uuid
+
+from httpx import AsyncClient
+
+
+async def _device(client: AsyncClient, headers: dict, **body) -> dict:
+ payload = {"label": "nas-01", "hostname": "nas-01.lan", "ip": "192.168.1.20", "discovery_source": "manual", **body}
+ res = await client.post("/api/v1/scan/pending", json=payload, headers=headers)
+ assert res.status_code in (200, 201), res.text
+ return res.json()
+
+
+async def _create(client: AsyncClient, headers: dict, **body) -> dict:
+ res = await client.post("/api/v1/documents", json={"title": "Page", **body}, headers=headers)
+ assert res.status_code == 201, res.text
+ return res.json()
+
+
+async def _design(client: AsyncClient, headers: dict) -> str:
+ res = await client.post("/api/v1/designs", json={"name": "D"}, headers=headers)
+ assert res.status_code == 201, res.text
+ return res.json()["id"]
+
+
+# ── auth ────────────────────────────────────────────────────────────────────
+
+
+async def test_list_requires_auth(client: AsyncClient):
+ assert (await client.get("/api/v1/documents")).status_code == 401
+
+
+async def test_create_requires_auth(client: AsyncClient):
+ assert (await client.post("/api/v1/documents", json={"title": "X"})).status_code == 401
+
+
+async def test_search_requires_auth(client: AsyncClient):
+ assert (await client.get("/api/v1/documents/search?q=x")).status_code == 401
+
+
+async def test_coverage_requires_auth(client: AsyncClient):
+ assert (await client.get("/api/v1/documents/coverage")).status_code == 401
+
+
+async def test_delete_requires_auth(client: AsyncClient):
+ assert (await client.delete("/api/v1/documents/x")).status_code == 401
+
+
+# ── create ──────────────────────────────────────────────────────────────────
+
+
+async def test_create_a_blank_page(client: AsyncClient, headers: dict):
+ doc = await _create(client, headers, title="VLAN plan")
+ assert doc["kind"] == "page"
+ assert doc["slug"] == "vlan-plan"
+ assert "# VLAN plan" in doc["body"]
+
+
+async def test_create_a_page_from_a_template(client: AsyncClient, headers: dict):
+ doc = await _create(client, headers, title="Reboot the NAS", template_id="runbook")
+ assert "## Rollback" in doc["body"]
+ assert doc["template_id"] == "runbook"
+
+
+async def test_create_a_page_with_an_explicit_body(client: AsyncClient, headers: dict):
+ doc = await _create(client, headers, title="Raw", body="---\ntags: [a]\n---\n\nhello")
+ assert doc["body"].endswith("hello")
+ # The frontmatter cache is derived from the body, never sent on its own.
+ assert doc["frontmatter"] == {"tags": ["a"]}
+ assert doc["tags"] == ["a"]
+
+
+async def test_create_a_folder(client: AsyncClient, headers: dict):
+ folder = await _create(client, headers, title="Runbooks", kind="folder")
+ child = await _create(client, headers, title="Reboot", parent_id=folder["id"])
+ assert child["parent_id"] == folder["id"]
+
+
+async def test_create_rejects_an_unknown_kind(client: AsyncClient, headers: dict):
+ res = await client.post("/api/v1/documents", json={"title": "X", "kind": "wat"}, headers=headers)
+ assert res.status_code == 422
+
+
+async def test_create_rejects_an_unknown_template(client: AsyncClient, headers: dict):
+ res = await client.post("/api/v1/documents", json={"title": "X", "template_id": "wat"}, headers=headers)
+ assert res.status_code == 422
+
+
+async def test_create_rejects_a_missing_parent(client: AsyncClient, headers: dict):
+ res = await client.post(
+ "/api/v1/documents", json={"title": "X", "parent_id": str(uuid.uuid4())}, headers=headers
+ )
+ assert res.status_code == 404
+
+
+async def test_create_rejects_a_page_that_also_names_a_device(client: AsyncClient, headers: dict):
+ device = await _device(client, headers)
+ res = await client.post(
+ "/api/v1/documents", json={"title": "X", "kind": "page", "device_id": device["id"]}, headers=headers
+ )
+ assert res.status_code == 400
+
+
+async def test_create_rejects_a_device_document_naming_nothing(client: AsyncClient, headers: dict):
+ res = await client.post("/api/v1/documents", json={"title": "X", "kind": "device"}, headers=headers)
+ assert res.status_code == 400
+
+
+async def test_create_rejects_two_links_at_once(client: AsyncClient, headers: dict):
+ device = await _device(client, headers)
+ res = await client.post(
+ "/api/v1/documents",
+ json={"title": "X", "kind": "device", "device_id": device["id"], "design_id": await _design(client, headers)},
+ headers=headers,
+ )
+ assert res.status_code == 400
+
+
+async def test_create_rejects_a_device_that_does_not_exist(client: AsyncClient, headers: dict):
+ res = await client.post(
+ "/api/v1/documents",
+ json={"title": "X", "kind": "device", "device_id": str(uuid.uuid4())},
+ headers=headers,
+ )
+ assert res.status_code == 404
+
+
+async def test_a_device_gets_at_most_one_document(client: AsyncClient, headers: dict):
+ device = await _device(client, headers)
+ body = {"title": "nas", "kind": "device", "device_id": device["id"]}
+ assert (await client.post("/api/v1/documents", json=body, headers=headers)).status_code == 201
+ second = await client.post("/api/v1/documents", json=body, headers=headers)
+ assert second.status_code == 409
+
+
+async def test_a_sibling_title_gets_a_distinct_slug(client: AsyncClient, headers: dict):
+ first = await _create(client, headers, title="Network")
+ second = await _create(client, headers, title="Network")
+ assert first["slug"] == "network"
+ assert second["slug"] == "network-2"
+
+
+# ── the generated device document ───────────────────────────────────────────
+
+
+async def test_a_device_document_is_scaffolded_from_the_live_facts(client: AsyncClient, headers: dict):
+ device = await _device(
+ client, headers, hostname="nas-01.lan", vendor="Synology", notes="Holds the backups."
+ )
+ doc = await _create(client, headers, title="nas-01", kind="device", device_id=device["id"])
+ assert "| Hostname | nas-01.lan |" in doc["body"]
+ assert "| IP | 192.168.1.20 |" in doc["body"]
+ assert "Holds the backups." in doc["body"]
+ assert doc["facts_snapshot"]["ip"] == "192.168.1.20"
+ assert doc["facts_synced_at"] is not None
+
+
+async def test_the_old_notes_column_is_left_untouched_by_scaffolding(client: AsyncClient, headers: dict):
+ device = await _device(client, headers, notes="Holds the backups.")
+ await _create(client, headers, title="nas-01", kind="device", device_id=device["id"])
+ res = await client.get("/api/v1/scan/pending", headers=headers)
+ row = next(d for d in res.json() if d["id"] == device["id"])
+ assert row["notes"] == "Holds the backups."
+
+
+async def test_a_device_document_records_its_zone_and_neighbours(client: AsyncClient, headers: dict):
+ design_id = await _design(client, headers)
+ device = await _device(client, headers)
+ zone = await client.post(
+ "/api/v1/nodes",
+ json={"type": "groupRect", "label": "Garage", "design_id": design_id, "pos_x": 0, "pos_y": 0},
+ headers=headers,
+ )
+ zone_id = zone.json()["id"]
+ # A node binds to its inventory row by its addresses, not by an id on the
+ # payload — the canvas is one more way to document hardware, not a store.
+ node = await client.post(
+ "/api/v1/nodes",
+ json={
+ "type": "nas",
+ "label": "nas-01",
+ "design_id": design_id,
+ "ip": "192.168.1.20",
+ "hostname": "nas-01.lan",
+ "parent_id": zone_id,
+ "pos_x": 0,
+ "pos_y": 0,
+ },
+ headers=headers,
+ )
+ assert node.json()["device_id"] == device["id"], node.text
+ peer = await client.post(
+ "/api/v1/nodes",
+ json={"type": "switch", "label": "switch-core", "design_id": design_id, "pos_x": 0, "pos_y": 0},
+ headers=headers,
+ )
+ await client.post(
+ "/api/v1/edges",
+ json={"source": node.json()["id"], "target": peer.json()["id"], "type": "ethernet"},
+ headers=headers,
+ )
+
+ doc = await _create(client, headers, title="nas-01", kind="device", device_id=device["id"])
+ assert "Zone **Garage**." in doc["body"]
+ assert "`switch-core`" in doc["body"]
+
+
+# ── blocks ──────────────────────────────────────────────────────────────────
+
+
+async def test_a_block_can_be_regenerated_on_demand(client: AsyncClient, headers: dict):
+ device = await _device(client, headers, hostname="nas-01.lan")
+ res = await client.get(
+ f"/api/v1/documents/blocks?block=device-info&device_id={device['id']}", headers=headers
+ )
+ assert res.status_code == 200, res.text
+ assert "| Hostname | nas-01.lan |" in res.json()["markdown"]
+
+
+async def test_an_unknown_block_is_rejected(client: AsyncClient, headers: dict):
+ device = await _device(client, headers)
+ res = await client.get(f"/api/v1/documents/blocks?block=nope&device_id={device['id']}", headers=headers)
+ assert res.status_code == 400
+
+
+async def test_a_block_for_a_missing_device_is_404(client: AsyncClient, headers: dict):
+ res = await client.get(
+ f"/api/v1/documents/blocks?block=device-info&device_id={uuid.uuid4()}", headers=headers
+ )
+ assert res.status_code == 404
+
+
+# ── read / list ─────────────────────────────────────────────────────────────
+
+
+async def test_get_a_missing_document_is_404(client: AsyncClient, headers: dict):
+ assert (await client.get(f"/api/v1/documents/{uuid.uuid4()}", headers=headers)).status_code == 404
+
+
+async def test_listing_carries_no_body(client: AsyncClient, headers: dict):
+ await _create(client, headers, title="VLAN plan")
+ row = (await client.get("/api/v1/documents", headers=headers)).json()[0]
+ assert "body" not in row
+
+
+async def test_listing_filters_by_kind_and_parent(client: AsyncClient, headers: dict):
+ folder = await _create(client, headers, title="Runbooks", kind="folder")
+ await _create(client, headers, title="Reboot", parent_id=folder["id"])
+ await _create(client, headers, title="Loose")
+
+ folders = (await client.get("/api/v1/documents?kind=folder", headers=headers)).json()
+ assert [d["title"] for d in folders] == ["Runbooks"]
+
+ children = (await client.get(f"/api/v1/documents?parent_id={folder['id']}", headers=headers)).json()
+ assert [d["title"] for d in children] == ["Reboot"]
+
+
+async def test_listing_filters_by_tag(client: AsyncClient, headers: dict):
+ await _create(client, headers, title="A", body="---\ntags: [Network]\n---\n")
+ await _create(client, headers, title="B", body="---\ntags: [storage]\n---\n")
+ hits = (await client.get("/api/v1/documents?tag=network", headers=headers)).json()
+ assert [d["title"] for d in hits] == ["A"]
+
+
+# ── update ──────────────────────────────────────────────────────────────────
+
+
+async def test_editing_the_body_refreshes_the_frontmatter_cache(client: AsyncClient, headers: dict):
+ doc = await _create(client, headers, title="Page")
+ res = await client.patch(
+ f"/api/v1/documents/{doc['id']}", json={"body": "---\ntags: [x]\n---\n\nnew"}, headers=headers
+ )
+ assert res.status_code == 200, res.text
+ assert res.json()["tags"] == ["x"]
+
+
+async def test_renaming_reslugs(client: AsyncClient, headers: dict):
+ doc = await _create(client, headers, title="Page")
+ res = await client.patch(f"/api/v1/documents/{doc['id']}", json={"title": "New name"}, headers=headers)
+ assert res.json()["slug"] == "new-name"
+
+
+async def test_starring_and_reviewing(client: AsyncClient, headers: dict):
+ doc = await _create(client, headers, title="Page")
+ res = await client.patch(
+ f"/api/v1/documents/{doc['id']}", json={"starred": True, "reviewed": True}, headers=headers
+ )
+ assert res.json()["starred"] is True
+ assert res.json()["reviewed_at"] is not None
+
+
+async def test_patching_a_missing_document_is_404(client: AsyncClient, headers: dict):
+ res = await client.patch(f"/api/v1/documents/{uuid.uuid4()}", json={"title": "X"}, headers=headers)
+ assert res.status_code == 404
+
+
+async def test_a_folder_cannot_be_moved_inside_itself(client: AsyncClient, headers: dict):
+ outer = await _create(client, headers, title="Outer", kind="folder")
+ inner = await _create(client, headers, title="Inner", kind="folder", parent_id=outer["id"])
+ res = await client.patch(f"/api/v1/documents/{outer['id']}", json={"parent_id": inner["id"]}, headers=headers)
+ assert res.status_code == 400
+
+
+async def test_a_document_can_only_be_filed_under_a_folder(client: AsyncClient, headers: dict):
+ page = await _create(client, headers, title="Page")
+ other = await _create(client, headers, title="Other")
+ res = await client.patch(f"/api/v1/documents/{other['id']}", json={"parent_id": page["id"]}, headers=headers)
+ assert res.status_code == 400
+
+
+async def test_a_device_document_does_not_live_in_the_library_tree(client: AsyncClient, headers: dict):
+ device = await _device(client, headers)
+ doc = await _create(client, headers, title="nas", kind="device", device_id=device["id"])
+ folder = await _create(client, headers, title="F", kind="folder")
+ res = await client.patch(f"/api/v1/documents/{doc['id']}", json={"parent_id": folder["id"]}, headers=headers)
+ assert res.status_code == 400
+
+
+async def test_resyncing_facts_clears_the_drift_without_touching_the_body(client: AsyncClient, headers: dict):
+ device = await _device(client, headers)
+ doc = await _create(client, headers, title="nas", kind="device", device_id=device["id"])
+ await client.patch(f"/api/v1/scan/pending/{device['id']}", json={"ip": "192.168.1.99"}, headers=headers)
+
+ res = await client.patch(f"/api/v1/documents/{doc['id']}", json={"resync_facts": True}, headers=headers)
+ assert res.json()["facts_snapshot"]["ip"] == "192.168.1.99"
+ # The header the user owns still says what it always said.
+ assert "192.168.1.20" in res.json()["body"]
+
+
+# ── revisions ───────────────────────────────────────────────────────────────
+
+
+async def test_an_edit_records_the_previous_body(client: AsyncClient, headers: dict):
+ doc = await _create(client, headers, title="Page", body="first")
+ await client.patch(f"/api/v1/documents/{doc['id']}", json={"body": "second"}, headers=headers)
+ revisions = (await client.get(f"/api/v1/documents/{doc['id']}/revisions", headers=headers)).json()
+ assert len(revisions) == 1
+ assert revisions[0]["reason"] == "edit"
+ stored = (await client.get(f"/api/v1/documents/revisions/{revisions[0]['id']}", headers=headers)).json()
+ assert stored["body"] == "first"
+
+
+async def test_saving_an_unchanged_body_records_nothing(client: AsyncClient, headers: dict):
+ doc = await _create(client, headers, title="Page", body="same")
+ await client.patch(f"/api/v1/documents/{doc['id']}", json={"body": "same"}, headers=headers)
+ assert (await client.get(f"/api/v1/documents/{doc['id']}/revisions", headers=headers)).json() == []
+
+
+async def test_restoring_brings_back_an_old_body_and_is_itself_undoable(client: AsyncClient, headers: dict):
+ doc = await _create(client, headers, title="Page", body="first")
+ await client.patch(f"/api/v1/documents/{doc['id']}", json={"body": "second"}, headers=headers)
+ revision = (await client.get(f"/api/v1/documents/{doc['id']}/revisions", headers=headers)).json()[0]
+
+ res = await client.post(
+ f"/api/v1/documents/{doc['id']}/revisions/{revision['id']}/restore", headers=headers
+ )
+ assert res.status_code == 200, res.text
+ assert res.json()["body"] == "first"
+
+ history = (await client.get(f"/api/v1/documents/{doc['id']}/revisions", headers=headers)).json()
+ assert [r["reason"] for r in history][0] == "restore"
+
+
+async def test_restoring_a_revision_of_another_document_is_404(client: AsyncClient, headers: dict):
+ a = await _create(client, headers, title="A", body="one")
+ b = await _create(client, headers, title="B", body="one")
+ await client.patch(f"/api/v1/documents/{a['id']}", json={"body": "two"}, headers=headers)
+ revision = (await client.get(f"/api/v1/documents/{a['id']}/revisions", headers=headers)).json()[0]
+ res = await client.post(f"/api/v1/documents/{b['id']}/revisions/{revision['id']}/restore", headers=headers)
+ assert res.status_code == 404
+
+
+async def test_history_is_pruned_to_the_limit(client: AsyncClient, headers: dict):
+ from app.services.doc_tree import REVISION_LIMIT
+
+ doc = await _create(client, headers, title="Page", body="v0")
+ for i in range(1, REVISION_LIMIT + 6):
+ await client.patch(f"/api/v1/documents/{doc['id']}", json={"body": f"v{i}"}, headers=headers)
+ revisions = (await client.get(f"/api/v1/documents/{doc['id']}/revisions", headers=headers)).json()
+ assert len(revisions) == REVISION_LIMIT
+
+
+# ── delete ──────────────────────────────────────────────────────────────────
+
+
+async def test_deleting_a_folder_takes_its_subtree(client: AsyncClient, headers: dict):
+ outer = await _create(client, headers, title="Outer", kind="folder")
+ inner = await _create(client, headers, title="Inner", kind="folder", parent_id=outer["id"])
+ leaf = await _create(client, headers, title="Leaf", parent_id=inner["id"])
+
+ assert (await client.delete(f"/api/v1/documents/{outer['id']}", headers=headers)).status_code == 204
+ for doc_id in (outer["id"], inner["id"], leaf["id"]):
+ assert (await client.get(f"/api/v1/documents/{doc_id}", headers=headers)).status_code == 404
+
+
+async def test_deleting_a_missing_document_is_404(client: AsyncClient, headers: dict):
+ assert (await client.delete(f"/api/v1/documents/{uuid.uuid4()}", headers=headers)).status_code == 404
+
+
+async def test_a_deleted_document_leaves_the_search_index(client: AsyncClient, headers: dict):
+ doc = await _create(client, headers, title="Page", body="unmistakable")
+ await client.delete(f"/api/v1/documents/{doc['id']}", headers=headers)
+ hits = (await client.get("/api/v1/documents/search?q=unmistakable", headers=headers)).json()["hits"]
+ assert hits == []
+
+
+# ── the document outlives what it describes ─────────────────────────────────
+
+
+async def test_deleting_a_device_orphans_its_document_but_keeps_the_body(client: AsyncClient, headers: dict):
+ device = await _device(client, headers, notes="Holds the backups.")
+ doc = await _create(client, headers, title="nas-01", kind="device", device_id=device["id"])
+
+ assert (await client.delete(f"/api/v1/scan/pending/{device['id']}", headers=headers)).status_code == 200
+
+ after = (await client.get(f"/api/v1/documents/{doc['id']}", headers=headers)).json()
+ assert after["device_id"] is None
+ assert after["title"] == "nas-01"
+ assert "Holds the backups." in after["body"]
+
+
+async def test_deleting_a_node_orphans_the_document_describing_it(client: AsyncClient, headers: dict):
+ design_id = await _design(client, headers)
+ zone = await client.post(
+ "/api/v1/nodes",
+ json={"type": "groupRect", "label": "Garage", "design_id": design_id, "pos_x": 0, "pos_y": 0},
+ headers=headers,
+ )
+ doc = await _create(client, headers, title="Garage", kind="node", node_id=zone.json()["id"])
+
+ await client.delete(f"/api/v1/nodes/{zone.json()['id']}", headers=headers)
+
+ after = (await client.get(f"/api/v1/documents/{doc['id']}", headers=headers)).json()
+ assert after["node_id"] is None
+ assert after["title"] == "Garage"
+
+
+# ── search ──────────────────────────────────────────────────────────────────
+
+
+async def test_search_names_its_engine_and_returns_hits(client: AsyncClient, headers: dict):
+ await _create(client, headers, title="VLAN plan", body="Guest traffic is isolated.")
+ res = await client.get("/api/v1/documents/search?q=isolated", headers=headers)
+ assert res.status_code == 200, res.text
+ payload = res.json()
+ assert payload["engine"] in ("fts5", "like")
+ assert [h["title"] for h in payload["hits"]] == ["VLAN plan"]
+
+
+async def test_search_carries_the_device_link_so_a_hit_can_be_opened(client: AsyncClient, headers: dict):
+ device = await _device(client, headers)
+ await _create(client, headers, title="nas-01", kind="device", device_id=device["id"])
+ hits = (await client.get("/api/v1/documents/search?q=nas", headers=headers)).json()["hits"]
+ assert hits[0]["device_id"] == device["id"]
+
+
+async def test_search_rejects_a_silly_limit(client: AsyncClient, headers: dict):
+ assert (await client.get("/api/v1/documents/search?q=x&limit=0", headers=headers)).status_code == 422
+
+
+# ── scaffold and coverage ───────────────────────────────────────────────────
+
+
+async def test_scaffold_documents_every_device_that_has_none(client: AsyncClient, headers: dict):
+ await _device(client, headers, label="a", ip="10.0.0.1")
+ await _device(client, headers, label="b", ip="10.0.0.2")
+ res = await client.post("/api/v1/documents/scaffold", json={}, headers=headers)
+ assert res.status_code == 200, res.text
+ assert len(res.json()["created"]) == 2
+
+
+async def test_scaffold_is_repeatable_and_skips_what_exists(client: AsyncClient, headers: dict):
+ await _device(client, headers, label="a", ip="10.0.0.1")
+ await client.post("/api/v1/documents/scaffold", json={}, headers=headers)
+ again = (await client.post("/api/v1/documents/scaffold", json={}, headers=headers)).json()
+ assert again["created"] == []
+ assert again["skipped"] == 1
+
+
+async def test_scaffold_can_be_limited_to_devices_that_have_notes(client: AsyncClient, headers: dict):
+ await _device(client, headers, label="a", ip="10.0.0.1", notes="worth keeping")
+ await _device(client, headers, label="b", ip="10.0.0.2")
+ res = (
+ await client.post("/api/v1/documents/scaffold", json={"only_with_notes": True}, headers=headers)
+ ).json()
+ assert [d["title"] for d in res["created"]] == ["a"]
+ assert res["skipped"] == 1
+
+
+async def test_scaffold_can_be_limited_to_named_devices(client: AsyncClient, headers: dict):
+ first = await _device(client, headers, label="a", ip="10.0.0.1")
+ await _device(client, headers, label="b", ip="10.0.0.2")
+ res = (
+ await client.post("/api/v1/documents/scaffold", json={"device_ids": [first["id"]]}, headers=headers)
+ ).json()
+ assert [d["title"] for d in res["created"]] == ["a"]
+
+
+async def test_a_migrated_document_records_why_it_exists(client: AsyncClient, headers: dict):
+ device = await _device(client, headers, notes="worth keeping")
+ created = (
+ await client.post("/api/v1/documents/scaffold", json={}, headers=headers)
+ ).json()["created"][0]
+ revisions = (await client.get(f"/api/v1/documents/{created['id']}/revisions", headers=headers)).json()
+ assert revisions[0]["reason"] == "migrate"
+ assert device["id"]
+
+
+async def test_coverage_counts_what_is_missing_and_unmigrated(client: AsyncClient, headers: dict):
+ await _device(client, headers, label="a", ip="10.0.0.1", notes="notes here")
+ await _device(client, headers, label="b", ip="10.0.0.2")
+
+ before = (await client.get("/api/v1/documents/coverage", headers=headers)).json()
+ assert before["devices"] == 2
+ assert before["documented"] == 0
+ assert before["missing"] == 2
+ assert before["notes_unmigrated"] == 1
+
+ await client.post("/api/v1/documents/scaffold", json={}, headers=headers)
+ after = (await client.get("/api/v1/documents/coverage", headers=headers)).json()
+ assert after["documented"] == 2
+ assert after["missing"] == 0
+ assert after["notes_unmigrated"] == 0
+ # Generated and not yet touched.
+ assert after["header_only"] == 2
+
+
+async def test_coverage_reports_a_document_that_has_drifted(client: AsyncClient, headers: dict):
+ device = await _device(client, headers)
+ await _create(client, headers, title="nas", kind="device", device_id=device["id"])
+ assert (await client.get("/api/v1/documents/coverage", headers=headers)).json()["drifted"] == 0
+
+ await client.patch(f"/api/v1/scan/pending/{device['id']}", json={"ip": "192.168.1.99"}, headers=headers)
+ assert (await client.get("/api/v1/documents/coverage", headers=headers)).json()["drifted"] == 1
+
+
+async def test_coverage_stops_calling_a_document_header_only_once_it_is_edited(
+ client: AsyncClient, headers: dict
+):
+ device = await _device(client, headers)
+ doc = await _create(client, headers, title="nas", kind="device", device_id=device["id"])
+ await client.patch(f"/api/v1/documents/{doc['id']}", json={"body": "written by hand"}, headers=headers)
+ assert (await client.get("/api/v1/documents/coverage", headers=headers)).json()["header_only"] == 0
+
+
+async def test_coverage_counts_library_pages_separately(client: AsyncClient, headers: dict):
+ await _create(client, headers, title="VLAN plan")
+ await _create(client, headers, title="Runbooks", kind="folder")
+ assert (await client.get("/api/v1/documents/coverage", headers=headers)).json()["library_pages"] == 2
diff --git a/backend/tests/test_documents_migration.py b/backend/tests/test_documents_migration.py
new file mode 100644
index 0000000..c8d9f78
--- /dev/null
+++ b/backend/tests/test_documents_migration.py
@@ -0,0 +1,84 @@
+"""The documents DDL `create_all` cannot express.
+
+A virtual table and three partial indexes, applied through `_try_migrate` at
+boot. Both have to survive a second boot untouched, and the partial uniques are
+what stop two documents claiming the same device behind the route's own check.
+"""
+
+import pytest
+from sqlalchemy.exc import IntegrityError
+from sqlalchemy.ext.asyncio import create_async_engine
+
+from app.db.database import DOCUMENT_DDL, Base, _try_migrate
+
+pytestmark = pytest.mark.asyncio
+
+
+async def _boot(tmp_path, times: int = 1):
+ engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'test.db'}")
+ for _ in range(times):
+ async with engine.begin() as conn:
+ await conn.run_sync(Base.metadata.create_all)
+ for label, sql in DOCUMENT_DDL:
+ await _try_migrate(conn, sql, label=label)
+ return engine
+
+
+async def _names(engine, kind: str) -> set[str]:
+ async with engine.begin() as conn:
+ rows = (
+ await conn.exec_driver_sql(f"SELECT name FROM sqlite_master WHERE type = '{kind}'")
+ ).fetchall()
+ return {row[0] for row in rows}
+
+
+async def test_the_tables_and_the_search_index_are_created(tmp_path):
+ engine = await _boot(tmp_path)
+ tables = await _names(engine, "table")
+ assert {"documents", "document_revisions", "documents_fts"} <= tables
+ await engine.dispose()
+
+
+async def test_the_partial_uniques_are_created(tmp_path):
+ engine = await _boot(tmp_path)
+ indexes = await _names(engine, "index")
+ assert {"ux_documents_device", "ux_documents_node", "ux_documents_design"} <= indexes
+ await engine.dispose()
+
+
+async def test_a_second_boot_changes_nothing(tmp_path):
+ engine = await _boot(tmp_path, times=3)
+ tables = await _names(engine, "table")
+ assert {"documents", "documents_fts"} <= tables
+ await engine.dispose()
+
+
+async def test_two_documents_cannot_claim_the_same_device(tmp_path):
+ engine = await _boot(tmp_path)
+ async with engine.begin() as conn:
+ insert = (
+ "INSERT INTO documents (id, kind, title, slug, body, device_id, sort_order, "
+ "frontmatter, tags, starred, created_at, updated_at) "
+ "VALUES (?, 'device', 'nas', ?, '', 'dev-1', 0, '{}', '[]', 0, "
+ "'2026-09-05', '2026-09-05')"
+ )
+ await conn.exec_driver_sql(insert, ("a", "nas"))
+ with pytest.raises(IntegrityError):
+ await conn.exec_driver_sql(insert, ("b", "nas-2"))
+ await engine.dispose()
+
+
+async def test_many_documents_may_have_no_device(tmp_path):
+ engine = await _boot(tmp_path)
+ async with engine.begin() as conn:
+ insert = (
+ "INSERT INTO documents (id, kind, title, slug, body, device_id, sort_order, "
+ "frontmatter, tags, starred, created_at, updated_at) "
+ "VALUES (?, 'page', 'p', ?, '', NULL, 0, '{}', '[]', 0, "
+ "'2026-09-05', '2026-09-05')"
+ )
+ await conn.exec_driver_sql(insert, ("a", "p1"))
+ await conn.exec_driver_sql(insert, ("b", "p2"))
+ count = (await conn.exec_driver_sql("SELECT COUNT(*) FROM documents")).scalar_one()
+ assert count == 2
+ await engine.dispose()
diff --git a/docs/documentation.md b/docs/documentation.md
new file mode 100644
index 0000000..e188892
--- /dev/null
+++ b/docs/documentation.md
@@ -0,0 +1,191 @@
+# Documentation
+
+A markdown document per device, plus a free-form Library of pages and folders,
+behind the **Documentation** entry in the left sidebar.
+
+Before this, the only writing surface in Homelable was `device_inventory.notes`
+— one `TEXT` column rendered as plain text. This replaces it with something that
+can be structured, linked, searched and kept honest, without ever throwing the
+old notes away.
+
+---
+
+## The model
+
+Three tables. See `docs/database-model.md` for the columns.
+
+| Table | What |
+|---|---|
+| `documents` | One markdown document. Either a Library `page`/`folder`, or a `device` / `node` / `design` document describing exactly one thing. |
+| `document_revisions` | Prior bodies, pruned to the most recent 50 per document. |
+| `documents_fts` | The FTS5 search index. Optional — see *Search* below. |
+
+**A document attaches to the device, not to the node.** Since 3.3.0 a node draws
+a device and the facts live on `device_inventory`, so one device reads the same
+on every canvas it appears on.
+
+**Every link is `SET NULL` and the title is denormalized.** Deleting a device or
+a canvas never destroys what was written: the document survives as an orphan and
+can be re-linked or filed into the Library. Foreign keys are off in this SQLite
+setup, so the delete paths clear the columns by hand through
+`app/services/doc_links.py::unlink_documents` — `nodes`, `scan` and `designs`
+each call it before they delete.
+
+**A folder is a document** (`kind='folder'`). That is what allows an empty
+folder, and lets a folder carry an index body.
+
+**One document per target.** Enforced twice: a 409 in the route, and partial
+unique indexes created in `init_db` (`DOCUMENT_DDL` in `db/database.py` —
+`create_all` cannot express a partial index or a virtual table).
+
+---
+
+## The generated header
+
+`app/services/doc_template.py` scaffolds a device document from the live facts:
+addresses, hardware, one section per fingerprinted service, rack and zone
+placement, canvas neighbours, custom properties. Old `notes` are appended
+verbatim under `## Notes` behind an HTML-comment provenance marker.
+
+**It is generated once and then belongs to the user.** Nothing rewrites a body
+that already exists. Two things keep it from going stale silently:
+
+- `facts_snapshot` records the facts as they read at generation time, so the UI
+ can say *the device has changed* and list what.
+- `GET /api/v1/documents/blocks?block=…&device_id=…` renders any single block on
+ demand — that is what the editor's `/device`, `/services`, `/rack`… commands
+ insert. Regeneration is always one keystroke away, and never automatic.
+
+A section whose data is empty is still emitted, with an italic prompt: the
+document is a checklist of what has not been written yet. Sections that are
+structural rather than descriptive — the rack position of an unracked device —
+are dropped instead.
+
+Service URLs in a document follow `frontend/src/utils/serviceUrl.ts`, including
+its non-HTTP port denylist, so a link in a document is the link the canvas
+offers.
+
+---
+
+## The tree
+
+Two roots, with different natures.
+
+**Devices** is a pivot, rebuilt client-side in
+`frontend/src/documentation/tree.ts` from data the app already holds. Grouping
+by zone, group, type, physical/virtual, subnet, canvas, rack, vendor, discovery
+source, status, tag, or flat A–Z is instant and needs no server round trip.
+
+- Zone and group come from walking `parent_id` up to the nearest `groupRect` /
+ `group` node.
+- Subnet prefers a configured scanner range, else the address's own /24. A
+ device with several IPs appears under each subnet it reaches.
+- Physical / Virtual / Host is derived: `vm`/`lxc`/`docker_container` are
+ virtual, `proxmox`/`docker_host` and anything drawn as a container are hosts.
+- Canvas answers "on the loaded canvas or not" — the app only holds one at a
+ time.
+
+**Library** is the real folder tree, ordered by `sort_order` then title.
+
+Badges: `·` no document, `○` only the generated header, `●` written, `⚠` the
+device changed since, `⏰` past its `review_every`.
+
+---
+
+## Editing
+
+Markdown source on the left, live preview on the right. Source rather than a
+rich editor on purpose: the body is exported verbatim, so what is typed is what
+the file holds.
+
+**Saving is explicit** — Ctrl/Cmd+S or the Save button — matching the canvas
+rule that nothing persists on a timer. An unsaved body is mirrored to
+`localStorage` under `homelable_docdraft:<id>` on every keystroke and cleared on
+save. On reopening, a draft taken against the version being opened is *offered*;
+a draft taken against an older version is discarded, because replaying it would
+revert a change made elsewhere.
+
+`/` at the start of a line opens the insert menu: the generated blocks above,
+plus table, checklist, callout, wiki-link and date.
+
+---
+
+## Links between documents
+
+`[[device:nas-01]]`, `[[doc:vlan-plan]]`, `[[node:<id>]]`, or a bare
+`[[VLAN plan]]`; `[[…|label]]` sets the text. A device resolves by id or label,
+a document by id, slug, then title, all case-insensitively. An unresolved link
+renders red and offers to create the document.
+
+Parsed as a text pass over the rendered children (`wikilinks.ts` +
+`markdown/WikiText.tsx`) rather than as a remark plugin, so the file stays
+ordinary markdown for anything else that reads it.
+
+**Raw HTML is deliberately not rendered** — `rehype-raw` is absent — so a
+document cannot inject markup and no sanitiser is needed.
+
+---
+
+## Search
+
+`GET /api/v1/documents/search?q=` over title, tags and body.
+
+FTS5 is **not** assumed: the SQLite shipped in the LXC and Docker images may be
+built without it, the same reason `database.py` avoids JSON1. `doc_search.py`
+probes once and falls back to `LIKE`, and the response says which engine
+answered (`fts5` or `like`) so the UI can drop snippet highlighting. The index is
+maintained from Python on every write — no triggers — and `_reindex_documents_fts`
+catches up on boot after an upgrade or a restored backup.
+
+User input is never FTS5 syntax: `build_match_query` quotes every term, so an
+IP or a stray quote is data.
+
+---
+
+## Migrating the old notes
+
+Non-destructive and repeatable.
+
+1. `GET /api/v1/documents/coverage` reports `notes_unmigrated`.
+2. A banner offers to migrate.
+3. `POST /api/v1/documents/scaffold {"only_with_notes": true}` creates one
+ document per device, old notes appended verbatim, with a `migrate` revision.
+4. **`device_inventory.notes` is left exactly as it was.** It is still the
+ column the HACS integration, the YAML export, the MCP tools and the canvas
+ search read. Deprecating it is a separate decision.
+
+---
+
+## API
+
+| Method | Path |
+|---|---|
+| `GET` | `/api/v1/documents` — metadata only, filterable by `kind`, `parent_id`, `device_id`, `tag` |
+| `GET` | `/api/v1/documents/{id}` |
+| `POST` | `/api/v1/documents` |
+| `PATCH` | `/api/v1/documents/{id}` |
+| `DELETE` | `/api/v1/documents/{id}` — a folder takes its subtree |
+| `GET` | `/api/v1/documents/{id}/revisions`, `/revisions/{rev_id}` |
+| `POST` | `/api/v1/documents/{id}/revisions/{rev_id}/restore` |
+| `GET` | `/api/v1/documents/search?q=&limit=` |
+| `GET` | `/api/v1/documents/blocks?block=&device_id=` |
+| `GET` | `/api/v1/documents/coverage` |
+| `POST` | `/api/v1/documents/scaffold` |
+
+---
+
+## Standalone mode
+
+Documents are **full-mode only**. Standalone has no backend to store or search
+them, and the same reasoning as ADR-001 applies: the section is hidden in the
+sidebar and explains itself if reached directly, rather than being polyfilled
+into `localStorage` with no search and no history.
+
+---
+
+## Not built yet
+
+Export/import of the tree as `.md` files, a print/handbook view, an aggregated
+open-tasks view, image upload inside a document (would reuse
+`api/routes/media.py`, full-mode only), and the MCP tools — those are the
+planned second lot.
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index 8e86d55..f184b26 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -25,6 +25,9 @@
"next-themes": "^0.4.6",
"react": "^19.2.0",
"react-dom": "^19.2.0",
+ "react-markdown": "^10.1.0",
+ "rehype-slug": "^6.0.0",
+ "remark-gfm": "^4.0.1",
"sonner": "^2.0.7",
"tailwind-merge": "^3.5.0",
"tw-animate-css": "^1.4.0",
@@ -3481,6 +3484,15 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@types/debug": {
+ "version": "4.1.13",
+ "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.13.tgz",
+ "integrity": "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/ms": "*"
+ }
+ },
"node_modules/@types/deep-eql": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
@@ -3492,9 +3504,26 @@
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
"integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",
- "dev": true,
"license": "MIT"
},
+ "node_modules/@types/estree-jsx": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/@types/estree-jsx/-/estree-jsx-1.0.5.tgz",
+ "integrity": "sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "*"
+ }
+ },
+ "node_modules/@types/hast": {
+ "version": "3.0.5",
+ "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.5.tgz",
+ "integrity": "sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "*"
+ }
+ },
"node_modules/@types/js-yaml": {
"version": "4.0.9",
"resolved": "https://registry.npmjs.org/@types/js-yaml/-/js-yaml-4.0.9.tgz",
@@ -3508,6 +3537,21 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@types/mdast": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz",
+ "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "*"
+ }
+ },
+ "node_modules/@types/ms": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz",
+ "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",
+ "license": "MIT"
+ },
"node_modules/@types/node": {
"version": "24.12.2",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.12.2.tgz",
@@ -3522,7 +3566,6 @@
"version": "19.2.14",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz",
"integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==",
- "devOptional": true,
"license": "MIT",
"dependencies": {
"csstype": "^3.2.2"
@@ -3545,6 +3588,12 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@types/unist": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz",
+ "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==",
+ "license": "MIT"
+ },
"node_modules/@types/validate-npm-package-name": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@types/validate-npm-package-name/-/validate-npm-package-name-4.0.2.tgz",
@@ -3847,6 +3896,12 @@
"url": "https://opencollective.com/eslint"
}
},
+ "node_modules/@ungap/structured-clone": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.4.0.tgz",
+ "integrity": "sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ==",
+ "license": "ISC"
+ },
"node_modules/@vitejs/plugin-react": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-5.2.0.tgz",
@@ -4332,6 +4387,16 @@
"node": ">= 6"
}
},
+ "node_modules/bail": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/bail/-/bail-2.0.2.tgz",
+ "integrity": "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/balanced-match": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
@@ -4546,6 +4611,16 @@
],
"license": "CC-BY-4.0"
},
+ "node_modules/ccount": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz",
+ "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/chai": {
"version": "6.2.2",
"resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz",
@@ -4573,6 +4648,46 @@
"url": "https://github.com/chalk/chalk?sponsor=1"
}
},
+ "node_modules/character-entities": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz",
+ "integrity": "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/character-entities-html4": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz",
+ "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/character-entities-legacy": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz",
+ "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/character-reference-invalid": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/character-reference-invalid/-/character-reference-invalid-2.0.1.tgz",
+ "integrity": "sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/class-variance-authority": {
"version": "0.7.1",
"resolved": "https://registry.npmjs.org/class-variance-authority/-/class-variance-authority-0.7.1.tgz",
@@ -4746,6 +4861,16 @@
"node": ">= 0.8"
}
},
+ "node_modules/comma-separated-tokens": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz",
+ "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/commander": {
"version": "14.0.3",
"resolved": "https://registry.npmjs.org/commander/-/commander-14.0.3.tgz",
@@ -4938,7 +5063,6 @@
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
- "devOptional": true,
"license": "MIT"
},
"node_modules/d3-color": {
@@ -5104,6 +5228,19 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/decode-named-character-reference": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz",
+ "integrity": "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==",
+ "license": "MIT",
+ "dependencies": {
+ "character-entities": "^2.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/dedent": {
"version": "1.7.2",
"resolved": "https://registry.npmjs.org/dedent/-/dedent-1.7.2.tgz",
@@ -5202,7 +5339,6 @@
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",
"integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
@@ -5218,6 +5354,19 @@
"node": ">=8"
}
},
+ "node_modules/devlop": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz",
+ "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==",
+ "license": "MIT",
+ "dependencies": {
+ "dequal": "^2.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/diff": {
"version": "8.0.4",
"resolved": "https://registry.npmjs.org/diff/-/diff-8.0.4.tgz",
@@ -5671,6 +5820,16 @@
"node": ">=4.0"
}
},
+ "node_modules/estree-util-is-identifier-name": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/estree-util-is-identifier-name/-/estree-util-is-identifier-name-3.0.0.tgz",
+ "integrity": "sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg==",
+ "license": "MIT",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/estree-walker": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
@@ -5851,6 +6010,12 @@
"url": "https://opencollective.com/express"
}
},
+ "node_modules/extend": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",
+ "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
+ "license": "MIT"
+ },
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
@@ -6288,6 +6453,12 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/github-slugger": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/github-slugger/-/github-slugger-2.0.0.tgz",
+ "integrity": "sha512-IaOQ9puYtjrkq7Y0Ygl9KDZnrf/aiUJYUpVf89y8kyaxbRG7Y1SrX/jaumrv81vc61+kiMempujsM3Yw7w5qcw==",
+ "license": "ISC"
+ },
"node_modules/glob-parent": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz",
@@ -6401,6 +6572,72 @@
"node": ">= 0.4"
}
},
+ "node_modules/hast-util-heading-rank": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/hast-util-heading-rank/-/hast-util-heading-rank-3.0.0.tgz",
+ "integrity": "sha512-EJKb8oMUXVHcWZTDepnr+WNbfnXKFNf9duMesmr4S8SXTJBJ9M4Yok08pu9vxdJwdlGRhVumk9mEhkEvKGifwA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hast-util-to-jsx-runtime": {
+ "version": "2.3.6",
+ "resolved": "https://registry.npmjs.org/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.6.tgz",
+ "integrity": "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "^1.0.0",
+ "@types/hast": "^3.0.0",
+ "@types/unist": "^3.0.0",
+ "comma-separated-tokens": "^2.0.0",
+ "devlop": "^1.0.0",
+ "estree-util-is-identifier-name": "^3.0.0",
+ "hast-util-whitespace": "^3.0.0",
+ "mdast-util-mdx-expression": "^2.0.0",
+ "mdast-util-mdx-jsx": "^3.0.0",
+ "mdast-util-mdxjs-esm": "^2.0.0",
+ "property-information": "^7.0.0",
+ "space-separated-tokens": "^2.0.0",
+ "style-to-js": "^1.0.0",
+ "unist-util-position": "^5.0.0",
+ "vfile-message": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hast-util-to-string": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/hast-util-to-string/-/hast-util-to-string-3.0.1.tgz",
+ "integrity": "sha512-XelQVTDWvqcl3axRfI0xSeoVKzyIFPwsAGSLIsKdJKQMXDYJS4WYrBNF/8J7RdhIcFI2BOHgAifggsvsxp/3+A==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hast-util-whitespace": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz",
+ "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/headers-polyfill": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/headers-polyfill/-/headers-polyfill-4.0.3.tgz",
@@ -6461,6 +6698,16 @@
"integrity": "sha512-cuOPoI7WApyhBElTTb9oqsawRvZ0rHhaHwghRLlTuffoD1B2aDemlCruLeZrUIIdvG7gs9xeELEPm6PhuASqrg==",
"license": "MIT"
},
+ "node_modules/html-url-attributes": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/html-url-attributes/-/html-url-attributes-3.0.1.tgz",
+ "integrity": "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/http-errors": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
@@ -6591,6 +6838,12 @@
"dev": true,
"license": "ISC"
},
+ "node_modules/inline-style-parser": {
+ "version": "0.2.7",
+ "resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.7.tgz",
+ "integrity": "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==",
+ "license": "MIT"
+ },
"node_modules/ip-address": {
"version": "10.5.0",
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.5.0.tgz",
@@ -6611,6 +6864,30 @@
"node": ">= 0.10"
}
},
+ "node_modules/is-alphabetical": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.1.tgz",
+ "integrity": "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/is-alphanumerical": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-2.0.1.tgz",
+ "integrity": "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==",
+ "license": "MIT",
+ "dependencies": {
+ "is-alphabetical": "^2.0.0",
+ "is-decimal": "^2.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/is-arrayish": {
"version": "0.2.1",
"resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz",
@@ -6618,6 +6895,16 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/is-decimal": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-2.0.1.tgz",
+ "integrity": "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/is-docker": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/is-docker/-/is-docker-3.0.0.tgz",
@@ -6667,6 +6954,16 @@
"node": ">=0.10.0"
}
},
+ "node_modules/is-hexadecimal": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/is-hexadecimal/-/is-hexadecimal-2.0.1.tgz",
+ "integrity": "sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/is-in-ssh": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/is-in-ssh/-/is-in-ssh-1.0.0.tgz",
@@ -6746,7 +7043,6 @@
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz",
"integrity": "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
@@ -7408,6 +7704,16 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/longest-streak": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-3.1.0.tgz",
+ "integrity": "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/lru-cache": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
@@ -7490,6 +7796,16 @@
"node": ">=10"
}
},
+ "node_modules/markdown-table": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/markdown-table/-/markdown-table-3.0.4.tgz",
+ "integrity": "sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
@@ -7499,88 +7815,933 @@
"node": ">= 0.4"
}
},
- "node_modules/mdn-data": {
- "version": "2.27.1",
- "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz",
- "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==",
- "dev": true,
- "license": "CC0-1.0"
- },
- "node_modules/media-typer": {
- "version": "1.1.0",
- "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz",
- "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==",
- "dev": true,
+ "node_modules/mdast-util-find-and-replace": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/mdast-util-find-and-replace/-/mdast-util-find-and-replace-3.0.2.tgz",
+ "integrity": "sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg==",
"license": "MIT",
- "engines": {
- "node": ">= 0.8"
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "escape-string-regexp": "^5.0.0",
+ "unist-util-is": "^6.0.0",
+ "unist-util-visit-parents": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
}
},
- "node_modules/merge-descriptors": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",
- "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",
- "dev": true,
+ "node_modules/mdast-util-find-and-replace/node_modules/escape-string-regexp": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz",
+ "integrity": "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==",
"license": "MIT",
"engines": {
- "node": ">=18"
+ "node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
- "node_modules/merge-stream": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",
- "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==",
- "dev": true,
- "license": "MIT"
- },
- "node_modules/merge2": {
- "version": "1.4.1",
- "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",
- "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==",
- "dev": true,
+ "node_modules/mdast-util-from-markdown": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-2.0.3.tgz",
+ "integrity": "sha512-W4mAWTvSlKvf8L6J+VN9yLSqQ9AOAAvHuoDAmPkz4dHf553m5gVj2ejadHJhoJmcmxEnOv6Pa8XJhpxE93kb8Q==",
"license": "MIT",
- "engines": {
- "node": ">= 8"
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "@types/unist": "^3.0.0",
+ "decode-named-character-reference": "^1.0.0",
+ "devlop": "^1.0.0",
+ "mdast-util-to-string": "^4.0.0",
+ "micromark": "^4.0.0",
+ "micromark-util-decode-numeric-character-reference": "^2.0.0",
+ "micromark-util-decode-string": "^2.0.0",
+ "micromark-util-normalize-identifier": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0",
+ "unist-util-stringify-position": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
}
},
- "node_modules/micromatch": {
- "version": "4.0.8",
- "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
- "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
- "dev": true,
+ "node_modules/mdast-util-gfm": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-gfm/-/mdast-util-gfm-3.1.0.tgz",
+ "integrity": "sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ==",
"license": "MIT",
"dependencies": {
- "braces": "^3.0.3",
- "picomatch": "^2.3.1"
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-gfm-autolink-literal": "^2.0.0",
+ "mdast-util-gfm-footnote": "^2.0.0",
+ "mdast-util-gfm-strikethrough": "^2.0.0",
+ "mdast-util-gfm-table": "^2.0.0",
+ "mdast-util-gfm-task-list-item": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0"
},
- "engines": {
- "node": ">=8.6"
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
}
},
- "node_modules/micromatch/node_modules/picomatch": {
- "version": "2.3.2",
- "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz",
- "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",
- "dev": true,
+ "node_modules/mdast-util-gfm-autolink-literal": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-autolink-literal/-/mdast-util-gfm-autolink-literal-2.0.1.tgz",
+ "integrity": "sha512-5HVP2MKaP6L+G6YaxPNjuL0BPrq9orG3TsrZ9YXbA3vDw/ACI4MEsnoDpn6ZNm7GnZgtAcONJyPhOP8tNJQavQ==",
"license": "MIT",
- "engines": {
- "node": ">=8.6"
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "ccount": "^2.0.0",
+ "devlop": "^1.0.0",
+ "mdast-util-find-and-replace": "^3.0.0",
+ "micromark-util-character": "^2.0.0"
},
"funding": {
- "url": "https://github.com/sponsors/jonschlinkert"
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
}
},
- "node_modules/mime-db": {
- "version": "1.52.0",
- "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
- "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
+ "node_modules/mdast-util-gfm-footnote": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-footnote/-/mdast-util-gfm-footnote-2.1.0.tgz",
+ "integrity": "sha512-sqpDWlsHn7Ac9GNZQMeUzPQSMzR6Wv0WKRNvQRg0KqHh02fpTz69Qc1QSseNX29bhz1ROIyNyxExfawVKTm1GQ==",
"license": "MIT",
- "engines": {
- "node": ">= 0.6"
- }
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.1.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0",
+ "micromark-util-normalize-identifier": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-gfm-strikethrough": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-strikethrough/-/mdast-util-gfm-strikethrough-2.0.0.tgz",
+ "integrity": "sha512-mKKb915TF+OC5ptj5bJ7WFRPdYtuHv0yTRxK2tJvi+BDqbkiG7h7u/9SI89nRAYcmap2xHQL9D+QG/6wSrTtXg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-gfm-table": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-table/-/mdast-util-gfm-table-2.0.0.tgz",
+ "integrity": "sha512-78UEvebzz/rJIxLvE7ZtDd/vIQ0RHv+3Mh5DR96p7cS7HsBhYIICDBCu8csTNWNO6tBWfqXPWekRuj2FNOGOZg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.0.0",
+ "markdown-table": "^3.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-gfm-task-list-item": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-task-list-item/-/mdast-util-gfm-task-list-item-2.0.0.tgz",
+ "integrity": "sha512-IrtvNvjxC1o06taBAVJznEnkiHxLFTzgonUdy8hzFVeDun0uTjxxrRGVaNFqkU1wJR3RBPEfsxmU6jDWPofrTQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-mdx-expression": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/mdast-util-mdx-expression/-/mdast-util-mdx-expression-2.0.1.tgz",
+ "integrity": "sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree-jsx": "^1.0.0",
+ "@types/hast": "^3.0.0",
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-mdx-jsx": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-mdx-jsx/-/mdast-util-mdx-jsx-3.2.0.tgz",
+ "integrity": "sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree-jsx": "^1.0.0",
+ "@types/hast": "^3.0.0",
+ "@types/mdast": "^4.0.0",
+ "@types/unist": "^3.0.0",
+ "ccount": "^2.0.0",
+ "devlop": "^1.1.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0",
+ "parse-entities": "^4.0.0",
+ "stringify-entities": "^4.0.0",
+ "unist-util-stringify-position": "^4.0.0",
+ "vfile-message": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-mdxjs-esm": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/mdast-util-mdxjs-esm/-/mdast-util-mdxjs-esm-2.0.1.tgz",
+ "integrity": "sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree-jsx": "^1.0.0",
+ "@types/hast": "^3.0.0",
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-phrasing": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-phrasing/-/mdast-util-phrasing-4.1.0.tgz",
+ "integrity": "sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "unist-util-is": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-to-hast": {
+ "version": "13.2.1",
+ "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.1.tgz",
+ "integrity": "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "@types/mdast": "^4.0.0",
+ "@ungap/structured-clone": "^1.0.0",
+ "devlop": "^1.0.0",
+ "micromark-util-sanitize-uri": "^2.0.0",
+ "trim-lines": "^3.0.0",
+ "unist-util-position": "^5.0.0",
+ "unist-util-visit": "^5.0.0",
+ "vfile": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-to-markdown": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/mdast-util-to-markdown/-/mdast-util-to-markdown-2.1.2.tgz",
+ "integrity": "sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "@types/unist": "^3.0.0",
+ "longest-streak": "^3.0.0",
+ "mdast-util-phrasing": "^4.0.0",
+ "mdast-util-to-string": "^4.0.0",
+ "micromark-util-classify-character": "^2.0.0",
+ "micromark-util-decode-string": "^2.0.0",
+ "unist-util-visit": "^5.0.0",
+ "zwitch": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-to-string": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-to-string/-/mdast-util-to-string-4.0.0.tgz",
+ "integrity": "sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdn-data": {
+ "version": "2.27.1",
+ "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz",
+ "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==",
+ "dev": true,
+ "license": "CC0-1.0"
+ },
+ "node_modules/media-typer": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz",
+ "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/merge-descriptors": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",
+ "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/merge-stream": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",
+ "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/merge2": {
+ "version": "1.4.1",
+ "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",
+ "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/micromark": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.2.tgz",
+ "integrity": "sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@types/debug": "^4.0.0",
+ "debug": "^4.0.0",
+ "decode-named-character-reference": "^1.0.0",
+ "devlop": "^1.0.0",
+ "micromark-core-commonmark": "^2.0.0",
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-chunked": "^2.0.0",
+ "micromark-util-combine-extensions": "^2.0.0",
+ "micromark-util-decode-numeric-character-reference": "^2.0.0",
+ "micromark-util-encode": "^2.0.0",
+ "micromark-util-normalize-identifier": "^2.0.0",
+ "micromark-util-resolve-all": "^2.0.0",
+ "micromark-util-sanitize-uri": "^2.0.0",
+ "micromark-util-subtokenize": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-core-commonmark": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-2.0.3.tgz",
+ "integrity": "sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "decode-named-character-reference": "^1.0.0",
+ "devlop": "^1.0.0",
+ "micromark-factory-destination": "^2.0.0",
+ "micromark-factory-label": "^2.0.0",
+ "micromark-factory-space": "^2.0.0",
+ "micromark-factory-title": "^2.0.0",
+ "micromark-factory-whitespace": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-chunked": "^2.0.0",
+ "micromark-util-classify-character": "^2.0.0",
+ "micromark-util-html-tag-name": "^2.0.0",
+ "micromark-util-normalize-identifier": "^2.0.0",
+ "micromark-util-resolve-all": "^2.0.0",
+ "micromark-util-subtokenize": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-extension-gfm": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm/-/micromark-extension-gfm-3.0.0.tgz",
+ "integrity": "sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w==",
+ "license": "MIT",
+ "dependencies": {
+ "micromark-extension-gfm-autolink-literal": "^2.0.0",
+ "micromark-extension-gfm-footnote": "^2.0.0",
+ "micromark-extension-gfm-strikethrough": "^2.0.0",
+ "micromark-extension-gfm-table": "^2.0.0",
+ "micromark-extension-gfm-tagfilter": "^2.0.0",
+ "micromark-extension-gfm-task-list-item": "^2.0.0",
+ "micromark-util-combine-extensions": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-autolink-literal": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-autolink-literal/-/micromark-extension-gfm-autolink-literal-2.1.0.tgz",
+ "integrity": "sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==",
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-sanitize-uri": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-footnote": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-footnote/-/micromark-extension-gfm-footnote-2.1.0.tgz",
+ "integrity": "sha512-/yPhxI1ntnDNsiHtzLKYnE3vf9JZ6cAisqVDauhp4CEHxlb4uoOTxOCJ+9s51bIB8U1N1FJ1RXOKTIlD5B/gqw==",
+ "license": "MIT",
+ "dependencies": {
+ "devlop": "^1.0.0",
+ "micromark-core-commonmark": "^2.0.0",
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-normalize-identifier": "^2.0.0",
+ "micromark-util-sanitize-uri": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-strikethrough": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-strikethrough/-/micromark-extension-gfm-strikethrough-2.1.0.tgz",
+ "integrity": "sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw==",
+ "license": "MIT",
+ "dependencies": {
+ "devlop": "^1.0.0",
+ "micromark-util-chunked": "^2.0.0",
+ "micromark-util-classify-character": "^2.0.0",
+ "micromark-util-resolve-all": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-table": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-table/-/micromark-extension-gfm-table-2.1.1.tgz",
+ "integrity": "sha512-t2OU/dXXioARrC6yWfJ4hqB7rct14e8f7m0cbI5hUmDyyIlwv5vEtooptH8INkbLzOatzKuVbQmAYcbWoyz6Dg==",
+ "license": "MIT",
+ "dependencies": {
+ "devlop": "^1.0.0",
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-tagfilter": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-tagfilter/-/micromark-extension-gfm-tagfilter-2.0.0.tgz",
+ "integrity": "sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg==",
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-task-list-item": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-task-list-item/-/micromark-extension-gfm-task-list-item-2.1.0.tgz",
+ "integrity": "sha512-qIBZhqxqI6fjLDYFTBIa4eivDMnP+OZqsNwmQ3xNLE4Cxwc+zfQEfbs6tzAo2Hjq+bh6q5F+Z8/cksrLFYWQQw==",
+ "license": "MIT",
+ "dependencies": {
+ "devlop": "^1.0.0",
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-factory-destination": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-factory-destination/-/micromark-factory-destination-2.0.1.tgz",
+ "integrity": "sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-factory-label": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-factory-label/-/micromark-factory-label-2.0.1.tgz",
+ "integrity": "sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "devlop": "^1.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-factory-space": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-factory-space/-/micromark-factory-space-2.0.1.tgz",
+ "integrity": "sha512-zRkxjtBxxLd2Sc0d+fbnEunsTj46SWXgXciZmHq0kDYGnck/ZSGj9/wULTV95uoeYiK5hRXP2mJ98Uo4cq/LQg==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-factory-title": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-factory-title/-/micromark-factory-title-2.0.1.tgz",
+ "integrity": "sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-factory-whitespace": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-factory-whitespace/-/micromark-factory-whitespace-2.0.1.tgz",
+ "integrity": "sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-character": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz",
+ "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-chunked": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-chunked/-/micromark-util-chunked-2.0.1.tgz",
+ "integrity": "sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-symbol": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-classify-character": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-classify-character/-/micromark-util-classify-character-2.0.1.tgz",
+ "integrity": "sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-combine-extensions": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-combine-extensions/-/micromark-util-combine-extensions-2.0.1.tgz",
+ "integrity": "sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-chunked": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-decode-numeric-character-reference": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/micromark-util-decode-numeric-character-reference/-/micromark-util-decode-numeric-character-reference-2.0.2.tgz",
+ "integrity": "sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-symbol": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-decode-string": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-decode-string/-/micromark-util-decode-string-2.0.1.tgz",
+ "integrity": "sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "decode-named-character-reference": "^1.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-decode-numeric-character-reference": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-encode": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz",
+ "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/micromark-util-html-tag-name": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-html-tag-name/-/micromark-util-html-tag-name-2.0.1.tgz",
+ "integrity": "sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/micromark-util-normalize-identifier": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-normalize-identifier/-/micromark-util-normalize-identifier-2.0.1.tgz",
+ "integrity": "sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-symbol": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-resolve-all": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-resolve-all/-/micromark-util-resolve-all-2.0.1.tgz",
+ "integrity": "sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-sanitize-uri": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz",
+ "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-encode": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-subtokenize": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/micromark-util-subtokenize/-/micromark-util-subtokenize-2.1.0.tgz",
+ "integrity": "sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "devlop": "^1.0.0",
+ "micromark-util-chunked": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-symbol": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz",
+ "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/micromark-util-types": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.2.tgz",
+ "integrity": "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/micromatch": {
+ "version": "4.0.8",
+ "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
+ "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "braces": "^3.0.3",
+ "picomatch": "^2.3.1"
+ },
+ "engines": {
+ "node": ">=8.6"
+ }
+ },
+ "node_modules/micromatch/node_modules/picomatch": {
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz",
+ "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/mime-db": {
+ "version": "1.52.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
},
"node_modules/mime-types": {
"version": "2.1.35",
@@ -8062,6 +9223,31 @@
"node": ">=6"
}
},
+ "node_modules/parse-entities": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/parse-entities/-/parse-entities-4.0.2.tgz",
+ "integrity": "sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^2.0.0",
+ "character-entities-legacy": "^3.0.0",
+ "character-reference-invalid": "^2.0.0",
+ "decode-named-character-reference": "^1.0.0",
+ "is-alphanumerical": "^2.0.0",
+ "is-decimal": "^2.0.0",
+ "is-hexadecimal": "^2.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/parse-entities/node_modules/@types/unist": {
+ "version": "2.0.11",
+ "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.11.tgz",
+ "integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==",
+ "license": "MIT"
+ },
"node_modules/parse-json": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz",
@@ -8324,6 +9510,16 @@
"node": ">=6"
}
},
+ "node_modules/property-information": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.2.0.tgz",
+ "integrity": "sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/proxy-addr": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
@@ -8450,6 +9646,33 @@
"license": "MIT",
"peer": true
},
+ "node_modules/react-markdown": {
+ "version": "10.1.0",
+ "resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-10.1.0.tgz",
+ "integrity": "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.0.0",
+ "hast-util-to-jsx-runtime": "^2.0.0",
+ "html-url-attributes": "^3.0.0",
+ "mdast-util-to-hast": "^13.0.0",
+ "remark-parse": "^11.0.0",
+ "remark-rehype": "^11.0.0",
+ "unified": "^11.0.0",
+ "unist-util-visit": "^5.0.0",
+ "vfile": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ },
+ "peerDependencies": {
+ "@types/react": ">=18",
+ "react": ">=18"
+ }
+ },
"node_modules/react-refresh": {
"version": "0.18.0",
"resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.18.0.tgz",
@@ -8491,6 +9714,89 @@
"node": ">=8"
}
},
+ "node_modules/rehype-slug": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/rehype-slug/-/rehype-slug-6.0.0.tgz",
+ "integrity": "sha512-lWyvf/jwu+oS5+hL5eClVd3hNdmwM1kAC0BUvEGD19pajQMIzcNUd/k9GsfQ+FfECvX+JE+e9/btsKH0EjJT6A==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "github-slugger": "^2.0.0",
+ "hast-util-heading-rank": "^3.0.0",
+ "hast-util-to-string": "^3.0.0",
+ "unist-util-visit": "^5.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/remark-gfm": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/remark-gfm/-/remark-gfm-4.0.1.tgz",
+ "integrity": "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "mdast-util-gfm": "^3.0.0",
+ "micromark-extension-gfm": "^3.0.0",
+ "remark-parse": "^11.0.0",
+ "remark-stringify": "^11.0.0",
+ "unified": "^11.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/remark-parse": {
+ "version": "11.0.0",
+ "resolved": "https://registry.npmjs.org/remark-parse/-/remark-parse-11.0.0.tgz",
+ "integrity": "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "micromark-util-types": "^2.0.0",
+ "unified": "^11.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/remark-rehype": {
+ "version": "11.1.2",
+ "resolved": "https://registry.npmjs.org/remark-rehype/-/remark-rehype-11.1.2.tgz",
+ "integrity": "sha512-Dh7l57ianaEoIpzbp0PC9UKAdCSVklD8E5Rpw7ETfbTl3FqcOOgq5q2LVDhgGCkaBv7p24JXikPdvhhmHvKMsw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "@types/mdast": "^4.0.0",
+ "mdast-util-to-hast": "^13.0.0",
+ "unified": "^11.0.0",
+ "vfile": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/remark-stringify": {
+ "version": "11.0.0",
+ "resolved": "https://registry.npmjs.org/remark-stringify/-/remark-stringify-11.0.0.tgz",
+ "integrity": "sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "mdast-util-to-markdown": "^2.0.0",
+ "unified": "^11.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/require-directory": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
@@ -9001,6 +10307,16 @@
"node": ">=0.10.0"
}
},
+ "node_modules/space-separated-tokens": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz",
+ "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/stackback": {
"version": "0.0.2",
"resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
@@ -9063,6 +10379,20 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/stringify-entities": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz",
+ "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==",
+ "license": "MIT",
+ "dependencies": {
+ "character-entities-html4": "^2.0.0",
+ "character-entities-legacy": "^3.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/stringify-object": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/stringify-object/-/stringify-object-5.0.0.tgz",
@@ -9159,6 +10489,24 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/style-to-js": {
+ "version": "1.1.21",
+ "resolved": "https://registry.npmjs.org/style-to-js/-/style-to-js-1.1.21.tgz",
+ "integrity": "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ==",
+ "license": "MIT",
+ "dependencies": {
+ "style-to-object": "1.0.14"
+ }
+ },
+ "node_modules/style-to-object": {
+ "version": "1.0.14",
+ "resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-1.0.14.tgz",
+ "integrity": "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw==",
+ "license": "MIT",
+ "dependencies": {
+ "inline-style-parser": "0.2.7"
+ }
+ },
"node_modules/supports-color": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
@@ -9349,6 +10697,26 @@
"node": ">=20"
}
},
+ "node_modules/trim-lines": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz",
+ "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/trough": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/trough/-/trough-2.2.0.tgz",
+ "integrity": "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/ts-api-utils": {
"version": "2.5.0",
"resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz",
@@ -9561,6 +10929,93 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/unified": {
+ "version": "11.0.5",
+ "resolved": "https://registry.npmjs.org/unified/-/unified-11.0.5.tgz",
+ "integrity": "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "bail": "^2.0.0",
+ "devlop": "^1.0.0",
+ "extend": "^3.0.0",
+ "is-plain-obj": "^4.0.0",
+ "trough": "^2.0.0",
+ "vfile": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/unist-util-is": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.1.tgz",
+ "integrity": "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/unist-util-position": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-5.0.0.tgz",
+ "integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/unist-util-stringify-position": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz",
+ "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/unist-util-visit": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.1.0.tgz",
+ "integrity": "sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "unist-util-is": "^6.0.0",
+ "unist-util-visit-parents": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/unist-util-visit-parents": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz",
+ "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "unist-util-is": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/universalify": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
@@ -9668,6 +11123,34 @@
"node": ">= 0.8"
}
},
+ "node_modules/vfile": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz",
+ "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "vfile-message": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/vfile-message": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.3.tgz",
+ "integrity": "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "unist-util-stringify-position": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/vite": {
"version": "7.3.5",
"resolved": "https://registry.npmjs.org/vite/-/vite-7.3.5.tgz",
@@ -10214,6 +11697,16 @@
"optional": true
}
}
+ },
+ "node_modules/zwitch": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz",
+ "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
}
}
}
diff --git a/frontend/package.json b/frontend/package.json
index 09ef6de..1df47e8 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -31,6 +31,9 @@
"next-themes": "^0.4.6",
"react": "^19.2.0",
"react-dom": "^19.2.0",
+ "react-markdown": "^10.1.0",
+ "rehype-slug": "^6.0.0",
+ "remark-gfm": "^4.0.1",
"sonner": "^2.0.7",
"tailwind-merge": "^3.5.0",
"tw-animate-css": "^1.4.0",
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 20a4def..929916d 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useCallback, useMemo, useRef, useState } from 'react'
+import { useEffect, useCallback, useMemo, useRef, useState, lazy, Suspense } from 'react'
import { ReactFlowProvider, type Connection, type Edge } from '@xyflow/react'
import { type Node } from '@xyflow/react'
import { applyDagreLayout } from '@/utils/layout'
@@ -8,7 +8,7 @@ import { getCenteredPosition } from '@/utils/viewportCenter'
import { resolveVirtualEdgeParent } from '@/utils/virtualEdgeParent'
import { generateMarkdownTable } from '@/utils/exportMarkdown'
import { copyToClipboard } from '@/utils/clipboard'
-import { getDesignIdFromUrl, setDesignIdInUrl } from '@/utils/designUrl'
+import { getDesignIdFromUrl, setDesignIdInUrl, getDocIdFromUrl, isDocsViewInUrl, setDocsViewInUrl } from '@/utils/designUrl'
import { withBase } from '@/utils/basePath'
import { ExportModal } from '@/components/modals/ExportModal'
import { exportCanvasToYaml, downloadYaml } from '@/utils/exportYaml'
@@ -54,6 +54,13 @@ import { WalkthroughOverlay } from '@/walkthrough/WalkthroughOverlay'
import { DEMO_SCAN_RUNS, DEMO_INVENTORY_DEVICES } from '@/walkthrough/demoTourData'
import { useStatusPolling } from '@/hooks/useStatusPolling'
import { bootstrapAuth } from '@/auth/bootstrap'
+// Code-split: the Documentation section pulls in the markdown renderer, which a
+// user who never leaves the canvas should not pay for on first load.
+const DocumentationView = lazy(async () => ({
+ default: (await import('@/documentation/components/DocumentationView')).DocumentationView,
+}))
+import { useDocsStore } from '@/documentation/store'
+import { useUiStore } from '@/stores/uiStore'
import { RackCanvas } from '@/rack/components/RackCanvas'
import { RackCablePanel } from '@/rack/components/RackCablePanel'
import { useRackStore } from '@/rack/store'
@@ -73,6 +80,9 @@ export default function App() {
const authBootstrapStarted = useRef(false)
const { activeTheme, setTheme, customStyle, setCustomStyle } = useThemeStore()
const { activeDesignId, activeDesignType, setDesigns, setActiveDesign } = useDesignStore()
+ const appView = useUiStore((s) => s.view)
+ const setAppView = useUiStore((s) => s.setView)
+ const openDocId = useDocsStore((s) => s.openDoc?.id ?? null)
const isRackDesign = activeDesignType === 'rack'
const rackDirty = useRackStore((s) => s.hasUnsavedChanges)
const rackEditSeq = useRackStore((s) => s.editSeq)
@@ -478,6 +488,21 @@ export default function App() {
if (activeDesignId) setDesignIdInUrl(activeDesignId)
}, [activeDesignId])
+ // A document is linkable in the same way: `?view=docs&doc=<id>`.
+ useEffect(() => {
+ setDocsViewInUrl(appView === 'documentation', openDocId)
+ }, [appView, openDocId])
+
+ // Reopen the section, and the document, the URL asks for. Once, on boot.
+ const docsUrlApplied = useRef(false)
+ useEffect(() => {
+ if (docsUrlApplied.current || STANDALONE || !isDocsViewInUrl()) return
+ docsUrlApplied.current = true
+ setAppView('documentation')
+ const docId = getDocIdFromUrl()
+ if (docId) void useDocsStore.getState().open(docId)
+ }, [setAppView])
+
// Keep refs for store actions so keydown handler is always up-to-date without re-registering
const undoRef = useRef(undo)
const redoRef = useRef(redo)
@@ -1114,6 +1139,14 @@ export default function App() {
</button>
</div>
)}
+ {appView === 'documentation' ? (
+ <Suspense
+ fallback={<div className="flex flex-1 items-center justify-center text-xs text-muted-foreground">Loading documentation…</div>}
+ >
+ <DocumentationView />
+ </Suspense>
+ ) : (
+ <>
<Toolbar
onSave={handleSave}
onAutoLayout={handleAutoLayout}
@@ -1158,6 +1191,8 @@ export default function App() {
/>
)}
</div>
+ </>
+ )}
</div>
</div>
diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts
index 9da093f..89f4f05 100644
--- a/frontend/src/api/client.ts
+++ b/frontend/src/api/client.ts
@@ -301,6 +301,58 @@ export const designsApi = {
delete: (id: string) => api.delete(`/designs/${id}`),
}
+export const documentsApi = {
+ list: (params?: { kind?: string; parent_id?: string; device_id?: string; tag?: string }) =>
+ api.get<import('@/documentation/types').DocumentSummary[]>('/documents', { params }),
+ get: (id: string) => api.get<import('@/documentation/types').Doc>(`/documents/${id}`),
+ create: (data: {
+ title: string
+ kind?: string
+ parent_id?: string | null
+ device_id?: string | null
+ node_id?: string | null
+ design_id?: string | null
+ template_id?: string | null
+ body?: string
+ }) => api.post<import('@/documentation/types').Doc>('/documents', data),
+ update: (
+ id: string,
+ data: {
+ title?: string
+ icon?: string | null
+ body?: string
+ parent_id?: string | null
+ sort_order?: number
+ starred?: boolean
+ reviewed?: boolean
+ resync_facts?: boolean
+ },
+ ) => api.patch<import('@/documentation/types').Doc>(`/documents/${id}`, data),
+ delete: (id: string) => api.delete(`/documents/${id}`),
+ revisions: (id: string) =>
+ api.get<import('@/documentation/types').DocRevision[]>(`/documents/${id}/revisions`),
+ revision: (revisionId: string) =>
+ api.get<import('@/documentation/types').DocRevision & { body: string }>(
+ `/documents/revisions/${revisionId}`,
+ ),
+ restore: (id: string, revisionId: string) =>
+ api.post<import('@/documentation/types').Doc>(`/documents/${id}/revisions/${revisionId}/restore`),
+ search: (q: string, limit = 25) =>
+ api.get<import('@/documentation/types').DocSearchResult>('/documents/search', {
+ params: { q, limit },
+ }),
+ block: (block: string, deviceId: string) =>
+ api.get<{ block: string; markdown: string }>('/documents/blocks', {
+ params: { block, device_id: deviceId },
+ }),
+ coverage: () => api.get<import('@/documentation/types').DocCoverage>('/documents/coverage'),
+ scaffold: (data: { device_ids?: string[]; only_with_notes?: boolean }) =>
+ api.post<{ created: import('@/documentation/types').DocumentSummary[]; skipped: number }>(
+ '/documents/scaffold',
+ data,
+ ),
+}
+
export const racksApi = {
load: (designId: string) =>
api.get<import('@/utils/rackSerializer').ApiRackState>('/racks', { params: { design_id: designId } }),
diff --git a/frontend/src/components/panels/Sidebar.tsx b/frontend/src/components/panels/Sidebar.tsx
index b241026..24cd3d6 100644
--- a/frontend/src/components/panels/Sidebar.tsx
+++ b/frontend/src/components/panels/Sidebar.tsx
@@ -1,5 +1,5 @@
import { useState, useCallback, useEffect } from 'react'
-import { Plus, Save, ScanLine, ChevronLeft, ChevronRight, LayoutDashboard, Clock, EyeOff, Square, Settings, LogOut, Network, RadioTower, Server, Type, PlusCircle, Pencil, Trash2, Rows3 } from 'lucide-react'
+import { Plus, Save, ScanLine, ChevronLeft, ChevronRight, LayoutDashboard, Clock, EyeOff, Square, Settings, LogOut, Network, RadioTower, Server, Type, PlusCircle, Pencil, Trash2, Rows3, BookOpen } from 'lucide-react'
import { Logo } from '@/components/ui/Logo'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import { useCanvasStore } from '@/stores/canvasStore'
@@ -9,6 +9,7 @@ import { authApi, designsApi, mediaApi } from '@/api/client'
import * as standaloneStorage from '@/utils/standaloneStorage'
import { resolveDesignIcon, DEFAULT_DESIGN_ICON } from '@/utils/designIcons'
import { DesignModal, type DesignFormData } from '@/components/modals/DesignModal'
+import { useUiStore } from '@/stores/uiStore'
import { AccessoryTray } from '@/rack/components/AccessoryTray'
import { useRackStore } from '@/rack/store'
import { freeUnits } from '@/rack/layout'
@@ -41,6 +42,8 @@ export function Sidebar({ onAddNode, onAddGroupRect, onAddText, onScan, onZigbee
const [collapsed, setCollapsed] = useState(false)
const logout = useAuthStore((s) => s.logout)
const { designs, activeDesignId, activeDesignType, setActiveDesign, addDesign, updateDesign, removeDesign } = useDesignStore()
+ const view = useUiStore((s) => s.view)
+ const setView = useUiStore((s) => s.setView)
const isRack = activeDesignType === 'rack'
const [designSwitcherOpen, setDesignSwitcherOpen] = useState(false)
const [designModal, setDesignModal] = useState<{ mode: 'create' | 'edit'; design?: Design } | null>(null)
@@ -243,8 +246,18 @@ export function Sidebar({ onAddNode, onAddGroupRect, onAddText, onScan, onZigbee
icon={isRack ? Rows3 : LayoutDashboard}
label={isRack ? 'Rack view' : 'Canvas'}
collapsed={collapsed}
- active
+ active={view === 'canvas'}
+ onClick={() => setView('canvas')}
/>
+ {!STANDALONE && (
+ <SidebarItem
+ icon={BookOpen}
+ label="Documentation"
+ collapsed={collapsed}
+ active={view === 'documentation'}
+ onClick={() => setView('documentation')}
+ />
+ )}
{!STANDALONE && PENDING_TRIGGERS.map((t) => (
<SidebarItem
key={t.kind}
diff --git a/frontend/src/documentation/__tests__/DocEditor.test.tsx b/frontend/src/documentation/__tests__/DocEditor.test.tsx
new file mode 100644
index 0000000..1b7e8fd
--- /dev/null
+++ b/frontend/src/documentation/__tests__/DocEditor.test.tsx
@@ -0,0 +1,151 @@
+import { render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { documentsApi } from '@/api/client'
+import { DocEditor } from '../components/DocEditor'
+
+vi.mock('@/api/client', () => ({
+ documentsApi: { block: vi.fn() },
+}))
+
+const api = vi.mocked(documentsApi)
+
+function setup(overrides: Partial<React.ComponentProps<typeof DocEditor>> = {}) {
+ const props = {
+ body: '',
+ onChange: vi.fn(),
+ onSave: vi.fn(),
+ onCancel: vi.fn(),
+ dirty: false,
+ saving: false,
+ deviceId: 'dev-1',
+ ...overrides,
+ }
+ render(<DocEditor {...props} />)
+ return props
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+})
+
+describe('DocEditor', () => {
+ it('shows the source in an editable field', () => {
+ setup({ body: '# NAS' })
+ expect(screen.getByLabelText('Document source')).toHaveValue('# NAS')
+ })
+
+ it('renders the preview beside it', () => {
+ setup({ body: '# NAS' })
+ expect(screen.getByRole('heading', { name: 'NAS' })).toBeInTheDocument()
+ })
+
+ it('saves on Ctrl+S even when the button is out of reach', async () => {
+ const user = userEvent.setup()
+ const props = setup({ body: 'text', dirty: true })
+ await user.click(screen.getByLabelText('Document source'))
+ await user.keyboard('{Control>}s{/Control}')
+ expect(props.onSave).toHaveBeenCalled()
+ })
+
+ it('disables Save until something has changed', () => {
+ setup({ dirty: false })
+ expect(screen.getByRole('button', { name: /save/i })).toBeDisabled()
+ })
+
+ it('says so while a save is in flight', () => {
+ setup({ dirty: true, saving: true })
+ expect(screen.getByRole('button', { name: /saving/i })).toBeDisabled()
+ })
+
+ it('leaves edit mode on Escape', async () => {
+ const user = userEvent.setup()
+ const props = setup()
+ await user.click(screen.getByLabelText('Document source'))
+ await user.keyboard('{Escape}')
+ expect(props.onCancel).toHaveBeenCalled()
+ })
+
+ it('opens the insert menu on a slash at the start of a line', async () => {
+ const user = userEvent.setup()
+ setup()
+ await user.click(screen.getByLabelText('Document source'))
+ await user.keyboard('/')
+ expect(await screen.findByLabelText('Insert a block')).toBeInTheDocument()
+ })
+
+ it('leaves a slash mid-sentence alone', async () => {
+ const user = userEvent.setup()
+ setup({ body: 'and/or' })
+ const field = screen.getByLabelText('Document source')
+ await user.click(field)
+ // Caret at the end, so the slash is not at the start of a line.
+ await user.keyboard('{End}/')
+ expect(screen.queryByLabelText('Insert a block')).not.toBeInTheDocument()
+ })
+
+ it('offers the generated blocks when the document describes a device', async () => {
+ const user = userEvent.setup()
+ setup()
+ await user.click(screen.getByLabelText('Document source'))
+ await user.keyboard('/')
+ expect(await screen.findByText('/device')).toBeInTheDocument()
+ expect(screen.getByText('/services')).toBeInTheDocument()
+ })
+
+ it('offers only the plain snippets for a page that describes nothing', async () => {
+ const user = userEvent.setup()
+ setup({ deviceId: null })
+ await user.click(screen.getByLabelText('Document source'))
+ await user.keyboard('/')
+ await screen.findByLabelText('Insert a block')
+ expect(screen.queryByText('/device')).not.toBeInTheDocument()
+ expect(screen.getByText('/table')).toBeInTheDocument()
+ })
+
+ it('fetches a generated block and inserts it in place of the slash', async () => {
+ const user = userEvent.setup()
+ api.block.mockResolvedValue({ data: { block: 'device-info', markdown: '| IP | 10.0.0.1 |' } } as never)
+ const props = setup()
+
+ await user.click(screen.getByLabelText('Document source'))
+ await user.keyboard('/')
+ await user.click(await screen.findByText('/device'))
+
+ await waitFor(() => expect(api.block).toHaveBeenCalledWith('device-info', 'dev-1'))
+ expect(props.onChange).toHaveBeenLastCalledWith('| IP | 10.0.0.1 |\n')
+ })
+
+ it('inserts a plain snippet without calling the server', async () => {
+ const user = userEvent.setup()
+ const props = setup()
+ await user.click(screen.getByLabelText('Document source'))
+ await user.keyboard('/')
+ await user.click(await screen.findByText('/task'))
+
+ await waitFor(() => expect(props.onChange).toHaveBeenCalledWith('- [ ] \n- [ ] \n'))
+ expect(api.block).not.toHaveBeenCalled()
+ })
+
+ it('narrows the menu as you type', async () => {
+ const user = userEvent.setup()
+ setup()
+ await user.click(screen.getByLabelText('Document source'))
+ await user.keyboard('/')
+ await user.type(await screen.findByLabelText('Insert a block'), 'serv')
+ expect(screen.getByText('/services')).toBeInTheDocument()
+ expect(screen.queryByText('/table')).not.toBeInTheDocument()
+ })
+
+ it('closes the menu on Escape without leaving edit mode', async () => {
+ const user = userEvent.setup()
+ const props = setup()
+ await user.click(screen.getByLabelText('Document source'))
+ await user.keyboard('/')
+ await screen.findByLabelText('Insert a block')
+ await user.keyboard('{Escape}')
+ expect(screen.queryByLabelText('Insert a block')).not.toBeInTheDocument()
+ expect(props.onCancel).not.toHaveBeenCalled()
+ })
+})
diff --git a/frontend/src/documentation/__tests__/frontmatter.test.ts b/frontend/src/documentation/__tests__/frontmatter.test.ts
new file mode 100644
index 0000000..7827f53
--- /dev/null
+++ b/frontend/src/documentation/__tests__/frontmatter.test.ts
@@ -0,0 +1,124 @@
+import { describe, expect, it } from 'vitest'
+
+import {
+ isOverdue,
+ parseFrontmatter,
+ reviewInterval,
+ summaryOf,
+ tagsOf,
+ withFrontmatter,
+} from '../frontmatter'
+
+describe('parseFrontmatter', () => {
+ it('reads the leading block and strips it from the content', () => {
+ const { data, content } = parseFrontmatter('---\ntitle: NAS\ntags: [a, b]\n---\n\n# NAS\n')
+ expect(data).toEqual({ title: 'NAS', tags: ['a', 'b'] })
+ expect(content.trim()).toBe('# NAS')
+ })
+
+ it('ignores a block that is not the first thing in the body', () => {
+ const body = '# Title\n\n---\ntitle: NAS\n---\n'
+ expect(parseFrontmatter(body)).toEqual({ data: {}, content: body })
+ })
+
+ it('leaves the body alone when there is no block', () => {
+ expect(parseFrontmatter('# Just a heading')).toEqual({ data: {}, content: '# Just a heading' })
+ })
+
+ it('treats malformed YAML as absent rather than failing', () => {
+ // The user is mid-edit; the document still has to render.
+ const { data, content } = parseFrontmatter('---\ntitle: [unclosed\n---\nbody')
+ expect(data).toEqual({})
+ expect(content).toBe('body')
+ })
+
+ it('ignores a block that parses to something that is not a mapping', () => {
+ expect(parseFrontmatter('---\n- a\n- b\n---\nbody').data).toEqual({})
+ })
+
+ it('handles CRLF line endings', () => {
+ expect(parseFrontmatter('---\r\ntitle: NAS\r\n---\r\nbody').data).toEqual({ title: 'NAS' })
+ })
+})
+
+describe('withFrontmatter', () => {
+ it('replaces an existing block, keeping the body', () => {
+ const next = withFrontmatter('---\ntitle: Old\n---\n\n# Body\n', { title: 'New' })
+ expect(parseFrontmatter(next).data).toEqual({ title: 'New' })
+ expect(next).toContain('# Body')
+ })
+
+ it('adds a block to a body that has none', () => {
+ const next = withFrontmatter('# Body', { title: 'New' })
+ expect(next.startsWith('---\n')).toBe(true)
+ expect(parseFrontmatter(next).content.trim()).toBe('# Body')
+ })
+
+ it('round-trips', () => {
+ const data = { title: 'NAS', tags: ['storage', 'backup'], criticality: 'high' }
+ expect(parseFrontmatter(withFrontmatter('# NAS', data)).data).toEqual(data)
+ })
+})
+
+describe('tagsOf', () => {
+ it('accepts a list, a comma string, and nothing', () => {
+ expect(tagsOf({ tags: ['a', ' b '] })).toEqual(['a', 'b'])
+ expect(tagsOf({ tags: 'a, b' })).toEqual(['a', 'b'])
+ expect(tagsOf({ tags: 7 })).toEqual([])
+ expect(tagsOf({})).toEqual([])
+ })
+})
+
+describe('reviewInterval', () => {
+ it('parses days, weeks, months and years', () => {
+ const day = 24 * 60 * 60 * 1000
+ expect(reviewInterval('30d')).toBe(30 * day)
+ expect(reviewInterval('2w')).toBe(14 * day)
+ expect(reviewInterval('6m')).toBe(180 * day)
+ expect(reviewInterval('1y')).toBe(365 * day)
+ })
+
+ it('is null for anything it cannot read, which means never due', () => {
+ expect(reviewInterval('soon')).toBeNull()
+ expect(reviewInterval(undefined)).toBeNull()
+ expect(reviewInterval('6')).toBeNull()
+ })
+})
+
+describe('isOverdue', () => {
+ const created = '2026-01-01T00:00:00Z'
+ const now = Date.parse('2026-09-05T00:00:00Z')
+
+ it('is false without a cadence', () => {
+ expect(isOverdue({}, null, created, now)).toBe(false)
+ })
+
+ it('counts from the creation date when it has never been reviewed', () => {
+ expect(isOverdue({ review_every: '1m' }, null, created, now)).toBe(true)
+ expect(isOverdue({ review_every: '5y' }, null, created, now)).toBe(false)
+ })
+
+ it('counts from the last review once there is one', () => {
+ expect(isOverdue({ review_every: '1m' }, '2026-09-01T00:00:00Z', created, now)).toBe(false)
+ })
+})
+
+describe('summaryOf', () => {
+ it('takes the first real line of prose', () => {
+ expect(summaryOf('---\ntitle: NAS\n---\n\n# NAS\n\n> Holds every backup.\n')).toBe(
+ 'Holds every backup.',
+ )
+ })
+
+ it('skips the generated placeholder rather than calling it a summary', () => {
+ expect(summaryOf('# NAS\n\n> _One line: what this device is for._\n\nReal text.')).toBe('Real text.')
+ })
+
+ it('is empty when there is nothing but headings', () => {
+ expect(summaryOf('# NAS\n\n## Services\n')).toBe('')
+ })
+
+ it('truncates a long line', () => {
+ expect(summaryOf(`# T\n\n${'x'.repeat(400)}`, 20)).toHaveLength(20)
+ })
+})
diff --git a/frontend/src/documentation/__tests__/markdown.test.ts b/frontend/src/documentation/__tests__/markdown.test.ts
new file mode 100644
index 0000000..894ec26
--- /dev/null
+++ b/frontend/src/documentation/__tests__/markdown.test.ts
@@ -0,0 +1,107 @@
+import { describe, expect, it } from 'vitest'
+
+import { extractToc, headingText, slugifyHeading } from '../markdown/toc'
+import { isTaskLine, toggleTaskAtLine } from '../markdown/tasks'
+
+describe('slugifyHeading', () => {
+ it('matches what rehype-slug puts on the anchor', () => {
+ expect(slugifyHeading('Device Information')).toBe('device-information')
+ expect(slugifyHeading('Start / stop')).toBe('start--stop')
+ })
+
+ it('keeps letters outside ASCII', () => {
+ expect(slugifyHeading('Réseau électrique')).toBe('réseau-électrique')
+ })
+})
+
+describe('headingText', () => {
+ it('strips the inline markup a heading can carry', () => {
+ expect(headingText('**Bold** and `code`')).toBe('Bold and code')
+ expect(headingText('[Link](https://example.com)')).toBe('Link')
+ expect(headingText('[[device:nas-01|the NAS]]')).toBe('the NAS')
+ })
+})
+
+describe('extractToc', () => {
+ const body = [
+ '---',
+ 'title: NAS',
+ '---',
+ '',
+ '# nas-01',
+ '',
+ '## Device Information',
+ '',
+ '### Hardware',
+ '',
+ '#### Too deep',
+ '',
+ '## Services',
+ ].join('\n')
+
+ it('takes h2 and h3 by default, skipping h1 and deeper', () => {
+ expect(extractToc(body).map((e) => e.text)).toEqual([
+ 'Device Information',
+ 'Hardware',
+ 'Services',
+ ])
+ })
+
+ it('records the level so the rail can indent', () => {
+ expect(extractToc(body).map((e) => e.level)).toEqual([2, 3, 2])
+ })
+
+ it('ignores headings inside a fenced code block', () => {
+ const fenced = '## Real\n\n```\n## Not a heading\n```\n\n## Also real'
+ expect(extractToc(fenced).map((e) => e.text)).toEqual(['Real', 'Also real'])
+ })
+
+ it('suffixes a repeated heading the way rehype-slug does', () => {
+ expect(extractToc('## Notes\n\n## Notes').map((e) => e.id)).toEqual(['notes', 'notes-1'])
+ })
+
+ it('is empty for a body with no headings', () => {
+ expect(extractToc('just text')).toEqual([])
+ })
+})
+
+describe('toggleTaskAtLine', () => {
+ const body = ['- [ ] first', '- [x] second', 'not a task'].join('\n')
+
+ it('ticks an unticked task', () => {
+ expect(toggleTaskAtLine(body, 1).split('\n')[0]).toBe('- [x] first')
+ })
+
+ it('unticks a ticked task', () => {
+ expect(toggleTaskAtLine(body, 2).split('\n')[1]).toBe('- [ ] second')
+ })
+
+ it('leaves every other line exactly as it was', () => {
+ const lines = toggleTaskAtLine(body, 1).split('\n')
+ expect(lines[1]).toBe('- [x] second')
+ expect(lines[2]).toBe('not a task')
+ })
+
+ it('handles indented and numbered tasks', () => {
+ expect(toggleTaskAtLine(' - [ ] nested', 1)).toBe(' - [x] nested')
+ expect(toggleTaskAtLine('1. [ ] numbered', 1)).toBe('1. [x] numbered')
+ })
+
+ it('does nothing when the line is not a task or is out of range', () => {
+ expect(toggleTaskAtLine(body, 3)).toBe(body)
+ expect(toggleTaskAtLine(body, 99)).toBe(body)
+ expect(toggleTaskAtLine(body, 0)).toBe(body)
+ })
+
+ it('is its own inverse', () => {
+ expect(toggleTaskAtLine(toggleTaskAtLine(body, 1), 1)).toBe(body)
+ })
+})
+
+describe('isTaskLine', () => {
+ it('recognises the shapes remark-gfm treats as tasks', () => {
+ expect(isTaskLine('- [ ] a')).toBe(true)
+ expect(isTaskLine('* [x] a')).toBe(true)
+ expect(isTaskLine('- a')).toBe(false)
+ })
+})
diff --git a/frontend/src/documentation/__tests__/store.test.ts b/frontend/src/documentation/__tests__/store.test.ts
new file mode 100644
index 0000000..bc5d175
--- /dev/null
+++ b/frontend/src/documentation/__tests__/store.test.ts
@@ -0,0 +1,349 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { documentsApi } from '@/api/client'
+import {
+ clearDraft,
+ draftKey,
+ isDescendant,
+ overdueIds,
+ readDraft,
+ useDocsStore,
+ writeDraft,
+} from '../store'
+import type { Doc, DocumentSummary } from '../types'
+
+vi.mock('@/api/client', () => ({
+ documentsApi: {
+ list: vi.fn(),
+ get: vi.fn(),
+ create: vi.fn(),
+ update: vi.fn(),
+ delete: vi.fn(),
+ revisions: vi.fn(),
+ revision: vi.fn(),
+ restore: vi.fn(),
+ search: vi.fn(),
+ block: vi.fn(),
+ coverage: vi.fn(),
+ scaffold: vi.fn(),
+ },
+}))
+
+const api = vi.mocked(documentsApi)
+
+function summary(overrides: Partial<DocumentSummary> = {}): DocumentSummary {
+ return {
+ id: 'doc-1',
+ kind: 'page',
+ title: 'Page',
+ slug: 'page',
+ sort_order: 0,
+ tags: [],
+ frontmatter: {},
+ starred: false,
+ created_at: '2026-01-01T00:00:00Z',
+ updated_at: '2026-01-01T00:00:00Z',
+ ...overrides,
+ }
+}
+
+function doc(overrides: Partial<Doc> = {}): Doc {
+ return { ...summary(), body: 'original', ...overrides } as Doc
+}
+
+const INITIAL = useDocsStore.getState()
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ localStorage.clear()
+ useDocsStore.setState({
+ ...INITIAL,
+ docs: [],
+ openDoc: null,
+ draft: null,
+ dirty: false,
+ pendingDraft: null,
+ loadError: null,
+ revisions: [],
+ coverage: null,
+ search: null,
+ })
+})
+
+// ── loading ─────────────────────────────────────────────────────────────────
+
+describe('loadDocs', () => {
+ it('stores the listing', async () => {
+ api.list.mockResolvedValue({ data: [summary()] } as never)
+ await useDocsStore.getState().loadDocs()
+ expect(useDocsStore.getState().docs).toHaveLength(1)
+ expect(useDocsStore.getState().loaded).toBe(true)
+ })
+
+ it('surfaces the server message on failure and still marks itself loaded', async () => {
+ api.list.mockRejectedValue({ response: { data: { detail: 'nope' } } })
+ await useDocsStore.getState().loadDocs()
+ expect(useDocsStore.getState().loadError).toBe('nope')
+ expect(useDocsStore.getState().loaded).toBe(true)
+ })
+})
+
+// ── the draft lifecycle ─────────────────────────────────────────────────────
+
+describe('editing', () => {
+ beforeEach(() => {
+ useDocsStore.setState({ openDoc: doc() })
+ })
+
+ it('starts clean, from the stored body', () => {
+ useDocsStore.getState().startEdit()
+ expect(useDocsStore.getState().draft).toBe('original')
+ expect(useDocsStore.getState().dirty).toBe(false)
+ })
+
+ it('goes dirty only once the text actually differs', () => {
+ useDocsStore.getState().startEdit()
+ useDocsStore.getState().setDraft('original')
+ expect(useDocsStore.getState().dirty).toBe(false)
+ useDocsStore.getState().setDraft('changed')
+ expect(useDocsStore.getState().dirty).toBe(true)
+ })
+
+ it('mirrors every keystroke to localStorage so a reload cannot lose it', () => {
+ useDocsStore.getState().startEdit()
+ useDocsStore.getState().setDraft('changed')
+ expect(readDraft('doc-1')?.body).toBe('changed')
+ })
+
+ it('drops the draft when the edit is cancelled', () => {
+ useDocsStore.getState().startEdit()
+ useDocsStore.getState().setDraft('changed')
+ useDocsStore.getState().cancelEdit()
+ expect(readDraft('doc-1')).toBeNull()
+ expect(useDocsStore.getState().draft).toBeNull()
+ })
+
+ it('saves explicitly and clears the draft once the server has it', async () => {
+ api.update.mockResolvedValue({ data: doc({ body: 'changed', updated_at: 'later' }) } as never)
+ useDocsStore.setState({ docs: [summary()] })
+ useDocsStore.getState().startEdit()
+ useDocsStore.getState().setDraft('changed')
+
+ expect(await useDocsStore.getState().save()).toBe(true)
+ expect(api.update).toHaveBeenCalledWith('doc-1', { body: 'changed' })
+ expect(readDraft('doc-1')).toBeNull()
+ expect(useDocsStore.getState().dirty).toBe(false)
+ expect(useDocsStore.getState().docs[0].updated_at).toBe('later')
+ })
+
+ it('keeps the draft when the save fails, so nothing is lost', async () => {
+ api.update.mockRejectedValue({ response: { data: { detail: 'server said no' } } })
+ useDocsStore.getState().startEdit()
+ useDocsStore.getState().setDraft('changed')
+
+ expect(await useDocsStore.getState().save()).toBe(false)
+ expect(readDraft('doc-1')?.body).toBe('changed')
+ expect(useDocsStore.getState().loadError).toBe('server said no')
+ })
+
+ it('does nothing when there is no draft to save', async () => {
+ expect(await useDocsStore.getState().save()).toBe(false)
+ expect(api.update).not.toHaveBeenCalled()
+ })
+})
+
+// ── draft recovery ──────────────────────────────────────────────────────────
+
+describe('opening a document with a draft on disk', () => {
+ it('offers a draft taken against the version being opened', async () => {
+ writeDraft('doc-1', { body: 'unsaved', savedAt: Date.now(), base: '2026-01-01T00:00:00Z' })
+ api.get.mockResolvedValue({ data: doc() } as never)
+
+ await useDocsStore.getState().open('doc-1')
+ expect(useDocsStore.getState().pendingDraft).toBe('unsaved')
+ })
+
+ it('throws away a draft taken against an older version', async () => {
+ // The document changed elsewhere; replaying the old draft would revert it.
+ writeDraft('doc-1', { body: 'unsaved', savedAt: Date.now(), base: 'an-older-version' })
+ api.get.mockResolvedValue({ data: doc() } as never)
+
+ await useDocsStore.getState().open('doc-1')
+ expect(useDocsStore.getState().pendingDraft).toBeNull()
+ expect(readDraft('doc-1')).toBeNull()
+ })
+
+ it('offers nothing when the draft matches what was saved', async () => {
+ writeDraft('doc-1', { body: 'original', savedAt: Date.now(), base: '2026-01-01T00:00:00Z' })
+ api.get.mockResolvedValue({ data: doc() } as never)
+
+ await useDocsStore.getState().open('doc-1')
+ expect(useDocsStore.getState().pendingDraft).toBeNull()
+ })
+
+ it('restores the offered draft into the editor', async () => {
+ writeDraft('doc-1', { body: 'unsaved', savedAt: Date.now(), base: '2026-01-01T00:00:00Z' })
+ api.get.mockResolvedValue({ data: doc() } as never)
+ await useDocsStore.getState().open('doc-1')
+
+ useDocsStore.getState().acceptPendingDraft()
+ expect(useDocsStore.getState().draft).toBe('unsaved')
+ expect(useDocsStore.getState().dirty).toBe(true)
+ })
+
+ it('discards the offered draft on request', async () => {
+ writeDraft('doc-1', { body: 'unsaved', savedAt: Date.now(), base: '2026-01-01T00:00:00Z' })
+ api.get.mockResolvedValue({ data: doc() } as never)
+ await useDocsStore.getState().open('doc-1')
+
+ useDocsStore.getState().discardPendingDraft()
+ expect(useDocsStore.getState().pendingDraft).toBeNull()
+ expect(readDraft('doc-1')).toBeNull()
+ })
+})
+
+describe('draft storage', () => {
+ it('namespaces the key by document', () => {
+ expect(draftKey('abc')).toBe('homelable_docdraft:abc')
+ })
+
+ it('reads nothing back from a corrupt entry rather than throwing', () => {
+ localStorage.setItem(draftKey('doc-1'), 'not json')
+ expect(readDraft('doc-1')).toBeNull()
+ })
+
+ it('clears cleanly when there is nothing to clear', () => {
+ expect(() => clearDraft('missing')).not.toThrow()
+ })
+})
+
+// ── mutations ───────────────────────────────────────────────────────────────
+
+describe('mutations', () => {
+ it('adds a created document to the list and opens it', async () => {
+ api.create.mockResolvedValue({ data: doc({ id: 'new' }) } as never)
+ await useDocsStore.getState().create({ title: 'New' })
+ expect(useDocsStore.getState().docs.map((d) => d.id)).toEqual(['new'])
+ expect(useDocsStore.getState().openDoc?.id).toBe('new')
+ })
+
+ it('reports a create failure instead of adding nothing silently', async () => {
+ api.create.mockRejectedValue({ response: { data: { detail: 'that already has a document' } } })
+ expect(await useDocsStore.getState().create({ title: 'New' })).toBeNull()
+ expect(useDocsStore.getState().loadError).toBe('that already has a document')
+ })
+
+ it('drops a deleted folder together with its subtree', async () => {
+ api.delete.mockResolvedValue({} as never)
+ useDocsStore.setState({
+ docs: [
+ summary({ id: 'f', kind: 'folder' }),
+ summary({ id: 'child', parent_id: 'f' }),
+ summary({ id: 'grandchild', parent_id: 'child' }),
+ summary({ id: 'elsewhere' }),
+ ],
+ })
+ await useDocsStore.getState().remove('f')
+ expect(useDocsStore.getState().docs.map((d) => d.id)).toEqual(['elsewhere'])
+ })
+
+ it('closes the open document when it is the one deleted', async () => {
+ api.delete.mockResolvedValue({} as never)
+ useDocsStore.setState({ docs: [summary()], openDoc: doc() })
+ await useDocsStore.getState().remove('doc-1')
+ expect(useDocsStore.getState().openDoc).toBeNull()
+ })
+
+ it('flips the star', async () => {
+ api.update.mockResolvedValue({ data: doc({ starred: true }) } as never)
+ useDocsStore.setState({ docs: [summary()] })
+ await useDocsStore.getState().toggleStar('doc-1')
+ expect(api.update).toHaveBeenCalledWith('doc-1', { starred: true })
+ expect(useDocsStore.getState().docs[0].starred).toBe(true)
+ })
+
+ it('accepts the current facts without touching the body', async () => {
+ api.update.mockResolvedValue({ data: doc() } as never)
+ useDocsStore.setState({ docs: [summary()] })
+ await useDocsStore.getState().resyncFacts('doc-1')
+ expect(api.update).toHaveBeenCalledWith('doc-1', { resync_facts: true })
+ })
+
+ it('restores a revision and refreshes the history', async () => {
+ api.restore.mockResolvedValue({ data: doc({ body: 'old' }) } as never)
+ api.revisions.mockResolvedValue({ data: [] } as never)
+ useDocsStore.setState({ docs: [summary()], openDoc: doc() })
+ await useDocsStore.getState().restore('doc-1', 'rev-1')
+ expect(useDocsStore.getState().openDoc?.body).toBe('old')
+ expect(api.revisions).toHaveBeenCalledWith('doc-1')
+ })
+})
+
+// ── search ──────────────────────────────────────────────────────────────────
+
+describe('search', () => {
+ it('stores the engine alongside the hits', async () => {
+ api.search.mockResolvedValue({ data: { engine: 'like', hits: [] } } as never)
+ await useDocsStore.getState().runSearch('nas')
+ expect(useDocsStore.getState().search?.engine).toBe('like')
+ })
+
+ it('does not call the server for an empty query', async () => {
+ await useDocsStore.getState().runSearch(' ')
+ expect(api.search).not.toHaveBeenCalled()
+ expect(useDocsStore.getState().search).toBeNull()
+ })
+})
+
+// ── preferences ─────────────────────────────────────────────────────────────
+
+describe('preferences', () => {
+ it('remembers the grouping across sessions', () => {
+ useDocsStore.getState().setGroupBy('subnet')
+ expect(JSON.parse(localStorage.getItem('homelable_docs_ui') ?? '{}').groupBy).toBe('subnet')
+ })
+
+ it('toggles a tree key on and off', () => {
+ useDocsStore.getState().toggleExpanded('zone:Garage')
+ expect(useDocsStore.getState().expanded).toContain('zone:Garage')
+ useDocsStore.getState().toggleExpanded('zone:Garage')
+ expect(useDocsStore.getState().expanded).not.toContain('zone:Garage')
+ })
+})
+
+// ── helpers ─────────────────────────────────────────────────────────────────
+
+describe('isDescendant', () => {
+ const all = [
+ summary({ id: 'root', kind: 'folder' }),
+ summary({ id: 'mid', kind: 'folder', parent_id: 'root' }),
+ summary({ id: 'leaf', parent_id: 'mid' }),
+ summary({ id: 'other' }),
+ ]
+
+ it('walks the whole chain', () => {
+ expect(isDescendant(all, all[2], 'root')).toBe(true)
+ expect(isDescendant(all, all[3], 'root')).toBe(false)
+ })
+
+ it('does not count a document as its own descendant', () => {
+ expect(isDescendant(all, all[0], 'root')).toBe(false)
+ })
+
+ it('survives a cycle', () => {
+ const cyclic = [summary({ id: 'a', parent_id: 'b' }), summary({ id: 'b', parent_id: 'a' })]
+ expect(() => isDescendant(cyclic, cyclic[0], 'nowhere')).not.toThrow()
+ })
+})
+
+describe('overdueIds', () => {
+ it('flags only the documents whose cadence has elapsed', () => {
+ const now = Date.parse('2026-09-05T00:00:00Z')
+ const docs = [
+ summary({ id: 'due', frontmatter: { review_every: '1m' }, created_at: '2026-01-01T00:00:00Z' }),
+ summary({ id: 'fresh', frontmatter: { review_every: '5y' }, created_at: '2026-01-01T00:00:00Z' }),
+ summary({ id: 'no-cadence', created_at: '2020-01-01T00:00:00Z' }),
+ ]
+ expect([...overdueIds(docs, now)]).toEqual(['due'])
+ })
+})
diff --git a/frontend/src/documentation/__tests__/tree.test.ts b/frontend/src/documentation/__tests__/tree.test.ts
new file mode 100644
index 0000000..24fe166
--- /dev/null
+++ b/frontend/src/documentation/__tests__/tree.test.ts
@@ -0,0 +1,384 @@
+import type { Node } from '@xyflow/react'
+import { describe, expect, it } from 'vitest'
+
+import type { Design, InventoryEntry, NodeData } from '@/types'
+import {
+ bucketsFor,
+ buildDeviceTree,
+ buildLibraryTree,
+ deviceLabel,
+ docState,
+ filterGroups,
+ filterTree,
+ nodeFactsByDevice,
+ physicality,
+ slash24,
+ splitIps,
+ subnetsOf,
+} from '../tree'
+import type { DocumentSummary } from '../types'
+
+function device(overrides: Partial<InventoryEntry> = {}): InventoryEntry {
+ return {
+ id: 'dev-1',
+ ip: '192.168.1.20',
+ mac: null,
+ hostname: 'nas-01.lan',
+ os: null,
+ services: [],
+ suggested_type: null,
+ status: 'approved',
+ discovered_at: '2026-01-01T00:00:00Z',
+ label: 'nas-01',
+ ...overrides,
+ }
+}
+
+function doc(overrides: Partial<DocumentSummary> = {}): DocumentSummary {
+ return {
+ id: 'doc-1',
+ kind: 'device',
+ title: 'nas-01',
+ slug: 'nas-01',
+ sort_order: 0,
+ tags: [],
+ frontmatter: {},
+ starred: false,
+ created_at: '2026-01-01T00:00:00Z',
+ updated_at: '2026-01-01T00:00:00Z',
+ ...overrides,
+ }
+}
+
+function node(id: string, data: Partial<NodeData>): Node<NodeData> {
+ return {
+ id,
+ position: { x: 0, y: 0 },
+ data: { label: id, type: 'server', status: 'unknown', services: [], ...data } as NodeData,
+ }
+}
+
+const designs: Design[] = [
+ { id: 'design-1', name: 'Home network', design_type: 'network' } as Design,
+]
+
+const emptyContext = { nodes: [], designs, activeDesignId: 'design-1' as string | null }
+
+// ── helpers ─────────────────────────────────────────────────────────────────
+
+describe('physicality', () => {
+ it('calls a guest virtual', () => {
+ expect(physicality('vm')).toBe('Virtual')
+ expect(physicality('lxc')).toBe('Virtual')
+ expect(physicality('docker_container')).toBe('Virtual')
+ })
+
+ it('calls a hypervisor a host', () => {
+ expect(physicality('proxmox')).toBe('Host')
+ expect(physicality('docker_host')).toBe('Host')
+ })
+
+ it('falls back to a container drawing when the type is generic', () => {
+ expect(physicality('server', { hasChildren: true })).toBe('Host')
+ expect(physicality('server', { containerMode: true })).toBe('Host')
+ })
+
+ it('is physical otherwise, including for an unknown type', () => {
+ expect(physicality('nas')).toBe('Physical')
+ expect(physicality(null)).toBe('Physical')
+ })
+})
+
+describe('splitIps', () => {
+ it('splits the comma-separated column and drops blanks', () => {
+ expect(splitIps('10.0.0.1, 192.168.1.2 ,')).toEqual(['10.0.0.1', '192.168.1.2'])
+ expect(splitIps(null)).toEqual([])
+ })
+})
+
+describe('slash24', () => {
+ it('is the network of an IPv4 address', () => {
+ expect(slash24('192.168.1.20')).toBe('192.168.1.0/24')
+ })
+
+ it('is null for anything that is not IPv4', () => {
+ expect(slash24('fe80::1')).toBeNull()
+ expect(slash24('not-an-ip')).toBeNull()
+ })
+})
+
+describe('subnetsOf', () => {
+ it('prefers a configured range over the guessed /24', () => {
+ expect(subnetsOf(device({ ip: '10.0.5.7' }), ['10.0.0.0/16'])).toEqual(['10.0.0.0/16'])
+ })
+
+ it('guesses a /24 when no range matches', () => {
+ expect(subnetsOf(device({ ip: '10.0.5.7' }), ['192.168.1.0/24'])).toEqual(['10.0.5.0/24'])
+ })
+
+ it('places a multi-homed device under every subnet it reaches', () => {
+ const found = subnetsOf(device({ ip: '10.0.0.5, 192.168.1.20' }), [])
+ expect(found).toEqual(['10.0.0.0/24', '192.168.1.0/24'])
+ })
+
+ it('falls back to a single bucket for a device with no usable address', () => {
+ expect(subnetsOf(device({ ip: null }), [])).toEqual(['Ungrouped'])
+ })
+})
+
+describe('deviceLabel', () => {
+ it('falls back through the names a device can carry', () => {
+ expect(deviceLabel(device())).toBe('nas-01')
+ expect(deviceLabel(device({ label: null }))).toBe('nas-01.lan')
+ expect(deviceLabel(device({ label: null, hostname: null }))).toBe('192.168.1.20')
+ expect(deviceLabel(device({ label: null, hostname: null, ip: null }))).toBe('Unnamed device')
+ })
+})
+
+describe('docState', () => {
+ it('reports what the badge should say', () => {
+ expect(docState(undefined)).toBe('none')
+ expect(docState(doc())).toBe('header-only')
+ expect(docState(doc({ edited_at: '2026-02-01T00:00:00Z' }))).toBe('written')
+ expect(docState(doc(), { drifted: true })).toBe('drifted')
+ expect(docState(doc(), { overdue: true })).toBe('overdue')
+ })
+
+ it('reports drift ahead of an overdue review — it is the more actionable one', () => {
+ expect(docState(doc(), { drifted: true, overdue: true })).toBe('drifted')
+ })
+})
+
+// ── canvas facts ────────────────────────────────────────────────────────────
+
+describe('nodeFactsByDevice', () => {
+ it('walks up to the nearest zone and the nearest group', () => {
+ const nodes = [
+ node('zone', { type: 'groupRect', label: 'Garage' }),
+ node('group', { type: 'group', label: 'Storage', parent_id: 'zone' }),
+ node('nas', { type: 'nas', label: 'nas-01', parent_id: 'group', device_id: 'dev-1' }),
+ ]
+ const facts = nodeFactsByDevice({ ...emptyContext, nodes })
+ expect(facts['dev-1'].zone).toBe('Garage')
+ expect(facts['dev-1'].group).toBe('Storage')
+ })
+
+ it('ignores furniture, which describes nothing', () => {
+ const nodes = [node('zone', { type: 'groupRect', label: 'Garage', device_id: 'dev-1' })]
+ expect(nodeFactsByDevice({ ...emptyContext, nodes })).toEqual({})
+ })
+
+ it('names the canvas the loaded nodes belong to', () => {
+ const nodes = [node('nas', { type: 'nas', device_id: 'dev-1' })]
+ expect(nodeFactsByDevice({ ...emptyContext, nodes })['dev-1'].canvas).toBe('Home network')
+ })
+
+ it('survives a parent cycle rather than recursing forever', () => {
+ const nodes = [
+ node('a', { type: 'groupRect', label: 'A', parent_id: 'b' }),
+ node('b', { type: 'groupRect', label: 'B', parent_id: 'a' }),
+ node('nas', { type: 'nas', parent_id: 'a', device_id: 'dev-1' }),
+ ]
+ expect(() => nodeFactsByDevice({ ...emptyContext, nodes })).not.toThrow()
+ })
+})
+
+// ── the pivots ──────────────────────────────────────────────────────────────
+
+describe('bucketsFor', () => {
+ const facts = { zone: 'Garage', group: 'Storage', hasChildren: false, containerMode: false }
+
+ it('groups by zone, falling back when there is none', () => {
+ expect(bucketsFor(device(), 'zone', facts, undefined, emptyContext)).toEqual(['Garage'])
+ expect(bucketsFor(device(), 'zone', undefined, undefined, emptyContext)).toEqual(['Unzoned'])
+ })
+
+ it('groups by the curated type before the guessed one', () => {
+ expect(bucketsFor(device({ type: 'nas', suggested_type: 'server' }), 'type', facts, undefined, emptyContext)).toEqual(['nas'])
+ expect(bucketsFor(device({ type: null, suggested_type: 'server' }), 'type', facts, undefined, emptyContext)).toEqual(['server'])
+ expect(bucketsFor(device({ type: null, suggested_type: null }), 'type', facts, undefined, emptyContext)).toEqual(['Untyped'])
+ })
+
+ it('groups by every discovery source that saw the device', () => {
+ const merged = device({ discovery_sources: ['arp', 'proxmox'] })
+ expect(bucketsFor(merged, 'source', facts, undefined, emptyContext)).toEqual(['arp', 'proxmox'])
+ })
+
+ it('falls back to the single source column on an older row', () => {
+ const legacy = device({ discovery_sources: [], discovery_source: 'mdns' })
+ expect(bucketsFor(legacy, 'source', facts, undefined, emptyContext)).toEqual(['mdns'])
+ })
+
+ it('groups by rack when one mounts the device', () => {
+ const context = { ...emptyContext, racksByDevice: { 'dev-1': 'Rack-A' } }
+ expect(bucketsFor(device(), 'rack', facts, undefined, context)).toEqual(['Rack-A'])
+ expect(bucketsFor(device(), 'rack', facts, undefined, emptyContext)).toEqual(['Not racked'])
+ })
+
+ it('groups by the tags on the document, not on the device', () => {
+ expect(bucketsFor(device(), 'tag', facts, doc({ tags: ['storage', 'loud'] }), emptyContext)).toEqual([
+ 'storage',
+ 'loud',
+ ])
+ expect(bucketsFor(device(), 'tag', facts, doc(), emptyContext)).toEqual(['Untagged'])
+ })
+
+ it('puts everything in one bucket when flat', () => {
+ expect(bucketsFor(device(), 'flat', facts, undefined, emptyContext)).toEqual(['All devices'])
+ })
+})
+
+describe('buildDeviceTree', () => {
+ it('groups devices and sorts them inside each group', () => {
+ const devices = [
+ device({ id: 'a', label: 'zeta', ip: '10.0.0.1' }),
+ device({ id: 'b', label: 'alpha', ip: '10.0.0.2' }),
+ ]
+ const groups = buildDeviceTree({ groupBy: 'flat', devices, docs: [], context: emptyContext })
+ expect(groups).toHaveLength(1)
+ expect(groups[0].items.map((i) => i.label)).toEqual(['alpha', 'zeta'])
+ })
+
+ it('marks a device with no document so the tree shows the gap', () => {
+ const groups = buildDeviceTree({ groupBy: 'flat', devices: [device()], docs: [], context: emptyContext })
+ expect(groups[0].items[0].kind).toBe('device-without-doc')
+ expect(groups[0].items[0].state).toBe('none')
+ expect(groups[0].items[0].docId).toBeUndefined()
+ })
+
+ it('attaches the document a device already has', () => {
+ const groups = buildDeviceTree({
+ groupBy: 'flat',
+ devices: [device()],
+ docs: [doc({ device_id: 'dev-1', edited_at: '2026-02-01T00:00:00Z' })],
+ context: emptyContext,
+ })
+ expect(groups[0].items[0].docId).toBe('doc-1')
+ expect(groups[0].items[0].state).toBe('written')
+ })
+
+ it('lists a multi-homed device under each of its subnets', () => {
+ const groups = buildDeviceTree({
+ groupBy: 'subnet',
+ devices: [device({ ip: '10.0.0.5, 192.168.1.20' })],
+ docs: [],
+ context: emptyContext,
+ })
+ expect(groups.map((g) => g.label)).toEqual(['10.0.0.0/24', '192.168.1.0/24'])
+ })
+
+ it('sinks the catch-all bucket to the bottom', () => {
+ const devices = [
+ device({ id: 'a', label: 'in-a-zone' }),
+ device({ id: 'b', label: 'loose' }),
+ ]
+ const nodes = [
+ node('zone', { type: 'groupRect', label: 'Garage' }),
+ node('n', { type: 'nas', parent_id: 'zone', device_id: 'a' }),
+ ]
+ const groups = buildDeviceTree({
+ groupBy: 'zone',
+ devices,
+ docs: [],
+ context: { ...emptyContext, nodes },
+ })
+ expect(groups.map((g) => g.label)).toEqual(['Garage', 'Unzoned'])
+ })
+
+ it('flags drift and overdue review from the sets it is given', () => {
+ const groups = buildDeviceTree({
+ groupBy: 'flat',
+ devices: [device()],
+ docs: [doc({ device_id: 'dev-1' })],
+ context: emptyContext,
+ drifted: new Set(['doc-1']),
+ })
+ expect(groups[0].items[0].state).toBe('drifted')
+ })
+})
+
+// ── the library ─────────────────────────────────────────────────────────────
+
+describe('buildLibraryTree', () => {
+ it('nests pages under their folder', () => {
+ const tree = buildLibraryTree([
+ doc({ id: 'f', kind: 'folder', title: 'Runbooks' }),
+ doc({ id: 'p', kind: 'page', title: 'Reboot', parent_id: 'f' }),
+ ])
+ expect(tree).toHaveLength(1)
+ expect(tree[0].children?.[0].label).toBe('Reboot')
+ })
+
+ it('leaves device documents out — they are placed by their pivot', () => {
+ expect(buildLibraryTree([doc({ kind: 'device', device_id: 'dev-1' })])).toEqual([])
+ })
+
+ it('orders by sort_order, then by title', () => {
+ const tree = buildLibraryTree([
+ doc({ id: 'b', kind: 'page', title: 'Beta', sort_order: 0 }),
+ doc({ id: 'a', kind: 'page', title: 'Alpha', sort_order: 1 }),
+ doc({ id: 'c', kind: 'page', title: 'Aardvark', sort_order: 0 }),
+ ])
+ expect(tree.map((t) => t.label)).toEqual(['Aardvark', 'Beta', 'Alpha'])
+ })
+
+ it('keeps an empty folder, which is the point of storing folders as rows', () => {
+ const tree = buildLibraryTree([doc({ id: 'f', kind: 'folder', title: 'Empty' })])
+ expect(tree[0].children).toEqual([])
+ })
+
+ it('does not recurse forever on a cycle', () => {
+ const tree = buildLibraryTree([
+ doc({ id: 'a', kind: 'folder', title: 'A', parent_id: 'b' }),
+ doc({ id: 'b', kind: 'folder', title: 'B', parent_id: 'a' }),
+ ])
+ expect(tree).toEqual([])
+ })
+})
+
+// ── filtering ───────────────────────────────────────────────────────────────
+
+describe('filterTree', () => {
+ const tree = buildLibraryTree([
+ doc({ id: 'f', kind: 'folder', title: 'Runbooks' }),
+ doc({ id: 'p', kind: 'page', title: 'Reboot the NAS', parent_id: 'f' }),
+ doc({ id: 'o', kind: 'page', title: 'VLAN plan' }),
+ ])
+
+ it('keeps the folder that leads to a match', () => {
+ const filtered = filterTree(tree, 'reboot')
+ expect(filtered).toHaveLength(1)
+ expect(filtered[0].label).toBe('Runbooks')
+ expect(filtered[0].children?.[0].label).toBe('Reboot the NAS')
+ })
+
+ it('is case-insensitive and returns everything for an empty query', () => {
+ expect(filterTree(tree, 'VLAN')).toHaveLength(1)
+ expect(filterTree(tree, ' ')).toEqual(tree)
+ })
+
+ it('returns nothing when nothing matches', () => {
+ expect(filterTree(tree, 'zzz')).toEqual([])
+ })
+})
+
+describe('filterGroups', () => {
+ const groups = buildDeviceTree({
+ groupBy: 'flat',
+ devices: [device({ id: 'a', label: 'nas-01' }), device({ id: 'b', label: 'switch-core' })],
+ docs: [],
+ context: emptyContext,
+ })
+
+ it('narrows a group to its matching items', () => {
+ expect(filterGroups(groups, 'nas')[0].items.map((i) => i.label)).toEqual(['nas-01'])
+ })
+
+ it('keeps every item when the group name itself matches', () => {
+ expect(filterGroups(groups, 'All devices')[0].items).toHaveLength(2)
+ })
+
+ it('drops a group that ends up empty', () => {
+ expect(filterGroups(groups, 'zzz')).toEqual([])
+ })
+})
diff --git a/frontend/src/documentation/__tests__/wikilinks.test.ts b/frontend/src/documentation/__tests__/wikilinks.test.ts
new file mode 100644
index 0000000..e070ddd
--- /dev/null
+++ b/frontend/src/documentation/__tests__/wikilinks.test.ts
@@ -0,0 +1,139 @@
+import { describe, expect, it } from 'vitest'
+
+import {
+ backlinkIndex,
+ collectWikiLinks,
+ parseWikiLink,
+ resolveWikiLink,
+ splitWikiLinks,
+ type LinkableDoc,
+} from '../wikilinks'
+
+const docs: LinkableDoc[] = [
+ { id: 'd1', slug: 'nas-01', title: 'nas-01', device_id: 'dev-1' },
+ { id: 'd2', slug: 'vlan-plan', title: 'VLAN plan' },
+ { id: 'd3', slug: 'garage', title: 'Garage', node_id: 'node-9' },
+]
+const devices = [{ id: 'dev-1', label: 'nas-01' }]
+
+describe('parseWikiLink', () => {
+ it('reads a bare link as a document link', () => {
+ expect(parseWikiLink('VLAN plan')).toEqual({
+ target: 'doc',
+ key: 'VLAN plan',
+ label: 'VLAN plan',
+ raw: '[[VLAN plan]]',
+ })
+ })
+
+ it('reads the device, doc and node prefixes', () => {
+ expect(parseWikiLink('device:nas-01')?.target).toBe('device')
+ expect(parseWikiLink('doc:vlan-plan')?.target).toBe('doc')
+ expect(parseWikiLink('node:node-9')?.target).toBe('node')
+ })
+
+ it('treats an unknown prefix as part of the key, not a target', () => {
+ const link = parseWikiLink('https://example.com')
+ expect(link?.target).toBe('doc')
+ expect(link?.key).toBe('https://example.com')
+ })
+
+ it('takes the label after a pipe', () => {
+ expect(parseWikiLink('device:nas-01|the NAS')?.label).toBe('the NAS')
+ })
+
+ it('is null for an empty link', () => {
+ expect(parseWikiLink('')).toBeNull()
+ expect(parseWikiLink('device:')).toBeNull()
+ })
+})
+
+describe('splitWikiLinks', () => {
+ it('splits text around a link, in order', () => {
+ expect(splitWikiLinks('see [[device:nas-01]] now')).toEqual([
+ { type: 'text', value: 'see ' },
+ { type: 'link', link: expect.objectContaining({ key: 'nas-01' }) },
+ { type: 'text', value: ' now' },
+ ])
+ })
+
+ it('handles several links in one line', () => {
+ const segments = splitWikiLinks('[[a]] and [[b]]')
+ expect(segments.filter((s) => s.type === 'link')).toHaveLength(2)
+ })
+
+ it('leaves text with no link untouched', () => {
+ expect(splitWikiLinks('plain')).toEqual([{ type: 'text', value: 'plain' }])
+ })
+
+ it('is reusable — the shared regex is reset between calls', () => {
+ splitWikiLinks('[[a]]')
+ expect(splitWikiLinks('[[a]]')).toHaveLength(1)
+ })
+})
+
+describe('resolveWikiLink', () => {
+ it('resolves a device by label to that device document', () => {
+ const link = parseWikiLink('device:nas-01')!
+ expect(resolveWikiLink(link, docs, devices)).toBe('d1')
+ })
+
+ it('resolves a device by id too', () => {
+ const link = parseWikiLink('device:dev-1')!
+ expect(resolveWikiLink(link, docs, devices)).toBe('d1')
+ })
+
+ it('resolves a document by slug, then by title', () => {
+ expect(resolveWikiLink(parseWikiLink('doc:vlan-plan')!, docs)).toBe('d2')
+ expect(resolveWikiLink(parseWikiLink('VLAN plan')!, docs)).toBe('d2')
+ })
+
+ it('is case-insensitive on titles and slugs', () => {
+ expect(resolveWikiLink(parseWikiLink('vlan PLAN')!, docs)).toBe('d2')
+ })
+
+ it('resolves a node link to the document describing it', () => {
+ expect(resolveWikiLink(parseWikiLink('node:node-9')!, docs)).toBe('d3')
+ })
+
+ it('is null when nothing matches, so the UI can offer to create it', () => {
+ expect(resolveWikiLink(parseWikiLink('doc:nope')!, docs)).toBeNull()
+ expect(resolveWikiLink(parseWikiLink('device:nope')!, docs, devices)).toBeNull()
+ })
+
+ it('is null for a device that exists but has no document yet', () => {
+ const link = parseWikiLink('device:switch-core')!
+ expect(resolveWikiLink(link, docs, [{ id: 'dev-2', label: 'switch-core' }])).toBeNull()
+ })
+})
+
+describe('collectWikiLinks', () => {
+ it('finds every link in a body', () => {
+ expect(collectWikiLinks('a [[x]] b [[doc:y]]')).toHaveLength(2)
+ })
+
+ it('finds none in a body with none', () => {
+ expect(collectWikiLinks('# Heading\n\nplain text')).toEqual([])
+ })
+})
+
+describe('backlinkIndex', () => {
+ it('maps a document to the documents that link to it', () => {
+ const bodies = [
+ { ...docs[0], body: 'see [[doc:vlan-plan]]' },
+ { ...docs[1], body: 'no links' },
+ { ...docs[2], body: 'also [[VLAN plan]]' },
+ ]
+ expect(backlinkIndex(bodies)).toEqual({ d2: ['d1', 'd3'] })
+ })
+
+ it('ignores a document linking to itself', () => {
+ const bodies = [{ ...docs[1], body: 'see [[VLAN plan]]' }]
+ expect(backlinkIndex(bodies)).toEqual({})
+ })
+
+ it('does not list the same source twice', () => {
+ const bodies = [{ ...docs[0], body: '[[VLAN plan]] and [[doc:vlan-plan]]' }, { ...docs[1], body: '' }]
+ expect(backlinkIndex(bodies)).toEqual({ d2: ['d1'] })
+ })
+})
diff --git a/frontend/src/documentation/components/DocEditor.tsx b/frontend/src/documentation/components/DocEditor.tsx
new file mode 100644
index 0000000..0b3af59
--- /dev/null
+++ b/frontend/src/documentation/components/DocEditor.tsx
@@ -0,0 +1,263 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { Bold, Italic, Link2, List, ListChecks, Save, Table, X } from 'lucide-react'
+
+import { documentsApi } from '@/api/client'
+import { Button } from '@/components/ui/button'
+import { cn } from '@/lib/utils'
+import { Markdown } from '../markdown/Markdown'
+import type { LinkableDevice, LinkableDoc } from '../wikilinks'
+
+/**
+ * Source on the left, rendered on the right.
+ *
+ * Markdown source rather than a rich editor on purpose: the body is exported
+ * to disk verbatim, so what the user types is what the file holds — no
+ * round-trip through another representation that could reformat it.
+ */
+
+export interface SlashCommand {
+ id: string
+ label: string
+ hint: string
+ /** Resolved when chosen; async because a generated block is fetched. */
+ insert: () => string | Promise<string>
+}
+
+interface Props {
+ body: string
+ onChange: (body: string) => void
+ onSave: () => void
+ onCancel: () => void
+ dirty: boolean
+ saving: boolean
+ /** Set when the document describes a device — enables the generated blocks. */
+ deviceId?: string | null
+ docs?: LinkableDoc[]
+ devices?: LinkableDevice[]
+}
+
+const GENERATED_BLOCKS: { id: string; label: string; hint: string; block: string }[] = [
+ { id: 'device', label: '/device', hint: 'Device Information table, from the current facts', block: 'device-info' },
+ { id: 'services', label: '/services', hint: 'One section per fingerprinted service', block: 'services' },
+ { id: 'hardware', label: '/hardware', hint: 'CPU, RAM and disk', block: 'hardware' },
+ { id: 'network', label: '/network', hint: 'Subnet, neighbours, exposure', block: 'network' },
+ { id: 'rack', label: '/rack', hint: 'Rack and zone placement', block: 'rack' },
+ { id: 'properties', label: '/properties', hint: 'The device custom properties', block: 'properties' },
+]
+
+const PLAIN_SNIPPETS: SlashCommand[] = [
+ { id: 'table', label: '/table', hint: 'An empty three-column table', insert: () => '| | | |\n|---|---|---|\n| | | |\n' },
+ { id: 'task', label: '/task', hint: 'A checklist', insert: () => '- [ ] \n- [ ] \n' },
+ { id: 'callout', label: '/callout', hint: 'A highlighted note', insert: () => '> [!note]\n> \n' },
+ { id: 'link', label: '/link', hint: 'A link to another document', insert: () => '[[doc:]]' },
+ { id: 'device-link', label: '/device-link', hint: 'A link to a device document', insert: () => '[[device:]]' },
+ { id: 'date', label: '/date', hint: "Today's date", insert: () => new Date().toISOString().slice(0, 10) },
+]
+
+export function DocEditor({
+ body,
+ onChange,
+ onSave,
+ onCancel,
+ dirty,
+ saving,
+ deviceId,
+ docs = [],
+ devices = [],
+}: Props) {
+ const textarea = useRef<HTMLTextAreaElement>(null)
+ const [slashOpen, setSlashOpen] = useState(false)
+ const [slashQuery, setSlashQuery] = useState('')
+ const [inserting, setInserting] = useState(false)
+
+ const commands = useMemo<SlashCommand[]>(() => {
+ const generated: SlashCommand[] = deviceId
+ ? GENERATED_BLOCKS.map((entry) => ({
+ id: entry.id,
+ label: entry.label,
+ hint: entry.hint,
+ insert: async () => {
+ const { data } = await documentsApi.block(entry.block, deviceId)
+ return `${data.markdown}\n`
+ },
+ }))
+ : []
+ return [...generated, ...PLAIN_SNIPPETS]
+ }, [deviceId])
+
+ const visible = useMemo(() => {
+ const needle = slashQuery.toLowerCase()
+ return needle ? commands.filter((c) => c.label.toLowerCase().includes(needle)) : commands
+ }, [commands, slashQuery])
+
+ const insertAtCursor = useCallback(
+ (text: string, replaceSlash: boolean) => {
+ const el = textarea.current
+ if (!el) return
+ const end = el.selectionEnd
+ // The `/query` the user typed to open the menu is consumed by the insert.
+ const start = replaceSlash ? Math.max(0, end - slashQuery.length - 1) : el.selectionStart
+ const next = `${body.slice(0, start)}${text}${body.slice(end)}`
+ onChange(next)
+ requestAnimationFrame(() => {
+ el.focus()
+ const caret = start + text.length
+ el.setSelectionRange(caret, caret)
+ })
+ },
+ [body, onChange, slashQuery.length],
+ )
+
+ const runCommand = useCallback(
+ async (command: SlashCommand) => {
+ setSlashOpen(false)
+ setInserting(true)
+ try {
+ insertAtCursor(await command.insert(), true)
+ } finally {
+ setInserting(false)
+ setSlashQuery('')
+ }
+ },
+ [insertAtCursor],
+ )
+
+ const wrapSelection = useCallback(
+ (before: string, after = before) => {
+ const el = textarea.current
+ if (!el) return
+ const { selectionStart: start, selectionEnd: end } = el
+ const selected = body.slice(start, end)
+ const next = `${body.slice(0, start)}${before}${selected}${after}${body.slice(end)}`
+ onChange(next)
+ requestAnimationFrame(() => {
+ el.focus()
+ el.setSelectionRange(start + before.length, end + before.length)
+ })
+ },
+ [body, onChange],
+ )
+
+ const handleKeyDown = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
+ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 's') {
+ event.preventDefault()
+ onSave()
+ return
+ }
+ if (event.key === 'Escape') {
+ if (slashOpen) {
+ event.preventDefault()
+ setSlashOpen(false)
+ return
+ }
+ event.preventDefault()
+ onCancel()
+ return
+ }
+ if (event.key === '/') {
+ const el = event.currentTarget
+ const before = body.slice(0, el.selectionStart)
+ // Only at the start of a line — mid-sentence a slash is just a slash.
+ if (before === '' || before.endsWith('\n')) {
+ setSlashOpen(true)
+ setSlashQuery('')
+ }
+ }
+ }
+
+ useEffect(() => {
+ if (!slashOpen) setSlashQuery('')
+ }, [slashOpen])
+
+ return (
+ <div className="flex h-full flex-col">
+ <div className="flex items-center gap-1 border-b border-border px-3 py-1.5">
+ <Button size="icon-xs" variant="ghost" title="Bold" onClick={() => wrapSelection('**')}>
+ <Bold />
+ </Button>
+ <Button size="icon-xs" variant="ghost" title="Italic" onClick={() => wrapSelection('_')}>
+ <Italic />
+ </Button>
+ <Button size="icon-xs" variant="ghost" title="Bullet list" onClick={() => insertAtCursor('\n- ', false)}>
+ <List />
+ </Button>
+ <Button size="icon-xs" variant="ghost" title="Checklist" onClick={() => insertAtCursor('\n- [ ] ', false)}>
+ <ListChecks />
+ </Button>
+ <Button size="icon-xs" variant="ghost" title="Table" onClick={() => insertAtCursor('\n| | |\n|---|---|\n| | |\n', false)}>
+ <Table />
+ </Button>
+ <Button size="icon-xs" variant="ghost" title="Link to a document" onClick={() => insertAtCursor('[[doc:]]', false)}>
+ <Link2 />
+ </Button>
+ <span className="ml-2 text-[10px] text-muted-foreground/70">
+ Type <kbd className="rounded border border-border px-1">/</kbd> on a new line to insert
+ </span>
+ <div className="ml-auto flex items-center gap-2">
+ {dirty && <span className="text-[10px] text-muted-foreground">Unsaved</span>}
+ <Button size="sm" variant="ghost" onClick={onCancel} className="cursor-pointer gap-1">
+ <X size={13} /> Cancel
+ </Button>
+ <Button size="sm" onClick={onSave} disabled={!dirty || saving} className="cursor-pointer gap-1">
+ <Save size={13} /> {saving ? 'Saving…' : 'Save'}
+ </Button>
+ </div>
+ </div>
+
+ <div className="grid min-h-0 flex-1 grid-cols-1 lg:grid-cols-2">
+ <div className="relative min-h-0 border-r border-border">
+ <textarea
+ ref={textarea}
+ value={body}
+ aria-label="Document source"
+ spellCheck={false}
+ onChange={(event) => onChange(event.target.value)}
+ onKeyDown={handleKeyDown}
+ className="h-full w-full resize-none bg-transparent p-4 font-mono text-xs leading-relaxed outline-none"
+ />
+ {slashOpen && (
+ <div className="absolute bottom-4 left-4 z-20 w-72 overflow-hidden rounded-lg border border-border bg-popover shadow-lg">
+ <input
+ autoFocus
+ value={slashQuery}
+ onChange={(event) => setSlashQuery(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === 'Escape') setSlashOpen(false)
+ if (event.key === 'Enter' && visible[0]) {
+ event.preventDefault()
+ void runCommand(visible[0])
+ }
+ }}
+ placeholder="Insert…"
+ aria-label="Insert a block"
+ className="w-full border-b border-border bg-transparent px-3 py-2 text-xs outline-none"
+ />
+ <div className="max-h-56 overflow-y-auto">
+ {visible.length === 0 && (
+ <p className="px-3 py-2 text-xs text-muted-foreground">Nothing matches.</p>
+ )}
+ {visible.map((command) => (
+ <button
+ key={command.id}
+ type="button"
+ onClick={() => void runCommand(command)}
+ className="flex w-full cursor-pointer flex-col items-start px-3 py-1.5 text-left hover:bg-muted"
+ >
+ <span className="font-mono text-xs">{command.label}</span>
+ <span className="text-[10px] text-muted-foreground">{command.hint}</span>
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+ {inserting && (
+ <span className="absolute bottom-2 right-3 text-[10px] text-muted-foreground">Inserting…</span>
+ )}
+ </div>
+ <div className={cn('min-h-0 overflow-y-auto p-4 text-sm', 'hidden lg:block')}>
+ <Markdown body={body} docs={docs} devices={devices} className="max-w-[72ch]" />
+ </div>
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/documentation/components/DocTree.tsx b/frontend/src/documentation/components/DocTree.tsx
new file mode 100644
index 0000000..468f6e2
--- /dev/null
+++ b/frontend/src/documentation/components/DocTree.tsx
@@ -0,0 +1,152 @@
+import { ChevronDown, ChevronRight, File, FileText, Folder, FolderOpen, Star } from 'lucide-react'
+
+import { cn } from '@/lib/utils'
+import type { DocState, TreeGroup, TreeLeaf } from '../types'
+
+/**
+ * The navigator.
+ *
+ * Two roots with different natures: Devices is a pivot recomputed from the
+ * inventory whenever the grouping changes, Library is the real folder tree the
+ * user files by hand. They share this renderer so both feel like one tree.
+ */
+
+const STATE_TITLE: Record<DocState, string> = {
+ none: 'No document yet',
+ 'header-only': 'Only the generated header — nothing written yet',
+ written: 'Documented',
+ drifted: 'The device changed since this was written',
+ overdue: 'Due for review',
+}
+
+const STATE_CLASS: Record<DocState, string> = {
+ none: 'bg-muted-foreground/30',
+ 'header-only': 'bg-muted-foreground/60 ring-1 ring-inset ring-background',
+ written: 'bg-[var(--status-online,#39d353)]',
+ drifted: 'bg-[var(--status-pending,#e3b341)]',
+ overdue: 'bg-[var(--status-pending,#e3b341)]',
+}
+
+export function DocStateDot({ state }: { state: DocState }) {
+ return (
+ <span
+ aria-label={STATE_TITLE[state]}
+ title={STATE_TITLE[state]}
+ className={cn('size-1.5 shrink-0 rounded-full', STATE_CLASS[state])}
+ />
+ )
+}
+
+interface ItemProps {
+ leaf: TreeLeaf
+ depth: number
+ activeId: string | null
+ expanded: string[]
+ starred: Set<string>
+ onSelect: (leaf: TreeLeaf) => void
+ onToggle: (key: string) => void
+}
+
+export function DocTreeItem({ leaf, depth, activeId, expanded, starred, onSelect, onToggle }: ItemProps) {
+ const isFolder = leaf.kind === 'folder'
+ const isOpen = expanded.includes(leaf.id)
+ const active = activeId !== null && leaf.docId === activeId
+ const Icon = isFolder ? (isOpen ? FolderOpen : Folder) : leaf.docId ? FileText : File
+
+ return (
+ <>
+ <button
+ type="button"
+ onClick={() => (isFolder ? onToggle(leaf.id) : onSelect(leaf))}
+ onDoubleClick={() => isFolder && onSelect(leaf)}
+ aria-current={active ? 'page' : undefined}
+ aria-expanded={isFolder ? isOpen : undefined}
+ style={{ paddingLeft: 8 + depth * 12 }}
+ className={cn(
+ 'flex w-full cursor-pointer items-center gap-1.5 rounded py-1 pr-2 text-left text-xs',
+ active ? 'bg-primary/15 text-foreground' : 'text-muted-foreground hover:bg-muted/60 hover:text-foreground',
+ !leaf.docId && !isFolder && 'italic',
+ )}
+ >
+ {isFolder ? (
+ isOpen ? <ChevronDown size={12} className="shrink-0" /> : <ChevronRight size={12} className="shrink-0" />
+ ) : (
+ <span className="w-3 shrink-0" />
+ )}
+ <Icon size={13} className="shrink-0 opacity-70" />
+ <span className="truncate">{leaf.label}</span>
+ {leaf.docId && starred.has(leaf.docId) && (
+ <Star size={11} className="shrink-0 fill-current text-[var(--accent-orange,#ff6e00)]" />
+ )}
+ <span className="ml-auto pl-1">
+ <DocStateDot state={leaf.state} />
+ </span>
+ </button>
+ {isFolder &&
+ isOpen &&
+ (leaf.children ?? []).map((child) => (
+ <DocTreeItem
+ key={child.id}
+ leaf={child}
+ depth={depth + 1}
+ activeId={activeId}
+ expanded={expanded}
+ starred={starred}
+ onSelect={onSelect}
+ onToggle={onToggle}
+ />
+ ))}
+ </>
+ )
+}
+
+interface GroupsProps {
+ groups: TreeGroup[]
+ activeId: string | null
+ expanded: string[]
+ starred: Set<string>
+ onSelect: (leaf: TreeLeaf) => void
+ onToggle: (key: string) => void
+}
+
+export function DocTreeGroups({ groups, activeId, expanded, starred, onSelect, onToggle }: GroupsProps) {
+ if (groups.length === 0) {
+ return <p className="px-3 py-2 text-xs text-muted-foreground/60">No devices to document yet.</p>
+ }
+ return (
+ <>
+ {groups.map((group) => {
+ // Collapsed is opt-in: a fresh pivot shows everything, so the user can
+ // see the shape they just asked for without expanding anything.
+ const collapsed = expanded.includes(`collapsed:${group.key}`)
+ return (
+ <div key={group.key}>
+ <button
+ type="button"
+ onClick={() => onToggle(`collapsed:${group.key}`)}
+ aria-expanded={!collapsed}
+ className="sticky top-0 z-10 flex w-full cursor-pointer items-center gap-1 bg-background/95 px-2 py-1 text-left text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/70 backdrop-blur"
+ >
+ {collapsed ? <ChevronRight size={10} /> : <ChevronDown size={10} />}
+ <span className="truncate">{group.label}</span>
+ <span className="ml-auto tabular-nums opacity-60">{group.items.length}</span>
+ </button>
+ {!collapsed &&
+ group.items.map((leaf) => (
+ <DocTreeItem
+ key={`${group.key}:${leaf.id}`}
+ leaf={leaf}
+ depth={1}
+ activeId={activeId}
+ expanded={expanded}
+ starred={starred}
+ onSelect={onSelect}
+ onToggle={onToggle}
+ />
+ ))}
+ </div>
+ )
+ })}
+ </>
+ )
+}
diff --git a/frontend/src/documentation/components/DocViewer.tsx b/frontend/src/documentation/components/DocViewer.tsx
new file mode 100644
index 0000000..4bb0f45
--- /dev/null
+++ b/frontend/src/documentation/components/DocViewer.tsx
@@ -0,0 +1,135 @@
+import { useMemo } from 'react'
+import { Clock, Pencil, RefreshCw, Star, Trash2 } from 'lucide-react'
+
+import { Button } from '@/components/ui/button'
+import { cn } from '@/lib/utils'
+import { isOverdue, parseFrontmatter } from '../frontmatter'
+import { Markdown } from '../markdown/Markdown'
+import { extractToc } from '../markdown/toc'
+import type { Doc } from '../types'
+import type { LinkableDevice, LinkableDoc } from '../wikilinks'
+
+interface Props {
+ doc: Doc
+ docs: LinkableDoc[]
+ devices: LinkableDevice[]
+ drifted: boolean
+ onEdit: () => void
+ onToggleStar: () => void
+ onMarkReviewed: () => void
+ onDelete: () => void
+ onOpenDoc: (id: string) => void
+ onCreateFromLink: (label: string) => void
+ onToggleTask: (body: string) => void
+}
+
+/** The metadata a frontmatter block is worth surfacing as a chip. */
+const CHIPS: { key: string; label: string }[] = [
+ { key: 'criticality', label: 'Criticality' },
+ { key: 'owner', label: 'Owner' },
+ { key: 'review_every', label: 'Review' },
+]
+
+export function DocViewer({
+ doc,
+ docs,
+ devices,
+ drifted,
+ onEdit,
+ onToggleStar,
+ onMarkReviewed,
+ onDelete,
+ onOpenDoc,
+ onCreateFromLink,
+ onToggleTask,
+}: Props) {
+ const { data } = useMemo(() => parseFrontmatter(doc.body), [doc.body])
+ const toc = useMemo(() => extractToc(doc.body), [doc.body])
+ const overdue = isOverdue(data, doc.reviewed_at, doc.created_at)
+
+ return (
+ <div className="flex min-h-0 flex-1">
+ <div className="min-w-0 flex-1 overflow-y-auto">
+ <div className="flex items-start gap-2 px-6 pt-5">
+ <h1 className="min-w-0 flex-1 truncate text-xl font-semibold">{doc.title}</h1>
+ <Button
+ size="icon-xs"
+ variant="ghost"
+ title={doc.starred ? 'Unstar' : 'Star'}
+ aria-pressed={doc.starred}
+ onClick={onToggleStar}
+ className="cursor-pointer"
+ >
+ <Star className={cn(doc.starred && 'fill-current text-[var(--accent-orange,#ff6e00)]')} />
+ </Button>
+ <Button size="sm" variant="ghost" onClick={onEdit} className="cursor-pointer gap-1">
+ <Pencil size={13} /> Edit
+ </Button>
+ <Button size="icon-xs" variant="ghost" title="Delete this document" onClick={onDelete} className="cursor-pointer">
+ <Trash2 />
+ </Button>
+ </div>
+
+ <div className="flex flex-wrap items-center gap-1.5 px-6 pt-2 text-[10px]">
+ {CHIPS.filter((chip) => data[chip.key]).map((chip) => (
+ <span key={chip.key} className="rounded bg-muted px-1.5 py-0.5 text-muted-foreground">
+ {chip.label}: <span className="text-foreground">{String(data[chip.key])}</span>
+ </span>
+ ))}
+ {doc.tags.map((tag) => (
+ <span key={tag} className="rounded bg-primary/10 px-1.5 py-0.5 text-primary">
+ #{tag}
+ </span>
+ ))}
+ {!doc.edited_at && (
+ <span className="rounded bg-muted px-1.5 py-0.5 text-muted-foreground">
+ Only the generated header so far
+ </span>
+ )}
+ {overdue && (
+ <button
+ type="button"
+ onClick={onMarkReviewed}
+ className="flex cursor-pointer items-center gap-1 rounded bg-[var(--status-pending,#e3b341)]/15 px-1.5 py-0.5 text-[var(--status-pending,#e3b341)]"
+ >
+ <Clock size={10} /> Due for review — mark as reviewed
+ </button>
+ )}
+ {drifted && (
+ <span className="flex items-center gap-1 rounded bg-[var(--status-pending,#e3b341)]/15 px-1.5 py-0.5 text-[var(--status-pending,#e3b341)]">
+ <RefreshCw size={10} /> The device has changed
+ </span>
+ )}
+ </div>
+
+ <Markdown
+ body={doc.body}
+ docs={docs}
+ devices={devices}
+ onOpenDoc={onOpenDoc}
+ onCreateFromLink={onCreateFromLink}
+ onToggleTask={onToggleTask}
+ className="max-w-[72ch] px-6 pb-16 pt-2 text-sm"
+ />
+ </div>
+
+ {toc.length > 1 && (
+ <nav aria-label="On this page" className="hidden w-52 shrink-0 overflow-y-auto border-l border-border px-3 py-5 xl:block">
+ <p className="mb-2 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/70">
+ On this page
+ </p>
+ {toc.map((entry) => (
+ <a
+ key={entry.id}
+ href={`#${entry.id}`}
+ style={{ paddingLeft: (entry.level - 2) * 10 }}
+ className="block truncate py-0.5 text-xs text-muted-foreground hover:text-foreground"
+ >
+ {entry.text}
+ </a>
+ ))}
+ </nav>
+ )}
+ </div>
+ )
+}
diff --git a/frontend/src/documentation/components/DocumentationView.tsx b/frontend/src/documentation/components/DocumentationView.tsx
new file mode 100644
index 0000000..c402336
--- /dev/null
+++ b/frontend/src/documentation/components/DocumentationView.tsx
@@ -0,0 +1,401 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { BookOpen, FilePlus, FolderPlus, Search, X } from 'lucide-react'
+import { toast } from 'sonner'
+
+import { scanApi } from '@/api/client'
+import { Button } from '@/components/ui/button'
+import { Input } from '@/components/ui/input'
+import { useCanvasStore } from '@/stores/canvasStore'
+import { useDesignStore } from '@/stores/designStore'
+import type { InventoryEntry } from '@/types'
+import { cn } from '@/lib/utils'
+import { isOverdue } from '../frontmatter'
+import { useDocsStore } from '../store'
+import { buildDeviceTree, buildLibraryTree, deviceLabel, filterGroups, filterTree } from '../tree'
+import { GROUP_BY_LABELS, type GroupBy, type TreeLeaf } from '../types'
+import { DocEditor } from './DocEditor'
+import { DocTreeGroups, DocTreeItem } from './DocTree'
+import { DocViewer } from './DocViewer'
+import { MigrateNotesBanner } from './MigrateNotesBanner'
+import { NewDocMenu } from './NewDocMenu'
+
+const STANDALONE = import.meta.env.VITE_STANDALONE === 'true'
+
+const GROUP_OPTIONS = Object.keys(GROUP_BY_LABELS) as GroupBy[]
+
+/**
+ * The Documentation section.
+ *
+ * The first part of the app that is not about one canvas: a device is
+ * documented once and reads the same wherever it is drawn, so this view sits
+ * beside the canvas rather than inside a design.
+ */
+export function DocumentationView() {
+ const {
+ docs,
+ loaded,
+ loadDocs,
+ openDoc,
+ open,
+ draft,
+ dirty,
+ saving,
+ pendingDraft,
+ startEdit,
+ setDraft,
+ cancelEdit,
+ save,
+ acceptPendingDraft,
+ discardPendingDraft,
+ create,
+ remove,
+ toggleStar,
+ markReviewed,
+ coverage,
+ loadCoverage,
+ scaffold,
+ groupBy,
+ setGroupBy,
+ expanded,
+ toggleExpanded,
+ treeWidth,
+ setTreeWidth,
+ filter,
+ setFilter,
+ } = useDocsStore()
+
+ const designs = useDesignStore((s) => s.designs)
+ const activeDesignId = useDesignStore((s) => s.activeDesignId)
+ const nodes = useCanvasStore((s) => s.nodes)
+
+ const [devices, setDevices] = useState<InventoryEntry[]>([])
+ const [libraryOpen, setLibraryOpen] = useState(true)
+
+ useEffect(() => {
+ void loadDocs()
+ void loadCoverage()
+ if (STANDALONE) return
+ scanApi
+ .pending()
+ .then((res) => setDevices(res.data as InventoryEntry[]))
+ // The tree still renders the Library without the inventory.
+ .catch(() => setDevices([]))
+ }, [loadDocs, loadCoverage])
+
+ // `review_every` rides along on the summary, so the badge needs no bodies.
+ const overdue = useMemo(
+ () =>
+ new Set(
+ docs
+ .filter((doc) => isOverdue(doc.frontmatter ?? {}, doc.reviewed_at, doc.created_at))
+ .map((doc) => doc.id),
+ ),
+ [docs],
+ )
+
+ const deviceGroups = useMemo(
+ () =>
+ filterGroups(
+ buildDeviceTree({
+ groupBy,
+ devices,
+ docs,
+ context: { nodes, designs, activeDesignId, ranges: [] },
+ overdue,
+ }),
+ filter,
+ ),
+ [activeDesignId, designs, devices, docs, filter, groupBy, nodes, overdue],
+ )
+
+ const libraryItems = useMemo(() => filterTree(buildLibraryTree(docs), filter), [docs, filter])
+ const starred = useMemo(() => new Set(docs.filter((d) => d.starred).map((d) => d.id)), [docs])
+ const linkableDevices = useMemo(
+ () => devices.map((d) => ({ id: d.id, label: deviceLabel(d) })),
+ [devices],
+ )
+
+ const drifted = useMemo(() => {
+ if (!openDoc?.device_id || !openDoc.facts_snapshot) return false
+ const device = devices.find((d) => d.id === openDoc.device_id)
+ if (!device) return false
+ // The snapshot is the server's shape; compare only what it recorded.
+ return Object.entries(openDoc.facts_snapshot).some(([key, value]) => {
+ if (key === 'services') return false
+ const current = (device as unknown as Record<string, unknown>)[key]
+ return (current ?? null) !== (value ?? null)
+ })
+ }, [devices, openDoc])
+
+ const handleSelect = useCallback(
+ async (leaf: TreeLeaf) => {
+ if (dirty && !window.confirm('Discard the unsaved changes to this document?')) return
+ if (leaf.docId) {
+ await open(leaf.docId)
+ return
+ }
+ if (!leaf.deviceId) return
+ const device = devices.find((d) => d.id === leaf.deviceId)
+ const doc = await create({
+ title: device ? deviceLabel(device) : leaf.label,
+ kind: 'device',
+ deviceId: leaf.deviceId,
+ })
+ if (doc) {
+ await open(doc.id)
+ toast.success('Document created from the device facts')
+ }
+ },
+ [create, devices, dirty, open],
+ )
+
+ const handleSave = useCallback(async () => {
+ if (await save()) toast.success('Saved')
+ }, [save])
+
+ const handleDelete = useCallback(async () => {
+ if (!openDoc) return
+ if (!window.confirm(`Delete “${openDoc.title}”? Its history goes with it.`)) return
+ await remove(openDoc.id)
+ toast.success('Document deleted')
+ }, [openDoc, remove])
+
+ const handleMigrate = useCallback(async () => {
+ const created = await scaffold({ onlyWithNotes: true })
+ await loadDocs()
+ toast.success(created === 1 ? '1 note became a document' : `${created} notes became documents`)
+ }, [loadDocs, scaffold])
+
+ // Drag-to-resize the tree pane. Width lives in localStorage, per viewer.
+ const dragging = useRef(false)
+ useEffect(() => {
+ const move = (event: MouseEvent) => {
+ if (!dragging.current) return
+ setTreeWidth(Math.min(520, Math.max(180, event.clientX - 48)))
+ }
+ const up = () => {
+ dragging.current = false
+ }
+ window.addEventListener('mousemove', move)
+ window.addEventListener('mouseup', up)
+ return () => {
+ window.removeEventListener('mousemove', move)
+ window.removeEventListener('mouseup', up)
+ }
+ }, [setTreeWidth])
+
+ if (STANDALONE) {
+ return (
+ <div className="flex flex-1 items-center justify-center p-8 text-center">
+ <div className="max-w-md">
+ <BookOpen className="mx-auto mb-3 opacity-40" size={28} />
+ <h2 className="mb-1 text-sm font-semibold">Documentation needs the backend</h2>
+ <p className="text-xs text-muted-foreground">
+ Standalone mode keeps canvases in the browser and has nowhere to store documents or
+ search them. Run Homelable with its API to use this section.
+ </p>
+ </div>
+ </div>
+ )
+ }
+
+ return (
+ <div className="flex min-h-0 flex-1">
+ <aside
+ style={{ width: treeWidth }}
+ className="flex min-h-0 shrink-0 flex-col border-r border-border"
+ >
+ <div className="flex items-center gap-1 border-b border-border px-2 py-2">
+ <Search size={13} className="shrink-0 opacity-50" />
+ <Input
+ value={filter}
+ onChange={(event) => setFilter(event.target.value)}
+ placeholder="Filter documents"
+ aria-label="Filter documents"
+ className="h-6 border-0 bg-transparent px-1 text-xs shadow-none focus-visible:ring-0"
+ />
+ {filter && (
+ <Button size="icon-xs" variant="ghost" aria-label="Clear filter" onClick={() => setFilter('')}>
+ <X />
+ </Button>
+ )}
+ </div>
+
+ <div className="flex items-center gap-1 border-b border-border px-2 py-1.5">
+ <label htmlFor="docs-group-by" className="text-[10px] uppercase tracking-wide text-muted-foreground/70">
+ Group by
+ </label>
+ <select
+ id="docs-group-by"
+ value={groupBy}
+ onChange={(event) => setGroupBy(event.target.value as GroupBy)}
+ className="ml-auto cursor-pointer rounded border border-border bg-transparent px-1 py-0.5 text-xs"
+ >
+ {GROUP_OPTIONS.map((option) => (
+ <option key={option} value={option}>
+ {GROUP_BY_LABELS[option]}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ <div className="min-h-0 flex-1 overflow-y-auto py-1">
+ <p className="px-2 pb-1 pt-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/50">
+ Devices
+ </p>
+ <DocTreeGroups
+ groups={deviceGroups}
+ activeId={openDoc?.id ?? null}
+ expanded={expanded}
+ starred={starred}
+ onSelect={(leaf) => void handleSelect(leaf)}
+ onToggle={toggleExpanded}
+ />
+
+ <button
+ type="button"
+ onClick={() => setLibraryOpen((value) => !value)}
+ aria-expanded={libraryOpen}
+ className="mt-3 flex w-full cursor-pointer items-center px-2 pb-1 pt-1 text-left text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/50"
+ >
+ Library
+ </button>
+ {libraryOpen &&
+ libraryItems.map((leaf) => (
+ <DocTreeItem
+ key={leaf.id}
+ leaf={leaf}
+ depth={1}
+ activeId={openDoc?.id ?? null}
+ expanded={expanded}
+ starred={starred}
+ onSelect={(item) => void handleSelect(item)}
+ onToggle={toggleExpanded}
+ />
+ ))}
+ {libraryOpen && libraryItems.length === 0 && (
+ <p className="px-3 py-1 text-xs text-muted-foreground/60">
+ Nothing here yet — runbooks and overviews live in the Library.
+ </p>
+ )}
+ </div>
+
+ <div className="flex items-center gap-1 border-t border-border px-2 py-1.5">
+ <NewDocMenu
+ onCreate={async (input) => {
+ const doc = await create(input)
+ if (doc) await open(doc.id)
+ }}
+ trigger={
+ <Button size="xs" variant="ghost" className="cursor-pointer gap-1">
+ <FilePlus size={12} /> New
+ </Button>
+ }
+ />
+ <Button
+ size="xs"
+ variant="ghost"
+ className="cursor-pointer gap-1"
+ onClick={async () => {
+ const title = window.prompt('Folder name')
+ if (title?.trim()) await create({ title: title.trim(), kind: 'folder' })
+ }}
+ >
+ <FolderPlus size={12} /> Folder
+ </Button>
+ {coverage && (
+ <span
+ className="ml-auto text-[10px] tabular-nums text-muted-foreground/70"
+ title={`${coverage.documented} of ${coverage.devices} devices documented · ${coverage.header_only} still only the generated header`}
+ >
+ {coverage.documented}/{coverage.devices}
+ </span>
+ )}
+ </div>
+ </aside>
+
+ <div
+ role="separator"
+ aria-orientation="vertical"
+ aria-label="Resize the document tree"
+ onMouseDown={() => {
+ dragging.current = true
+ }}
+ className="w-1 shrink-0 cursor-col-resize bg-transparent hover:bg-primary/30"
+ />
+
+ <div className="flex min-h-0 min-w-0 flex-1 flex-col">
+ {coverage && coverage.notes_unmigrated > 0 && (
+ <MigrateNotesBanner count={coverage.notes_unmigrated} onMigrate={() => void handleMigrate()} />
+ )}
+
+ {pendingDraft !== null && (
+ <div className="flex items-center gap-2 border-b border-border bg-[var(--status-pending,#e3b341)]/10 px-4 py-1.5 text-xs">
+ <span className="text-[var(--status-pending,#e3b341)]">
+ Unsaved changes from a previous session were found.
+ </span>
+ <Button size="xs" variant="secondary" className="cursor-pointer" onClick={acceptPendingDraft}>
+ Restore them
+ </Button>
+ <Button size="xs" variant="ghost" className="cursor-pointer" onClick={discardPendingDraft}>
+ Discard
+ </Button>
+ </div>
+ )}
+
+ {!openDoc && (
+ <div className={cn('flex flex-1 items-center justify-center p-8 text-center')}>
+ <div className="max-w-sm">
+ <BookOpen className="mx-auto mb-3 opacity-30" size={26} />
+ <p className="text-sm font-medium">
+ {loaded && docs.length === 0 ? 'Nothing is documented yet' : 'Pick a document'}
+ </p>
+ <p className="mt-1 text-xs text-muted-foreground">
+ Selecting a device with no document creates one from its scanned facts, filled in
+ for you and yours to maintain from there.
+ </p>
+ </div>
+ </div>
+ )}
+
+ {openDoc && draft === null && (
+ <DocViewer
+ doc={openDoc}
+ docs={docs}
+ devices={linkableDevices}
+ drifted={drifted}
+ onEdit={startEdit}
+ onToggleStar={() => void toggleStar(openDoc.id)}
+ onMarkReviewed={() => void markReviewed(openDoc.id)}
+ onDelete={() => void handleDelete()}
+ onOpenDoc={(id) => void open(id)}
+ onCreateFromLink={async (label) => {
+ const doc = await create({ title: label })
+ if (doc) await open(doc.id)
+ }}
+ onToggleTask={(body) => {
+ // A checkbox is an edit like any other: it goes through the draft
+ // so it is saved explicitly, never behind the user's back.
+ startEdit()
+ setDraft(body)
+ }}
+ />
+ )}
+
+ {openDoc && draft !== null && (
+ <DocEditor
+ body={draft}
+ onChange={setDraft}
+ onSave={() => void handleSave()}
+ onCancel={cancelEdit}
+ dirty={dirty}
+ saving={saving}
+ deviceId={openDoc.device_id}
+ docs={docs}
+ devices={linkableDevices}
+ />
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/documentation/components/MigrateNotesBanner.tsx b/frontend/src/documentation/components/MigrateNotesBanner.tsx
new file mode 100644
index 0000000..515b787
--- /dev/null
+++ b/frontend/src/documentation/components/MigrateNotesBanner.tsx
@@ -0,0 +1,27 @@
+import { ArrowRight, StickyNote } from 'lucide-react'
+
+import { Button } from '@/components/ui/button'
+
+/**
+ * The one-time move from `device_inventory.notes` to real documents.
+ *
+ * Explicit rather than automatic, and non-destructive: the old column is left
+ * exactly as it was, so nothing is lost and the migration can be run again for
+ * devices added later.
+ */
+export function MigrateNotesBanner({ count, onMigrate }: { count: number; onMigrate: () => void }) {
+ return (
+ <div className="flex items-center gap-2 border-b border-border bg-primary/5 px-4 py-1.5 text-xs">
+ <StickyNote size={13} className="shrink-0 text-primary" />
+ <span>
+ {count === 1
+ ? '1 device has notes that are not a document yet.'
+ : `${count} devices have notes that are not documents yet.`}{' '}
+ <span className="text-muted-foreground">The notes are copied, never moved.</span>
+ </span>
+ <Button size="xs" variant="secondary" className="ml-auto cursor-pointer gap-1" onClick={onMigrate}>
+ Migrate <ArrowRight size={11} />
+ </Button>
+ </div>
+ )
+}
diff --git a/frontend/src/documentation/components/NewDocMenu.tsx b/frontend/src/documentation/components/NewDocMenu.tsx
new file mode 100644
index 0000000..29811d9
--- /dev/null
+++ b/frontend/src/documentation/components/NewDocMenu.tsx
@@ -0,0 +1,63 @@
+import { useEffect, useRef, useState, type ReactNode } from 'react'
+
+import { DOC_TEMPLATES } from '../types'
+
+interface Props {
+ trigger: ReactNode
+ parentId?: string | null
+ onCreate: (input: { title: string; templateId: string; parentId?: string | null }) => void | Promise<void>
+}
+
+/**
+ * The template picker.
+ *
+ * A plain popover rather than a shadcn dropdown: the project only ships a
+ * handful of primitives and this needs no focus trapping beyond closing on an
+ * outside click or Escape.
+ */
+export function NewDocMenu({ trigger, parentId, onCreate }: Props) {
+ const [open, setOpen] = useState(false)
+ const root = useRef<HTMLDivElement>(null)
+
+ useEffect(() => {
+ if (!open) return
+ const onDown = (event: MouseEvent) => {
+ if (!root.current?.contains(event.target as Node)) setOpen(false)
+ }
+ const onKey = (event: KeyboardEvent) => {
+ if (event.key === 'Escape') setOpen(false)
+ }
+ document.addEventListener('mousedown', onDown)
+ document.addEventListener('keydown', onKey)
+ return () => {
+ document.removeEventListener('mousedown', onDown)
+ document.removeEventListener('keydown', onKey)
+ }
+ }, [open])
+
+ return (
+ <div ref={root} className="relative">
+ <div onClick={() => setOpen((value) => !value)}>{trigger}</div>
+ {open && (
+ <div className="absolute bottom-full left-0 z-30 mb-1 w-64 overflow-hidden rounded-lg border border-border bg-popover shadow-lg">
+ {DOC_TEMPLATES.map((template) => (
+ <button
+ key={template.id}
+ type="button"
+ onClick={async () => {
+ setOpen(false)
+ const title = window.prompt('Document title', template.label)
+ if (!title?.trim()) return
+ await onCreate({ title: title.trim(), templateId: template.id, parentId })
+ }}
+ className="flex w-full cursor-pointer flex-col items-start px-3 py-1.5 text-left hover:bg-muted"
+ >
+ <span className="text-xs">{template.label}</span>
+ <span className="text-[10px] text-muted-foreground">{template.hint}</span>
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/frontend/src/documentation/frontmatter.ts b/frontend/src/documentation/frontmatter.ts
new file mode 100644
index 0000000..5a099d9
--- /dev/null
+++ b/frontend/src/documentation/frontmatter.ts
@@ -0,0 +1,86 @@
+import yaml from 'js-yaml'
+
+/**
+ * The YAML block at the top of a document body.
+ *
+ * The body is the source of truth — it is what exports to disk — so nothing
+ * here ever writes the parsed object back on its own. Malformed YAML is not an
+ * error: the user is mid-edit, and the metadata simply reads empty until the
+ * block parses again.
+ */
+
+const BLOCK = /^---\s*\r?\n([\s\S]*?)\r?\n---\s*(?:\r?\n|$)/
+
+export interface Frontmatter {
+ data: Record<string, unknown>
+ /** The body with the block removed, for rendering. */
+ content: string
+}
+
+export function parseFrontmatter(body: string): Frontmatter {
+ const match = BLOCK.exec(body ?? '')
+ if (!match) return { data: {}, content: body ?? '' }
+ let data: Record<string, unknown> = {}
+ try {
+ const parsed = yaml.load(match[1])
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
+ data = parsed as Record<string, unknown>
+ }
+ } catch {
+ // Mid-edit YAML. The document still renders; only the metadata is missing.
+ }
+ return { data, content: (body ?? '').slice(match[0].length) }
+}
+
+export function tagsOf(data: Record<string, unknown>): string[] {
+ const raw = data.tags
+ if (typeof raw === 'string') return raw.split(',').map((t) => t.trim()).filter(Boolean)
+ if (!Array.isArray(raw)) return []
+ return raw.map((t) => String(t).trim()).filter(Boolean)
+}
+
+/** Replace the frontmatter block, or add one when the body has none. */
+export function withFrontmatter(body: string, data: Record<string, unknown>): string {
+ const block = `---\n${yaml.dump(data, { lineWidth: 120 }).trimEnd()}\n---\n`
+ const match = BLOCK.exec(body ?? '')
+ return match ? block + (body ?? '').slice(match[0].length) : `${block}\n${body ?? ''}`
+}
+
+const INTERVAL = /^\s*(\d+)\s*([dwmy])\s*$/i
+const INTERVAL_DAYS: Record<string, number> = { d: 1, w: 7, m: 30, y: 365 }
+
+/** `6m` → 180 days in ms. Anything unparseable means "never due". */
+export function reviewInterval(raw: unknown): number | null {
+ const match = INTERVAL.exec(String(raw ?? ''))
+ if (!match) return null
+ return Number(match[1]) * INTERVAL_DAYS[match[2].toLowerCase()] * 24 * 60 * 60 * 1000
+}
+
+export function isOverdue(
+ data: Record<string, unknown>,
+ reviewedAt: string | null | undefined,
+ createdAt: string,
+ now = Date.now(),
+): boolean {
+ const interval = reviewInterval(data.review_every)
+ if (interval === null) return false
+ const since = Date.parse(reviewedAt || createdAt)
+ return Number.isFinite(since) && now - since > interval
+}
+
+/** The one-line summary shown on a card: the first blockquote or paragraph. */
+export function summaryOf(body: string, limit = 160): string {
+ const { content } = parseFrontmatter(body)
+ for (const raw of content.split(/\r?\n/)) {
+ const line = raw.trim()
+ if (!line || line.startsWith('#') || line.startsWith('<!--')) continue
+ const withoutQuote = line.replace(/^>\s?/, '').trim()
+ // A generated prompt is not a summary — it is the absence of one. Checked
+ // before the emphasis is stripped, since the underscores are the marker.
+ if (/^[_*].*[_*]$/.test(withoutQuote)) continue
+ const text = withoutQuote.replace(/[*_`]/g, '').trim()
+ if (!text) continue
+ return text.length > limit ? `${text.slice(0, limit - 1)}…` : text
+ }
+ return ''
+}
diff --git a/frontend/src/documentation/markdown/Markdown.tsx b/frontend/src/documentation/markdown/Markdown.tsx
new file mode 100644
index 0000000..853db53
--- /dev/null
+++ b/frontend/src/documentation/markdown/Markdown.tsx
@@ -0,0 +1,145 @@
+import { useMemo } from 'react'
+import ReactMarkdown, { type Components } from 'react-markdown'
+import rehypeSlug from 'rehype-slug'
+import remarkGfm from 'remark-gfm'
+
+import { parseFrontmatter } from '../frontmatter'
+import { toggleTaskAtLine } from './tasks'
+import { WikiText } from './WikiText'
+import type { LinkableDevice, LinkableDoc } from '../wikilinks'
+
+/**
+ * Renders a document body.
+ *
+ * Raw HTML is deliberately **not** enabled (`rehype-raw` is absent), so a
+ * document cannot inject markup and no sanitiser is needed. The HTML comments
+ * the generator writes as provenance markers simply do not render, which is
+ * what we want: they stay in the source and out of the page.
+ */
+
+export interface MarkdownProps {
+ body: string
+ docs?: LinkableDoc[]
+ devices?: LinkableDevice[]
+ onOpenDoc?: (docId: string) => void
+ onCreateFromLink?: (label: string) => void
+ /** Called when a task checkbox is toggled, with the rewritten body. */
+ onToggleTask?: (nextBody: string) => void
+ className?: string
+}
+
+export function Markdown({
+ body,
+ docs = [],
+ devices = [],
+ onOpenDoc,
+ onCreateFromLink,
+ onToggleTask,
+ className,
+}: MarkdownProps) {
+ const { content } = useMemo(() => parseFrontmatter(body), [body])
+
+ const components = useMemo<Components>(() => {
+ return {
+ // Every text node passes through the wiki-link splitter.
+ p: ({ children }) => (
+ <p className="my-3 leading-relaxed">
+ <WikiText docs={docs} devices={devices} onOpenDoc={onOpenDoc} onCreate={onCreateFromLink}>
+ {children}
+ </WikiText>
+ </p>
+ ),
+ li: ({ children }) => (
+ <li className="my-1">
+ <WikiText docs={docs} devices={devices} onOpenDoc={onOpenDoc} onCreate={onCreateFromLink}>
+ {children}
+ </WikiText>
+ </li>
+ ),
+ td: ({ children }) => (
+ <td className="border border-border px-3 py-1.5 align-top">
+ <WikiText docs={docs} devices={devices} onOpenDoc={onOpenDoc} onCreate={onCreateFromLink}>
+ {children}
+ </WikiText>
+ </td>
+ ),
+ h1: ({ children, ...props }) => (
+ <h1 {...props} className="mt-8 mb-3 scroll-mt-20 text-2xl font-semibold first:mt-0">
+ {children}
+ </h1>
+ ),
+ h2: ({ children, ...props }) => (
+ <h2 {...props} className="mt-8 mb-3 scroll-mt-20 border-b border-border pb-1.5 text-lg font-semibold">
+ {children}
+ </h2>
+ ),
+ h3: ({ children, ...props }) => (
+ <h3 {...props} className="mt-6 mb-2 scroll-mt-20 text-sm font-semibold uppercase tracking-wide text-muted-foreground">
+ {children}
+ </h3>
+ ),
+ a: ({ children, href }) => (
+ <a
+ href={href}
+ target={href?.startsWith('http') ? '_blank' : undefined}
+ rel="noreferrer"
+ className="text-primary underline underline-offset-2 hover:no-underline"
+ >
+ {children}
+ </a>
+ ),
+ // Wide tables scroll inside their own box; the page never scrolls sideways.
+ table: ({ children }) => (
+ <div className="my-4 overflow-x-auto">
+ <table className="w-full border-collapse text-xs">{children}</table>
+ </div>
+ ),
+ th: ({ children }) => (
+ <th className="border border-border bg-muted/40 px-3 py-1.5 text-left font-medium">{children}</th>
+ ),
+ blockquote: ({ children }) => (
+ <blockquote className="my-4 border-l-2 border-primary/50 bg-muted/30 py-1 pl-4 text-muted-foreground">
+ {children}
+ </blockquote>
+ ),
+ code: ({ children, className: cls }) =>
+ cls?.includes('language-') ? (
+ <code className="font-mono text-xs">{children}</code>
+ ) : (
+ <code className="rounded bg-muted px-1 py-0.5 font-mono text-[0.85em]">{children}</code>
+ ),
+ pre: ({ children }) => (
+ <pre className="my-4 overflow-x-auto rounded-lg border border-border bg-muted/40 p-3">{children}</pre>
+ ),
+ hr: () => <hr className="my-6 border-border" />,
+ ul: ({ children }) => <ul className="my-3 list-disc pl-5">{children}</ul>,
+ ol: ({ children }) => <ol className="my-3 list-decimal pl-5">{children}</ol>,
+ img: ({ src, alt }) => (
+ <img src={typeof src === 'string' ? src : undefined} alt={alt ?? ''} className="my-4 max-w-full rounded-lg border border-border" />
+ ),
+ // The node carries its source position, so a click edits the line that
+ // produced it — no counting, and nesting cannot shift the target.
+ input: ({ checked, type, node }) => {
+ if (type !== 'checkbox') return null
+ const line = node?.position?.start.line
+ return (
+ <input
+ type="checkbox"
+ checked={Boolean(checked)}
+ disabled={!onToggleTask || line === undefined}
+ onChange={() => line !== undefined && onToggleTask?.(toggleTaskAtLine(body, line))}
+ className="mr-2 -mb-px align-middle accent-primary"
+ />
+ )
+ },
+ }
+ }, [body, devices, docs, onCreateFromLink, onOpenDoc, onToggleTask])
+
+ return (
+ <div className={className}>
+ <ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeSlug]} components={components}>
+ {content}
+ </ReactMarkdown>
+ </div>
+ )
+}
diff --git a/frontend/src/documentation/markdown/WikiText.tsx b/frontend/src/documentation/markdown/WikiText.tsx
new file mode 100644
index 0000000..a09c599
--- /dev/null
+++ b/frontend/src/documentation/markdown/WikiText.tsx
@@ -0,0 +1,61 @@
+import { Children, isValidElement, type ReactNode } from 'react'
+
+import { resolveWikiLink, splitWikiLinks, type LinkableDevice, type LinkableDoc } from '../wikilinks'
+
+/**
+ * Rewrites `[[…]]` inside already-rendered markdown children.
+ *
+ * Walking the rendered children rather than the markdown source keeps the
+ * wiki-link syntax out of the AST pipeline, so emphasis, code spans and links
+ * around it still parse as ordinary markdown.
+ */
+
+interface Props {
+ children: ReactNode
+ docs: LinkableDoc[]
+ devices: LinkableDevice[]
+ onOpenDoc?: (docId: string) => void
+ onCreate?: (label: string) => void
+}
+
+export function WikiText({ children, docs, devices, onOpenDoc, onCreate }: Props) {
+ return (
+ <>
+ {Children.map(children, (child, childIndex) => {
+ if (typeof child !== 'string') {
+ // Only bare text can carry a wiki-link; anything already rendered
+ // (a code span, a link) is left exactly as markdown produced it.
+ return isValidElement(child) ? child : child
+ }
+ return splitWikiLinks(child).map((segment, index) => {
+ if (segment.type === 'text') return segment.value
+ const targetId = resolveWikiLink(segment.link, docs, devices)
+ const key = `${childIndex}-${index}`
+ if (!targetId) {
+ return (
+ <button
+ key={key}
+ type="button"
+ onClick={() => onCreate?.(segment.link.label)}
+ title="No document matches this link yet — click to create one"
+ className="cursor-pointer rounded border border-dashed border-destructive/50 px-1 text-destructive"
+ >
+ {segment.link.label}
+ </button>
+ )
+ }
+ return (
+ <button
+ key={key}
+ type="button"
+ onClick={() => onOpenDoc?.(targetId)}
+ className="cursor-pointer rounded bg-primary/10 px-1 text-primary hover:bg-primary/20"
+ >
+ {segment.link.label}
+ </button>
+ )
+ })
+ })}
+ </>
+ )
+}
diff --git a/frontend/src/documentation/markdown/tasks.ts b/frontend/src/documentation/markdown/tasks.ts
new file mode 100644
index 0000000..6568332
--- /dev/null
+++ b/frontend/src/documentation/markdown/tasks.ts
@@ -0,0 +1,25 @@
+/**
+ * Toggling a checkbox in a rendered document.
+ *
+ * Addressed by source line rather than by counting checkboxes: the rendered
+ * tree carries each node's position, so a click maps straight back to the line
+ * that produced it and nested or reordered lists cannot shift the target.
+ */
+
+const TASK = /^(\s*(?:[-*+]|\d+[.)])\s+\[)([ xX])(\])/
+
+export function isTaskLine(line: string): boolean {
+ return TASK.test(line)
+}
+
+/** Flip the task on 1-based `line`. Returns the body unchanged if it is not one. */
+export function toggleTaskAtLine(body: string, line: number): string {
+ const lines = (body ?? '').split('\n')
+ const index = line - 1
+ if (index < 0 || index >= lines.length) return body
+ const match = TASK.exec(lines[index])
+ if (!match) return body
+ const next = match[2].trim() ? ' ' : 'x'
+ lines[index] = `${match[1]}${next}${match[3]}${lines[index].slice(match[0].length)}`
+ return lines.join('\n')
+}
diff --git a/frontend/src/documentation/markdown/toc.ts b/frontend/src/documentation/markdown/toc.ts
new file mode 100644
index 0000000..259955d
--- /dev/null
+++ b/frontend/src/documentation/markdown/toc.ts
@@ -0,0 +1,62 @@
+/**
+ * Headings for the "On this page" rail.
+ *
+ * Read from the markdown source rather than the DOM so the rail renders with
+ * the document instead of one paint later, and so it works in tests. Slugs
+ * match `rehype-slug`'s GitHub algorithm — lowercase, punctuation dropped,
+ * spaces to dashes, duplicates suffixed — because that is what the rendered
+ * anchors carry.
+ */
+
+export interface TocEntry {
+ id: string
+ text: string
+ level: number
+}
+
+const HEADING = /^(#{1,4})\s+(.+?)\s*#*\s*$/
+const FENCE = /^\s*(```|~~~)/
+
+export function slugifyHeading(text: string): string {
+ return text
+ .trim()
+ .toLowerCase()
+ .replace(/[^\p{L}\p{N}\s-]/gu, '')
+ // Each whitespace character becomes its own dash — github-slugger does not
+ // collapse runs, so "Start / stop" anchors as "start--stop".
+ .replace(/\s/g, '-')
+}
+
+/** Strip the inline markup a heading may carry before it becomes a label. */
+export function headingText(raw: string): string {
+ return raw
+ .replace(/\[\[([^\]]+)\]\]/g, (_, inner: string) => inner.split('|').pop()?.trim() ?? inner)
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
+ .replace(/[*_`]/g, '')
+ .trim()
+}
+
+export function extractToc(body: string, minLevel = 2, maxLevel = 3): TocEntry[] {
+ const entries: TocEntry[] = []
+ const used = new Map<string, number>()
+ let inFence = false
+
+ for (const line of (body ?? '').split('\n')) {
+ if (FENCE.test(line)) {
+ inFence = !inFence
+ continue
+ }
+ if (inFence) continue
+ const match = HEADING.exec(line)
+ if (!match) continue
+ const level = match[1].length
+ if (level < minLevel || level > maxLevel) continue
+ const text = headingText(match[2])
+ if (!text) continue
+ const base = slugifyHeading(text)
+ const seen = used.get(base) ?? 0
+ used.set(base, seen + 1)
+ entries.push({ id: seen === 0 ? base : `${base}-${seen}`, text, level })
+ }
+ return entries
+}
diff --git a/frontend/src/documentation/store.ts b/frontend/src/documentation/store.ts
new file mode 100644
index 0000000..532dc2d
--- /dev/null
+++ b/frontend/src/documentation/store.ts
@@ -0,0 +1,443 @@
+import { create } from 'zustand'
+
+import { documentsApi } from '@/api/client'
+import { isOverdue } from './frontmatter'
+import type {
+ Doc,
+ DocCoverage,
+ DocRevision,
+ DocSearchResult,
+ DocumentSummary,
+ GroupBy,
+} from './types'
+
+/**
+ * Documentation state.
+ *
+ * Two rules shape this store. Saving is explicit — a body is never written to
+ * the server on a timer, matching the canvas — and an unsaved body is mirrored
+ * to localStorage so closing a tab or switching documents cannot lose an edit.
+ * The draft is cleared the moment the save lands.
+ */
+
+const STANDALONE = import.meta.env.VITE_STANDALONE === 'true'
+
+const UI_KEY = 'homelable_docs_ui'
+const DRAFT_PREFIX = 'homelable_docdraft:'
+
+interface DraftRecord {
+ body: string
+ savedAt: number
+ /** The document's `updated_at` when the draft was taken, to detect staleness. */
+ base: string
+}
+
+export function draftKey(docId: string): string {
+ return `${DRAFT_PREFIX}${docId}`
+}
+
+export function readDraft(docId: string): DraftRecord | null {
+ try {
+ const raw = localStorage.getItem(draftKey(docId))
+ return raw ? (JSON.parse(raw) as DraftRecord) : null
+ } catch {
+ return null
+ }
+}
+
+export function writeDraft(docId: string, record: DraftRecord): void {
+ try {
+ localStorage.setItem(draftKey(docId), JSON.stringify(record))
+ } catch {
+ // A full or blocked storage must never break editing.
+ }
+}
+
+export function clearDraft(docId: string): void {
+ try {
+ localStorage.removeItem(draftKey(docId))
+ } catch {
+ // Ignored for the same reason.
+ }
+}
+
+interface UiPrefs {
+ groupBy: GroupBy
+ expanded: string[]
+ lastDocId: string | null
+ treeWidth: number
+}
+
+const DEFAULT_UI: UiPrefs = { groupBy: 'zone', expanded: [], lastDocId: null, treeWidth: 260 }
+
+function readUi(): UiPrefs {
+ try {
+ const raw = localStorage.getItem(UI_KEY)
+ return raw ? { ...DEFAULT_UI, ...(JSON.parse(raw) as Partial<UiPrefs>) } : DEFAULT_UI
+ } catch {
+ return DEFAULT_UI
+ }
+}
+
+function writeUi(prefs: UiPrefs): void {
+ try {
+ localStorage.setItem(UI_KEY, JSON.stringify(prefs))
+ } catch {
+ // Preferences are a convenience; losing them is not an error.
+ }
+}
+
+export interface DocsState {
+ docs: DocumentSummary[]
+ loaded: boolean
+ loading: boolean
+ loadError: string | null
+
+ openDoc: Doc | null
+ openLoading: boolean
+
+ /** The body being edited. Null when not in edit mode. */
+ draft: string | null
+ dirty: boolean
+ saving: boolean
+ /** A recovered draft awaiting the user's yes or no. */
+ pendingDraft: string | null
+
+ revisions: DocRevision[]
+ coverage: DocCoverage | null
+ search: DocSearchResult | null
+ searching: boolean
+
+ groupBy: GroupBy
+ expanded: string[]
+ treeWidth: number
+ filter: string
+
+ loadDocs: () => Promise<void>
+ open: (id: string) => Promise<void>
+ close: () => void
+
+ startEdit: () => void
+ setDraft: (body: string) => void
+ cancelEdit: () => void
+ save: () => Promise<boolean>
+ acceptPendingDraft: () => void
+ discardPendingDraft: () => void
+
+ create: (input: {
+ title: string
+ kind?: string
+ parentId?: string | null
+ deviceId?: string | null
+ nodeId?: string | null
+ templateId?: string | null
+ }) => Promise<Doc | null>
+ rename: (id: string, title: string) => Promise<void>
+ move: (id: string, parentId: string | null) => Promise<void>
+ toggleStar: (id: string) => Promise<void>
+ markReviewed: (id: string) => Promise<void>
+ resyncFacts: (id: string) => Promise<void>
+ remove: (id: string) => Promise<void>
+
+ loadRevisions: (id: string) => Promise<void>
+ restore: (id: string, revisionId: string) => Promise<void>
+
+ loadCoverage: () => Promise<void>
+ scaffold: (input: { deviceIds?: string[]; onlyWithNotes?: boolean }) => Promise<number>
+ runSearch: (query: string) => Promise<void>
+ clearSearch: () => void
+
+ setGroupBy: (groupBy: GroupBy) => void
+ toggleExpanded: (key: string) => void
+ setExpanded: (keys: string[]) => void
+ setTreeWidth: (width: number) => void
+ setFilter: (filter: string) => void
+}
+
+function message(error: unknown, fallback: string): string {
+ const detail = (error as { response?: { data?: { detail?: unknown } } })?.response?.data?.detail
+ return typeof detail === 'string' ? detail : fallback
+}
+
+const initialUi = readUi()
+
+export const useDocsStore = create<DocsState>()((set, get) => ({
+ docs: [],
+ loaded: false,
+ loading: false,
+ loadError: null,
+
+ openDoc: null,
+ openLoading: false,
+
+ draft: null,
+ dirty: false,
+ saving: false,
+ pendingDraft: null,
+
+ revisions: [],
+ coverage: null,
+ search: null,
+ searching: false,
+
+ groupBy: initialUi.groupBy,
+ expanded: initialUi.expanded,
+ treeWidth: initialUi.treeWidth,
+ filter: '',
+
+ loadDocs: async () => {
+ if (STANDALONE) {
+ // Documents need the backend. Standalone shows the section empty with an
+ // explanation rather than pretending to have loaded nothing.
+ set({ loaded: true, docs: [], loadError: null })
+ return
+ }
+ set({ loading: true, loadError: null })
+ try {
+ const { data } = await documentsApi.list()
+ set({ docs: data, loaded: true, loading: false })
+ } catch (error) {
+ set({ loading: false, loaded: true, loadError: message(error, 'Could not load documents') })
+ }
+ },
+
+ open: async (id) => {
+ set({ openLoading: true, draft: null, dirty: false, pendingDraft: null, revisions: [] })
+ try {
+ const { data } = await documentsApi.get(id)
+ // A draft newer than the stored document is unsaved work from a previous
+ // session; offer it rather than silently applying or dropping it.
+ const draft = readDraft(id)
+ const stale = draft !== null && draft.base !== data.updated_at
+ set({
+ openDoc: data,
+ openLoading: false,
+ pendingDraft: draft && !stale && draft.body !== data.body ? draft.body : null,
+ })
+ if (draft && stale) clearDraft(id)
+ writeUi({ ...readUi(), lastDocId: id })
+ } catch (error) {
+ set({ openLoading: false, loadError: message(error, 'Could not open that document') })
+ }
+ },
+
+ close: () => set({ openDoc: null, draft: null, dirty: false, pendingDraft: null, revisions: [] }),
+
+ startEdit: () => {
+ const doc = get().openDoc
+ if (doc) set({ draft: doc.body, dirty: false })
+ },
+
+ setDraft: (body) => {
+ const doc = get().openDoc
+ set({ draft: body, dirty: doc ? body !== doc.body : false })
+ if (doc) writeDraft(doc.id, { body, savedAt: Date.now(), base: doc.updated_at })
+ },
+
+ cancelEdit: () => {
+ const doc = get().openDoc
+ if (doc) clearDraft(doc.id)
+ set({ draft: null, dirty: false })
+ },
+
+ save: async () => {
+ const { openDoc, draft } = get()
+ if (!openDoc || draft === null) return false
+ set({ saving: true })
+ try {
+ const { data } = await documentsApi.update(openDoc.id, { body: draft })
+ clearDraft(openDoc.id)
+ set((state) => ({
+ openDoc: data,
+ draft: data.body,
+ dirty: false,
+ saving: false,
+ docs: state.docs.map((d) => (d.id === data.id ? { ...d, ...data } : d)),
+ }))
+ return true
+ } catch (error) {
+ set({ saving: false, loadError: message(error, 'Could not save') })
+ return false
+ }
+ },
+
+ acceptPendingDraft: () => {
+ const { pendingDraft, openDoc } = get()
+ if (pendingDraft === null || !openDoc) return
+ set({ draft: pendingDraft, dirty: pendingDraft !== openDoc.body, pendingDraft: null })
+ },
+
+ discardPendingDraft: () => {
+ const doc = get().openDoc
+ if (doc) clearDraft(doc.id)
+ set({ pendingDraft: null })
+ },
+
+ create: async (input) => {
+ try {
+ const { data } = await documentsApi.create({
+ title: input.title,
+ kind: input.kind,
+ parent_id: input.parentId ?? null,
+ device_id: input.deviceId ?? null,
+ node_id: input.nodeId ?? null,
+ template_id: input.templateId ?? null,
+ })
+ set((state) => ({ docs: [...state.docs, data], openDoc: data }))
+ return data
+ } catch (error) {
+ set({ loadError: message(error, 'Could not create that document') })
+ return null
+ }
+ },
+
+ rename: async (id, title) => {
+ const { data } = await documentsApi.update(id, { title })
+ set((state) => ({
+ docs: state.docs.map((d) => (d.id === id ? { ...d, ...data } : d)),
+ openDoc: state.openDoc?.id === id ? data : state.openDoc,
+ }))
+ },
+
+ move: async (id, parentId) => {
+ const { data } = await documentsApi.update(id, { parent_id: parentId })
+ set((state) => ({ docs: state.docs.map((d) => (d.id === id ? { ...d, ...data } : d)) }))
+ },
+
+ toggleStar: async (id) => {
+ const current = get().docs.find((d) => d.id === id)
+ const { data } = await documentsApi.update(id, { starred: !current?.starred })
+ set((state) => ({
+ docs: state.docs.map((d) => (d.id === id ? { ...d, ...data } : d)),
+ openDoc: state.openDoc?.id === id ? data : state.openDoc,
+ }))
+ },
+
+ markReviewed: async (id) => {
+ const { data } = await documentsApi.update(id, { reviewed: true })
+ set((state) => ({
+ docs: state.docs.map((d) => (d.id === id ? { ...d, ...data } : d)),
+ openDoc: state.openDoc?.id === id ? data : state.openDoc,
+ }))
+ },
+
+ resyncFacts: async (id) => {
+ const { data } = await documentsApi.update(id, { resync_facts: true })
+ set((state) => ({
+ docs: state.docs.map((d) => (d.id === id ? { ...d, ...data } : d)),
+ openDoc: state.openDoc?.id === id ? data : state.openDoc,
+ }))
+ },
+
+ remove: async (id) => {
+ await documentsApi.delete(id)
+ clearDraft(id)
+ set((state) => ({
+ // The server takes a folder's subtree with it; drop the descendants here
+ // too rather than reloading the whole list.
+ docs: state.docs.filter((d) => d.id !== id && !isDescendant(state.docs, d, id)),
+ openDoc: state.openDoc?.id === id ? null : state.openDoc,
+ draft: state.openDoc?.id === id ? null : state.draft,
+ }))
+ },
+
+ loadRevisions: async (id) => {
+ const { data } = await documentsApi.revisions(id)
+ set({ revisions: data })
+ },
+
+ restore: async (id, revisionId) => {
+ const { data } = await documentsApi.restore(id, revisionId)
+ clearDraft(id)
+ set((state) => ({
+ openDoc: data,
+ draft: state.draft === null ? null : data.body,
+ dirty: false,
+ docs: state.docs.map((d) => (d.id === id ? { ...d, ...data } : d)),
+ }))
+ await get().loadRevisions(id)
+ },
+
+ loadCoverage: async () => {
+ if (STANDALONE) return
+ try {
+ const { data } = await documentsApi.coverage()
+ set({ coverage: data })
+ } catch {
+ // Coverage is informational — a failure must not block the section.
+ }
+ },
+
+ scaffold: async ({ deviceIds, onlyWithNotes }) => {
+ const { data } = await documentsApi.scaffold({
+ device_ids: deviceIds,
+ only_with_notes: onlyWithNotes,
+ })
+ set((state) => ({ docs: [...state.docs, ...data.created] }))
+ await get().loadCoverage()
+ return data.created.length
+ },
+
+ runSearch: async (query) => {
+ if (!query.trim()) {
+ set({ search: null, searching: false })
+ return
+ }
+ set({ searching: true })
+ try {
+ const { data } = await documentsApi.search(query)
+ set({ search: data, searching: false })
+ } catch (error) {
+ set({ searching: false, loadError: message(error, 'Search failed') })
+ }
+ },
+
+ clearSearch: () => set({ search: null }),
+
+ setGroupBy: (groupBy) => {
+ set({ groupBy })
+ writeUi({ ...readUi(), groupBy })
+ },
+
+ toggleExpanded: (key) => {
+ const expanded = get().expanded.includes(key)
+ ? get().expanded.filter((k) => k !== key)
+ : [...get().expanded, key]
+ set({ expanded })
+ writeUi({ ...readUi(), expanded })
+ },
+
+ setExpanded: (keys) => {
+ set({ expanded: keys })
+ writeUi({ ...readUi(), expanded: keys })
+ },
+
+ setTreeWidth: (treeWidth) => {
+ set({ treeWidth })
+ writeUi({ ...readUi(), treeWidth })
+ },
+
+ setFilter: (filter) => set({ filter }),
+}))
+
+/** Whether `doc` sits anywhere under `ancestorId`. */
+export function isDescendant(all: DocumentSummary[], doc: DocumentSummary, ancestorId: string): boolean {
+ const byId = new Map(all.map((d) => [d.id, d]))
+ const seen = new Set<string>()
+ let cursor = doc.parent_id ?? null
+ while (cursor && !seen.has(cursor)) {
+ if (cursor === ancestorId) return true
+ seen.add(cursor)
+ cursor = byId.get(cursor)?.parent_id ?? null
+ }
+ return false
+}
+
+/** Document ids whose `review_every` has elapsed. Used for the tree badge. */
+export function overdueIds(docs: DocumentSummary[], now = Date.now()): Set<string> {
+ return new Set(
+ docs
+ .filter((doc) => isOverdue(doc.frontmatter ?? {}, doc.reviewed_at, doc.created_at, now))
+ .map((doc) => doc.id),
+ )
+}
diff --git a/frontend/src/documentation/tree.ts b/frontend/src/documentation/tree.ts
new file mode 100644
index 0000000..75ea16f
--- /dev/null
+++ b/frontend/src/documentation/tree.ts
@@ -0,0 +1,329 @@
+import type { Node } from '@xyflow/react'
+
+import type { Design, InventoryEntry, NodeData } from '@/types'
+import { ipToInt, parseCidr } from '@/utils/subnet'
+import type { DocState, DocumentSummary, GroupBy, TreeGroup, TreeLeaf } from './types'
+
+/**
+ * The Devices tree, pivoted.
+ *
+ * Every grouping the user can pick is derivable from data the app has already
+ * loaded — the inventory rows, the canvas nodes, the racks — so the tree is
+ * built here rather than fetched. Re-pivoting is then instant and there is no
+ * server-side tree to keep in sync with the canvas.
+ *
+ * The Library tree is the opposite: real folders the user files by hand, so it
+ * comes straight from `parent_id` and never re-shapes.
+ */
+
+const UNGROUPED = 'Ungrouped'
+
+/** Canvas furniture. A zone or a group is a container, not a device. */
+const FURNITURE = new Set(['group', 'groupRect', 'text'])
+
+/** Types that are a guest rather than a box you can touch. */
+const VIRTUAL_TYPES = new Set(['vm', 'lxc', 'docker_container'])
+
+/** Types that host guests. Reported separately so the split reads as three. */
+const HOST_TYPES = new Set(['proxmox', 'docker_host'])
+
+export type Physicality = 'Physical' | 'Virtual' | 'Host'
+
+/**
+ * Physical, virtual, or a host running guests.
+ *
+ * The type decides it; `container_mode` and having children are the fallback
+ * for a device typed generically but drawn as a container.
+ */
+export function physicality(
+ type: string | null | undefined,
+ opts: { hasChildren?: boolean; containerMode?: boolean } = {},
+): Physicality {
+ const t = type ?? ''
+ if (VIRTUAL_TYPES.has(t)) return 'Virtual'
+ if (HOST_TYPES.has(t)) return 'Host'
+ if (opts.containerMode || opts.hasChildren) return 'Host'
+ return 'Physical'
+}
+
+/** Every IP a device declares. The column is a comma-separated list. */
+export function splitIps(ip: string | null | undefined): string[] {
+ return (ip ?? '')
+ .split(',')
+ .map((token) => token.trim())
+ .filter(Boolean)
+}
+
+/** The /24 an address sits in, for grouping when no CIDR is configured. */
+export function slash24(ip: string): string | null {
+ if (ipToInt(ip) === null) return null
+ const octets = ip.split('.')
+ return `${octets[0]}.${octets[1]}.${octets[2]}.0/24`
+}
+
+/**
+ * Which of the configured ranges an address falls in, else its own /24.
+ * A device declaring several addresses lands under each of their subnets.
+ */
+export function subnetsOf(device: InventoryEntry, ranges: string[]): string[] {
+ const found = new Set<string>()
+ for (const ip of splitIps(device.ip)) {
+ const value = ipToInt(ip)
+ if (value === null) continue
+ const match = ranges.find((cidr) => {
+ const parsed = parseCidr(cidr)
+ if (!parsed) return false
+ const mask = parsed.bits === 0 ? 0 : (-1 << (32 - parsed.bits)) >>> 0
+ return ((value & mask) >>> 0) === parsed.base
+ })
+ const subnet = match ?? slash24(ip)
+ if (subnet) found.add(subnet)
+ }
+ return found.size ? [...found] : [UNGROUPED]
+}
+
+export interface DeviceContext {
+ /**
+ * Nodes of the canvas that is currently loaded. The app only ever holds one
+ * canvas at a time, so the "Canvas" pivot answers "on this one or not"
+ * rather than naming every canvas a device appears on.
+ */
+ nodes: Node<NodeData>[]
+ designs: Design[]
+ /** The design those nodes belong to. */
+ activeDesignId?: string | null
+ /** deviceId → rack name, from the rack store when a rack canvas is loaded. */
+ racksByDevice?: Record<string, string>
+ /** CIDRs from the scan settings; falls back to a per-address /24. */
+ ranges?: string[]
+}
+
+interface NodeFacts {
+ zone?: string
+ group?: string
+ canvas?: string
+ hasChildren: boolean
+ containerMode: boolean
+ type?: string
+}
+
+/**
+ * What the canvas knows about each device: the containers it sits in and the
+ * canvas it is drawn on. A device drawn twice keeps the first placement per
+ * grouping, so it appears once under each distinct answer.
+ */
+export function nodeFactsByDevice(context: DeviceContext): Record<string, NodeFacts> {
+ const byId = new Map(context.nodes.map((n) => [n.id, n]))
+ const designName = new Map(context.designs.map((d) => [d.id, d.name]))
+ const parentOf = new Map<string, string>()
+ for (const node of context.nodes) {
+ if (node.data.parent_id) parentOf.set(node.id, node.data.parent_id)
+ }
+ const hasChildren = new Set([...parentOf.values()])
+
+ const facts: Record<string, NodeFacts> = {}
+ for (const node of context.nodes) {
+ const deviceId = node.data.device_id
+ if (!deviceId || FURNITURE.has(node.data.type)) continue
+ const entry: NodeFacts = facts[deviceId] ?? {
+ hasChildren: hasChildren.has(node.id),
+ containerMode: node.data.container_mode === true,
+ type: node.data.type,
+ }
+ // Walk up to the nearest zone and the nearest group; they are different
+ // containers and a node can sit in one, the other, or both.
+ const seen = new Set<string>()
+ let cursor = node.data.parent_id
+ while (cursor && !seen.has(cursor)) {
+ seen.add(cursor)
+ const parent = byId.get(cursor)
+ if (!parent) break
+ if (parent.data.type === 'groupRect' && !entry.zone) entry.zone = parent.data.label
+ if (parent.data.type === 'group' && !entry.group) entry.group = parent.data.label
+ cursor = parent.data.parent_id
+ }
+ if (!entry.canvas && context.activeDesignId) {
+ entry.canvas = designName.get(context.activeDesignId)
+ }
+ facts[deviceId] = entry
+ }
+ return facts
+}
+
+/** The buckets one device belongs to under a given pivot. Usually exactly one. */
+export function bucketsFor(
+ device: InventoryEntry,
+ groupBy: GroupBy,
+ facts: NodeFacts | undefined,
+ doc: DocumentSummary | undefined,
+ context: DeviceContext,
+): string[] {
+ switch (groupBy) {
+ case 'zone':
+ return [facts?.zone || 'Unzoned']
+ case 'group':
+ return [facts?.group || 'Ungrouped']
+ case 'type':
+ return [device.type || device.suggested_type || 'Untyped']
+ case 'physicality':
+ return [
+ physicality(device.type || device.suggested_type || facts?.type, {
+ hasChildren: facts?.hasChildren,
+ containerMode: facts?.containerMode,
+ }),
+ ]
+ case 'subnet':
+ return subnetsOf(device, context.ranges ?? [])
+ case 'canvas':
+ return [facts?.canvas || 'Not on this canvas']
+ case 'rack':
+ return [context.racksByDevice?.[device.id] || 'Not racked']
+ case 'vendor':
+ return [device.vendor || 'Unknown vendor']
+ case 'source': {
+ const sources = device.discovery_sources?.length
+ ? device.discovery_sources
+ : [device.discovery_source].filter(Boolean)
+ return sources.length ? (sources as string[]) : [UNGROUPED]
+ }
+ case 'status':
+ return [device.status_live || 'unknown']
+ case 'tag':
+ return doc?.tags?.length ? doc.tags : ['Untagged']
+ case 'flat':
+ default:
+ return ['All devices']
+ }
+}
+
+/** What the badge next to a device says. */
+export function docState(
+ doc: DocumentSummary | undefined,
+ opts: { drifted?: boolean; overdue?: boolean } = {},
+): DocState {
+ if (!doc) return 'none'
+ if (opts.drifted) return 'drifted'
+ if (opts.overdue) return 'overdue'
+ return doc.edited_at ? 'written' : 'header-only'
+}
+
+export function deviceLabel(device: InventoryEntry): string {
+ return device.label || device.friendly_name || device.hostname || device.ip || 'Unnamed device'
+}
+
+const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' })
+
+/** Groups last-resort buckets to the bottom, everything else alphabetically. */
+function compareGroups(a: TreeGroup, b: TreeGroup): number {
+ const trailing = new Set(['Unzoned', 'Ungrouped', 'Untyped', 'Untagged', 'Not racked', 'Not on this canvas', 'Unknown vendor', UNGROUPED])
+ const aLast = trailing.has(a.label)
+ const bLast = trailing.has(b.label)
+ if (aLast !== bLast) return aLast ? 1 : -1
+ return collator.compare(a.label, b.label)
+}
+
+export interface DeviceTreeOptions {
+ groupBy: GroupBy
+ devices: InventoryEntry[]
+ docs: DocumentSummary[]
+ context: DeviceContext
+ /** Document ids the coverage pass flagged. */
+ drifted?: Set<string>
+ overdue?: Set<string>
+}
+
+/** The Devices root, grouped as asked. */
+export function buildDeviceTree(options: DeviceTreeOptions): TreeGroup[] {
+ const { groupBy, devices, docs, context } = options
+ const docByDevice = new Map(docs.filter((d) => d.device_id).map((d) => [d.device_id as string, d]))
+ const facts = nodeFactsByDevice(context)
+
+ const groups = new Map<string, TreeLeaf[]>()
+ for (const device of devices) {
+ const doc = docByDevice.get(device.id)
+ const leaf: TreeLeaf = {
+ id: doc?.id ?? `device:${device.id}`,
+ label: deviceLabel(device),
+ docId: doc?.id,
+ deviceId: device.id,
+ kind: doc ? 'device' : 'device-without-doc',
+ state: docState(doc, {
+ drifted: doc ? options.drifted?.has(doc.id) : false,
+ overdue: doc ? options.overdue?.has(doc.id) : false,
+ }),
+ }
+ for (const bucket of bucketsFor(device, groupBy, facts[device.id], doc, context)) {
+ const items = groups.get(bucket) ?? []
+ items.push(leaf)
+ groups.set(bucket, items)
+ }
+ }
+
+ return [...groups.entries()]
+ .map(([label, items]) => ({
+ key: `${groupBy}:${label}`,
+ label,
+ items: items.sort((a, b) => collator.compare(a.label, b.label)),
+ }))
+ .sort(compareGroups)
+}
+
+/** The Library root: real folders, nested by `parent_id`. */
+export function buildLibraryTree(docs: DocumentSummary[]): TreeLeaf[] {
+ const tree = docs.filter((d) => d.kind === 'page' || d.kind === 'folder')
+ const byParent = new Map<string | null, DocumentSummary[]>()
+ for (const doc of tree) {
+ const key = doc.parent_id ?? null
+ byParent.set(key, [...(byParent.get(key) ?? []), doc])
+ }
+
+ const seen = new Set<string>()
+ const build = (parentId: string | null): TreeLeaf[] =>
+ (byParent.get(parentId) ?? [])
+ .filter((doc) => !seen.has(doc.id))
+ .sort((a, b) => a.sort_order - b.sort_order || collator.compare(a.title, b.title))
+ .map((doc): TreeLeaf => {
+ // A cycle would recurse forever; a folder can only be built once.
+ seen.add(doc.id)
+ return {
+ id: doc.id,
+ label: doc.title,
+ docId: doc.id,
+ kind: doc.kind,
+ state: docState(doc),
+ icon: doc.icon,
+ children: doc.kind === 'folder' ? build(doc.id) : undefined,
+ }
+ })
+
+ return build(null)
+}
+
+/** Filter a tree by a typed query, keeping the folders that lead to a match. */
+export function filterTree(items: TreeLeaf[], query: string): TreeLeaf[] {
+ const needle = query.trim().toLowerCase()
+ if (!needle) return items
+ const walk = (leaves: TreeLeaf[]): TreeLeaf[] =>
+ leaves
+ .map((leaf): TreeLeaf | null => {
+ const children = leaf.children ? walk(leaf.children) : undefined
+ const hit = leaf.label.toLowerCase().includes(needle)
+ if (!hit && !children?.length) return null
+ return { ...leaf, children }
+ })
+ .filter((leaf): leaf is TreeLeaf => leaf !== null)
+ return walk(items)
+}
+
+export function filterGroups(groups: TreeGroup[], query: string): TreeGroup[] {
+ const needle = query.trim().toLowerCase()
+ if (!needle) return groups
+ return groups
+ .map((group) => ({
+ ...group,
+ items: group.label.toLowerCase().includes(needle)
+ ? group.items
+ : group.items.filter((item) => item.label.toLowerCase().includes(needle)),
+ }))
+ .filter((group) => group.items.length > 0)
+}
diff --git a/frontend/src/documentation/types.ts b/frontend/src/documentation/types.ts
new file mode 100644
index 0000000..a8d0f31
--- /dev/null
+++ b/frontend/src/documentation/types.ts
@@ -0,0 +1,137 @@
+/**
+ * A document either lives in the Library tree (`page`, `folder`) or describes
+ * exactly one thing elsewhere in the app (`device`, `node`, `design`).
+ *
+ * Kept in sync with DOCUMENT_KINDS in `backend/app/services/doc_tree.py`.
+ */
+export type DocKind = 'device' | 'node' | 'design' | 'page' | 'folder'
+
+/** Kinds the user files by hand. Everything else is placed by its link. */
+export const TREE_KINDS: readonly DocKind[] = ['page', 'folder']
+
+export interface DocumentSummary {
+ id: string
+ kind: DocKind
+ title: string
+ slug: string
+ icon?: string | null
+ parent_id?: string | null
+ sort_order: number
+ device_id?: string | null
+ node_id?: string | null
+ design_id?: string | null
+ tags: string[]
+ /** The parsed frontmatter, so the tree can badge without loading bodies. */
+ frontmatter: Record<string, unknown>
+ starred: boolean
+ template_id?: string | null
+ reviewed_at?: string | null
+ edited_at?: string | null
+ facts_synced_at?: string | null
+ created_at: string
+ updated_at: string
+}
+
+export interface Doc extends DocumentSummary {
+ body: string
+ facts_snapshot?: Record<string, unknown> | null
+}
+
+export interface DocRevision {
+ id: string
+ document_id: string
+ title: string
+ reason: 'edit' | 'restore' | 'import' | 'migrate' | 'scaffold'
+ saved_at: string
+ size: number
+}
+
+export interface DocSearchHit {
+ doc_id: string
+ title: string
+ kind: DocKind
+ snippet: string
+ device_id?: string | null
+}
+
+export interface DocSearchResult {
+ /** "like" means no FTS5 — the UI drops snippet highlighting. */
+ engine: 'fts5' | 'like'
+ hits: DocSearchHit[]
+}
+
+export interface DocCoverage {
+ devices: number
+ documented: number
+ header_only: number
+ missing: number
+ drifted: number
+ overdue: number
+ notes_unmigrated: number
+ library_pages: number
+}
+
+/** Templates the "New document" menu offers. Mirrors `doc_template.py`. */
+export const DOC_TEMPLATES = [
+ { id: 'blank', label: 'Blank page', hint: 'A title and nothing else' },
+ { id: 'runbook', label: 'Runbook', hint: 'Trigger, steps, rollback' },
+ { id: 'service', label: 'Service', hint: 'A service spanning hosts' },
+ { id: 'network', label: 'Network overview', hint: 'Topology, subnets, routing' },
+ { id: 'incident', label: 'Incident', hint: 'Timeline, cause, fix' },
+ { id: 'procedure', label: 'Procedure', hint: 'Goal, prerequisites, steps' },
+ { id: 'decision', label: 'Decision (ADR)', hint: 'Context, decision, consequences' },
+ { id: 'zone', label: 'Zone / group', hint: 'Purpose, members, addressing' },
+] as const
+
+export type DocTemplateId = (typeof DOC_TEMPLATES)[number]['id']
+
+/** How the Devices root is pivoted. The Library tree never changes shape. */
+export type GroupBy =
+ | 'zone'
+ | 'group'
+ | 'type'
+ | 'physicality'
+ | 'subnet'
+ | 'canvas'
+ | 'rack'
+ | 'vendor'
+ | 'source'
+ | 'status'
+ | 'tag'
+ | 'flat'
+
+export const GROUP_BY_LABELS: Record<GroupBy, string> = {
+ zone: 'Zone',
+ group: 'Group',
+ type: 'Type',
+ physicality: 'Physical / virtual',
+ subnet: 'Subnet',
+ canvas: 'Canvas',
+ rack: 'Rack',
+ vendor: 'Vendor',
+ source: 'Discovery source',
+ status: 'Status',
+ tag: 'Tag',
+ flat: 'A–Z',
+}
+
+/** What the tree badge says about a device at a glance. */
+export type DocState = 'none' | 'header-only' | 'written' | 'drifted' | 'overdue'
+
+export interface TreeLeaf {
+ id: string
+ label: string
+ docId?: string
+ deviceId?: string
+ nodeId?: string
+ kind: DocKind | 'device-without-doc'
+ state: DocState
+ icon?: string | null
+ children?: TreeLeaf[]
+}
+
+export interface TreeGroup {
+ key: string
+ label: string
+ items: TreeLeaf[]
+}
diff --git a/frontend/src/documentation/wikilinks.ts b/frontend/src/documentation/wikilinks.ts
new file mode 100644
index 0000000..a5c0916
--- /dev/null
+++ b/frontend/src/documentation/wikilinks.ts
@@ -0,0 +1,123 @@
+/**
+ * `[[device:nas-01]]`, `[[doc:vlan-plan]]` and bare `[[VLAN plan]]`.
+ *
+ * Parsed as a plain text pass rather than a remark plugin: the syntax is one
+ * token with no nesting, and keeping it out of the AST pipeline means the
+ * markdown stays ordinary markdown for anything that reads the file elsewhere.
+ */
+
+export type WikiTarget = 'device' | 'doc' | 'node'
+
+export interface WikiLink {
+ target: WikiTarget
+ /** What was written after the colon, or the whole label for a bare link. */
+ key: string
+ /** The text to show; the part after `|`, else the key. */
+ label: string
+ raw: string
+}
+
+const LINK = /\[\[([^\]]+)\]\]/g
+
+export function parseWikiLink(inner: string): WikiLink | null {
+ const [addressPart, labelPart] = inner.split('|', 2).map((part) => part.trim())
+ if (!addressPart) return null
+ const colon = addressPart.indexOf(':')
+ let target: WikiTarget = 'doc'
+ let key = addressPart
+ if (colon > 0) {
+ const prefix = addressPart.slice(0, colon).toLowerCase()
+ if (prefix === 'device' || prefix === 'doc' || prefix === 'node') {
+ target = prefix
+ key = addressPart.slice(colon + 1).trim()
+ }
+ }
+ if (!key) return null
+ return { target, key, label: labelPart || key, raw: `[[${inner}]]` }
+}
+
+export type Segment = { type: 'text'; value: string } | { type: 'link'; link: WikiLink }
+
+/** Split a string into plain text and wiki-link segments, in order. */
+export function splitWikiLinks(text: string): Segment[] {
+ const segments: Segment[] = []
+ let cursor = 0
+ LINK.lastIndex = 0
+ let match: RegExpExecArray | null
+ while ((match = LINK.exec(text)) !== null) {
+ const link = parseWikiLink(match[1])
+ if (!link) continue
+ if (match.index > cursor) segments.push({ type: 'text', value: text.slice(cursor, match.index) })
+ segments.push({ type: 'link', link })
+ cursor = match.index + match[0].length
+ }
+ if (cursor < text.length) segments.push({ type: 'text', value: text.slice(cursor) })
+ return segments
+}
+
+/** Every wiki-link in a body, for the backlinks index. */
+export function collectWikiLinks(body: string): WikiLink[] {
+ const found: WikiLink[] = []
+ LINK.lastIndex = 0
+ let match: RegExpExecArray | null
+ while ((match = LINK.exec(body)) !== null) {
+ const link = parseWikiLink(match[1])
+ if (link) found.push(link)
+ }
+ return found
+}
+
+export interface LinkableDoc {
+ id: string
+ slug: string
+ title: string
+ device_id?: string | null
+ node_id?: string | null
+}
+
+export interface LinkableDevice {
+ id: string
+ label: string
+}
+
+/** Resolve a link to a document id, or null when nothing matches yet. */
+export function resolveWikiLink(
+ link: WikiLink,
+ docs: LinkableDoc[],
+ devices: LinkableDevice[] = [],
+): string | null {
+ const key = link.key.toLowerCase()
+ if (link.target === 'device') {
+ const device = devices.find(
+ (d) => d.id === link.key || d.label.toLowerCase() === key,
+ )
+ if (!device) return null
+ return docs.find((doc) => doc.device_id === device.id)?.id ?? null
+ }
+ if (link.target === 'node') {
+ return docs.find((doc) => doc.node_id === link.key)?.id ?? null
+ }
+ return (
+ docs.find((doc) => doc.id === link.key)?.id ??
+ docs.find((doc) => doc.slug.toLowerCase() === key)?.id ??
+ docs.find((doc) => doc.title.toLowerCase() === key)?.id ??
+ null
+ )
+}
+
+/** doc id → the documents that link to it. */
+export function backlinkIndex(
+ docs: (LinkableDoc & { body: string })[],
+ devices: LinkableDevice[] = [],
+): Record<string, string[]> {
+ const index: Record<string, string[]> = {}
+ for (const doc of docs) {
+ for (const link of collectWikiLinks(doc.body)) {
+ const targetId = resolveWikiLink(link, docs, devices)
+ if (!targetId || targetId === doc.id) continue
+ const current = index[targetId] ?? []
+ if (!current.includes(doc.id)) index[targetId] = [...current, doc.id]
+ }
+ }
+ return index
+}
diff --git a/frontend/src/stores/uiStore.ts b/frontend/src/stores/uiStore.ts
new file mode 100644
index 0000000..1ef7da0
--- /dev/null
+++ b/frontend/src/stores/uiStore.ts
@@ -0,0 +1,21 @@
+import { create } from 'zustand'
+
+/**
+ * Which top-level section the app is showing.
+ *
+ * Until Documentation there was no such thing: the view was implied by the
+ * active design's type, because everything was a canvas. Documentation is the
+ * first section that belongs to the whole homelab rather than to one design, so
+ * the mode has to be state of its own.
+ */
+export type AppView = 'canvas' | 'documentation'
+
+interface UiState {
+ view: AppView
+ setView: (view: AppView) => void
+}
+
+export const useUiStore = create<UiState>()((set) => ({
+ view: 'canvas',
+ setView: (view) => set({ view }),
+}))
diff --git a/frontend/src/utils/designUrl.ts b/frontend/src/utils/designUrl.ts
index fdad2cb..0d96f99 100644
--- a/frontend/src/utils/designUrl.ts
+++ b/frontend/src/utils/designUrl.ts
@@ -20,3 +20,32 @@ export function setDesignIdInUrl(id: string | null): void {
else url.searchParams.delete(DESIGN_PARAM)
window.history.replaceState(window.history.state, '', url)
}
+
+// The Documentation section is not a design, so it needs its own params:
+// `?view=docs` for the section and `?doc=<id>` for the open document. Same
+// replaceState discipline — switching sections is not a navigation.
+const VIEW_PARAM = 'view'
+const DOC_PARAM = 'doc'
+
+/** True when the URL asks for the Documentation section. */
+export function isDocsViewInUrl(): boolean {
+ if (typeof window === 'undefined') return false
+ return new URLSearchParams(window.location.search).get(VIEW_PARAM) === 'docs'
+}
+
+/** The document id the URL points at, or null. */
+export function getDocIdFromUrl(): string | null {
+ if (typeof window === 'undefined') return null
+ return new URLSearchParams(window.location.search).get(DOC_PARAM)
+}
+
+/** Reflect the section and the open document into the URL. */
+export function setDocsViewInUrl(active: boolean, docId: string | null = null): void {
+ if (typeof window === 'undefined') return
+ const url = new URL(window.location.href)
+ if (active) url.searchParams.set(VIEW_PARAM, 'docs')
+ else url.searchParams.delete(VIEW_PARAM)
+ if (active && docId) url.searchParams.set(DOC_PARAM, docId)
+ else url.searchParams.delete(DOC_PARAM)
+ window.history.replaceState(window.history.state, '', url)
+}