Skip to content

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

feat(docs): add device reconciliation engine (#484) (#489)

Sebastian6d78266471dc
diff --git a/backend/app/api/routes/documents.py b/backend/app/api/routes/documents.py
index 8d9b4fa..0c40e65 100644
--- a/backend/app/api/routes/documents.py
+++ b/backend/app/api/routes/documents.py
@@ -7,10 +7,15 @@ 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.
+The generated header is written once, at creation; `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. The one flow that
+rewrites a body is `POST /{id}/update-from-device`, and only through the guided
+three-way merge of `app.services.doc_reconcile`: nothing is overwritten unless
+the device simply moved on (automatic) or the user resolved the conflict
+explicitly. `baseline_body` records the body that was *generated* at the last
+sync — never the merged one — so a value the user deliberately kept is surfaced
+again when the device moves on once more.
"""
import re
@@ -31,15 +36,26 @@ from app.schemas.documents import (
DocumentResponse,
DocumentSummary,
DocumentUpdate,
+ ReconcileChange,
+ ResolutionItem,
RevisionResponse,
RevisionSummary,
ScaffoldRequest,
ScaffoldResponse,
SearchHit,
SearchResponse,
+ UpdateApplyRequest,
+ UpdatePreviewRequest,
+ UpdatePreviewResponse,
)
from app.services import doc_backlinks, doc_search
from app.services.doc_export import ExportDoc, build_zip
+from app.services.doc_reconcile import (
+ Resolution,
+ Result,
+ preview_id,
+ reconcile,
+)
from app.services.doc_template import (
BLOCKS,
TEMPLATE_DEVICE,
@@ -134,50 +150,101 @@ async def _record_revision(db: AsyncSession, doc: Document, reason: str) -> None
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.
+async def _device_contexts(db: AsyncSession, device_ids: list[str]) -> dict[str, dict[str, Any]]:
+ """Zone, rack placement and canvas neighbours for a batch of devices.
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.
+
+ The query count depends on how deep the zones nest, not on how many devices
+ are asked for — the document list resolves every drifted device at once.
"""
- 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)
+ contexts: dict[str, dict[str, Any]] = {
+ device_id: {"zone_label": None, "rack": None, "connections": []} for device_id in device_ids
+ }
+ if not contexts:
+ return contexts
+
+ # A device placed on several canvases is described by its oldest node.
+ node_of: dict[str, Node] = {}
+ for node in (
+ await db.execute(select(Node).where(Node.device_id.in_(contexts)).order_by(Node.created_at))
+ ).scalars():
+ if node.device_id is not None:
+ node_of.setdefault(node.device_id, node)
+
+ # Walk every parent chain one level per query until each device has met a
+ # zone, run out of parents or looped.
+ known: dict[str, Node] = {}
+ cursor = {device_id: node.parent_id for device_id, node in node_of.items() if node.parent_id}
+ seen: dict[str, set[str]] = {device_id: set() for device_id in cursor}
+ while cursor:
+ missing = {parent_id for parent_id in cursor.values() if parent_id not in known}
+ if missing:
+ for found in (await db.execute(select(Node).where(Node.id.in_(missing)))).scalars():
+ known[found.id] = found
+ following: dict[str, str] = {}
+ for device_id, parent_id in cursor.items():
+ seen[device_id].add(parent_id)
+ parent = known.get(parent_id)
if parent is None:
- break
+ continue
if parent.type in _ZONE_TYPES:
- context["zone_label"] = parent.label
- break
- parent_id = parent.parent_id
-
+ contexts[device_id]["zone_label"] = parent.label
+ elif parent.parent_id and parent.parent_id not in seen[device_id]:
+ following[device_id] = parent.parent_id
+ cursor = following
+
+ device_of_node = {node.id: device_id for device_id, node in node_of.items()}
+ if device_of_node:
+ peers_of: dict[str, set[str]] = {device_id: set() for device_id in node_of}
edges = (
- await db.execute(select(Edge).where((Edge.source == node.id) | (Edge.target == node.id)))
+ await db.execute(
+ select(Edge).where(Edge.source.in_(device_of_node) | Edge.target.in_(device_of_node))
+ )
).scalars().all()
- peer_ids = [e.target if e.source == node.id else e.source for e in edges]
+ for edge in edges:
+ if edge.source in device_of_node:
+ peers_of[device_of_node[edge.source]].add(edge.target)
+ if edge.target in device_of_node:
+ peers_of[device_of_node[edge.target]].add(edge.source)
+ peer_ids = set().union(*peers_of.values())
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,
+ labels = dict(
+ (await db.execute(select(Node.id, Node.label).where(Node.id.in_(peer_ids)))).tuples().all()
+ )
+ for device_id, peers in peers_of.items():
+ contexts[device_id]["connections"] = sorted(
+ {labels[peer] for peer in peers if labels.get(peer)}
+ )
+
+ mounts: dict[str, RackDevice] = {}
+ for mount in (
+ await db.execute(select(RackDevice).where(RackDevice.device_id.in_(contexts)))
+ ).scalars():
+ if mount.device_id is not None:
+ mounts.setdefault(mount.device_id, mount)
+ if mounts:
+ racks = {
+ rack.id: rack
+ for rack in (
+ await db.execute(select(Rack).where(Rack.id.in_({m.rack_id for m in mounts.values()})))
+ ).scalars()
}
- return context
+ for device_id, mount in mounts.items():
+ rack = racks.get(mount.rack_id)
+ contexts[device_id]["rack"] = {
+ "name": rack.name if rack else None,
+ "u_start": mount.u_start,
+ "u_height": mount.u_height,
+ "col_span": mount.col_span,
+ }
+ return contexts
+
+
+async def _device_context(db: AsyncSession, device_id: str) -> dict[str, Any]:
+ """Zone, rack placement and canvas neighbours for one device."""
+ return (await _device_contexts(db, [device_id]))[device_id]
async def _scaffold_body(db: AsyncSession, doc: Document, template_id: str | None) -> None:
@@ -186,7 +253,9 @@ async def _scaffold_body(db: AsyncSession, doc: Document, template_id: str | Non
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))
+ generated = render_device_document(device, **context)
+ _apply_body(doc, generated)
+ doc.baseline_body = generated
doc.facts_snapshot = facts_snapshot(device)
doc.facts_synced_at = _now()
doc.template_id = TEMPLATE_DEVICE
@@ -195,17 +264,37 @@ async def _scaffold_body(db: AsyncSession, doc: Document, template_id: str | Non
doc.template_id = template_id or "blank"
-def _has_drifted(doc: Document, device: InventoryDevice | None) -> bool:
- """Whether the device has moved on since this document was snapshotted.
+async def _drifted_ids(
+ db: AsyncSession, pairs: list[tuple[Document, InventoryDevice | None]]
+) -> set[str]:
+ """The documents whose device has moved on in a way they do not show yet.
The comparison lives on the server rather than in the UI because
`facts_snapshot` is the server's own shape — `label` and `type` are stored
through their fallbacks and `properties` as a flat map — so nothing else
can compare it to a device row correctly. Same rule as the coverage count.
+
+ A snapshot that differs is necessary, not sufficient: the body may already
+ say what the device says now (the user wrote it, or the snapshot predates a
+ fact the body was generated with). "Update from device" would then have
+ nothing to offer, so the document is not flagged — the merge itself decides.
+ Only those candidates pay for a generated body, and their render contexts
+ are fetched together.
"""
- if not doc.device_id or not doc.facts_snapshot or device is None:
- return False
- return doc.facts_snapshot != facts_snapshot(device)
+ candidates = [
+ (doc, device)
+ for doc, device in pairs
+ if doc.device_id and doc.facts_snapshot and device is not None
+ and doc.facts_snapshot != facts_snapshot(device)
+ ]
+ contexts = await _device_contexts(db, [device.id for _, device in candidates])
+ drifted: set[str] = set()
+ for doc, device in candidates:
+ generated = render_device_document(device, **contexts[device.id])
+ result = await _reconcile_document(doc, [], generated=generated, snapshot=_sync_snapshot(doc))
+ if result.auto or result.conflicts:
+ drifted.add(doc.id)
+ return drifted
async def _devices_for(db: AsyncSession, docs: list[Document]) -> dict[str, InventoryDevice]:
@@ -219,19 +308,91 @@ async def _devices_for(db: AsyncSession, docs: list[Document]) -> dict[str, Inve
return {device.id: device for device in rows}
-def _summary(doc: Document, device: InventoryDevice | None) -> DocumentSummary:
+def _summary(doc: Document, drifted: bool) -> DocumentSummary:
payload = DocumentSummary.model_validate(doc)
- payload.drifted = _has_drifted(doc, device)
+ payload.drifted = drifted
return payload
async def _response(db: AsyncSession, doc: Document) -> DocumentResponse:
"""One document, with the drift flag resolved against the live device."""
payload = DocumentResponse.model_validate(doc)
- payload.drifted = _has_drifted(doc, await db.get(InventoryDevice, doc.device_id) if doc.device_id else None)
+ device = await db.get(InventoryDevice, doc.device_id) if doc.device_id else None
+ payload.drifted = doc.id in await _drifted_ids(db, [(doc, device)])
return payload
+def _sync_snapshot(doc: Document) -> dict[str, Any] | None:
+ """The facts the document's baseline was computed against, if it has one."""
+ return doc.facts_snapshot if isinstance(doc.facts_snapshot, dict) else None
+
+
+async def _reconcile_document(
+ doc: Document,
+ resolutions: list[ResolutionItem],
+ *,
+ generated: str,
+ snapshot: dict[str, Any] | None,
+) -> Result:
+ """The three-way merge of the live body against a fresh generation.
+
+ ``generated`` is the body the proposal is computed from — the caller has
+ already fetched the device context once and must pass the same body it will
+ record as the new baseline, so the merge never straddles two context reads.
+ """
+ return reconcile(
+ current=doc.body or "",
+ new=generated,
+ baseline_body=doc.baseline_body,
+ snapshot=snapshot,
+ resolutions=[Resolution(r.id, r.choice, r.custom) for r in resolutions],
+ )
+
+
+async def _generated_body(db: AsyncSession, device: InventoryDevice) -> tuple[dict[str, Any], str]:
+ """The render context for a device and the body it generates, fetched once.
+
+ Both the preview token and the saved baseline are derived from this single
+ snapshot, so the proposal and the recorded baseline can never come from two
+ different device contexts.
+ """
+ context = await _device_context(db, device.id)
+ return context, render_device_document(device, **context)
+
+
+def _live_binding(device: InventoryDevice, context: dict[str, Any], generated: str) -> dict[str, Any]:
+ """The live inputs a proposal was computed from.
+
+ Binds the facts, the render context and the generated body itself — a
+ rendered-only change such as a service URL override or the migrated notes
+ would otherwise slip the fact-level bindings.
+ """
+ return {"facts": facts_snapshot(device), "context": context, "generated": generated}
+
+
+def _preview_payload(doc: Document, result: Result, live: dict[str, Any]) -> UpdatePreviewResponse:
+ """The wire shape of a merge result, the preview id included.
+
+ The id binds the very inputs the merge began from — the document's `updated_at`,
+ the snapshot, the baseline, the body and the live device facts, context and
+ generated body the proposal was computed from — so a save is only valid
+ against the exact preview it was computed from.
+ """
+ return UpdatePreviewResponse(
+ preview_id=preview_id(
+ doc.updated_at.isoformat(),
+ _sync_snapshot(doc),
+ doc.body or "",
+ baseline_body=doc.baseline_body,
+ live=live,
+ ),
+ changes=[ReconcileChange.model_validate(change) for change in result.changes],
+ proposed_body=result.proposed_body,
+ summary=result.summary,
+ unresolved=[change.id for change in result.unresolved],
+ )
+
+
# ── list / read ─────────────────────────────────────────────────────────────
@@ -256,7 +417,8 @@ async def list_documents(
wanted = tag.lower()
docs = [d for d in docs if any(str(t).lower() == wanted for t in (d.tags or []))]
devices = await _devices_for(db, list(docs))
- return [_summary(d, devices.get(d.device_id or "")) for d in docs]
+ drifted = await _drifted_ids(db, [(d, devices.get(d.device_id or "")) for d in docs])
+ return [_summary(d, d.id in drifted) for d in docs]
@router.get("/coverage", response_model=CoverageResponse)
@@ -271,6 +433,9 @@ async def coverage(
docs = (await db.execute(select(Document))).scalars().all()
by_device = {d.device_id: d for d in docs if d.device_id}
+ drifted_ids = await _drifted_ids(
+ db, [(by_device[device.id], device) for device in devices if device.id in by_device]
+ )
header_only = drifted = overdue = 0
now = _now()
for device in devices:
@@ -280,7 +445,7 @@ async def coverage(
# 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):
+ if doc.id in drifted_ids:
drifted += 1
interval = _parse_interval((doc.frontmatter or {}).get("review_every"))
since = _aware(doc.reviewed_at) or _aware(doc.created_at)
@@ -607,6 +772,12 @@ async def update_document(
if sent.get("resync_facts") and doc.device_id:
device = await db.get(InventoryDevice, doc.device_id)
if device is not None:
+ context = await _device_context(db, doc.device_id)
+ # Accepting the current facts also moves the merge baseline onto the
+ # body those facts *would* generate, so the next device change is
+ # still compared from a truthful common ancestor — the banner is
+ # dismissed, the safety of the three-way merge is not.
+ doc.baseline_body = render_device_document(device, **context)
doc.facts_snapshot = facts_snapshot(device)
doc.facts_synced_at = _now()
@@ -673,6 +844,113 @@ async def regenerate_document(
return await _response(db, doc)
[email protected]("/{document_id}/update-preview", response_model=UpdatePreviewResponse)
+async def preview_device_update(
+ document_id: str,
+ body: UpdatePreviewRequest,
+ db: AsyncSession = Depends(get_db),
+ _: str = Depends(get_current_user),
+) -> UpdatePreviewResponse:
+ """Preview an update-from-device without changing anything.
+
+ The device document is re-rendered from the live facts and merged against
+ the body the user owns. The response is read-only: a changed device value
+ the user never touched is offered for automatic application, a value both
+ sides changed is a conflict to resolve, and the user's prose is untouched.
+ The caller folds resolutions in as they are chosen, so the previewed body is
+ always the server's merge rather than a local approximation.
+ """
+ doc = await db.get(Document, document_id)
+ if not doc:
+ raise HTTPException(404, "Document not found")
+ if doc.kind == "folder":
+ raise HTTPException(400, "A folder has no body to update from a device")
+ device = await db.get(InventoryDevice, doc.device_id) if doc.device_id else None
+ if device is None:
+ raise HTTPException(400, "This document has no device to update from")
+ context, generated = await _generated_body(db, device)
+ result = await _reconcile_document(
+ doc, body.resolutions, generated=generated, snapshot=_sync_snapshot(doc)
+ )
+ return _preview_payload(doc, result, _live_binding(device, context, generated))
+
+
[email protected]("/{document_id}/update-from-device", response_model=DocumentResponse)
+async def apply_device_update(
+ document_id: str,
+ body: UpdateApplyRequest,
+ db: AsyncSession = Depends(get_db),
+ _: str = Depends(get_current_user),
+) -> DocumentResponse:
+ """Apply a preview the user has reviewed.
+
+ The merge is recomputed from the current state with the given resolutions,
+ so whatever the modal showed last is exactly what lands. The echoed
+ `preview_id` guards the flow: if the document or the device changed while
+ the preview was open — a device value the proposal was made against moved
+ on, or the body/baseline was edited — the id no longer matches and a 409 is
+ returned instead of a silent overwrite; nothing is saved and no history is
+ written. Every conflict must be resolved first — the endpoint will not
+ guess. The previous body is snapshotted (reason `sync`) and the baseline
+ is replaced by the *freshly generated* body the proposal was computed from,
+ so a deliberately kept value surfaces again when the device moves on.
+ """
+ doc = await db.get(Document, document_id)
+ if not doc:
+ raise HTTPException(404, "Document not found")
+ if doc.kind == "folder":
+ raise HTTPException(400, "A folder has no body to update from a device")
+ device = await db.get(InventoryDevice, doc.device_id) if doc.device_id else None
+ if device is None:
+ raise HTTPException(400, "This document has no device to update from")
+
+ context, generated = await _generated_body(db, device)
+ expected = preview_id(
+ doc.updated_at.isoformat(),
+ _sync_snapshot(doc),
+ doc.body or "",
+ baseline_body=doc.baseline_body,
+ live=_live_binding(device, context, generated),
+ )
+ if body.preview_id != expected:
+ raise HTTPException(
+ 409,
+ "The document or device changed while the preview was open — review it again",
+ )
+
+ result = await _reconcile_document(
+ doc, body.resolutions, generated=generated, snapshot=_sync_snapshot(doc)
+ )
+ if result.unresolved:
+ raise HTTPException(
+ 400,
+ f"Resolve every conflict first: {', '.join(c.name for c in result.unresolved)}",
+ )
+
+ # A body that already matched the device, with no decision to record, is
+ # an acknowledgement, not an edit: the facts below are still stored so the
+ # drift clears, but history gets no revision identical to the body it would
+ # restore. A kept conflict is a decision and keeps its revision.
+ if body.resolutions or result.proposed_body != (doc.body or ""):
+ await _record_revision(db, doc, "sync")
+ _apply_body(doc, result.proposed_body)
+ # The baseline is the body the device *actually* read — the very generated
+ # body the proposal above was merged from, fetched once — not the merged
+ # one: a decision the user made (a kept line, a custom value) must stay
+ # visible when the device moves again, and only a fresh generation records
+ # it. The proposal and the saved baseline therefore never come from two
+ # different context snapshots.
+ doc.baseline_body = generated
+ doc.facts_snapshot = facts_snapshot(device)
+ doc.facts_synced_at = _now()
+ await _adopt_frontmatter_title(db, doc)
+ await db.flush()
+ await doc_search.index_document(db, doc)
+ await db.commit()
+ await db.refresh(doc)
+ return await _response(db, doc)
+
+
@router.post("/scaffold", response_model=ScaffoldResponse)
async def scaffold_documents(
body: ScaffoldRequest,
@@ -706,17 +984,19 @@ async def scaffold_documents(
skipped += 1
continue
context = await _device_context(db, device.id)
+ generated = render_device_document(device, **context)
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,
+ baseline_body=generated,
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))
+ _apply_body(doc, generated)
db.add(doc)
await db.flush()
db.add(
diff --git a/backend/app/db/database.py b/backend/app/db/database.py
index 48ed706..986359c 100644
--- a/backend/app/db/database.py
+++ b/backend/app/db/database.py
@@ -41,6 +41,10 @@ DOCUMENT_DDL: tuple[tuple[str, str], ...] = (
("documents.facts_snapshot", "ALTER TABLE documents ADD COLUMN facts_snapshot JSON"),
("documents.facts_synced_at", "ALTER TABLE documents ADD COLUMN facts_synced_at DATETIME"),
("documents.reviewed_at", "ALTER TABLE documents ADD COLUMN reviewed_at DATETIME"),
+ # The generated body as it was when the document was scaffolded or last
+ # reconciled. Three-way update-from-device compares `current <-> baseline <-
+ # fresh-generate`; NULL means "no baseline yet", which forces the safe side.
+ ("documents.baseline_body", "ALTER TABLE documents ADD COLUMN baseline_body TEXT"),
# Set only when a body is edited, so "never touched since it was generated"
# is distinguishable from "edited" — `created_at` and `updated_at` are two
# separate clock reads on insert and are never equal.
diff --git a/backend/app/db/models.py b/backend/app/db/models.py
index 13584c8..5c6896c 100644
--- a/backend/app/db/models.py
+++ b/backend/app/db/models.py
@@ -391,6 +391,13 @@ class Document(Base):
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)
+
+ # The whole generated body as it read when this document was scaffolded or
+ # last reconciled. Together with `facts_snapshot` this is the baseline of a
+ # three-way update-from-device: `current <-> baseline <- fresh-generate`.
+ # It is *not* the merged body — only the freshly generated one, so a value
+ # the user deliberately kept is still noticed when the device moves again.
+ baseline_body: Mapped[str | None] = mapped_column(Text, 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
diff --git a/backend/app/schemas/documents.py b/backend/app/schemas/documents.py
index baa1e07..fdca790 100644
--- a/backend/app/schemas/documents.py
+++ b/backend/app/schemas/documents.py
@@ -1,5 +1,5 @@
from datetime import datetime
-from typing import Any
+from typing import Any, Literal
from pydantic import BaseModel, field_validator
@@ -237,6 +237,72 @@ class DriftField(BaseModel):
current: Any = None
+class ResolutionItem(BaseModel):
+ """What the user wants for one conflicting fact or section.
+
+ ``choice`` is one of ``keep`` (keep the document's text), ``device`` (take
+ the device's value) or ``custom`` (the user's own replacement, in
+ ``custom``). Sent for every conflict the user has decided on; conflicts the
+ modal still shows are simply absent.
+ """
+
+ id: str
+ choice: Literal["keep", "device", "custom"] = "keep"
+ custom: str | None = None
+
+
+class ReconcileChange(BaseModel):
+ """One fact or section the update preview surfaced, and its disposition.
+
+ ``status`` is ``same``, ``auto`` or ``conflict``. A conflict carries its
+ resolution here once the user has decided, so a preview rendered back can
+ show exactly where the merge landed.
+ """
+
+ id: str
+ name: str
+ kind: str # "field" | "section"
+ status: str
+ documented: str
+ device: str
+ previous: str = ""
+ resolution: str | None = None # keep | device | custom
+ custom: str | None = None
+
+ model_config = {"from_attributes": True}
+
+
+class UpdatePreviewRequest(BaseModel):
+ """Optional resolutions to fold into the preview.
+
+ Sent with none to open the modal; the modal then re-previews with each
+ decision as the user makes it, so the merged body is always the server's
+ merge — never a local approximation.
+ """
+
+ resolutions: list[ResolutionItem] = []
+
+
+class UpdatePreviewResponse(BaseModel):
+ preview_id: str
+ changes: list[ReconcileChange]
+ proposed_body: str
+ summary: list[str] = []
+ # The conflict ids still waiting on a decision (drives the review step).
+ unresolved: list[str] = []
+
+
+class UpdateApplyRequest(BaseModel):
+ """Settle a preview, then save the merge.
+
+ ``preview_id`` is echoed back so the server can reject a save made against
+ a preview the document has moved on from.
+ """
+
+ preview_id: str
+ resolutions: list[ResolutionItem] = []
+
+
class CoverageResponse(BaseModel):
devices: int
documented: int
diff --git a/backend/app/services/doc_reconcile.py b/backend/app/services/doc_reconcile.py
new file mode 100644
index 0000000..0a435a0
--- /dev/null
+++ b/backend/app/services/doc_reconcile.py
@@ -0,0 +1,987 @@
+"""Reconcile a device document against the live device facts — the engine
+behind "Update from device".
+
+``regenerate`` throws the body away, so it is only right for a user who wants a
+fresh document. The everyday need is different: the device moved on, and the
+document should keep up without losing the notes, annotations and reformatting
+the user added around the generated sections. This module is that path, built
+on a three-way comparison:
+
+* **baseline** — the body recorded at the last sync (``doc.baseline_body``),
+ with ``doc.facts_snapshot`` as a fallback for the tables it can reconstruct
+ (the Device Information cells, Hardware and Properties);
+* **current** — the body the user has *now*, manual edits included;
+* **new** — a freshly generated body from the live device.
+
+Comparing current vs new alone cannot tell a device change from a user edit. A
+fact that reads the same in current as in baseline was never touched by the
+user, so the device's new value can be applied without asking; a fact the user
+changed *and* the device changed is a conflict the user must resolve (keep /
+take the device / write their own). User-owned sections — Configuration,
+Operations, Troubleshooting, Dependencies, Changelog, Notes, the preamble, any
+heading this module does not know — are never touched. Where the baseline
+cannot reconstruct what a fact used to say, the module is deliberately
+conservative: the user decides rather than risking a silent overwrite.
+
+Nothing here writes to the database. It turns three bodies, the old device
+facts and optional resolutions into a proposed body plus the list of changes
+and the decisions behind them.
+"""
+
+import hashlib
+import json
+import re
+from dataclasses import dataclass, field
+from enum import Enum
+from typing import Any
+
+import yaml
+
+from app.services.doc_template import _hardware_property, cell
+
+# The disposition of a fact or section after the three-way comparison.
+SAME = "same" # no decision needed — include it in the merge as it is
+AUTO = "auto" # safe to apply the device value without asking
+CONFLICT = "conflict" # user edited it *and* the device changed it — ask
+
+# How a conflict is resolved. Sentinels for "not decided yet" are None.
+KEEP = "keep" # keep the user's text
+DEVICE = "device" # take the device's value
+CUSTOM = "custom" # the user's own replacement text
+
+
+class _SectionAction(Enum):
+ """Internal outcomes that cannot collide with user-provided text."""
+
+ SKIP = "skip"
+ REMOVE = "remove"
+
+# The rows of the generated Device Information table, mapped to the words a
+# decision surface should use for them ("IP" is not an IP *address*).
+_INFO_ROWS = (
+ ("Type", "Type"),
+ ("Vendor / Model", "Vendor / Model"),
+ ("Hostname", "Hostname"),
+ ("IP", "IP address"),
+ ("MAC", "MAC address"),
+ ("IEEE", "IEEE address"),
+ ("OS", "Operating system"),
+ ("First discovered", "First discovered"),
+ ("Status check", "Status check"),
+)
+_INFO_NAME_BY_LABEL = {label: name for label, name in _INFO_ROWS}
+
+# The generated, device-owned sections, in the order the generator emits them.
+_DEVICE_SECTIONS = ("Hardware", "Physical location", "Properties", "Services", "Network")
+
+# The table of facts every generated device document opens with.
+_DEVICE_INFO_HEADING = "Device Information"
+
+# Section names that own their block: the generated ones plus the user-owned
+# sections that end a generated document. A block boundary is one of these, the
+# device-name H1, or any level-2 heading (a user's free `## Something` must not
+# be swallowed by the section above it). Anything else — the `### <service>` sub
+# blocks under Services, `### Start / stop` under Operations, an arbitrary
+# `###` decoration — stays inside the block that hosts it, which is exactly what
+# lets a whole generated section be compared and replaced in one piece.
+_SECTION_NAMES = frozenset((_DEVICE_INFO_HEADING, *_DEVICE_SECTIONS))
+_USER_SECTION_NAMES = frozenset(
+ ("Configuration", "Operations", "Troubleshooting", "Dependencies", "Changelog", "Notes")
+)
+_ALL_SECTION_NAMES = _SECTION_NAMES | _USER_SECTION_NAMES
+
+_HEADING = re.compile(r"^(#{1,3})\s+(.*?)\s*$")
+_ROW = re.compile(r"^\|\s*([^|]+?)\s*\|\s*(.*?)\s*\|$")
+_TABLE_SEPARATOR = re.compile(r"^\|\s*:?-{3,}:?\s*\|\s*:?-{3,}:?\s*\|$")
+@dataclass
+class Block:
+ """A run of contiguous lines: the preamble, or one heading and its body."""
+
+ level: int
+ heading: str | None
+ lines: list[str]
+ removed: bool = False
+
+
+@dataclass
+class Change:
+ """One fact or section whose disposition the preview surfaces.
+
+ ``status`` is ``same``, ``auto`` or ``conflict``. A conflict carries a
+ resolution once the user has decided, and that resolution changes what the
+ merged body holds for it.
+ """
+
+ id: str
+ name: str
+ kind: str # "field" | "section"
+ status: str
+ documented: str
+ device: str
+ previous: str = ""
+ resolution: str | None = None # keep | device | custom
+ custom: str | None = None
+
+
+@dataclass
+class Resolution:
+ """What the user wants for one conflict: keep, take the device, or custom."""
+
+ id: str
+ choice: str
+ custom: str | None = None
+
+
+@dataclass
+class Result:
+ changes: list[Change] = field(default_factory=list)
+ proposed_body: str = ""
+ summary: list[str] = field(default_factory=list)
+
+ @property
+ def conflicts(self) -> list[Change]:
+ return [c for c in self.changes if c.status == CONFLICT]
+
+ @property
+ def auto(self) -> list[Change]:
+ return [c for c in self.changes if c.status == AUTO]
+
+ @property
+ def unresolved(self) -> list[Change]:
+ return [c for c in self.changes if c.status == CONFLICT and not c.resolution]
+
+
+# ── parsing ─────────────────────────────────────────────────────────────────
+
+
+def _norm(text: str | None) -> str:
+ """Compare bodies tolerantly: trailing space and blank runoff don't matter."""
+ if not text:
+ return ""
+ return "\n".join(line.rstrip() for line in text.splitlines()).strip()
+
+
+def _or_none(text: str | None) -> str | None:
+ """A normalized string that collapses the empty state to None."""
+ if not text:
+ return None
+ return "\n".join(line.rstrip() for line in text.splitlines()).strip()
+
+
+def split_blocks(body: str) -> list[Block]:
+ """The body as a list of blocks.
+
+ The preamble comes first, then one block per section. A block boundary is a
+ heading that owns its block (a generated section, a user section, the
+ device-name H1) or any level-2 heading; everything between two such
+ boundaries — including nested ``###`` subheadings such as the per-service
+ entries under ``## Services`` — stays inside the block that hosts it.
+ """
+ blocks: list[Block] = []
+ current = Block(level=0, heading=None, lines=[])
+ for line in body.splitlines():
+ match = _HEADING.match(line)
+ if match:
+ level = len(match.group(1))
+ name = match.group(2)
+ if level == 1 or level == 2 or name in _ALL_SECTION_NAMES:
+ if current.lines:
+ blocks.append(current)
+ current = Block(level=level, heading=name, lines=[line])
+ continue
+ current.lines.append(line)
+ if current.lines:
+ blocks.append(current)
+ return blocks
+
+
+def _find(blocks: list[Block], heading: str) -> Block | None:
+ for block in blocks:
+ if block.heading == heading:
+ return block
+ return None
+
+
+def _first_h1(blocks: list[Block]) -> str | None:
+ for block in blocks:
+ if block.level == 1 and block.heading:
+ return block.heading
+ return None
+
+
+def _heading_level(line: str) -> int:
+ """The level (`#` count) of a heading line, or 0 for anything else."""
+ match = _HEADING.match(line)
+ return len(match.group(1)) if match else 0
+
+
+def _block_text(block: Block) -> str:
+ return "\n".join(block.lines)
+
+
+def _content(block: Block | None) -> list[str]:
+ """A section's lines without its heading line."""
+ if block is None:
+ return []
+ return block.lines[1:] if block.heading else block.lines
+
+
+def _content_text(block: Block | None) -> str:
+ return "\n".join(_content(block))
+
+
+def _row_from_line(line: str) -> tuple[str, str] | None:
+ """The (label, cell) of a markdown data row, or None for anything else."""
+ match = _ROW.match(line)
+ if not match:
+ return None
+ label = match.group(1).strip()
+ if not label or set(label) <= {"-", ":"}:
+ return None # header or separator row
+ return label, match.group(2).strip()
+
+
+def _table_rows(text: str) -> list[tuple[str, str]]:
+ """The data rows after a markdown table separator, in order."""
+ pairs: list[tuple[str, str]] = []
+ in_table = False
+ for line in text.splitlines():
+ if _TABLE_SEPARATOR.match(line):
+ in_table = True
+ continue
+ if not in_table:
+ continue
+ row = _row_from_line(line)
+ if row is not None:
+ pairs.append(row)
+ return pairs
+
+
+def _first_cells(rows: list[tuple[str, str]]) -> dict[str, str]:
+ """Label → cell for the first (representational) row of the table.
+
+ The first copy of a duplicated label provides the ``documented`` cell of
+ the change surfaced for it; it is *not* treated as "the generated row".
+ Duplicates are ambiguous and therefore require an explicit decision — the
+ proposed body never guesses which copy is which (see ``_rebuild_info_table``).
+ """
+ cells: dict[str, str] = {}
+ for label, value in rows:
+ cells.setdefault(label, value)
+ return cells
+
+
+# ── baseline reconstruction from the old device facts ──────────────────────
+
+
+def _info_old_cell(snapshot: dict[str, Any] | None, label: str) -> str | None:
+ """What a Device Information cell read at snapshot time, if reconstructable.
+
+ ``None`` means the snapshot cannot say — the reconcile then treats the fact
+ conservatively (the user decides if current and device values differ).
+ """
+ if not snapshot:
+ return None
+ if label == "Type":
+ return cell(snapshot.get("type"))
+ if label == "Vendor / Model":
+ parts = [p for p in (snapshot.get("vendor"), snapshot.get("model")) if p]
+ return cell(" / ".join(parts) or "—")
+ if label == "Hostname":
+ return cell(snapshot.get("hostname"))
+ if label == "IP":
+ return cell(snapshot.get("ip"))
+ if label == "MAC":
+ return cell(snapshot.get("mac"))
+ if label == "IEEE":
+ return cell(snapshot.get("ieee_address"))
+ if label == "OS":
+ return cell(snapshot.get("os"))
+ if label == "First discovered":
+ return None # date and sources are not in the snapshot
+ if label == "Status check":
+ check, target = snapshot.get("check_method"), snapshot.get("check_target")
+ if check and target:
+ return f"`{check}` → `{target}`"
+ if check:
+ return f"`{check}`"
+ return "—"
+ return None
+
+
+def _info_old_table(snapshot: dict[str, Any] | None, baseline: Block | None) -> str | None:
+ """The full Device Information table as of the last sync, if known."""
+ if baseline is not None:
+ return _content_text(baseline)
+ if not snapshot:
+ return None
+ rows: list[tuple[str, str]] = []
+ for label, _ in _INFO_ROWS:
+ value = _info_old_cell(snapshot, label)
+ if value is None:
+ return None # cannot reconstruct faithfully → conservative
+ rows.append((label, value))
+ return "\n".join(_render_info_rows(rows))
+
+
+def _render_info_rows(rows: list[tuple[str, str]]) -> list[str]:
+ return [f"| {label} | {value} |" for label, value in rows]
+
+
+def _hardware_old_content(snapshot: dict[str, Any] | None) -> str | None:
+ """The Hardware table at snapshot time, generator-shape, or None."""
+ if not snapshot:
+ return None
+ props = snapshot.get("properties") or {}
+
+ cpu_model = _hardware_property(props, "cpu_model") or snapshot.get("cpu_model")
+ cpu_count = _hardware_property(props, "cpu_count") or snapshot.get("cpu_count")
+ cpu = cpu_model or (f"{cpu_count} cores" if cpu_count else None)
+ ram_gb = snapshot.get("ram_gb")
+ ram = _hardware_property(props, "ram") or (f"{ram_gb:g} GB" if ram_gb else None)
+ disk_gb = snapshot.get("disk_gb")
+ disk = _hardware_property(props, "disk") or (f"{disk_gb:g} GB" if disk_gb else None)
+
+ row = f"| {cell(cpu)} | {cell(ram)} | {cell(disk)} |"
+ return "| CPU | RAM | Disk |\n|---|---|---|\n" + row
+
+
+def _properties_old_content(snapshot: dict[str, Any] | None) -> str | None:
+ """The Properties table at snapshot time, generator-shape, or None."""
+ if not snapshot:
+ return None
+ props = snapshot.get("properties") or {}
+ if not props:
+ return None # generator would not have emitted the section at all
+ rows = [f"| {cell(key)} | {cell(value)} |" for key, value in props.items()]
+ return "\n".join(["| Key | Value |", "|---|---|", *rows])
+
+
+# ── the three-way decision ──────────────────────────────────────────────────
+
+
+def decide(cur: str | None, old: str | None, new: str | None) -> str:
+ """Classify one fact or section given its current, baseline and device value.
+
+ The rules, in order:
+
+ * the user already has the device's value → nothing to do;
+ * the device is unchanged → nothing to do, whatever the user wrote;
+ * an untouched, baseline-backed value follows a device removal;
+ * a device removal whose current value differs from the baseline → ask;
+ * no baseline for it and nothing in the document → safe to add;
+ * no baseline for it and the document differs → ask (conservative);
+ * the user left the baseline value → safe to apply;
+ * anything else → the user touched it and the device changed it: conflict.
+ """
+ if cur == new:
+ return SAME
+ if old == new:
+ return SAME
+ if old is not None and cur == old:
+ return AUTO
+ if not new:
+ return CONFLICT # device dropped the value the user still shows
+ if old is None:
+ return AUTO if not cur else CONFLICT
+ return CONFLICT
+
+
+def _inform_closed_change(change: Change, resolutions: dict[str, Resolution]) -> None:
+ resolution = resolutions.get(change.id)
+ if resolution is not None:
+ change.resolution = resolution.choice
+ change.custom = resolution.custom
+
+
+# ── the reconcile ───────────────────────────────────────────────────────────
+
+
+def reconcile(
+ current: str,
+ new: str,
+ baseline_body: str | None = None,
+ snapshot: dict[str, Any] | None = None,
+ resolutions: list[Resolution] | None = None,
+) -> Result:
+ """Merge ``current`` up to the device's current facts.
+
+ ``baseline_body`` is the body recorded at the last sync; ``snapshot`` backs
+ it up for the tables it can reconstruct. ``resolutions`` settle conflicts;
+ anything left open keeps the user's text in the proposed body, so a preview
+ reads like a draft, not a guess.
+ """
+ by_id = {r.id: r for r in (resolutions or [])}
+ new_blocks = split_blocks(new)
+ baseline_blocks = split_blocks(baseline_body) if baseline_body else []
+ changes: list[Change] = []
+
+ def add(change: Change) -> Change:
+ _inform_closed_change(change, by_id)
+ changes.append(change)
+ return change
+
+ # ── Device name ─────────────────────────────────────────────────────────
+ new_name = _first_h1(new_blocks) or ""
+ cur_name = _first_h1(split_blocks(current))
+ old_name = (snapshot or {}).get("label") if snapshot else None
+ name_change = add(
+ Change(
+ id="name",
+ name="Device name",
+ kind="field",
+ status=decide(_or_none(cur_name), _or_none(old_name), _or_none(new_name) or None),
+ documented=cur_name or "",
+ device=new_name,
+ previous=old_name or "",
+ )
+ )
+
+ # ── Document title in frontmatter — decided independently of the H1 ────
+ current_blocks = split_blocks(current)
+ cur_title = _frontmatter_title(next((b for b in current_blocks if b.level == 0), None))
+ old_title = _frontmatter_title(next((b for b in baseline_blocks if b.level == 0), None))
+ new_title = _frontmatter_title(next((b for b in new_blocks if b.level == 0), None))
+ title_change = add(
+ Change(
+ id="title",
+ name="Document title",
+ kind="field",
+ status=decide(
+ _or_none(cur_title), _or_none(old_title), _or_none(new_title) or None
+ ),
+ documented=cur_title or "",
+ device=new_title or "",
+ previous=old_title or "",
+ )
+ )
+
+ # ── Device Information rows ─────────────────────────────────────────────
+ cur_info = _find(current_blocks, "Device Information")
+ new_info = _find(new_blocks, "Device Information")
+ baseline_info = _find(baseline_blocks, "Device Information")
+ info_changes: dict[str, Change] = {}
+
+ new_rows = _table_rows(_content_text(new_info)) if new_info else []
+ new_by_label = {label: value for label, value in new_rows}
+ base_cells = dict(_table_rows(_content_text(baseline_info))) if baseline_info else {}
+
+ if new_rows:
+ cur_rows = _table_rows(_content_text(cur_info)) if cur_info else []
+ cur_cells = _first_cells(cur_rows)
+ row_counts: dict[str, int] = {}
+ for label, _ in cur_rows:
+ row_counts[label] = row_counts.get(label, 0) + 1
+ info_heading_count = sum(
+ 1 for b in current_blocks if b.heading == _DEVICE_INFO_HEADING
+ )
+ for label, new_cell in new_rows:
+ old_cell = base_cells.get(label)
+ if label not in base_cells:
+ old_cell = _info_old_cell(snapshot, label)
+ status = _decide_cell(
+ cur_cells.get(label) if label in cur_cells else None,
+ old_cell,
+ new_cell,
+ )
+ if (row_counts.get(label, 0) > 1 or info_heading_count > 1) and status == AUTO:
+ # A duplicated label or duplicate Device Information heading is
+ # ambiguous: which row or table is the generator's own copy is
+ # unknowable, so never auto-apply to a guess; surface an
+ # explicit decision instead.
+ status = CONFLICT
+ change = add(
+ Change(
+ id=f"device-info.{label}",
+ name=_INFO_NAME_BY_LABEL.get(label, label),
+ kind="field",
+ status=status,
+ documented=cur_cells.get(label, ""),
+ device=new_cell,
+ previous=old_cell or "",
+ )
+ )
+ info_changes[label] = change
+ # Rows the user added that the generator never emits are theirs alone.
+ for label, cur_cell in cur_rows:
+ if label not in new_by_label:
+ add(
+ Change(
+ id=f"device-info.{label}",
+ name=_INFO_NAME_BY_LABEL.get(label, label),
+ kind="field",
+ status=SAME,
+ documented=cur_cell,
+ device=cur_cell,
+ previous=cur_cell,
+ )
+ )
+
+ # ── generated sections ──────────────────────────────────────────────────
+ section_counts: dict[str, int] = {}
+ for block in current_blocks:
+ if block.heading is not None and block.heading in _DEVICE_SECTIONS:
+ section_counts[block.heading] = section_counts.get(block.heading, 0) + 1
+
+ section_changes: dict[str, Change] = {}
+ for name in _DEVICE_SECTIONS:
+ cur_section = _find(current_blocks, name)
+ new_section = _find(new_blocks, name)
+ if cur_section is None and new_section is None:
+ continue
+ cur_text = _content_text(cur_section) if cur_section else ""
+ new_text = _content_text(new_section) if new_section else ""
+ baseline_section = _find(baseline_blocks, name)
+ if baseline_section is not None:
+ old_text: str | None = _content_text(baseline_section)
+ elif name == "Hardware":
+ old_text = _hardware_old_content(snapshot)
+ elif name == "Properties":
+ old_text = _properties_old_content(snapshot)
+ else:
+ old_text = None # snapshot cannot say → conservative
+ has_known_history = baseline_body is not None or (
+ snapshot is not None and name in ("Hardware", "Properties")
+ )
+ status = (
+ CONFLICT
+ if (
+ cur_section is None
+ and new_section is not None
+ and not has_known_history
+ )
+ else decide(
+ _or_none(cur_text), _or_none(old_text) if old_text is not None else None,
+ _or_none(new_text) or None,
+ )
+ )
+ if section_counts.get(name, 0) > 1 and status == AUTO:
+ # A duplicated heading is ambiguous: the generator's own copy is
+ # unknowable, so never overwrite a guessed first block; surface an
+ # explicit decision instead.
+ status = CONFLICT
+ section_changes[name] = add(
+ Change(
+ id=f"section.{name}",
+ name=name,
+ kind="section",
+ status=status,
+ documented=cur_text,
+ device=new_text,
+ previous=_or_none(old_text) or "",
+ )
+ )
+
+ # ── Device Information handled sectionally when the user dropped the table ─
+ info_table_change: Change | None = None
+ if new_info is not None and cur_info is None:
+ # A recorded baseline that lacks this block proves it was absent. An
+ # absent baseline, though, is not proof that this is a newly added
+ # section: a legacy document may have deleted the table deliberately.
+ old_text = (
+ None
+ if baseline_body is not None and baseline_info is None
+ else _info_old_table(snapshot, baseline_info)
+ )
+ status = (
+ CONFLICT
+ if baseline_body is None and old_text is None
+ else decide(
+ None,
+ _or_none(old_text) if old_text is not None else None,
+ _or_none(_content_text(new_info)) or None,
+ )
+ )
+ info_table_change = add(
+ Change(
+ id="device-info",
+ name="Device Information",
+ kind="section",
+ status=status,
+ documented="",
+ device=_content_text(new_info),
+ previous=_or_none(old_text) or "",
+ )
+ )
+
+ proposed = _assemble(
+ current_blocks,
+ new_blocks,
+ name_change=name_change,
+ title_change=title_change,
+ info_changes=info_changes,
+ section_changes=section_changes,
+ info_table_change=info_table_change,
+ )
+ if current.endswith("\n") and not proposed.endswith("\n"):
+ proposed += "\n"
+ return Result(changes=changes, proposed_body=proposed, summary=_summarise(changes))
+
+
+# ── assembling the merged body ──────────────────────────────────────────────
+
+
+def _assemble(
+ current_blocks: list[Block],
+ new_blocks: list[Block],
+ *,
+ name_change: Change,
+ title_change: Change,
+ info_changes: dict[str, Change],
+ section_changes: dict[str, Change],
+ info_table_change: Change | None,
+) -> str:
+ blocks = [Block(level=b.level, heading=b.heading, lines=list(b.lines)) for b in current_blocks]
+
+ if name_change.status == AUTO:
+ _apply_h1(blocks, name_change.device)
+ elif name_change.status == CONFLICT:
+ if name_change.resolution == DEVICE:
+ _apply_h1(blocks, name_change.device)
+ elif name_change.resolution == CUSTOM and name_change.custom:
+ _apply_h1(blocks, name_change.custom)
+
+ if title_change.status == AUTO:
+ _apply_frontmatter_title(blocks, title_change.device)
+ elif title_change.status == CONFLICT:
+ if title_change.resolution == DEVICE:
+ _apply_frontmatter_title(blocks, title_change.device)
+ elif title_change.resolution == CUSTOM and title_change.custom is not None:
+ _apply_frontmatter_title(blocks, title_change.custom)
+
+ handled_sections: set[str] = set()
+ for block in blocks:
+ if block.heading is None:
+ continue
+ if block.heading == "Device Information":
+ if info_changes and block.heading not in handled_sections:
+ handled_sections.add(block.heading)
+ _rebuild_info_table(block, info_changes)
+ continue
+ if block.heading in section_changes and block.heading not in handled_sections:
+ handled_sections.add(block.heading)
+ change = section_changes[block.heading]
+ new_section = _find(new_blocks, block.heading)
+ _apply_section(block, change, new_section)
+
+ if current_blocks and not any(b.heading == "Device Information" for b in current_blocks) and info_table_change:
+ _apply_added_table(blocks, new_blocks, info_table_change)
+
+ for name in _DEVICE_SECTIONS:
+ if any(b.heading == name for b in current_blocks):
+ continue
+ pending_change = section_changes.get(name)
+ new_section = _find(new_blocks, name)
+ if pending_change is None or new_section is None:
+ continue
+ content = _section_result(pending_change)
+ if content is _SectionAction.SKIP or content is _SectionAction.REMOVE:
+ continue
+ heading = new_section.lines[0]
+ body_lines = ([""] + content.splitlines() + [""]) if content else []
+ block = Block(
+ level=_heading_level(heading), heading=name, lines=[heading, *body_lines]
+ )
+ _insert_before_user_sections(blocks, block)
+
+ return "\n".join(_block_text(b) for b in blocks if not b.removed)
+
+
+def _apply_section(block: Block, change: Change, new_section: Block | None) -> None:
+ """Apply one device-owned section's decision to its block."""
+ heading = block.lines[0] if block.lines else ""
+ if change.status == SAME:
+ return
+ if change.status == AUTO:
+ if new_section is None:
+ block.removed = True
+ return
+ replacement = _content(new_section) if new_section else []
+ block.lines = [heading, *replacement]
+ return
+ # CONFLICT
+ result = _section_result(change)
+ if result is _SectionAction.REMOVE:
+ block.removed = True
+ elif result is not _SectionAction.SKIP:
+ body_lines = ([""] + result.splitlines() + [""]) if result else [""]
+ block.lines = [heading, *body_lines]
+
+
+def _apply_added_table(blocks: list[Block], new_blocks: list[Block], change: Change) -> None:
+ """Re-introduce a Device Information table the user had removed."""
+ result = _section_result(change)
+ if result is _SectionAction.SKIP or result is _SectionAction.REMOVE:
+ return
+ new_section = _find(new_blocks, "Device Information")
+ if new_section is None:
+ return
+ heading = new_section.lines[0]
+ body_lines = ([""] + result.splitlines() + [""]) if result else [""]
+ _insert_before_user_sections(
+ blocks,
+ Block(
+ level=_heading_level(heading),
+ heading="Device Information",
+ lines=[heading, *body_lines],
+ ),
+ )
+
+
+def _section_result(change: Change) -> str | _SectionAction:
+ """The replacement content for a section, or an internal action."""
+ if change.status == SAME:
+ return _SectionAction.SKIP
+ if change.status == AUTO:
+ return change.device
+ # CONFLICT
+ if change.resolution is None or change.resolution == KEEP:
+ return _SectionAction.SKIP
+ if change.resolution == DEVICE:
+ return change.device if change.device else _SectionAction.REMOVE
+ if change.resolution == CUSTOM:
+ return change.custom if change.custom is not None else _SectionAction.REMOVE
+ return _SectionAction.SKIP
+
+
+def _explicit_row_resolution(change: Change | None) -> bool:
+ """Whether the user has settled an ambiguous duplicate row's fate explicitly."""
+ if change is None or change.status != CONFLICT:
+ return False
+ return change.resolution == DEVICE or (
+ change.resolution == CUSTOM and change.custom is not None
+ )
+
+
+def _rebuild_info_table(block: Block, info_changes: dict[str, Change]) -> None:
+ """Rebuild the Device Information rows according to the decisions.
+
+ The non-data lines (the header and separator of the table, and the blank
+ lines around them) stay exactly where they are; the data rows are replaced
+ in place, and a label the device has but the document does not is appended
+ at the end of the table when its decision calls for it.
+
+ A duplicated label is ambiguous — which row is the generator's own copy is
+ unknowable. Every copy is kept byte for byte, silently, and only an
+ explicit device/custom decision writes the first copy; nothing ever guesses
+ which duplicate is "the" row.
+ """
+ counts: dict[str, int] = {}
+ content = _content(block)
+ in_table = False
+ rows: list[tuple[int, str, str]] = []
+ for index, line in enumerate(content):
+ if _TABLE_SEPARATOR.match(line):
+ in_table = True
+ continue
+ if not in_table:
+ continue
+ row = _row_from_line(line)
+ if row is not None:
+ label, value = row
+ rows.append((index, label, value))
+ counts[label] = counts.get(label, 0) + 1
+
+ rebuilt = list(content)
+ seen: set[str] = set()
+ for index, label, cur_cell in rows:
+ if label in seen:
+ continue
+ seen.add(label)
+ if counts[label] > 1 and not _explicit_row_resolution(info_changes.get(label)):
+ continue
+ replacement = _value_for(info_changes.get(label), cur_cell)
+ if replacement is not None and replacement != cur_cell:
+ rebuilt[index] = _replace_cell(content[index], replacement)
+ for label, change in info_changes.items():
+ if label in seen:
+ continue
+ if not _adds_missing_row(change):
+ continue
+ replacement = _value_for(change, "")
+ if replacement is not None:
+ rebuilt.append(f"| {label} | {replacement} |")
+
+ block.lines = [block.lines[0] if block.lines else "## Device Information", *rebuilt]
+
+
+def _value_for(change: Change | None, cur_cell: str) -> str | None:
+ """The cell text a decided row should carry; None means the row stays out."""
+ if change is None:
+ return cur_cell
+ if change.status == SAME:
+ return cur_cell
+ if change.status == AUTO:
+ return change.device
+ # CONFLICT
+ if change.resolution is None or change.resolution == KEEP:
+ return cur_cell
+ if change.resolution == DEVICE:
+ return change.device
+ if change.resolution == CUSTOM:
+ return cell(change.custom) if change.custom is not None else None
+ return None
+
+
+def _adds_missing_row(change: Change) -> bool:
+ """Only a device addition or an accepted decision restores an absent row."""
+ return change.status == AUTO or (
+ change.status == CONFLICT and change.resolution in (DEVICE, CUSTOM)
+ )
+
+
+def _decide_cell(cur: str | None, old: str | None, new: str | None) -> str:
+ """Three-way decision for table cells, where an empty cell is still a row."""
+ if cur == new or old == new:
+ return SAME
+ if new is None:
+ return CONFLICT
+ if old is None:
+ return AUTO if cur is None else CONFLICT
+ return AUTO if cur == old else CONFLICT
+
+
+def _replace_cell(line: str, value: str) -> str:
+ """Replace only a row's second cell, retaining its user formatting."""
+ if _row_from_line(line) is None:
+ return line
+ separator = line.find("|", 1)
+ end = line.rfind("|")
+ if separator < 0 or separator == end:
+ return line
+ cell_text = line[separator + 1:end]
+ leading = cell_text[: len(cell_text) - len(cell_text.lstrip())]
+ trailing = cell_text[len(cell_text.rstrip()):]
+ return f"{line[:separator + 1]}{leading}{value}{trailing}{line[end:]}"
+
+
+def _insert_before_user_sections(blocks: list[Block], block: Block) -> None:
+ for index, existing in enumerate(blocks):
+ if existing.heading in _USER_SECTION_NAMES:
+ blocks.insert(index, block)
+ return
+ blocks.append(block)
+
+
+def _frontmatter_title(block: Block | None) -> str | None:
+ """The semantic YAML title in the frontmatter block, if it is a string."""
+ if block is None:
+ return None
+ lines = block.lines
+ open_index = next((i for i, line in enumerate(lines) if line.strip() == "---"), None)
+ if open_index is None:
+ return None
+ close_index = next(
+ (i for i in range(open_index + 1, len(lines)) if lines[i].strip() == "---"), None
+ )
+ if close_index is None:
+ return None
+ try:
+ parsed = yaml.safe_load("\n".join(lines[open_index + 1:close_index]))
+ except yaml.YAMLError:
+ return None
+ return parsed.get("title") if isinstance(parsed, dict) and isinstance(parsed.get("title"), str) else None
+
+
+def _apply_h1(blocks: list[Block], name: str) -> None:
+ """Rename the document in its first H1 only."""
+ for block in blocks:
+ if block.level == 1 and block.heading is not None:
+ block.lines[0] = f"# {name}"
+ break
+
+
+def _apply_frontmatter_title(blocks: list[Block], title: str) -> None:
+ """Set the frontmatter `title:` only, independent of the H1 decision."""
+ for block in blocks:
+ if block.level == 0:
+ _set_frontmatter_title(block, title)
+
+
+def _set_frontmatter_title(block: Block, title: str) -> None:
+ """Replace the complete YAML title scalar without touching other entries."""
+ lines = block.lines
+ open_index = next((i for i, line in enumerate(lines) if line.strip() == "---"), None)
+ if open_index is None:
+ return
+ close_index = next((i for i in range(open_index + 1, len(lines)) if lines[i].strip() == "---"), None)
+ if close_index is None:
+ return
+ start = open_index + 1
+ try:
+ document = yaml.compose("\n".join(lines[start:close_index]))
+ except yaml.YAMLError:
+ return
+ if not isinstance(document, yaml.MappingNode):
+ return
+ rendered = f"title: {json.dumps(title, ensure_ascii=False)}"
+ for key, value in document.value:
+ if isinstance(key, yaml.ScalarNode) and key.value == "title":
+ # A block scalar ends at column zero on the next line; quoted
+ # multi-line scalars end inside their final line.
+ end = max(
+ key.start_mark.line + 1,
+ value.end_mark.line + bool(value.end_mark.column),
+ )
+ lines[start + key.start_mark.line:start + end] = [rendered]
+ return
+ lines.insert(close_index, rendered)
+
+
+# ── summary & fingerprint ───────────────────────────────────────────────────
+
+
+def _updated(change: Change) -> str:
+ """One line for a value taken from the device.
+
+ A field's new value is short enough to quote. A section's is a whole block
+ of markdown — a table collapsed onto one line reads as noise — so it is
+ named, not quoted.
+ """
+ if not change.device:
+ return f"{change.name} removed"
+ if change.kind == "section":
+ return f"{change.name} updated from the device"
+ return f"{change.name} updated to {change.device}"
+
+
+def _summarise(changes: list[Change]) -> list[str]:
+ lines: list[str] = []
+ for change in changes:
+ if change.status == SAME:
+ continue
+ if change.status == AUTO:
+ lines.append(_updated(change))
+ elif change.resolution == KEEP:
+ lines.append(f"{change.name} kept as written")
+ elif change.resolution == DEVICE:
+ lines.append(_updated(change))
+ elif change.resolution == CUSTOM:
+ lines.append(f"{change.name} set from your text")
+ return [re.sub(r"\s+", " ", line).strip() for line in lines]
+
+
+def preview_id(
+ updated_at: str,
+ snapshot: dict[str, Any] | None,
+ body: str,
+ baseline_body: str | None = None,
+ live: dict[str, Any] | None = None,
+) -> str:
+ """Stable id for a preview, so a stale save is rejected instead of overwriting.
+
+ Binds the latest ``updated_at``, the facts the preview was computed against,
+ the body it began from, the generation baseline and the live device facts,
+ render context and generated body the proposal was computed from: any of
+ them moving since the modal opened means a new preview is needed before the
+ resolution can be saved.
+ """
+ material = {
+ "updated_at": updated_at,
+ "snapshot": snapshot,
+ "body": body,
+ "baseline_body": baseline_body,
+ "live": live,
+ }
+ payload = json.dumps(material, sort_keys=True, default=str).encode("utf-8")
+ return hashlib.sha256(payload).hexdigest()[:16]
diff --git a/backend/tests/test_device_update.py b/backend/tests/test_device_update.py
new file mode 100644
index 0000000..4820aa7
--- /dev/null
+++ b/backend/tests/test_device_update.py
@@ -0,0 +1,468 @@
+"""The update-from-device endpoints (#484).
+
+Three-way merge on the wire: a preview that changes nothing, an apply that only
+saves a fully reviewed merge, and a staleness guard that refuses to run a
+resolution made against a document that moved on.
+"""
+
+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 _doc(client: AsyncClient, headers: dict, device: dict) -> dict:
+ res = await client.post(
+ "/api/v1/documents", json={"title": "nas", "kind": "device", "device_id": device["id"]}, headers=headers
+ )
+ assert res.status_code == 201, res.text
+ return res.json()
+
+
+async def _set_ip(client: AsyncClient, headers: dict, device: dict, ip: str) -> None:
+ res = await client.patch(f"/api/v1/scan/pending/{device['id']}", json={"ip": ip}, headers=headers)
+ assert res.status_code == 200, res.text
+
+
+async def _edit_ip(client: AsyncClient, headers: dict, doc: dict, ip: str) -> dict:
+ body = doc["body"].replace("| IP | 192.168.1.20 |", f"| IP | {ip} |")
+ res = await client.patch(f"/api/v1/documents/{doc['id']}", json={"body": body}, headers=headers)
+ assert res.status_code == 200, res.text
+ return res.json()
+
+
+async def _preview(client: AsyncClient, headers: dict, doc_id: str, **kwargs) -> dict:
+ res = await client.post(f"/api/v1/documents/{doc_id}/update-preview", json=kwargs, headers=headers)
+ assert res.status_code == 200, res.text
+ return res.json()
+
+
+# ── auth and guards ─────────────────────────────────────────────────────────
+
+
+async def test_preview_requires_auth(client: AsyncClient):
+ assert (await client.post("/api/v1/documents/x/update-preview", json={})).status_code == 401
+
+
+async def test_apply_requires_auth(client: AsyncClient):
+ assert (await client.post("/api/v1/documents/x/update-from-device", json={})).status_code == 401
+
+
+async def test_preview_of_an_unknown_document_is_404(client: AsyncClient, headers: dict):
+ res = await client.post("/api/v1/documents/x/update-preview", json={}, headers=headers)
+ assert res.status_code == 404
+
+
+async def test_apply_of_an_unknown_document_is_404(client: AsyncClient, headers: dict):
+ res = await client.post("/api/v1/documents/x/update-from-device", json={"preview_id": "x"}, headers=headers)
+ assert res.status_code == 404
+
+
+async def test_preview_of_a_plain_page_is_rejected(client: AsyncClient, headers: dict):
+ res = await client.post("/api/v1/documents", json={"title": "Notes"}, headers=headers)
+ doc = res.json()
+ res = await client.post(f"/api/v1/documents/{doc['id']}/update-preview", json={}, headers=headers)
+ assert res.status_code == 400
+
+
+async def test_apply_of_a_plain_page_is_rejected(client: AsyncClient, headers: dict):
+ res = await client.post("/api/v1/documents", json={"title": "Notes"}, headers=headers)
+ doc = res.json()
+ res = await client.post(
+ f"/api/v1/documents/{doc['id']}/update-from-device", json={"preview_id": "x"}, headers=headers
+ )
+ assert res.status_code == 400
+
+
+# ── preview ─────────────────────────────────────────────────────────────────
+
+
+async def test_a_stable_device_previews_no_changes(client: AsyncClient, headers: dict):
+ device = await _device(client, headers)
+ doc = await _doc(client, headers, device)
+ preview = await _preview(client, headers, doc["id"])
+ assert preview["unresolved"] == []
+ assert all(c["status"] in ("same", "auto") for c in preview["changes"])
+ # An untouched document: the merge is the document.
+ assert preview["proposed_body"] == doc["body"]
+
+
+async def test_an_untouched_field_is_offered_for_automatic_application(client: AsyncClient, headers: dict):
+ device = await _device(client, headers)
+ doc = await _doc(client, headers, device)
+ await _set_ip(client, headers, device, "192.168.1.99")
+
+ preview = await _preview(client, headers, doc["id"])
+ ip = next(c for c in preview["changes"] if c["id"] == "device-info.IP")
+ assert ip["status"] == "auto"
+ assert ip["device"] == "192.168.1.99"
+ assert preview["unresolved"] == []
+ assert "| IP | 192.168.1.99 |" in preview["proposed_body"]
+
+
+async def test_a_user_edit_against_a_device_change_is_a_conflict(client: AsyncClient, headers: dict):
+ device = await _device(client, headers)
+ doc = await _doc(client, headers, device)
+ await _edit_ip(client, headers, doc, "192.168.1.20 (jump host)")
+ await _set_ip(client, headers, device, "192.168.1.99")
+
+ preview = await _preview(client, headers, doc["id"])
+ ip = next(c for c in preview["changes"] if c["id"] == "device-info.IP")
+ assert ip["status"] == "conflict"
+ assert ip["documented"] == "192.168.1.20 (jump host)"
+ assert ip["device"] == "192.168.1.99"
+ assert preview["unresolved"] == ["device-info.IP"]
+ # An unresolved merge keeps the user's text — the preview is a draft.
+ assert "192.168.1.20 (jump host)" in preview["proposed_body"]
+
+
+async def test_a_preview_folds_resolutions_in(client: AsyncClient, headers: dict):
+ device = await _device(client, headers)
+ doc = await _doc(client, headers, device)
+ await _edit_ip(client, headers, doc, "192.168.1.20 (jump host)")
+ await _set_ip(client, headers, device, "192.168.1.99")
+
+ preview = await _preview(
+ client, headers, doc["id"],
+ resolutions=[{"id": "device-info.IP", "choice": "custom", "custom": "10.9.8.7 (lan) "}],
+ )
+ ip = next(c for c in preview["changes"] if c["id"] == "device-info.IP")
+ assert ip["resolution"] == "custom"
+ assert preview["unresolved"] == []
+ assert "| IP | 10.9.8.7 (lan) |" in preview["proposed_body"]
+
+
+# ── apply ───────────────────────────────────────────────────────────────────
+
+
+async def test_apply_lands_an_automatic_merge(client: AsyncClient, headers: dict):
+ device = await _device(client, headers)
+ doc = await _doc(client, headers, device)
+ await _set_ip(client, headers, device, "192.168.1.99")
+ preview_id = (await _preview(client, headers, doc["id"]))["preview_id"]
+
+ res = await client.post(
+ f"/api/v1/documents/{doc['id']}/update-from-device",
+ json={"preview_id": preview_id, "resolutions": []},
+ headers=headers,
+ )
+ assert res.status_code == 200, res.text
+ updated = res.json()
+ assert "| IP | 192.168.1.99 |" in updated["body"]
+ # The device is recorded as documented again — the drift banner clears.
+ assert updated["facts_snapshot"]["ip"] == "192.168.1.99"
+ assert updated["drifted"] is False
+ assert (await client.get(f"/api/v1/documents/{doc['id']}", headers=headers)).json()["drifted"] is False
+
+ # The old body is in history, flagged as a sync.
+ revisions = (await client.get(f"/api/v1/documents/{doc['id']}/revisions", headers=headers)).json()
+ assert [r["reason"] for r in revisions] == ["sync"]
+
+
+async def test_a_body_that_already_matches_the_device_is_not_drifted(client: AsyncClient, headers: dict):
+ """The user already wrote the device's new value: an update would have
+ nothing to offer, so neither the document, the list nor coverage flag it."""
+ device = await _device(client, headers)
+ doc = await _doc(client, headers, device)
+ await _set_ip(client, headers, device, "192.168.1.99")
+ assert (await client.get(f"/api/v1/documents/{doc['id']}", headers=headers)).json()["drifted"] is True
+
+ await _edit_ip(client, headers, doc, "192.168.1.99")
+ assert (await client.get(f"/api/v1/documents/{doc['id']}", headers=headers)).json()["drifted"] is False
+ listed = (await client.get("/api/v1/documents", headers=headers)).json()
+ assert next(d for d in listed if d["id"] == doc["id"])["drifted"] is False
+ assert (await client.get("/api/v1/documents/coverage", headers=headers)).json()["drifted"] == 0
+
+
+async def test_the_list_flags_each_drifted_document_on_its_own_device(client: AsyncClient, headers: dict):
+ """The list resolves every candidate's render context in one batch; each
+ document must still be judged against its own device."""
+ docs = {}
+ for name, ip in (("nas-a", "192.168.1.31"), ("nas-b", "192.168.1.32"), ("nas-c", "192.168.1.33")):
+ device = await _device(client, headers, label=name, hostname=f"{name}.lan", ip=ip)
+ docs[name] = (device, await _doc(client, headers, device))
+
+ for name, ip in (("nas-a", "192.168.1.41"), ("nas-b", "192.168.1.42"), ("nas-c", "192.168.1.43")):
+ await _set_ip(client, headers, docs[name][0], ip)
+ # nas-c's owner already wrote the new address down.
+ matching = docs["nas-c"][1]
+ res = await client.patch(
+ f"/api/v1/documents/{matching['id']}",
+ json={"body": matching["body"].replace("| IP | 192.168.1.33 |", "| IP | 192.168.1.43 |")},
+ headers=headers,
+ )
+ assert res.status_code == 200, res.text
+
+ listed = {d["id"]: d["drifted"] for d in (await client.get("/api/v1/documents", headers=headers)).json()}
+ assert listed[docs["nas-a"][1]["id"]] is True
+ assert listed[docs["nas-b"][1]["id"]] is True
+ assert listed[matching["id"]] is False
+ assert (await client.get("/api/v1/documents/coverage", headers=headers)).json()["drifted"] == 2
+
+
+async def test_a_conflict_keeps_the_document_drifted(client: AsyncClient, headers: dict):
+ """The user and the device disagree: that is exactly what the flag is for."""
+ device = await _device(client, headers)
+ doc = await _doc(client, headers, device)
+ await _edit_ip(client, headers, doc, "nas.example.lan")
+ await _set_ip(client, headers, device, "192.168.1.99")
+ assert (await client.get(f"/api/v1/documents/{doc['id']}", headers=headers)).json()["drifted"] is True
+
+
+async def test_apply_with_nothing_to_change_records_the_facts_without_a_revision(
+ client: AsyncClient, headers: dict
+):
+ device = await _device(client, headers)
+ doc = await _doc(client, headers, device)
+ await _set_ip(client, headers, device, "192.168.1.99")
+ edited = await _edit_ip(client, headers, doc, "192.168.1.99")
+
+ preview = await _preview(client, headers, doc["id"])
+ assert preview["summary"] == []
+ assert preview["unresolved"] == []
+
+ res = await client.post(
+ f"/api/v1/documents/{doc['id']}/update-from-device",
+ json={"preview_id": preview["preview_id"], "resolutions": []},
+ headers=headers,
+ )
+ assert res.status_code == 200, res.text
+ updated = res.json()
+ assert updated["body"] == edited["body"]
+ assert updated["facts_snapshot"]["ip"] == "192.168.1.99"
+ assert updated["drifted"] is False
+
+ # Nothing was rewritten, so history gains no sync revision.
+ revisions = (await client.get(f"/api/v1/documents/{doc['id']}/revisions", headers=headers)).json()
+ assert "sync" not in [r["reason"] for r in revisions]
+
+
+async def test_apply_records_a_durable_decision(client: AsyncClient, headers: dict):
+ device = await _device(client, headers)
+ doc = await _doc(client, headers, device)
+ await _edit_ip(client, headers, doc, "192.168.1.20 (primary)")
+ await _set_ip(client, headers, device, "192.168.1.99")
+
+ preview = await _preview(
+ client, headers, doc["id"],
+ resolutions=[{"id": "device-info.IP", "choice": "keep"}],
+ )
+ res = await client.post(
+ f"/api/v1/documents/{doc['id']}/update-from-device",
+ json={"preview_id": preview["preview_id"], "resolutions": [{"id": "device-info.IP", "choice": "keep"}]},
+ headers=headers,
+ )
+ assert res.status_code == 200, res.text
+ assert "| IP | 192.168.1.20 (primary) |" in res.json()["body"]
+
+
+async def test_a_kept_value_is_surfaced_again_on_the_next_change(client: AsyncClient, headers: dict):
+ """The baseline is the generated body, never the merged one, so a deliberate
+ keep is not permanent blindness — the next device move asks once more."""
+ device = await _device(client, headers)
+ doc = await _doc(client, headers, device)
+ await _edit_ip(client, headers, doc, "192.168.1.20 (primary)")
+ await _set_ip(client, headers, device, "192.168.1.99")
+
+ preview = await _preview(client, headers, doc["id"])
+ assert preview["unresolved"] == ["device-info.IP"]
+
+ # User keeps their note and applies.
+ preview = await _preview(client, headers, doc["id"], resolutions=[{"id": "device-info.IP", "choice": "keep"}])
+ res = await client.post(
+ f"/api/v1/documents/{doc['id']}/update-from-device",
+ json={"preview_id": preview["preview_id"], "resolutions": [{"id": "device-info.IP", "choice": "keep"}]},
+ headers=headers,
+ )
+ assert res.status_code == 200, res.text
+ assert "192.168.1.20 (primary)" in res.json()["body"]
+
+ # Device stays put: the kept value is quiet.
+ steady = await _preview(client, headers, doc["id"])
+ assert steady["unresolved"] == []
+
+ # The device moves again: the kept value is in question once more.
+ await _set_ip(client, headers, device, "192.168.1.120")
+ later = await _preview(client, headers, doc["id"])
+ assert later["unresolved"] == ["device-info.IP"]
+
+
+async def test_kept_hostname_is_acknowledged_once_per_ip_change(client: AsyncClient, headers: dict):
+ """Each Keep records the current IP as baseline without losing the hostname."""
+ device = await _device(
+ client,
+ headers,
+ label="homelabcluster",
+ hostname="homelabcluster.example.lan",
+ ip="192.168.10.10",
+ )
+ doc = await _doc(client, headers, device)
+ hostname = "homelabcluster.example.lan"
+ edited_body = doc["body"].replace("| IP | 192.168.10.10 |", f"| IP | {hostname} |")
+ edit = await client.patch(
+ f"/api/v1/documents/{doc['id']}", json={"body": edited_body}, headers=headers
+ )
+ assert edit.status_code == 200, edit.text
+
+ # The original baseline was .10, so the reviewed .20 needs an initial Keep.
+ await _set_ip(client, headers, device, "192.168.10.20")
+ first = await _preview(client, headers, doc["id"])
+ assert first["unresolved"] == ["device-info.IP"]
+ applied = await client.post(
+ f"/api/v1/documents/{doc['id']}/update-from-device",
+ json={"preview_id": first["preview_id"], "resolutions": [{"id": "device-info.IP", "choice": "keep"}]},
+ headers=headers,
+ )
+ assert applied.status_code == 200, applied.text
+ assert f"| IP | {hostname} |" in applied.json()["body"]
+
+ # The prior body is recoverable through the global revision URL, not a
+ # document-nested lookalike route.
+ revisions = (await client.get(f"/api/v1/documents/{doc['id']}/revisions", headers=headers)).json()
+ sync = next(revision for revision in revisions if revision["reason"] == "sync")
+ previous = await client.get(f"/api/v1/documents/revisions/{sync['id']}", headers=headers)
+ assert previous.status_code == 200, previous.text
+ assert previous.json()["body"] == edited_body
+
+ quiet = await _preview(client, headers, doc["id"])
+ assert quiet["unresolved"] == []
+
+ await _set_ip(client, headers, device, "192.168.10.25")
+ second = await _preview(client, headers, doc["id"])
+ assert second["unresolved"] == ["device-info.IP"]
+ applied = await client.post(
+ f"/api/v1/documents/{doc['id']}/update-from-device",
+ json={"preview_id": second["preview_id"], "resolutions": [{"id": "device-info.IP", "choice": "keep"}]},
+ headers=headers,
+ )
+ assert applied.status_code == 200, applied.text
+ assert applied.json()["facts_snapshot"]["ip"] == "192.168.10.25"
+ assert (await _preview(client, headers, doc["id"]))["unresolved"] == []
+
+ await _set_ip(client, headers, device, "192.168.10.30")
+ later = await _preview(client, headers, doc["id"])
+ assert later["unresolved"] == ["device-info.IP"]
+
+
+async def test_apply_rejects_a_stale_preview(client: AsyncClient, headers: dict):
+ device = await _device(client, headers)
+ doc = await _doc(client, headers, device)
+ await _set_ip(client, headers, device, "192.168.1.99")
+ preview_id = (await _preview(client, headers, doc["id"]))["preview_id"]
+
+ # The document is edited while the preview is open.
+ res = await client.patch(
+ f"/api/v1/documents/{doc['id']}", json={"body": doc["body"] + "\n"}, headers=headers
+ )
+ assert res.status_code == 200, res.text
+
+ res = await client.post(
+ f"/api/v1/documents/{doc['id']}/update-from-device",
+ json={"preview_id": preview_id, "resolutions": []},
+ headers=headers,
+ )
+ assert res.status_code == 409
+
+
+async def test_apply_rejects_unresolved_conflicts(client: AsyncClient, headers: dict):
+ device = await _device(client, headers)
+ doc = await _doc(client, headers, device)
+ await _edit_ip(client, headers, doc, "192.168.1.20 (jump host)")
+ await _set_ip(client, headers, device, "192.168.1.99")
+ preview_id = (await _preview(client, headers, doc["id"]))["preview_id"]
+
+ res = await client.post(
+ f"/api/v1/documents/{doc['id']}/update-from-device",
+ json={"preview_id": preview_id, "resolutions": []},
+ headers=headers,
+ )
+ assert res.status_code == 400
+ assert "IP address" in res.json()["detail"]
+
+
+async def test_apply_rejects_a_device_change_made_while_the_preview_was_open(
+ client: AsyncClient, headers: dict
+):
+ """A device that moves on during review is a different review thread.
+
+ The preview id binds the live device facts and generated context the
+ proposal was computed from — not just the document state — so applying an
+ old resolution to a device that changed must fail with 409 and save
+ nothing: no body change and no history entry.
+ """
+ device = await _device(client, headers)
+ doc = await _doc(client, headers, device)
+ doc = await _edit_ip(client, headers, doc, "nas.example.lan")
+ await _set_ip(client, headers, device, "192.168.1.30")
+
+ preview = await _preview(
+ client, headers, doc["id"], resolutions=[{"id": "device-info.IP", "choice": "device"}]
+ )
+ await _set_ip(client, headers, device, "192.168.1.40")
+ # The device moved on, so a fresh preview is a different id now.
+ fresh = await _preview(client, headers, doc["id"])
+ assert preview["preview_id"] != fresh["preview_id"]
+
+ res = await client.post(
+ f"/api/v1/documents/{doc['id']}/update-from-device",
+ json={
+ "preview_id": preview["preview_id"],
+ "resolutions": [{"id": "device-info.IP", "choice": "device"}],
+ },
+ headers=headers,
+ )
+ assert res.status_code == 409
+ # Nothing landed: the un-reviewed .40 is not in the body, the user edit
+ # survives, drift is untouched and no sync history was written.
+ current = (await client.get(f"/api/v1/documents/{doc['id']}", headers=headers)).json()
+ assert "| IP | 192.168.1.40 |" not in current["body"]
+ assert "| IP | nas.example.lan |" in current["body"]
+ assert current["drifted"] is True
+ # No sync history was written — the rejected apply recorded nothing, only
+ # the user's own earlier body edit exists.
+ revisions = (await client.get(f"/api/v1/documents/{doc['id']}/revisions", headers=headers)).json()
+ assert [r["reason"] for r in revisions] == ["edit"]
+
+
+async def test_apply_rejects_a_generated_content_only_device_change(
+ client: AsyncClient, headers: dict
+):
+ """A device edit that only changes the *rendered* document binds too.
+
+ The device notes print into the generated body but are deliberately absent
+ from `facts_snapshot`, so changing them between preview and apply is a
+ rendered-content-only change: only a preview id that binds the generated
+ body itself can reject it.
+ """
+ device = await _device(client, headers)
+ doc = await _doc(client, headers, device)
+ res = await client.patch(
+ f"/api/v1/scan/pending/{device['id']}", json={"notes": "serve the home media"}, headers=headers
+ )
+ assert res.status_code == 200, res.text
+
+ preview = await _preview(client, headers, doc["id"])
+ res = await client.patch(
+ f"/api/v1/scan/pending/{device['id']}",
+ json={"notes": "serve the home media — NFS too"},
+ headers=headers,
+ )
+ assert res.status_code == 200, res.text
+ # Same facts, same context — only the rendered body differs.
+ fresh = await _preview(client, headers, doc["id"])
+ assert preview["preview_id"] != fresh["preview_id"]
+
+ res = await client.post(
+ f"/api/v1/documents/{doc['id']}/update-from-device",
+ json={"preview_id": preview["preview_id"], "resolutions": []},
+ headers=headers,
+ )
+ assert res.status_code == 409
+ # Nothing landed: the body is untouched and no sync history was written.
+ assert (await client.get(f"/api/v1/documents/{doc['id']}", headers=headers)).json()["body"] == doc["body"]
+ revisions = (await client.get(f"/api/v1/documents/{doc['id']}/revisions", headers=headers)).json()
+ assert [r["reason"] for r in revisions] == []
diff --git a/backend/tests/test_doc_reconcile.py b/backend/tests/test_doc_reconcile.py
new file mode 100644
index 0000000..adc6b91
--- /dev/null
+++ b/backend/tests/test_doc_reconcile.py
@@ -0,0 +1,976 @@
+"""The three-way reconcile behind "Update from device".
+
+Baseline (the generated body recorded at the last sync) / current (the body the
+user has now) / new (freshly generated from the live device). The contract:
+
+* user-only edits are preserved, identical changes never conflict;
+* untouched facts where the device moved are applied without asking;
+* a fact both sides changed is a conflict the user resolves (keep / device /
+ custom), and the resolution is what lands in the merged body;
+* the generated sections are reconciled whole; user sections never move a
+ character;
+* a missing baseline is conservative: never a silent overwrite.
+"""
+
+from datetime import date
+from types import SimpleNamespace
+
+import yaml
+
+from app.services import doc_template as t
+from app.services.doc_reconcile import (
+ AUTO,
+ CUSTOM,
+ DEVICE,
+ KEEP,
+ SAME,
+ Resolution,
+ preview_id,
+ reconcile,
+)
+
+
+# What the template reads off a row.
+def _device(**overrides):
+ base = dict(
+ id="dev-1",
+ label="homelabcluster",
+ friendly_name=None,
+ hostname="homelabcluster.example.lan",
+ ip="192.168.10.20",
+ mac="00:11:32:aa:bb:cc",
+ ieee_address=None,
+ os="Debian 12",
+ vendor="Intel",
+ model="N100",
+ type="server",
+ suggested_type=None,
+ services=[
+ {"port": 443, "protocol": "tcp", "service_name": "https", "category": "management"},
+ {"port": 22, "protocol": "tcp", "service_name": "ssh"},
+ ],
+ properties=[{"key": "Serial", "value": "ABC123", "icon": None, "visible": True}],
+ cpu_count=4,
+ cpu_model="N100",
+ ram_gb=16.0,
+ disk_gb=2000.0,
+ check_method="ping",
+ check_target="-",
+ discovery_source="arp",
+ discovery_sources=["arp"],
+ discovered_at=None,
+ notes="",
+ rack=None,
+ zone_label="Homelab",
+ connections=["switch-01"],
+ )
+ base.update(overrides)
+ return SimpleNamespace(**base)
+
+
+def _body(device, *, today=None) -> str:
+ return t.render_device_document(device, today=today or date(2026, 3, 4))
+
+
+def _run(current_dev, device, *, baseline=None, snapshot=None, resolutions=None):
+ """Reconcile the document generated for current_dev against the live device."""
+ if baseline is None:
+ baseline = _body(current_dev)
+ if snapshot is None:
+ snapshot = t.facts_snapshot(current_dev)
+ return reconcile(
+ current=_body(current_dev),
+ new=_body(device),
+ baseline_body=baseline,
+ snapshot=snapshot,
+ resolutions=resolutions,
+ )
+
+
+def _by_id(changes):
+ return {c.id: c for c in changes}
+
+
+def _after(body, marker):
+ """Everything from the marker line to the end."""
+ start = body.find(marker)
+ return body[start:] if start >= 0 else ""
+
+
+# ── no change ───────────────────────────────────────────────────────────────
+
+
+def test_stable_device_is_a_noop():
+ result = _run(_device(), _device())
+ assert all(c.status == SAME for c in result.changes)
+ assert result.conflicts == []
+ assert result.summary == []
+ assert result.proposed_body == _body(_device())
+
+
+# ── safe auto-updates ───────────────────────────────────────────────────────
+
+
+def test_untouched_ip_is_applied_automatically():
+ result = _run(_device(), _device(ip="192.168.10.25"))
+ by_id = _by_id(result.changes)
+
+ assert by_id["device-info.IP"].status == AUTO
+ ip = by_id["device-info.IP"]
+ assert "IP address updated to 192.168.10.25" in result.summary
+ assert ip.previous == "192.168.10.20"
+
+ assert by_id["device-info.Hostname"].status == SAME
+ assert by_id["device-info.Hostname"].documented == "homelabcluster.example.lan"
+ assert not result.conflicts
+
+ assert "| IP | 192.168.10.25 |" in result.proposed_body
+ # The service URL follows the IP, and is applied just as silently.
+ assert "https://192.168.10.25" in result.proposed_body
+ # User-owned sections come through byte for byte.
+ assert _after(result.proposed_body, "## Configuration") == _after(_body(_device()), "## Configuration")
+
+
+def test_device_info_ip_update_preserves_table_layout_and_empty_cells():
+ """A device-only update must not re-render its user's table."""
+ baseline = _body(_device())
+ current = (
+ baseline.replace("| | |\n|---|---|", "| Field | Value |\n|:------|-----:|")
+ .replace("| IP | 192.168.10.20 |", "| IP | 192.168.10.20 |")
+ .replace("| OS | Debian 12 |", "| OS | |")
+ .replace("| Status check | `ping` → `-` |", "| Status check | `ping` → `-` |\n\n_table note_")
+ )
+ result = reconcile(
+ current,
+ _body(_device(ip="192.168.10.25")),
+ baseline_body=baseline,
+ snapshot=t.facts_snapshot(_device()),
+ )
+
+ expected = current.replace("192.168.10.20", "192.168.10.25", 1)
+ assert _after(result.proposed_body, "## Device Information").split("### Hardware", 1)[0] == (
+ _after(expected, "## Device Information").split("### Hardware", 1)[0]
+ )
+ assert "| Field | Value |\n|:------|-----:|" in result.proposed_body
+ assert "| OS | |" in result.proposed_body
+
+
+def test_deleted_os_row_stays_absent_until_device_restore_is_approved():
+ baseline = _body(_device())
+ current = baseline.replace("| OS | Debian 12 |\n", "")
+
+ unchanged = reconcile(
+ current, baseline, baseline_body=baseline, snapshot=t.facts_snapshot(_device())
+ )
+ assert _by_id(unchanged.changes)["device-info.OS"].status == SAME
+ assert unchanged.proposed_body == current
+
+ changed = reconcile(
+ current,
+ _body(_device(os="Debian 13")),
+ baseline_body=baseline,
+ snapshot=t.facts_snapshot(_device()),
+ )
+ assert _by_id(changed.changes)["device-info.OS"].status == "conflict"
+ assert changed.proposed_body == current
+
+ restored = reconcile(
+ current,
+ _body(_device(os="Debian 13")),
+ baseline_body=baseline,
+ snapshot=t.facts_snapshot(_device()),
+ resolutions=[Resolution(id="device-info.OS", choice=DEVICE)],
+ )
+ assert "| OS | Debian 13 |" in restored.proposed_body
+
+
+def test_user_edit_is_kept_when_device_unchanged():
+ current = _body(_device()).replace("| OS | Debian 12 |", "| OS | Debian 12 (tuned) |")
+ snapshot = t.facts_snapshot(_device())
+ result = reconcile(current, _body(_device()), baseline_body=_body(_device()), snapshot=snapshot)
+ by_id = _by_id(result.changes)
+
+ assert by_id["device-info.OS"].status == SAME
+ assert "Debian 12 (tuned)" in result.proposed_body
+ assert not result.conflicts
+
+
+def test_identical_change_never_conflicts():
+ # The user wrote the device's *new* value before the sync.
+ current = _body(_device()).replace("| IP | 192.168.10.20 |", "| IP | 192.168.10.25 |")
+ result = reconcile(current, _body(_device(ip="192.168.10.25")), baseline_body=_body(_device()), snapshot=t.facts_snapshot(_device()))
+ assert result.conflicts == []
+ assert _by_id(result.changes)["device-info.IP"].status == SAME
+ assert "| IP | 192.168.10.25 |" in result.proposed_body
+ assert _after(result.proposed_body, "## Configuration") == _after(current, "## Configuration")
+
+
+# ── conflicts and resolutions ───────────────────────────────────────────────
+
+
+def test_both_sides_changed_is_a_conflict():
+ current = _body(_device()).replace("| IP | 192.168.10.20 |", "| IP | 10.0.0.9 |")
+ result = reconcile(current, _body(_device(ip="192.168.10.25")), baseline_body=_body(_device()), snapshot=t.facts_snapshot(_device()))
+ by_id = _by_id(result.changes)
+ assert by_id["device-info.IP"].status == "conflict"
+ assert [c.id for c in result.conflicts] == ["device-info.IP"]
+ # Undecided conflicts keep the user's text in the draft.
+ assert "| IP | 10.0.0.9 |" in result.proposed_body
+
+
+def test_keep_resolution_keeps_user_text():
+ current = _body(_device()).replace("| IP | 192.168.10.20 |", "| IP | 10.0.0.9 |")
+ result = reconcile(current, _body(_device(ip="192.168.10.25")), baseline_body=_body(_device()), snapshot=t.facts_snapshot(_device()), resolutions=[Resolution(id="device-info.IP", choice=KEEP)])
+ assert "| IP | 10.0.0.9 |" in result.proposed_body
+ assert "IP address kept as written" in result.summary
+ assert result.unresolved == []
+
+
+def test_device_resolution_takes_device_value():
+ current = _body(_device()).replace("| IP | 192.168.10.20 |", "| IP | 10.0.0.9 |")
+ result = reconcile(current, _body(_device(ip="192.168.10.25")), baseline_body=_body(_device()), snapshot=t.facts_snapshot(_device()), resolutions=[Resolution(id="device-info.IP", choice=DEVICE)])
+ assert "| IP | 192.168.10.25 |" in result.proposed_body
+
+
+def test_escaped_pipe_ip_row_keeps_its_shape_for_device_and_custom_resolution():
+ baseline = _body(_device())
+ current = baseline.replace(
+ "| IP | 192.168.10.20 |", "| IP | nas.example \\| backup |"
+ )
+ new = _body(_device(ip="192.168.10.25"))
+
+ device = reconcile(
+ current,
+ new,
+ baseline_body=baseline,
+ snapshot=t.facts_snapshot(_device()),
+ resolutions=[Resolution(id="device-info.IP", choice=DEVICE)],
+ )
+ assert "| IP | 192.168.10.25 |" in device.proposed_body
+
+ custom = reconcile(
+ current,
+ new,
+ baseline_body=baseline,
+ snapshot=t.facts_snapshot(_device()),
+ resolutions=[Resolution(id="device-info.IP", choice=CUSTOM, custom="manual | route")],
+ )
+ assert "| IP | manual \\| route |" in custom.proposed_body
+
+
+def test_custom_resolution_uses_user_text_and_escapes_it():
+ current = _body(_device()).replace("| IP | 192.168.10.20 |", "| IP | 10.0.0.9 |")
+ result = reconcile(current, _body(_device(ip="192.168.10.25")), baseline_body=_body(_device()), snapshot=t.facts_snapshot(_device()), resolutions=[Resolution(id="device-info.IP", choice=CUSTOM, custom="10.0.0.9 (jump host)")])
+ assert "| IP | 10.0.0.9 (jump host) |" in result.proposed_body
+ assert "IP address set from your text" in result.summary
+
+
+# ── the regression scenario from the issue ──────────────────────────────────
+
+
+def test_hostname_change_suppresses_repeat_ip_notice():
+ """Device hostname lands *once*; the untouched IP is not re-asked."""
+ snapshot = t.facts_snapshot(_device(ip="192.168.10.20", hostname="old.example.lan"))
+ baseline = _body(_device(ip="192.168.10.20", hostname="old.example.lan"))
+ current = baseline # generated at that time, untouched since
+ result = reconcile(current, _body(_device(ip="192.168.10.25", hostname="homelabcluster.example.lan")), baseline_body=baseline, snapshot=snapshot)
+ by_id = _by_id(result.changes)
+
+ assert by_id["device-info.Hostname"].status == AUTO
+ assert by_id["device-info.IP"].status == AUTO # safe: never touched
+ assert [c.id for c in result.conflicts] == []
+
+
+def test_keeping_a_new_ip_acknowledges_it_once_and_warns_again_on_next_change():
+ """A KEEP records the *device's* value as baseline, so the next device change
+ asks again — acknowledgement is not permanent blindness."""
+ # The doc carries a deliberate user value, so a device IP move is a conflict.
+ current = _body(_device(ip="192.168.10.20")).replace("| IP | 192.168.10.20 |", "| IP | 192.168.10.20 (primary) |")
+ baseline = _body(_device(ip="192.168.10.20"))
+ snapshot = t.facts_snapshot(_device(ip="192.168.10.20"))
+
+ # Device moved to .25, the user keeps their own entry.
+ result = reconcile(current, _body(_device(ip="192.168.10.25")), baseline_body=baseline, snapshot=snapshot, resolutions=[Resolution(id="device-info.IP", choice=KEEP)])
+ assert result.unresolved == []
+ merged = result.proposed_body
+ assert "| IP | 192.168.10.20 (primary) |" in merged
+
+ # Nothing changed since: no repeat warning.
+ steady = reconcile(merged, _body(_device(ip="192.168.10.25")), baseline_body=_body(_device(ip="192.168.10.25")), snapshot=t.facts_snapshot(_device(ip="192.168.10.25")))
+ assert steady.conflicts == []
+ assert "| IP | 192.168.10.20 (primary) |" in steady.proposed_body
+
+ # The device moves again → the kept value is in question once more.
+ later = reconcile(merged, _body(_device(ip="192.168.10.30")), baseline_body=_body(_device(ip="192.168.10.25")), snapshot=t.facts_snapshot(_device(ip="192.168.10.25")))
+ assert [c.id for c in later.conflicts] == ["device-info.IP"]
+
+
+# ── whole sections ──────────────────────────────────────────────────────────
+
+
+def test_untouched_hardware_section_is_replaced_wholesale():
+ result = _run(_device(), _device(cpu_model="N200"))
+ by_id = _by_id(result.changes)
+ assert by_id["section.Hardware"].status == AUTO
+ assert "N200" in result.proposed_body
+ assert _after(result.proposed_body, "## Configuration") == _after(_body(_device()), "## Configuration")
+
+
+def test_a_section_summary_names_the_section_instead_of_quoting_it():
+ # A whole table collapsed onto one summary line reads as noise.
+ result = _run(_device(), _device(cpu_model="N200"))
+ assert result.summary == ["Hardware updated from the device"]
+
+
+def test_a_dropped_section_is_summarised_as_removed():
+ baseline = _body(_device())
+ result = reconcile(
+ baseline, _body(_device(properties=[])), baseline_body=baseline, snapshot=t.facts_snapshot(_device())
+ )
+ assert result.summary == ["Properties removed"]
+
+
+def test_section_conflict_resolves_three_ways():
+ current = _body(_device()).replace(
+ "| CPU | RAM | Disk |",
+ "| CPU | RAM | Disk |\n|---|---|---|\n| manual | row | here |",
+ )
+ baseline = _body(_device())
+ snapshot = t.facts_snapshot(_device())
+ new = _body(_device(cpu_model="N200"))
+
+ keep = reconcile(current, new, baseline_body=baseline, snapshot=snapshot, resolutions=[Resolution(id="section.Hardware", choice=KEEP)])
+ assert "| manual | row | here |" in keep.proposed_body
+
+ take = reconcile(current, new, baseline_body=baseline, snapshot=snapshot, resolutions=[Resolution(id="section.Hardware", choice=DEVICE)])
+ assert "| manual | row | here |" not in take.proposed_body
+ assert "N200" in take.proposed_body
+
+ custom = reconcile(current, new, baseline_body=baseline, snapshot=snapshot, resolutions=[Resolution(id="section.Hardware", choice=CUSTOM, custom="| A | B | C |")])
+ assert "| A | B | C |" in custom.proposed_body
+
+
+def test_custom_section_text_never_collides_with_internal_actions():
+ baseline = _body(_device())
+ current = baseline.replace("| CPU | RAM | Disk |", "manual hardware notes")
+ new = _body(_device(cpu_model="N200"))
+
+ for custom in ("remove", "skip"):
+ result = reconcile(
+ current,
+ new,
+ baseline_body=baseline,
+ snapshot=t.facts_snapshot(_device()),
+ resolutions=[Resolution(id="section.Hardware", choice=CUSTOM, custom=custom)],
+ )
+ section = _after(result.proposed_body, "### Hardware").split("### Properties", 1)[0]
+ assert custom in section
+ assert "N200" not in section
+
+ empty = reconcile(
+ current,
+ new,
+ baseline_body=baseline,
+ snapshot=t.facts_snapshot(_device()),
+ resolutions=[Resolution(id="section.Hardware", choice=CUSTOM, custom="")],
+ )
+ section = _after(empty.proposed_body, "### Hardware").split("### Properties", 1)[0]
+ assert section.strip() == "### Hardware"
+
+
+def test_user_sections_never_touched():
+ current = _body(_device())
+ edited = current.replace("## Notes", "## Notes\n\n_Every byte here is the user's._")
+ result = reconcile(
+ edited,
+ _body(_device(ip="192.168.10.25", cpu_model="N200")),
+ baseline_body=current,
+ snapshot=t.facts_snapshot(_device()),
+ )
+ tail = _after(edited, "## Notes")
+ assert _after(result.proposed_body, "## Notes") == tail
+ assert "## Operations" in result.proposed_body and "### Backup" in result.proposed_body
+
+
+def test_unknown_baseline_never_recreates_deleted_device_info_table():
+ """Legacy documents need an explicit review before restoring a missing table."""
+ generated = _body(_device())
+ start = generated.index("## Device Information")
+ end = generated.index("### Hardware")
+ current = generated[:start] + generated[end:]
+
+ preview = reconcile(current, generated, baseline_body=None, snapshot=None)
+ table_change = _by_id(preview.changes)["device-info"]
+ assert table_change.status == "conflict"
+ assert preview.unresolved == [table_change]
+ assert "## Device Information" not in preview.proposed_body
+
+ reviewed = reconcile(
+ current,
+ generated,
+ baseline_body=None,
+ snapshot=None,
+ resolutions=[Resolution(id="device-info", choice=DEVICE)],
+ )
+ assert "## Device Information" in reviewed.proposed_body
+
+
+# ── ambiguous duplicates ────────────────────────────────────────────────
+
+
+def test_duplicate_ip_row_no_device_change_preserves_both():
+ baseline = _body(_device())
+ current = baseline.replace(
+ "| IP | 192.168.10.20 |",
+ "| IP | 192.168.10.20 |\n| IP | manual-secondary |",
+ )
+ result = reconcile(
+ current,
+ _body(_device()),
+ baseline_body=baseline,
+ snapshot=t.facts_snapshot(_device()),
+ )
+ assert result.conflicts == []
+ assert result.proposed_body.count("| IP |") == 2
+ assert "| IP | 192.168.10.20 |" in result.proposed_body
+ assert "| IP | manual-secondary |" in result.proposed_body
+
+
+def test_duplicate_ip_row_prepended_no_device_change_preserves_both():
+ baseline = _body(_device())
+ current = baseline.replace(
+ "| IP | 192.168.10.20 |",
+ "| IP | manual-first |\n| IP | 192.168.10.20 |",
+ )
+ result = reconcile(
+ current,
+ _body(_device()),
+ baseline_body=baseline,
+ snapshot=t.facts_snapshot(_device()),
+ )
+ assert result.conflicts == []
+ assert result.proposed_body.count("| IP |") == 2
+ assert "| IP | manual-first |" in result.proposed_body
+ assert "| IP | 192.168.10.20 |" in result.proposed_body
+
+
+def test_duplicate_ip_row_device_change_surfaces_conflict():
+ baseline = _body(_device())
+ current = baseline.replace(
+ "| IP | 192.168.10.20 |",
+ "| IP | 192.168.10.20 |\n| IP | manual-secondary |",
+ )
+ result = reconcile(
+ current,
+ _body(_device(ip="192.168.10.25")),
+ baseline_body=baseline,
+ snapshot=t.facts_snapshot(_device()),
+ )
+ assert "device-info.IP" in [c.id for c in result.conflicts]
+ # Neither row is touched silently; both are preserved verbatim.
+ info_rows = [line for line in result.proposed_body.splitlines() if line.startswith("| IP |")]
+ assert info_rows == ["| IP | 192.168.10.20 |", "| IP | manual-secondary |"]
+
+
+def test_duplicate_ip_row_device_resolution_updates_first_only():
+ baseline = _body(_device())
+ current = baseline.replace(
+ "| IP | 192.168.10.20 |",
+ "| IP | 192.168.10.20 |\n| IP | manual-secondary |",
+ )
+ result = reconcile(
+ current,
+ _body(_device(ip="192.168.10.25")),
+ baseline_body=baseline,
+ snapshot=t.facts_snapshot(_device()),
+ resolutions=[Resolution(id="device-info.IP", choice=DEVICE)],
+ )
+ rows = [line for line in result.proposed_body.splitlines() if line.startswith("| IP |")]
+ assert rows == ["| IP | 192.168.10.25 |", "| IP | manual-secondary |"]
+
+
+def test_duplicate_hardware_no_device_change_preserves_both():
+ baseline = _body(_device())
+ current = baseline + "\n### Hardware\n\nMANUAL DISK RECOVERY PROCEDURE\n"
+ result = reconcile(
+ current,
+ _body(_device()),
+ baseline_body=baseline,
+ snapshot=t.facts_snapshot(_device()),
+ )
+ assert result.conflicts == []
+ assert result.proposed_body.count("### Hardware") == 2
+ assert "MANUAL DISK RECOVERY PROCEDURE" in result.proposed_body
+
+
+def test_duplicate_hardware_prepended_no_device_change_preserves_both():
+ baseline = _body(_device())
+ hw_offset = baseline.index("### Hardware")
+ current = (
+ baseline[:hw_offset]
+ + "### Hardware\n\nMANUAL DISK RECOVERY PROCEDURE\n\n"
+ + baseline[hw_offset:]
+ )
+ result = reconcile(
+ current,
+ _body(_device()),
+ baseline_body=baseline,
+ snapshot=t.facts_snapshot(_device()),
+ )
+ assert result.conflicts == []
+ assert result.proposed_body.count("### Hardware") == 2
+ assert "MANUAL DISK RECOVERY PROCEDURE" in result.proposed_body
+
+
+def test_duplicate_hardware_device_change_surfaces_conflict():
+ baseline = _body(_device())
+ current = baseline + "\n### Hardware\n\nMANUAL DISK RECOVERY PROCEDURE\n"
+ result = reconcile(
+ current,
+ _body(_device(cpu_model="N200")),
+ baseline_body=baseline,
+ snapshot=t.facts_snapshot(_device()),
+ )
+ assert "section.Hardware" in [c.id for c in result.conflicts]
+ # No auto-edit to the guessed-first block; both are preserved untouched.
+ assert "MANUAL DISK RECOVERY PROCEDURE" in result.proposed_body
+ assert "N200" not in result.proposed_body
+
+
+def test_duplicate_hardware_resolution_updates_generated_block_only():
+ baseline = _body(_device())
+ current = baseline + "\n### Hardware\n\nMANUAL DISK RECOVERY PROCEDURE\n"
+ result = reconcile(
+ current,
+ _body(_device(cpu_model="N200")),
+ baseline_body=baseline,
+ snapshot=t.facts_snapshot(_device()),
+ resolutions=[Resolution(id="section.Hardware", choice=DEVICE)],
+ )
+ assert result.proposed_body.count("### Hardware") == 2
+ assert "N200" in result.proposed_body
+ assert "MANUAL DISK RECOVERY PROCEDURE" in result.proposed_body
+
+
+def test_duplicate_hardware_custom_resolution_updates_generated_block_only():
+ baseline = _body(_device())
+ current = baseline + "\n### Hardware\n\nMANUAL DISK RECOVERY PROCEDURE\n"
+ result = reconcile(
+ current,
+ _body(_device(cpu_model="N200")),
+ baseline_body=baseline,
+ snapshot=t.facts_snapshot(_device()),
+ resolutions=[Resolution(id="section.Hardware", choice=CUSTOM, custom="| A | B | C |")],
+ )
+ assert result.proposed_body.count("### Hardware") == 2
+ assert "| A | B | C |" in result.proposed_body
+ assert "MANUAL DISK RECOVERY PROCEDURE" in result.proposed_body
+
+
+def test_duplicate_hardware_prepended_device_change_surfaces_conflict():
+ baseline = _body(_device())
+ hw_offset = baseline.index("### Hardware")
+ current = (
+ baseline[:hw_offset]
+ + "### Hardware\n\nMANUAL DISK RECOVERY PROCEDURE\n\n"
+ + baseline[hw_offset:]
+ )
+ result = reconcile(
+ current,
+ _body(_device(cpu_model="N200")),
+ baseline_body=baseline,
+ snapshot=t.facts_snapshot(_device()),
+ )
+ assert "section.Hardware" in [c.id for c in result.conflicts]
+ assert "N200" not in result.proposed_body
+ assert "MANUAL DISK RECOVERY PROCEDURE" in result.proposed_body
+
+
+def _duplicate_device_info(current, manual_os=None):
+ """Duplicate the whole generated Device Information block in the body.
+
+ The copy goes BEFORE the original; ``manual_os`` marks it as the user's own
+ table so a fix that edits the guessed-first copy on its own is testable.
+ """
+ heading = "## Device Information"
+ start = current.index(heading)
+ end = current.index("### Hardware")
+ info_block = current[start:end]
+ if manual_os is not None:
+ info_block = info_block.replace("| OS | Debian 12 |", f"| OS | {manual_os} |")
+ return current[:start] + info_block + info_block + current[end:]
+
+
+def test_duplicate_device_info_heading_ip_change_surfaces_conflict():
+ baseline = _body(_device())
+ current = _duplicate_device_info(baseline)
+ result = reconcile(
+ current,
+ _body(_device(ip="192.168.10.25")),
+ baseline_body=baseline,
+ snapshot=t.facts_snapshot(_device()),
+ )
+ assert "device-info.IP" in [c.id for c in result.conflicts]
+ # No silent auto-edit of the guessed-first table; both keep their value.
+ assert result.proposed_body.count("## Device Information") == 2
+ assert result.proposed_body.count("| IP | 192.168.10.20 |") == 2
+ assert "| IP | 192.168.10.25 |" not in result.proposed_body
+
+
+def test_duplicate_device_info_heading_ip_resolution_updates_first_only():
+ baseline = _body(_device())
+ current = _duplicate_device_info(baseline)
+ result = reconcile(
+ current,
+ _body(_device(ip="192.168.10.25")),
+ baseline_body=baseline,
+ snapshot=t.facts_snapshot(_device()),
+ resolutions=[Resolution(id="device-info.IP", choice=KEEP)],
+ )
+ assert result.proposed_body.count("## Device Information") == 2
+ assert result.proposed_body.count("| IP | 192.168.10.20 |") == 2
+
+
+def test_duplicate_device_info_prepended_ip_change_surfaces_conflict():
+ baseline = _body(_device())
+ current = _duplicate_device_info(baseline, manual_os="Debian 12 (manual)")
+ result = reconcile(
+ current,
+ _body(_device(ip="192.168.10.25")),
+ baseline_body=baseline,
+ snapshot=t.facts_snapshot(_device()),
+ )
+ assert "device-info.IP" in [c.id for c in result.conflicts]
+ assert result.proposed_body.count("## Device Information") == 2
+ # The user-owned copy is the first one; it must not be silently edited.
+ assert "| OS | Debian 12 (manual) |" in result.proposed_body
+ assert "| IP | 192.168.10.25 |" not in result.proposed_body
+
+
+# ── device name ─────────────────────────────────────────────────────────
+
+
+def test_device_name_auto_and_conflict():
+ baseline = _body(_device(label="nas-01"))
+ snapshot = t.facts_snapshot(_device(label="nas-01"))
+ new = _body(_device(label="nas-02"))
+ current = baseline
+
+ auto = reconcile(current, new, baseline_body=baseline, snapshot=snapshot)
+ assert _by_id(auto.changes)["name"].status == AUTO
+ assert 'title: "nas-02"' in auto.proposed_body
+ assert "# nas-02\n" in auto.proposed_body
+
+ renamed = current.replace("# nas-01", "# my-nas")
+ conflict = reconcile(renamed, new, baseline_body=baseline, snapshot=snapshot, resolutions=[Resolution(id="name", choice=KEEP)])
+ assert _by_id(conflict.changes)["name"].status == "conflict"
+ assert "# my-nas" in conflict.proposed_body and "# nas-02" not in conflict.proposed_body
+
+
+def test_ordinary_rename_follows_in_h1_and_title():
+ baseline = _body(_device(label="nas-01"))
+ result = reconcile(
+ baseline,
+ _body(_device(label="nas-02")),
+ baseline_body=baseline,
+ snapshot=t.facts_snapshot(_device(label="nas-01")),
+ )
+ by_id = _by_id(result.changes)
+ assert by_id["name"].status == AUTO
+ assert by_id["title"].status == AUTO
+ assert 'title: "nas-02"' in result.proposed_body
+ assert "# nas-02\n" in result.proposed_body
+
+
+def test_independently_edited_title_survives_device_rename():
+ """Finding 3: a manual frontmatter title must not be copied from the H1
+ decision; the untouched H1 may follow the device while the manual title
+ stays, surfaced as an explicit title conflict."""
+ baseline = _body(_device(label="homelabcluster"))
+ current = baseline.replace("title: homelabcluster", "title: Recovery Runbook")
+ result = reconcile(
+ current,
+ _body(_device(label="new-name")),
+ baseline_body=baseline,
+ snapshot=t.facts_snapshot(_device(label="homelabcluster")),
+ )
+ by_id = _by_id(result.changes)
+ # The untouched H1 follows the rename, the manual title does not.
+ assert by_id["name"].status == AUTO
+ assert by_id["title"].status == "conflict"
+ assert "title" in [c.id for c in result.conflicts]
+ assert "title: Recovery Runbook" in result.proposed_body
+ assert "title: new-name" not in result.proposed_body
+ assert "# new-name\n" in result.proposed_body
+
+
+def test_title_conflict_resolves_keep_and_device():
+ baseline = _body(_device(label="homelabcluster"))
+ current = baseline.replace("title: homelabcluster", "title: Recovery Runbook")
+ new = _body(_device(label="new-name"))
+ snapshot = t.facts_snapshot(_device(label="homelabcluster"))
+
+ keep = reconcile(current, new, baseline_body=baseline, snapshot=snapshot, resolutions=[Resolution(id="title", choice=KEEP)])
+ assert "title: Recovery Runbook" in keep.proposed_body
+
+ take = reconcile(current, new, baseline_body=baseline, snapshot=snapshot, resolutions=[Resolution(id="title", choice=DEVICE)])
+ assert 'title: "new-name"' in take.proposed_body
+
+
+def test_custom_title_with_yaml_syntax_is_serialized_semantically():
+ baseline = _body(_device(label="homelabcluster"))
+ current = baseline.replace(
+ "title: homelabcluster", "title: Recovery Runbook\ncustom_frontmatter: 'keep: exact'"
+ )
+ new = _body(_device(label="new-name"))
+
+ for title in ("Recovery: primary", "Recovery #1"):
+ result = reconcile(
+ current,
+ new,
+ baseline_body=baseline,
+ snapshot=t.facts_snapshot(_device(label="homelabcluster")),
+ resolutions=[Resolution(id="title", choice=CUSTOM, custom=title)],
+ )
+ frontmatter = result.proposed_body.split("---", 2)[1]
+ assert yaml.safe_load(frontmatter)["title"] == title
+ assert "custom_frontmatter: 'keep: exact'" in frontmatter
+
+
+def test_title_scalar_replacement_removes_continuation_and_keep_preserves_frontmatter():
+ baseline = _body(_device(label="homelabcluster"))
+ current = baseline.replace(
+ "title: homelabcluster",
+ "title: |\n Recovery Runbook\ncustom_frontmatter: 'keep: exact'",
+ )
+ new = _body(_device(label="new-name"))
+ snapshot = t.facts_snapshot(_device(label="homelabcluster"))
+
+ device = reconcile(
+ current,
+ new,
+ baseline_body=baseline,
+ snapshot=snapshot,
+ resolutions=[Resolution(id="title", choice=DEVICE)],
+ )
+ frontmatter = device.proposed_body.split("---", 2)[1]
+ assert yaml.safe_load(frontmatter)["title"] == "new-name"
+ assert "Recovery Runbook" not in frontmatter
+ assert "custom_frontmatter: 'keep: exact'" in frontmatter
+
+ kept = reconcile(
+ current,
+ new,
+ baseline_body=baseline,
+ snapshot=snapshot,
+ resolutions=[Resolution(id="title", choice=KEEP)],
+ )
+ assert kept.proposed_body.split("---", 2)[1] == current.split("---", 2)[1]
+
+
+def test_title_replacement_removes_multiline_quoted_scalar():
+ baseline = _body(_device(label="homelabcluster"))
+ current = baseline.replace(
+ "title: homelabcluster",
+ 'title: "Recovery\n Runbook"\ncustom_frontmatter: \'keep: exact\'',
+ )
+ result = reconcile(
+ current,
+ _body(_device(label="new-name")),
+ baseline_body=baseline,
+ snapshot=t.facts_snapshot(_device(label="homelabcluster")),
+ resolutions=[Resolution(id="title", choice=DEVICE)],
+ )
+ frontmatter = result.proposed_body.split("---", 2)[1]
+ assert yaml.safe_load(frontmatter)["title"] == "new-name"
+ assert "Recovery" not in frontmatter and "Runbook" not in frontmatter
+ assert "custom_frontmatter: 'keep: exact'" in frontmatter
+
+
+def test_new_properties_section_is_added_before_user_sections():
+ plain = _device(properties=[])
+ result = _run(plain, _device(properties=[{"key": "Serial", "value": "ABC123"}]))
+ assert _by_id(result.changes)["section.Properties"].status == AUTO
+ lines = result.proposed_body.splitlines()
+ props_index = lines.index("### Properties")
+ config_index = lines.index("## Configuration")
+ assert props_index < config_index
+ assert "| Serial | ABC123 |" in result.proposed_body
+
+
+def test_unknown_history_never_recreates_deleted_generated_sections():
+ generated = _body(_device())
+ sections = (
+ ("Hardware", "### Hardware", "### Properties"),
+ ("Properties", "### Properties", "## Services"),
+ ("Services", "## Services", "## Network"),
+ ("Network", "## Network", "## Configuration"),
+ )
+
+ for name, heading, next_heading in sections:
+ start = generated.index(heading)
+ end = generated.index(next_heading, start)
+ current = generated[:start] + generated[end:]
+ result = reconcile(current, generated, baseline_body=None, snapshot=None)
+
+ assert _by_id(result.changes)[f"section.{name}"].status == "conflict"
+ assert heading not in result.proposed_body
+
+
+def test_complete_baseline_can_add_a_new_generated_section():
+ generated = _body(_device())
+ start = generated.index("### Properties")
+ end = generated.index("## Services", start)
+ baseline = generated[:start] + generated[end:]
+ result = reconcile(baseline, generated, baseline_body=baseline, snapshot=None)
+
+ assert _by_id(result.changes)["section.Properties"].status == AUTO
+ assert "### Properties" in result.proposed_body
+
+
+def test_snapshot_proves_a_new_properties_section_can_be_added():
+ generated = _body(_device())
+ start = generated.index("### Properties")
+ end = generated.index("## Services", start)
+ current = generated[:start] + generated[end:]
+ result = reconcile(
+ current,
+ generated,
+ baseline_body=None,
+ snapshot=t.facts_snapshot(_device(properties=[])),
+ )
+
+ assert _by_id(result.changes)["section.Properties"].status == AUTO
+ assert "### Properties" in result.proposed_body
+
+
+def test_snapshot_does_not_restore_deleted_services_without_a_baseline():
+ generated = _body(_device())
+ start = generated.index("## Services")
+ end = generated.index("## Network", start)
+ current = generated[:start] + generated[end:]
+ result = reconcile(
+ current,
+ _body(_device(ip="192.168.10.25")),
+ baseline_body=None,
+ snapshot=t.facts_snapshot(_device()),
+ )
+
+ assert _by_id(result.changes)["section.Services"].status == "conflict"
+ assert "## Services" not in result.proposed_body
+
+
+def test_snapshot_does_not_restore_deleted_network_without_a_baseline():
+ generated = _body(_device())
+ start = generated.index("## Network")
+ end = generated.index("## Configuration", start)
+ current = generated[:start] + generated[end:]
+ result = reconcile(
+ current,
+ _body(_device(ip="192.168.10.25")),
+ baseline_body=None,
+ snapshot=t.facts_snapshot(_device()),
+ )
+
+ assert _by_id(result.changes)["section.Network"].status == "conflict"
+ assert "## Network" not in result.proposed_body
+
+
+def test_untouched_removed_properties_are_dropped_automatically():
+ # The complete baseline proves the section was device-owned and untouched.
+ baseline = _body(_device())
+ current = _body(_device())
+ new = _body(_device(properties=[]))
+ result = reconcile(current, new, baseline_body=baseline, snapshot=t.facts_snapshot(_device()))
+ assert _by_id(result.changes)["section.Properties"].status == AUTO
+ assert "### Properties" not in result.proposed_body
+
+
+def test_edited_removed_properties_require_a_decision():
+ baseline = _body(_device())
+ current = baseline.replace("| Serial | ABC123 |", "| Serial | manual recovery token |")
+ new = _body(_device(properties=[]))
+ result = reconcile(current, new, baseline_body=baseline, snapshot=t.facts_snapshot(_device()))
+
+ assert _by_id(result.changes)["section.Properties"].status == "conflict"
+ assert "### Properties" in result.proposed_body
+ assert "manual recovery token" in result.proposed_body
+
+
+# ── conservatism and fingerprints ───────────────────────────────────────────
+
+
+def test_missing_baseline_is_conservative_never_silent():
+ """No baseline and no snapshot: a changed device still surfaces conflicts."""
+ current = _body(_device())
+ result = reconcile(current, _body(_device(ip="192.168.10.25")), baseline_body=None, snapshot=None)
+ by_id = _by_id(result.changes)
+ assert by_id["device-info.IP"].status == "conflict"
+ # A stable device without a baseline is still quiet.
+ stable = reconcile(current, _body(_device()), baseline_body=None, snapshot=None)
+ assert stable.conflicts == []
+ assert stable.proposed_body == current
+
+
+def test_preview_id_binds_body_facts_and_timestamp():
+ a = preview_id("2026-03-04T10:00:00Z", {"ip": "192.168.10.20"}, "# body")
+ assert a == preview_id("2026-03-04T10:00:00Z", {"ip": "192.168.10.20"}, "# body")
+ assert a != preview_id("2026-03-04T10:00:01Z", {"ip": "192.168.10.20"}, "# body")
+ assert a != preview_id("2026-03-04T10:00:00Z", {"ip": "192.168.10.25"}, "# body")
+ assert a != preview_id("2026-03-04T10:00:00Z", {"ip": "192.168.10.20"}, "# other")
+
+
+def test_preview_id_binds_baseline_and_live_device():
+ base = preview_id("2026-03-04T10:00:00Z", {"ip": "192.168.10.20"}, "# body")
+ baseline = preview_id(
+ "2026-03-04T10:00:00Z", {"ip": "192.168.10.20"}, "# body", baseline_body="# generated"
+ )
+ live = preview_id(
+ "2026-03-04T10:00:00Z",
+ {"ip": "192.168.10.20"},
+ "# body",
+ baseline_body="# generated",
+ live={"facts": {"ip": "192.168.10.30"}, "context": {"zone_label": "lan"}, "generated": "# …"},
+ )
+ assert base != baseline
+ assert baseline != live
+ # A device that moved on between preview and apply changes the id.
+ assert live != preview_id(
+ "2026-03-04T10:00:00Z",
+ {"ip": "192.168.10.20"},
+ "# body",
+ baseline_body="# generated",
+ live={"facts": {"ip": "192.168.10.40"}, "context": {"zone_label": "lan"}, "generated": "# …"},
+ )
+ # A rendered-only change — same facts and context, different generated body.
+ assert live != preview_id(
+ "2026-03-04T10:00:00Z",
+ {"ip": "192.168.10.20"},
+ "# body",
+ baseline_body="# generated",
+ live={
+ "facts": {"ip": "192.168.10.30"},
+ "context": {"zone_label": "lan"},
+ "generated": "# changed rendering",
+ },
+ )
+ # Same device, context and generated body keep it stable.
+ assert live == preview_id(
+ "2026-03-04T10:00:00Z",
+ {"ip": "192.168.10.20"},
+ "# body",
+ baseline_body="# generated",
+ live={"facts": {"ip": "192.168.10.30"}, "context": {"zone_label": "lan"}, "generated": "# …"},
+ )
+
+
+def test_document_drift_clears_after_apply_style_refresh():
+ """After applying, regenerating the document from the *new* snapshot stays quiet."""
+ baseline = _body(_device())
+ snapshot = t.facts_snapshot(_device())
+ result = reconcile(baseline, _body(_device(ip="192.168.10.25")), baseline_body=baseline, snapshot=snapshot)
+ merged = result.proposed_body
+ # What a successful sync records: merged body + generated body + new facts.
+ refreshed = reconcile(merged, _body(_device(ip="192.168.10.25")), baseline_body=_body(_device(ip="192.168.10.25")), snapshot=t.facts_snapshot(_device(ip="192.168.10.25")))
+ assert refreshed.conflicts == []
+ assert refreshed.proposed_body == merged
diff --git a/docs/update-from-device/01-doc-viewer.png b/docs/update-from-device/01-doc-viewer.png
new file mode 100644
index 0000000..f12f816
Binary files /dev/null and b/docs/update-from-device/01-doc-viewer.png differ
diff --git a/docs/update-from-device/02-conflict-modal.png b/docs/update-from-device/02-conflict-modal.png
new file mode 100644
index 0000000..885c851
Binary files /dev/null and b/docs/update-from-device/02-conflict-modal.png differ
diff --git a/docs/update-from-device/03-one-resolved.png b/docs/update-from-device/03-one-resolved.png
new file mode 100644
index 0000000..f7eff99
Binary files /dev/null and b/docs/update-from-device/03-one-resolved.png differ
diff --git a/docs/update-from-device/04-applied.png b/docs/update-from-device/04-applied.png
new file mode 100644
index 0000000..ba7431f
Binary files /dev/null and b/docs/update-from-device/04-applied.png differ
diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts
index 4b88fc4..458663b 100644
--- a/frontend/src/api/client.ts
+++ b/frontend/src/api/client.ts
@@ -381,6 +381,22 @@ export const documentsApi = {
api.get<import('@/documentation/types').DocBacklink[]>(`/documents/${id}/backlinks`),
regenerate: (id: string) =>
api.post<import('@/documentation/types').Doc>(`/documents/${id}/regenerate`),
+ updatePreview: (
+ id: string,
+ resolutions: import('@/documentation/types').ResolutionItem[] = [],
+ ) =>
+ api.post<import('@/documentation/types').UpdatePreview>(`/documents/${id}/update-preview`, {
+ resolutions,
+ }),
+ updateFromDevice: (
+ id: string,
+ preview_id: string,
+ resolutions: import('@/documentation/types').ResolutionItem[] = [],
+ ) =>
+ api.post<import('@/documentation/types').Doc>(`/documents/${id}/update-from-device`, {
+ preview_id,
+ resolutions,
+ }),
search: (q: string, limit = 25) =>
api.get<import('@/documentation/types').DocSearchResult>('/documents/search', {
params: { q, limit },
diff --git a/frontend/src/documentation/__tests__/DocViewer.test.tsx b/frontend/src/documentation/__tests__/DocViewer.test.tsx
index 46b3e99..23ac758 100644
--- a/frontend/src/documentation/__tests__/DocViewer.test.tsx
+++ b/frontend/src/documentation/__tests__/DocViewer.test.tsx
@@ -4,6 +4,7 @@
*/
import { describe, expect, it, vi } from 'vitest'
import { fireEvent, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { DocViewer } from '../components/DocViewer'
import type { Doc } from '../types'
@@ -184,3 +185,28 @@ describe('DocViewer — download', () => {
expect(onDownload).toHaveBeenCalledTimes(1)
})
})
+
+describe('DocViewer — destructive replacement', () => {
+ it('keeps update prominent and puts full replacement in the overflow menu', async () => {
+ const user = userEvent.setup()
+ const onUpdateFromDevice = vi.fn()
+ const onRegenerate = vi.fn()
+ render(
+ <DocViewer
+ {...noop}
+ doc={makeDoc({ kind: 'device', device_id: 'device-1' })}
+ drifted
+ onUpdateFromDevice={onUpdateFromDevice}
+ onRegenerate={onRegenerate}
+ onSetTags={vi.fn()}
+ />,
+ )
+
+ expect(screen.getByRole('button', { name: 'Update from device' })).toBeTruthy()
+ expect(screen.queryByRole('button', { name: 'Regenerate this document' })).toBeNull()
+ await user.click(screen.getByRole('button', { name: 'More document actions' }))
+ await user.click(await screen.findByRole('menuitem', { name: 'Replace entire document…' }))
+ expect(onRegenerate).toHaveBeenCalledTimes(1)
+ expect(onUpdateFromDevice).not.toHaveBeenCalled()
+ })
+})
diff --git a/frontend/src/documentation/__tests__/DocumentationViewUpdate.test.tsx b/frontend/src/documentation/__tests__/DocumentationViewUpdate.test.tsx
new file mode 100644
index 0000000..674a766
--- /dev/null
+++ b/frontend/src/documentation/__tests__/DocumentationViewUpdate.test.tsx
@@ -0,0 +1,329 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+
+import { documentsApi } from '@/api/client'
+import { DocumentationView } from '../components/DocumentationView'
+import { useDocsStore } from '../store'
+import type { Doc, DocumentSummary, UpdatePreview } from '../types'
+
+vi.mock('sonner', async () => (await import('@/test/mocks')).mockSonner())
+
+vi.mock('@/api/client', () => ({
+ documentsApi: {
+ list: vi.fn(),
+ coverage: vi.fn(),
+ updatePreview: vi.fn(),
+ updateFromDevice: vi.fn(),
+ revisions: vi.fn(),
+ get: vi.fn(),
+ backlinks: vi.fn().mockResolvedValue({ data: [] }),
+ },
+ scanApi: { pending: vi.fn().mockResolvedValue({ data: [] }) },
+ docsviewApi: { getConfig: vi.fn().mockResolvedValue({ data: { enabled: false, key: null } }) },
+}))
+
+const api = vi.mocked(documentsApi)
+const INITIAL = useDocsStore.getState()
+
+function doc(overrides: Partial<Doc> = {}): Doc {
+ return {
+ id: 'doc-1',
+ kind: 'device',
+ title: 'NAS',
+ slug: 'nas',
+ sort_order: 0,
+ device_id: 'device-1',
+ tags: [],
+ frontmatter: {},
+ starred: false,
+ drifted: true,
+ body: '# NAS\n\nManual backup notes.',
+ created_at: '2026-01-01T00:00:00Z',
+ updated_at: '2026-01-01T00:00:00Z',
+ ...overrides,
+ }
+}
+
+function preview(overrides: Partial<UpdatePreview> = {}): UpdatePreview {
+ return {
+ preview_id: 'preview-1',
+ changes: [],
+ proposed_body: '# NAS\n\nManual backup notes.',
+ summary: [],
+ unresolved: [],
+ ...overrides,
+ }
+}
+
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ let reject!: (reason: unknown) => void
+ const promise = new Promise<T>((done, fail) => {
+ resolve = done
+ reject = fail
+ })
+ return { promise, resolve, reject }
+}
+
+function renderView(openDoc = doc()) {
+ const docs = [openDoc as DocumentSummary]
+ api.list.mockResolvedValue({ data: docs } as never)
+ api.coverage.mockResolvedValue({
+ data: { devices: 1, documented: 1, header_only: 0, notes_unmigrated: 0 },
+ } as never)
+ useDocsStore.setState({
+ ...INITIAL,
+ docs,
+ loaded: true,
+ openDoc,
+ preview: null,
+ previewLoading: false,
+ resolutions: {},
+ })
+ render(<DocumentationView />)
+ return screen.getByRole('button', { name: 'Update from device' })
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ localStorage.clear()
+})
+
+afterEach(() => cleanup())
+
+describe('DocumentationView — update from device', () => {
+ it('shows a conflict-free update for review and applies it only once Update is clicked', async () => {
+ const merged = doc({ body: '# NAS\n\nIP: 192.168.1.30\n\nManual backup notes.', drifted: false })
+ api.updatePreview.mockResolvedValue({
+ data: preview({
+ changes: [{
+ id: 'section.Network details',
+ name: 'Network details',
+ kind: 'section',
+ status: 'auto',
+ documented: 'IP: 192.168.1.20',
+ device: '## Network details\n\nIP: 192.168.1.30\n\nA long generated section.',
+ previous: 'IP: 192.168.1.20',
+ }],
+ proposed_body: merged.body,
+ summary: ['Network details updated to ## Network details IP: 192.168.1.30 A long generated section.'],
+ }),
+ } as never)
+ api.updateFromDevice.mockResolvedValue({ data: merged } as never)
+ api.revisions.mockResolvedValue({ data: [] } as never)
+ const { toast } = await import('sonner')
+
+ fireEvent.click(renderView())
+
+ // No conflict to settle, yet nothing is written until the user confirms.
+ const confirm = await screen.findByRole('button', { name: 'Update the document' })
+ expect(screen.getByRole('dialog')).toBeInTheDocument()
+ expect(api.updateFromDevice).not.toHaveBeenCalled()
+ fireEvent.click(confirm)
+
+ await waitFor(() => expect(api.updateFromDevice).toHaveBeenCalledTimes(1))
+ expect(api.updatePreview).toHaveBeenCalledTimes(1)
+ expect(api.updateFromDevice).toHaveBeenCalledWith('doc-1', 'preview-1', [])
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
+ expect(screen.queryByRole('dialog')).toBeNull()
+ expect(screen.getByText('Manual backup notes.')).toBeInTheDocument()
+ expect(toast.success).toHaveBeenCalledWith(
+ 'Documentation updated: Network details',
+ expect.objectContaining({ action: expect.objectContaining({ label: 'View history' }) }),
+ )
+
+ const options = vi.mocked(toast.success).mock.calls[0]?.[1]
+ const action = options?.action
+ if (!action || typeof action === 'function' || !('onClick' in action)) {
+ throw new Error('Expected a history action on the update confirmation')
+ }
+ action.onClick({} as never)
+ await waitFor(() => expect(api.revisions).toHaveBeenCalledWith('doc-1'))
+ })
+
+ it('only previews conflicts and cancelling writes nothing', async () => {
+ api.updatePreview.mockResolvedValue({
+ data: preview({
+ changes: [{
+ id: 'device-info.IP Address',
+ name: 'IP address',
+ kind: 'field',
+ status: 'conflict',
+ documented: 'nas.example.lan',
+ device: '192.168.1.30',
+ previous: '192.168.1.20',
+ }],
+ unresolved: ['device-info.IP Address'],
+ }),
+ } as never)
+
+ fireEvent.click(renderView())
+
+ expect(await screen.findByRole('dialog')).toBeInTheDocument()
+ expect(screen.getByText('IP address')).toBeInTheDocument()
+ expect(api.updatePreview).toHaveBeenCalledTimes(1)
+ expect(api.updateFromDevice).not.toHaveBeenCalled()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
+ expect(api.updateFromDevice).not.toHaveBeenCalled()
+ })
+
+ it('retries a failed conflict preview without saving until Update is clicked', async () => {
+ const conflict = {
+ id: 'device-info.IP Address',
+ name: 'IP address',
+ kind: 'field' as const,
+ status: 'conflict' as const,
+ documented: 'nas.example.lan',
+ device: '192.168.1.30',
+ previous: '192.168.1.20',
+ }
+ api.updatePreview
+ .mockResolvedValueOnce({
+ data: preview({ changes: [conflict], unresolved: [conflict.id] }),
+ } as never)
+ .mockRejectedValueOnce(new Error('offline'))
+ .mockResolvedValueOnce({
+ data: preview({
+ preview_id: 'resolved-preview',
+ changes: [conflict],
+ unresolved: [],
+ summary: ['IP address kept as written'],
+ }),
+ } as never)
+ api.updateFromDevice.mockResolvedValue({ data: doc({ drifted: false }) } as never)
+
+ fireEvent.click(renderView())
+ fireEvent.click(await screen.findByRole('radio', { name: 'Keep actual documentation' }))
+ fireEvent.click(await screen.findByRole('button', { name: 'Try again' }))
+
+ await waitFor(() => expect(api.updatePreview).toHaveBeenCalledTimes(3))
+ expect(api.updateFromDevice).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByRole('button', { name: 'Update the document' }))
+ await waitFor(() => expect(api.updateFromDevice).toHaveBeenCalledWith(
+ 'doc-1',
+ 'resolved-preview',
+ [{ id: conflict.id, choice: 'keep' }],
+ ))
+ })
+
+ it('keeps a failed comparison visible without writing', async () => {
+ api.updatePreview.mockRejectedValueOnce(new Error('offline'))
+
+ fireEvent.click(renderView())
+
+ expect(await screen.findByText('Could not compare this document with the device.')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Try again' })).toBeInTheDocument()
+ expect(api.updateFromDevice).not.toHaveBeenCalled()
+ })
+
+ it('shows a fresh preview after a stale apply without applying it', async () => {
+ const first = preview({
+ changes: [{
+ id: 'device-info.IP Address',
+ name: 'IP address',
+ kind: 'field',
+ status: 'auto',
+ documented: '192.168.1.20',
+ device: '192.168.1.30',
+ previous: '192.168.1.20',
+ }],
+ summary: ['IP address updated to 192.168.1.30'],
+ })
+ const fresh = preview({
+ preview_id: 'fresh-preview',
+ changes: [{
+ id: 'device-info.Hostname',
+ name: 'Hostname',
+ kind: 'field',
+ status: 'auto',
+ documented: 'nas-old',
+ device: 'nas-new',
+ previous: 'nas-old',
+ }],
+ summary: ['Hostname updated to nas-new'],
+ })
+ api.updatePreview
+ .mockResolvedValueOnce({ data: first } as never)
+ .mockResolvedValueOnce({ data: fresh } as never)
+ api.updateFromDevice.mockRejectedValueOnce(Object.assign(new Error('stale'), {
+ response: { status: 409 },
+ }))
+ api.get.mockResolvedValueOnce({ data: doc({ updated_at: '2026-01-02T00:00:00Z' }) } as never)
+
+ fireEvent.click(renderView())
+ fireEvent.click(await screen.findByRole('button', { name: 'Update the document' }))
+
+ await waitFor(() => expect(api.updatePreview).toHaveBeenCalledTimes(2))
+ expect(api.updateFromDevice).toHaveBeenCalledTimes(1)
+ expect(await screen.findByRole('dialog')).toBeInTheDocument()
+ expect(screen.getByText('Hostname updated to nas-new')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Update the document' })).toBeInTheDocument()
+ })
+
+ it('does not apply a preview that finishes after navigation', async () => {
+ const comparing = deferred<{ data: UpdatePreview }>()
+ api.updatePreview.mockImplementationOnce(() => comparing.promise)
+ api.get.mockResolvedValueOnce({ data: doc({ id: 'doc-2', title: 'Router', slug: 'router' }) } as never)
+ const { toast } = await import('sonner')
+
+ fireEvent.click(renderView())
+ await waitFor(() => expect(api.updatePreview).toHaveBeenCalledTimes(1))
+ await act(async () => {
+ await useDocsStore.getState().open('doc-2')
+ })
+ expect(screen.getByRole('heading', { name: 'Router' })).toBeInTheDocument()
+
+ await act(async () => {
+ comparing.resolve({ data: preview({ summary: ['IP address updated to 192.168.1.30'] }) })
+ await comparing.promise
+ })
+
+ expect(api.updateFromDevice).not.toHaveBeenCalled()
+ expect(toast.error).not.toHaveBeenCalled()
+ expect(useDocsStore.getState().openDoc?.id).toBe('doc-2')
+ })
+
+ it('does not close a newer review when an old apply finishes after navigation', async () => {
+ const applying = deferred<{ data: Doc }>()
+ api.updatePreview.mockResolvedValueOnce({
+ data: preview({
+ changes: [{
+ id: 'device-info.IP Address',
+ name: 'IP address',
+ kind: 'field',
+ status: 'auto',
+ documented: '192.168.1.20',
+ device: '192.168.1.30',
+ previous: '192.168.1.20',
+ }],
+ summary: ['IP address updated to 192.168.1.30'],
+ }),
+ } as never)
+ api.updateFromDevice.mockImplementationOnce(() => applying.promise)
+ api.get.mockResolvedValueOnce({ data: doc({ id: 'doc-2', title: 'Router', slug: 'router' }) } as never)
+ const { toast } = await import('sonner')
+
+ fireEvent.click(renderView())
+ fireEvent.click(await screen.findByRole('button', { name: 'Update the document' }))
+ await waitFor(() => expect(api.updateFromDevice).toHaveBeenCalledTimes(1))
+ await act(async () => {
+ await useDocsStore.getState().open('doc-2')
+ })
+ useDocsStore.setState({
+ preview: preview({ preview_id: 'doc-2-preview', unresolved: ['new-conflict'] }),
+ resolutions: { newer: { id: 'newer', choice: 'keep' } },
+ })
+
+ await act(async () => {
+ applying.resolve({ data: doc({ body: '# NAS\n\nApplied late.' }) })
+ await applying.promise
+ })
+
+ expect(useDocsStore.getState().openDoc?.id).toBe('doc-2')
+ expect(useDocsStore.getState().preview?.preview_id).toBe('doc-2-preview')
+ expect(useDocsStore.getState().resolutions).toEqual({ newer: { id: 'newer', choice: 'keep' } })
+ expect(toast.success).not.toHaveBeenCalled()
+ })
+})
diff --git a/frontend/src/documentation/__tests__/RegenerateDoc.test.tsx b/frontend/src/documentation/__tests__/RegenerateDoc.test.tsx
index 127d383..fd796d1 100644
--- a/frontend/src/documentation/__tests__/RegenerateDoc.test.tsx
+++ b/frontend/src/documentation/__tests__/RegenerateDoc.test.tsx
@@ -49,13 +49,14 @@ function viewer(overrides: Partial<React.ComponentProps<typeof DocViewer>> = {})
describe('the regenerate button', () => {
it('asks the view to confirm rather than regenerating on the spot', async () => {
const { onRegenerate } = viewer()
- await userEvent.click(screen.getByRole('button', { name: 'Regenerate this document' }))
+ await userEvent.click(screen.getByRole('button', { name: 'More document actions' }))
+ await userEvent.click(await screen.findByRole('menuitem', { name: 'Replace entire document…' }))
expect(onRegenerate).toHaveBeenCalledTimes(1)
})
it('is not offered on a folder, which has no generated body', () => {
viewer({ doc: doc({ kind: 'folder', device_id: null }) })
- expect(screen.queryByRole('button', { name: 'Regenerate this document' })).toBeNull()
+ expect(screen.queryByRole('button', { name: 'More document actions' })).toBeNull()
})
})
diff --git a/frontend/src/documentation/__tests__/UpdateFromDevice.test.tsx b/frontend/src/documentation/__tests__/UpdateFromDevice.test.tsx
new file mode 100644
index 0000000..cd77cfa
--- /dev/null
+++ b/frontend/src/documentation/__tests__/UpdateFromDevice.test.tsx
@@ -0,0 +1,372 @@
+import { useState } from 'react'
+import { render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { describe, expect, it, vi } from 'vitest'
+
+import { UpdateFromDeviceModal } from '../components/UpdateFromDeviceModal'
+import type { ReconcileChange, ResolutionItem, UpdatePreview } from '../types'
+
+function preview(overrides: Partial<UpdatePreview> = {}): UpdatePreview {
+ return {
+ preview_id: 'abc123',
+ changes: [],
+ proposed_body: 'body',
+ summary: [],
+ unresolved: [],
+ ...overrides,
+ }
+}
+
+function change(overrides: Partial<ReconcileChange> = {}): ReconcileChange {
+ return {
+ id: 'conflict-1',
+ name: 'IP',
+ kind: 'field',
+ status: 'conflict',
+ documented: 'old',
+ device: 'new',
+ previous: '',
+ ...overrides,
+ }
+}
+
+const PROPS = {
+ open: true,
+ docTitle: 'nas-01',
+ preview: null,
+ loading: false,
+ resolutions: {},
+ onPreview: vi.fn(),
+ onResolve: vi.fn(),
+ onCancel: vi.fn(),
+ onApply: vi.fn(),
+ docs: [],
+ devices: [],
+}
+
+/**
+ * A stateful host that behaves like the real store: `onResolve` records the
+ * decision, flips the preview into its loading state, and only after the merge
+ * answers drops the settled conflict from `unresolved` while keeping every
+ * conflict row in `changes`.
+ */
+function StatefulReview({
+ onApply = vi.fn(),
+ onResolveLog,
+ previewDelay = 20,
+}: {
+ onApply?: () => void
+ onResolveLog: ResolutionItem[]
+ previewDelay?: number
+}) {
+ const [resolutions, setResolutions] = useState<Record<string, ResolutionItem>>({})
+ const [current, setCurrent] = useState<UpdatePreview | null>(() =>
+ preview({ changes: [change()], unresolved: ['conflict-1'] }),
+ )
+ const [previewLoading, setPreviewLoading] = useState(false)
+ return (
+ <UpdateFromDeviceModal
+ {...PROPS}
+ preview={current}
+ loading={previewLoading}
+ resolutions={resolutions}
+ onResolve={(id, item) => {
+ onResolveLog.push(item)
+ setResolutions((state) => ({ ...state, [id]: item }))
+ setPreviewLoading(true)
+ window.setTimeout(() => {
+ setCurrent((state) => (state ? { ...state, unresolved: state.unresolved.filter((x) => x !== id) } : state))
+ setPreviewLoading(false)
+ }, previewDelay)
+ }}
+ onCancel={() => {
+ setResolutions({})
+ setCurrent(null)
+ setPreviewLoading(false)
+ }}
+ onApply={onApply}
+ />
+ )
+}
+
+describe('UpdateFromDeviceModal', () => {
+ it('opens wide enough to read the two versions side by side', () => {
+ render(<UpdateFromDeviceModal {...PROPS} preview={null} loading />)
+ // The dialog primitive caps every dialog at `sm:max-w-sm`; only an
+ // important override lifts it.
+ const dialog = screen.getByRole('dialog')
+ expect(dialog.className).toContain('!max-w-none')
+ expect(dialog.className).toContain('w-[95vw]')
+ })
+
+ it('shows a spinner while the preview is loading', () => {
+ render(<UpdateFromDeviceModal {...PROPS} preview={null} loading />)
+ expect(screen.getByText('Comparing with the device…')).toBeTruthy()
+ })
+
+ it('offers a retry when the preview could not be fetched', () => {
+ render(<UpdateFromDeviceModal {...PROPS} preview={null} loading={false} />)
+ expect(screen.getByText(/Could not compare this document with the device/)).toBeTruthy()
+ expect(screen.getByRole('button', { name: 'Try again' })).toBeTruthy()
+ })
+
+ it('declares that nothing to change when summary and unresolved are empty', () => {
+ render(<UpdateFromDeviceModal {...PROPS} preview={preview()} />)
+ expect(screen.getByText('Nothing to change')).toBeTruthy()
+ expect(screen.getByText(/already matches the device/)).toBeTruthy()
+ })
+
+ it('records the device as reviewed when there is nothing to change', async () => {
+ // Closing without applying would leave "The device has changed" on a
+ // document whose body already matches.
+ const user = userEvent.setup()
+ const onApply = vi.fn()
+ const onCancel = vi.fn()
+ render(<UpdateFromDeviceModal {...PROPS} preview={preview()} onApply={onApply} onCancel={onCancel} />)
+
+ await user.click(screen.getByRole('button', { name: 'Mark as up to date' }))
+ expect(onApply).toHaveBeenCalledTimes(1)
+ expect(onCancel).not.toHaveBeenCalled()
+ })
+
+ it('hides the Update button when conflicts remain unresolved', () => {
+ render(
+ <UpdateFromDeviceModal
+ {...PROPS}
+ preview={preview({ changes: [change()], unresolved: ['conflict-1'] })}
+ />,
+ )
+ expect(screen.queryByRole('button', { name: 'Update the document' })).toBeNull()
+ expect(screen.getByRole('button', { name: /Resolve 1 more/ })).toBeTruthy()
+ })
+
+ it('shows Update when every conflict is settled', () => {
+ render(
+ <UpdateFromDeviceModal
+ {...PROPS}
+ preview={preview({ changes: [change()], unresolved: ['conflict-1'] })}
+ resolutions={{ 'conflict-1': { id: 'conflict-1', choice: 'device' } }}
+ />,
+ )
+ expect(screen.getByRole('button', { name: 'Update the document' })).toBeTruthy()
+ })
+
+ it('marks only the changed part of each field version and keeps the prior value available', () => {
+ render(
+ <UpdateFromDeviceModal
+ {...PROPS}
+ preview={preview({
+ changes: [
+ change({ documented: 'nas-old.example', device: 'nas-new.example', previous: 'nas-base.example' }),
+ ],
+ unresolved: ['conflict-1'],
+ })}
+ />,
+ )
+
+ expect(screen.getByText('Your documentation')).toBeTruthy()
+ expect(screen.getByText('Latest device information')).toBeTruthy()
+ expect(screen.getByText('old')).toHaveProperty('tagName', 'MARK')
+ expect(screen.getByText('new')).toHaveProperty('tagName', 'MARK')
+ expect(screen.getByText('Show previous shared value')).toBeTruthy()
+ })
+
+ it('hides the previous value when it carries no data', () => {
+ // A document with no recorded baseline gets its previous Hardware table
+ // rebuilt from a snapshot whose facts were unknown: dashes only.
+ const empties = ['', '—', '| CPU | RAM | Disk |\n|---|---|---|\n| — | — | — |']
+ for (const previous of empties) {
+ const { unmount } = render(
+ <UpdateFromDeviceModal
+ {...PROPS}
+ preview={preview({ changes: [change({ kind: 'section', previous })], unresolved: ['conflict-1'] })}
+ />,
+ )
+ expect(screen.queryByText('Show previous shared value')).toBeNull()
+ unmount()
+ }
+ })
+
+ it('shows a previous table as soon as one of its cells is known', () => {
+ render(
+ <UpdateFromDeviceModal
+ {...PROPS}
+ preview={preview({
+ changes: [change({ kind: 'section', previous: '| CPU | RAM | Disk |\n|---|---|---|\n| — | 2 GB | — |' })],
+ unresolved: ['conflict-1'],
+ })}
+ />,
+ )
+ expect(screen.getByText('Show previous shared value')).toBeTruthy()
+ })
+
+ it('renders generated hardware tables as tables and highlights their changed rows', () => {
+ render(
+ <UpdateFromDeviceModal
+ {...PROPS}
+ preview={preview({
+ changes: [
+ change({
+ kind: 'section',
+ documented: '## Hardware\n\n| Component | Model |\n| --- | --- |\n| CPU | Xeon D-1521 |\n| RAM | 32 GB ECC |',
+ device: '## Hardware\n\n| Component | Model |\n| --- | --- |\n| CPU | Xeon D-1528 |\n| RAM | 32 GB ECC |',
+ }),
+ ],
+ unresolved: ['conflict-1'],
+ })}
+ />,
+ )
+
+ expect(screen.getAllByRole('table')).toHaveLength(2)
+ expect(screen.queryByText('| --- | --- |')).toBeNull()
+ expect(screen.getByRole('cell', { name: 'Xeon D-1521' }).closest('tr')).toHaveClass('bg-[var(--status-pending,#e3b341)]/20')
+ expect(screen.getByRole('cell', { name: 'Xeon D-1528' }).closest('tr')).toHaveClass('bg-[var(--status-online,#39d353)]/20')
+ })
+
+ it('highlights multiline paragraphs and fenced code when a later source line changes', () => {
+ render(
+ <UpdateFromDeviceModal
+ {...PROPS}
+ preview={preview({
+ changes: [
+ change({
+ kind: 'section',
+ documented: '## Notes\n\nThis is a multiline paragraph where\nthe old firmware is still documented.\n\n```yaml\nfirmware: old\nfeature: enabled\n```',
+ device: '## Notes\n\nThis is a multiline paragraph where\nthe new firmware is now installed.\n\n```yaml\nfirmware: new\nfeature: enabled\n```',
+ }),
+ ],
+ unresolved: ['conflict-1'],
+ })}
+ />,
+ )
+
+ expect(screen.getByText(/old firmware is still documented/, { selector: 'p' })).toHaveClass('bg-[var(--status-pending,#e3b341)]/20')
+ expect(screen.getByText(/new firmware is now installed/, { selector: 'p' })).toHaveClass('bg-[var(--status-online,#39d353)]/20')
+ expect(screen.getByText((_, node) => node?.tagName === 'PRE' && node.textContent?.includes('firmware: old') === true)).toHaveClass('bg-[var(--status-pending,#e3b341)]/20')
+ expect(screen.getByText((_, node) => node?.tagName === 'PRE' && node.textContent?.includes('firmware: new') === true)).toHaveClass('bg-[var(--status-online,#39d353)]/20')
+ })
+
+ it('offers only the documentation and the device as choices', () => {
+ render(
+ <UpdateFromDeviceModal
+ {...PROPS}
+ preview={preview({ changes: [change()], unresolved: ['conflict-1'] })}
+ />,
+ )
+ expect(screen.getAllByRole('radio')).toHaveLength(2)
+ expect(screen.getByRole('radio', { name: 'Keep actual documentation' })).toBeTruthy()
+ expect(screen.getByRole('radio', { name: 'Take new device information' })).toBeTruthy()
+ expect(screen.queryByRole('radio', { name: 'Write my own' })).toBeNull()
+ expect(screen.queryByRole('textbox')).toBeNull()
+ })
+
+ it('names the device choice without echoing the raw device value', () => {
+ render(
+ <UpdateFromDeviceModal
+ {...PROPS}
+ preview={preview({
+ changes: [change({ kind: 'section', device: '| CPU | RAM | Disk |\n|---|---|---|\n| 2 cores | 1 GB | 4 GB |' })],
+ unresolved: ['conflict-1'],
+ })}
+ />,
+ )
+ expect(screen.getByRole('radio', { name: 'Take new device information' })).toBeTruthy()
+ })
+
+ it('offers to remove the entry when the device no longer has it', () => {
+ render(
+ <UpdateFromDeviceModal
+ {...PROPS}
+ preview={preview({ changes: [change({ device: '' })], unresolved: ['conflict-1'] })}
+ />,
+ )
+ expect(screen.getByRole('radio', { name: 'Remove it' })).toBeTruthy()
+ expect(screen.queryByRole('radio', { name: 'Take new device information' })).toBeNull()
+ })
+
+ it('records a choice as soon as it is picked', async () => {
+ const user = userEvent.setup()
+ const onResolve = vi.fn()
+ render(
+ <UpdateFromDeviceModal
+ {...PROPS}
+ preview={preview({ changes: [change()], unresolved: ['conflict-1'] })}
+ onResolve={onResolve}
+ />,
+ )
+
+ await user.click(screen.getByRole('radio', { name: 'Keep actual documentation' }))
+ expect(onResolve).toHaveBeenLastCalledWith('conflict-1', { id: 'conflict-1', choice: 'keep' })
+ await user.click(screen.getByRole('radio', { name: 'Take new device information' }))
+ expect(onResolve).toHaveBeenLastCalledWith('conflict-1', { id: 'conflict-1', choice: 'device' })
+ })
+
+ it('resets the local choice when its resolution is cleared', () => {
+ const current = preview({ changes: [change()], unresolved: ['conflict-1'] })
+ const { rerender } = render(
+ <UpdateFromDeviceModal
+ {...PROPS}
+ preview={current}
+ resolutions={{ 'conflict-1': { id: 'conflict-1', choice: 'device' } }}
+ />,
+ )
+ expect((screen.getByRole('radio', { name: /Take new/ }) as HTMLInputElement).checked).toBe(true)
+
+ rerender(<UpdateFromDeviceModal {...PROPS} preview={current} resolutions={{}} />)
+
+ expect((screen.getByRole('radio', { name: /Take new/ }) as HTMLInputElement).checked).toBe(false)
+ expect(screen.getByRole('button', { name: /Resolve 1 more/ })).toBeTruthy()
+ })
+
+ it('locks both buttons while the server is working', () => {
+ render(
+ <UpdateFromDeviceModal
+ {...PROPS}
+ preview={preview()}
+ loading
+ />,
+ )
+ expect(screen.getByRole('button', { name: 'Cancel' }).hasAttribute('disabled')).toBe(true)
+ })
+
+ it('keeps a settled row on screen so the decision can be revised', async () => {
+ const user = userEvent.setup()
+ const log: ResolutionItem[] = []
+ render(<StatefulReview onResolveLog={log} />)
+
+ expect(screen.getByRole('button', { name: /Resolve 1 more/ })).toBeTruthy()
+ await user.click(screen.getByRole('radio', { name: 'Keep actual documentation' }))
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'Update the document' })).toBeTruthy()
+ }, { timeout: 2000 })
+ expect(log.at(-1)).toEqual({ id: 'conflict-1', choice: 'keep' })
+
+ await user.click(screen.getByRole('radio', { name: 'Take new device information' }))
+ await waitFor(() => {
+ expect(log.at(-1)).toEqual({ id: 'conflict-1', choice: 'device' })
+ }, { timeout: 2000 })
+ })
+
+ it('leaves Update locked from the choice until the matching preview has arrived', async () => {
+ const user = userEvent.setup()
+ const log: ResolutionItem[] = []
+ const onApply = vi.fn()
+ render(<StatefulReview onApply={onApply} onResolveLog={log} previewDelay={150} />)
+
+ await user.click(screen.getByRole('radio', { name: 'Take new device information' }))
+
+ // The resolution is committed, but the preview it needs is still in flight:
+ // saving before it lands would write something the user has not seen.
+ expect(log.at(-1)).toEqual({ id: 'conflict-1', choice: 'device' })
+ expect(screen.queryByRole('button', { name: 'Update the document' })).toBeNull()
+ expect(screen.getByRole('button', { name: /Working…/ })).toBeTruthy()
+ expect(onApply).not.toHaveBeenCalled()
+
+ // Once the merge answered, Update is offered and applies the shown result.
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'Update the document' })).toBeTruthy()
+ }, { timeout: 2000 })
+ await user.click(screen.getByRole('button', { name: 'Update the document' }))
+ expect(onApply).toHaveBeenCalled()
+ })
+})
diff --git a/frontend/src/documentation/__tests__/store.test.ts b/frontend/src/documentation/__tests__/store.test.ts
index 0d9a7fa..0debcc8 100644
--- a/frontend/src/documentation/__tests__/store.test.ts
+++ b/frontend/src/documentation/__tests__/store.test.ts
@@ -11,7 +11,7 @@ import {
useDocsStore,
writeDraft,
} from '../store'
-import type { Doc, DocumentSummary } from '../types'
+import type { Doc, DocumentSummary, UpdatePreview } from '../types'
vi.mock('@/api/client', () => ({
documentsApi: {
@@ -28,6 +28,8 @@ vi.mock('@/api/client', () => ({
block: vi.fn(),
coverage: vi.fn(),
scaffold: vi.fn(),
+ updatePreview: vi.fn(),
+ updateFromDevice: vi.fn(),
},
}))
@@ -53,6 +55,28 @@ function doc(overrides: Partial<Doc> = {}): Doc {
return { ...summary(), body: 'original', ...overrides } as Doc
}
+function preview(overrides: Partial<UpdatePreview> = {}): UpdatePreview {
+ return {
+ preview_id: 'p1',
+ changes: [],
+ proposed_body: 'body',
+ summary: [],
+ unresolved: [],
+ ...overrides,
+ }
+}
+
+/** A promise the test settles by hand, to race the store's requests. */
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ let reject!: (reason: unknown) => void
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res
+ reject = rej
+ })
+ return { promise, resolve, reject }
+}
+
const INITIAL = useDocsStore.getState()
beforeEach(() => {
@@ -69,6 +93,9 @@ beforeEach(() => {
revisions: [],
coverage: null,
search: null,
+ preview: null,
+ previewLoading: false,
+ resolutions: {},
})
})
@@ -590,3 +617,341 @@ describe('openForDevice', () => {
expect(useDocsStore.getState().openDoc).toBeNull()
})
})
+
+// ── update-from-device ────────────────────────────────────────────────────
+
+describe('openUpdatePreview', () => {
+ it('fetches the preview for the open document', async () => {
+ const previewResponse = {
+ preview_id: 'abc123',
+ changes: [],
+ proposed_body: 'updated body',
+ summary: [],
+ unresolved: [],
+ }
+ useDocsStore.setState({ openDoc: doc({ id: 'doc-1', device_id: 'dev-1' }) as Doc })
+ api.updatePreview.mockResolvedValue({ data: previewResponse } as never)
+
+ const result = await useDocsStore.getState().openUpdatePreview()
+
+ expect(result).toEqual(previewResponse)
+ expect(api.updatePreview).toHaveBeenCalledWith('doc-1', [])
+ expect(useDocsStore.getState().preview?.preview_id).toBe('abc123')
+ })
+
+ it('drops a superseded answer that resolves after the newest request', async () => {
+ const first = deferred<{ data: UpdatePreview }>()
+ const second = deferred<{ data: UpdatePreview }>()
+ api.updatePreview
+ .mockImplementationOnce(() => first.promise)
+ .mockImplementationOnce(() => second.promise)
+ useDocsStore.setState({ openDoc: doc() })
+
+ // The first request answers with the resolutions of the moment it was
+ // issued; by the time it returns, a newer request owns the review.
+ const firstCall = useDocsStore.getState().openUpdatePreview()
+ useDocsStore.setState({ resolutions: { a: { id: 'a', choice: 'device' } } })
+ const secondCall = useDocsStore.getState().openUpdatePreview()
+
+ second.resolve({ data: preview({ preview_id: 'newest' }) })
+ first.resolve({ data: preview({ preview_id: 'stale' }) })
+
+ expect(await firstCall).toBeNull()
+ expect(await secondCall).toEqual(preview({ preview_id: 'newest' }))
+ expect(useDocsStore.getState().preview?.preview_id).toBe('newest')
+ expect(useDocsStore.getState().previewLoading).toBe(false)
+ expect(api.updatePreview).toHaveBeenNthCalledWith(1, 'doc-1', [])
+ expect(api.updatePreview).toHaveBeenNthCalledWith(2, 'doc-1', [{ id: 'a', choice: 'device' }])
+ })
+
+ it('does not clear the current preview when a superseded request fails', async () => {
+ const stale = deferred<{ data: UpdatePreview }>()
+ const newest = deferred<{ data: UpdatePreview }>()
+ api.updatePreview
+ .mockImplementationOnce(() => stale.promise)
+ .mockImplementationOnce(() => newest.promise)
+ useDocsStore.setState({ openDoc: doc() })
+
+ const staleCall = useDocsStore.getState().openUpdatePreview()
+ const newestCall = useDocsStore.getState().openUpdatePreview()
+
+ newest.resolve({ data: preview({ preview_id: 'newest' }) })
+ stale.reject(new Error('connection dropped'))
+
+ expect(await staleCall).toBeNull()
+ expect(await newestCall).toEqual(preview({ preview_id: 'newest' }))
+ expect(useDocsStore.getState().preview?.preview_id).toBe('newest')
+ expect(useDocsStore.getState().previewLoading).toBe(false)
+ // The superseded failure must not surface as if the review had failed.
+ expect(useDocsStore.getState().loadError).toBeNull()
+ })
+
+ it('ignores an answer for a document that was closed meanwhile', async () => {
+ const inFlight = deferred<{ data: UpdatePreview }>()
+ api.updatePreview.mockImplementationOnce(() => inFlight.promise)
+ useDocsStore.setState({ openDoc: doc() })
+
+ const call = useDocsStore.getState().openUpdatePreview()
+ useDocsStore.getState().close()
+ inFlight.resolve({ data: preview({ preview_id: 'ghost' }) })
+
+ expect(await call).toBeNull()
+ expect(useDocsStore.getState().preview).toBeNull()
+ expect(useDocsStore.getState().previewLoading).toBe(false)
+ })
+
+ it('ignores an answer for a document the user already switched away from', async () => {
+ const inFlight = deferred<{ data: UpdatePreview }>()
+ api.updatePreview.mockImplementationOnce(() => inFlight.promise)
+ api.get.mockResolvedValue({ data: doc({ id: 'doc-2' }) } as never)
+ useDocsStore.setState({ openDoc: doc({ id: 'doc-1' }) })
+
+ const call = useDocsStore.getState().openUpdatePreview()
+ const opening = useDocsStore.getState().open('doc-2')
+ inFlight.resolve({ data: preview({ preview_id: 'ghost' }) })
+
+ expect(await call).toBeNull()
+ await opening
+ expect(useDocsStore.getState().openDoc?.id).toBe('doc-2')
+ expect(useDocsStore.getState().preview).toBeNull()
+ })
+
+ it('ignores an answer when the review was cancelled during the request', async () => {
+ const inFlight = deferred<{ data: UpdatePreview }>()
+ api.updatePreview.mockImplementationOnce(() => inFlight.promise)
+ useDocsStore.setState({ openDoc: doc() })
+
+ const call = useDocsStore.getState().openUpdatePreview()
+ expect(useDocsStore.getState().previewLoading).toBe(true)
+ useDocsStore.getState().clearResolutions()
+ // The cancel stops the spinner itself: the in-flight request is now going
+ // to be ignored, so it can never be the one to clear the flag.
+ expect(useDocsStore.getState().previewLoading).toBe(false)
+ inFlight.resolve({ data: preview({ preview_id: 'ghost' }) })
+
+ expect(await call).toBeNull()
+ expect(useDocsStore.getState().preview).toBeNull()
+ expect(useDocsStore.getState().previewLoading).toBe(false)
+ })
+})
+
+describe('setResolution', () => {
+ it('stores the decision and re-previews', async () => {
+ const previewResponse = {
+ preview_id: 'xyz',
+ changes: [{ id: 'conflict-1', name: 'IP', status: 'conflict', documented: 'old', device: 'new' }],
+ proposed_body: 'body',
+ summary: [],
+ unresolved: ['conflict-1'],
+ }
+ useDocsStore.setState({ openDoc: doc({ id: 'doc-1' }) as Doc })
+ api.updatePreview.mockResolvedValue({ data: previewResponse } as never)
+
+ useDocsStore.getState().setResolution('conflict-1', { id: 'conflict-1', choice: 'device' })
+
+ expect(useDocsStore.getState().resolutions['conflict-1']?.choice).toBe('device')
+ expect(api.updatePreview).toHaveBeenCalledTimes(1)
+ })
+
+ it('keeps the preview of the newest decision when two reviews race', async () => {
+ const first = deferred<{ data: UpdatePreview }>()
+ const second = deferred<{ data: UpdatePreview }>()
+ api.updatePreview
+ .mockImplementationOnce(() => first.promise)
+ .mockImplementationOnce(() => second.promise)
+ useDocsStore.setState({ openDoc: doc() })
+
+ // Two decisions land back to back; each fires its own preview, and the
+ // older one answers last — it must not undo the newer review.
+ useDocsStore.getState().setResolution('a', { id: 'a', choice: 'device' })
+ useDocsStore.getState().setResolution('b', { id: 'b', choice: 'custom', custom: '10.0.0.5' })
+
+ second.resolve({ data: preview({ preview_id: 'newest' }) })
+ first.resolve({ data: preview({ preview_id: 'stale' }) })
+ await Promise.resolve()
+
+ expect(useDocsStore.getState().preview?.preview_id).toBe('newest')
+ expect(useDocsStore.getState().resolutions).toEqual({
+ a: { id: 'a', choice: 'device' },
+ b: { id: 'b', choice: 'custom', custom: '10.0.0.5' },
+ })
+ expect(useDocsStore.getState().previewLoading).toBe(false)
+ })
+})
+
+describe('applyUpdate', () => {
+ it('applies the merge and refreshes the document', async () => {
+ const updatedDoc = doc({ id: 'doc-1', body: 'merged', device_id: 'dev-1' })
+ const previewResponse = {
+ preview_id: 'preview-1',
+ changes: [],
+ proposed_body: 'merged',
+ summary: ['Applied IP'],
+ unresolved: [],
+ }
+ useDocsStore.setState({
+ openDoc: doc({ id: 'doc-1', device_id: 'dev-1', body: 'old' }) as Doc,
+ resolutions: { 'conflict-1': { id: 'conflict-1', choice: 'device' } },
+ })
+ // The preview is installed the way the review installs it, so apply can
+ // verify the merge on screen was computed over these exact decisions.
+ api.updatePreview.mockResolvedValue({ data: previewResponse } as never)
+ await useDocsStore.getState().openUpdatePreview()
+
+ api.updateFromDevice.mockResolvedValue({ data: updatedDoc } as never)
+ api.get.mockResolvedValue({ data: updatedDoc } as never)
+
+ const result = await useDocsStore.getState().applyUpdate()
+
+ expect(result).toBe('applied')
+ expect(api.updateFromDevice).toHaveBeenCalledWith('doc-1', 'preview-1', [
+ { id: 'conflict-1', choice: 'device' },
+ ])
+ expect(useDocsStore.getState().preview).toBeNull()
+ expect(useDocsStore.getState().resolutions).toEqual({})
+ })
+
+ it('returns stale on 409 and resets the review', async () => {
+ const error = Object.assign(new Error('Conflict'), { response: { status: 409 } })
+ useDocsStore.setState({ openDoc: doc({ id: 'doc-1' }) as Doc })
+ api.updatePreview.mockResolvedValue({
+ data: { preview_id: 'p1', changes: [], proposed_body: '', summary: [], unresolved: [] },
+ } as never)
+ await useDocsStore.getState().openUpdatePreview()
+ api.updateFromDevice.mockRejectedValue(error)
+
+ const result = await useDocsStore.getState().applyUpdate()
+
+ expect(result).toBe('stale')
+ expect(useDocsStore.getState().loadError).toBeTruthy()
+ // The stale merge and the choices that went with it are void; the fresh
+ // review must start clean rather than carry decisions made on a baseline
+ // that no longer holds.
+ expect(useDocsStore.getState().preview).toBeNull()
+ expect(useDocsStore.getState().resolutions).toEqual({})
+ expect(useDocsStore.getState().previewLoading).toBe(false)
+ })
+
+ it('refuses to apply once the latest preview has failed', async () => {
+ useDocsStore.setState({ openDoc: doc() })
+ api.updatePreview.mockResolvedValueOnce({ data: preview({ preview_id: 'first' }) } as never)
+ await useDocsStore.getState().openUpdatePreview()
+ expect(useDocsStore.getState().preview?.preview_id).toBe('first')
+
+ // The re-preview that would supersede it fails. The merge on screen is no
+ // longer the one that would land, so it must not be applicable either.
+ api.updatePreview.mockRejectedValueOnce({ response: { data: { detail: 'device offline' } } })
+ expect(await useDocsStore.getState().openUpdatePreview()).toBeNull()
+ expect(useDocsStore.getState().preview).toBeNull()
+ expect(useDocsStore.getState().loadError).toBe('device offline')
+
+ expect(await useDocsStore.getState().applyUpdate()).toBe('failed')
+ expect(api.updateFromDevice).not.toHaveBeenCalled()
+ })
+
+ it('refuses to apply while a newer preview is still loading', async () => {
+ const inFlight = deferred<{ data: UpdatePreview }>()
+ api.updatePreview.mockImplementationOnce(() => inFlight.promise)
+ useDocsStore.setState({ openDoc: doc(), resolutions: {} })
+ const previewing = useDocsStore.getState().openUpdatePreview()
+
+ expect(await useDocsStore.getState().applyUpdate()).toBe('failed')
+ expect(api.updateFromDevice).not.toHaveBeenCalled()
+
+ inFlight.resolve({ data: preview({ preview_id: 'p' }) })
+ await previewing
+ expect(useDocsStore.getState().previewLoading).toBe(false)
+ })
+
+ it('refuses to apply while conflicts are still open', async () => {
+ api.updatePreview.mockResolvedValue({
+ data: preview({ preview_id: 'p1', unresolved: ['conflict-1'] }),
+ } as never)
+ useDocsStore.setState({ openDoc: doc(), resolutions: {} })
+ await useDocsStore.getState().openUpdatePreview()
+
+ expect(useDocsStore.getState().preview?.unresolved).toEqual(['conflict-1'])
+ expect(await useDocsStore.getState().applyUpdate()).toBe('failed')
+ expect(api.updateFromDevice).not.toHaveBeenCalled()
+ })
+
+ it('refuses to apply a preview computed before the latest decision', async () => {
+ api.updatePreview.mockResolvedValue({ data: preview({ preview_id: 'p1', unresolved: [] }) } as never)
+ useDocsStore.setState({
+ openDoc: doc(),
+ resolutions: { a: { id: 'a', choice: 'device' } },
+ })
+ await useDocsStore.getState().openUpdatePreview()
+
+ // A further decision lands after the preview was computed, and its
+ // re-preview has not answered yet: applying now would merge with decisions
+ // the user has never seen on top of this body.
+ useDocsStore.setState({
+ resolutions: { a: { id: 'a', choice: 'device' }, b: { id: 'b', choice: 'keep' } },
+ })
+ expect(await useDocsStore.getState().applyUpdate()).toBe('failed')
+ expect(api.updateFromDevice).not.toHaveBeenCalled()
+
+ // Once the matching preview for the fuller set of decisions has arrived,
+ // the same apply is accepted and lands exactly that set.
+ api.updatePreview.mockResolvedValue({ data: preview({ preview_id: 'p2', unresolved: [] }) } as never)
+ await useDocsStore.getState().openUpdatePreview()
+ api.updateFromDevice.mockResolvedValue({ data: doc({ id: 'doc-1', body: 'merged' }) } as never)
+
+ expect(await useDocsStore.getState().applyUpdate()).toBe('applied')
+ expect(api.updateFromDevice).toHaveBeenCalledWith('doc-1', 'p2', [
+ { id: 'a', choice: 'device' },
+ { id: 'b', choice: 'keep' },
+ ])
+ })
+
+ it('does not replace a newer document and review when an old apply succeeds late', async () => {
+ const applying = deferred<{ data: Doc }>()
+ useDocsStore.setState({ openDoc: doc({ id: 'doc-1' }) })
+ api.updatePreview.mockResolvedValueOnce({ data: preview({ preview_id: 'doc-1-preview' }) } as never)
+ await useDocsStore.getState().openUpdatePreview()
+ api.updateFromDevice.mockImplementationOnce(() => applying.promise)
+ const oldApply = useDocsStore.getState().applyUpdate()
+
+ api.get.mockResolvedValueOnce({ data: doc({ id: 'doc-2', body: 'second' }) } as never)
+ await useDocsStore.getState().open('doc-2')
+ useDocsStore.setState({ resolutions: { newer: { id: 'newer', choice: 'device' } } })
+ api.updatePreview.mockResolvedValueOnce({ data: preview({ preview_id: 'doc-2-preview' }) } as never)
+ await useDocsStore.getState().openUpdatePreview()
+
+ applying.resolve({ data: doc({ id: 'doc-1', body: 'applied late' }) })
+ expect(await oldApply).toBe('applied')
+ expect(useDocsStore.getState().openDoc?.id).toBe('doc-2')
+ expect(useDocsStore.getState().preview?.preview_id).toBe('doc-2-preview')
+ expect(useDocsStore.getState().resolutions).toEqual({
+ newer: { id: 'newer', choice: 'device' },
+ })
+
+ api.updateFromDevice.mockResolvedValueOnce({ data: doc({ id: 'doc-2', body: 'merged second' }) } as never)
+ expect(await useDocsStore.getState().applyUpdate()).toBe('applied')
+ })
+
+ it('does not clear a newer document review when an old apply rejects late', async () => {
+ const applying = deferred<{ data: Doc }>()
+ useDocsStore.setState({ openDoc: doc({ id: 'doc-1' }) })
+ api.updatePreview.mockResolvedValueOnce({ data: preview({ preview_id: 'doc-1-preview' }) } as never)
+ await useDocsStore.getState().openUpdatePreview()
+ api.updateFromDevice.mockImplementationOnce(() => applying.promise)
+ const oldApply = useDocsStore.getState().applyUpdate()
+
+ api.get.mockResolvedValueOnce({ data: doc({ id: 'doc-2', body: 'second' }) } as never)
+ await useDocsStore.getState().open('doc-2')
+ useDocsStore.setState({ resolutions: { newer: { id: 'newer', choice: 'device' } } })
+ api.updatePreview.mockResolvedValueOnce({ data: preview({ preview_id: 'doc-2-preview' }) } as never)
+ await useDocsStore.getState().openUpdatePreview()
+
+ applying.reject(Object.assign(new Error('stale'), { response: { status: 409 } }))
+ expect(await oldApply).toBe('stale')
+ expect(useDocsStore.getState().openDoc?.id).toBe('doc-2')
+ expect(useDocsStore.getState().preview?.preview_id).toBe('doc-2-preview')
+ expect(useDocsStore.getState().resolutions).toEqual({
+ newer: { id: 'newer', choice: 'device' },
+ })
+ expect(useDocsStore.getState().previewLoading).toBe(false)
+ })
+})
diff --git a/frontend/src/documentation/components/DocHistory.tsx b/frontend/src/documentation/components/DocHistory.tsx
index 53ef34b..13bfa96 100644
--- a/frontend/src/documentation/components/DocHistory.tsx
+++ b/frontend/src/documentation/components/DocHistory.tsx
@@ -29,6 +29,7 @@ const REASONS: Record<DocRevision['reason'], string> = {
scaffold: 'Generated',
regenerate: 'Regenerated',
mcp: 'Saved by an AI client',
+ sync: 'Updated from device',
}
function size(bytes: number): string {
diff --git a/frontend/src/documentation/components/DocViewer.tsx b/frontend/src/documentation/components/DocViewer.tsx
index 2dec49b..fdda103 100644
--- a/frontend/src/documentation/components/DocViewer.tsx
+++ b/frontend/src/documentation/components/DocViewer.tsx
@@ -1,5 +1,6 @@
import { useMemo, useState } from 'react'
-import { Clock, Download, History, Link2, Pencil, Plus, RefreshCw, Star, Trash2, X } from 'lucide-react'
+import { Menu } from '@base-ui/react/menu'
+import { Clock, Download, Ellipsis, History, Link2, Pencil, Plus, RefreshCw, Star, Trash2, X } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
@@ -49,6 +50,8 @@ interface Props {
onToggleStar?: () => void
onMarkReviewed?: () => void
onRegenerate?: () => void
+ /** Opens the update-from-device review for a drifted device document. */
+ onUpdateFromDevice?: () => void
/** Saves this document to disk as the `.md` file its body already is. */
onDownload: () => void
onDelete?: () => void
@@ -88,6 +91,7 @@ export function DocViewer({
onEdit,
onToggleStar,
onMarkReviewed,
+ onUpdateFromDevice,
onRegenerate,
onDownload,
onDelete,
@@ -171,6 +175,15 @@ export function DocViewer({
<Button size="sm" variant="ghost" onClick={onEdit} className="cursor-pointer gap-1">
<Pencil size={13} /> Edit
</Button>
+ {doc.kind === 'device' && drifted && onUpdateFromDevice && (
+ <Button
+ size="sm"
+ onClick={onUpdateFromDevice}
+ className="cursor-pointer gap-1.5 bg-[var(--status-online,#39d353)] text-[#0d1117] hover:bg-[var(--status-online,#39d353)]/90"
+ >
+ <RefreshCw size={13} /> Update from device
+ </Button>
+ )}
</>
)}
{history && (
@@ -188,16 +201,27 @@ export function DocViewer({
)}
{/* A folder holds children, not a generated body — nothing to rebuild. */}
{!readOnly && doc.kind !== 'folder' && (
- <Button
- size="icon-xs"
- variant="ghost"
- title="Regenerate this document from the database"
- aria-label="Regenerate this document"
- onClick={onRegenerate}
- className="cursor-pointer"
- >
- <RefreshCw />
- </Button>
+ <Menu.Root>
+ <Menu.Trigger
+ title="More document actions"
+ aria-label="More document actions"
+ className="flex size-6 cursor-pointer items-center justify-center rounded-[min(var(--radius-md),10px)] text-muted-foreground outline-none hover:bg-muted hover:text-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50"
+ >
+ <Ellipsis size={14} />
+ </Menu.Trigger>
+ <Menu.Portal>
+ <Menu.Positioner align="end" sideOffset={4} className="isolate z-50">
+ <Menu.Popup className="min-w-52 rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10">
+ <Menu.Item
+ onClick={onRegenerate}
+ className="flex w-full cursor-pointer items-center gap-1.5 rounded-md px-2 py-1.5 text-sm outline-none hover:bg-muted focus:bg-muted"
+ >
+ <RefreshCw size={13} /> Replace entire document…
+ </Menu.Item>
+ </Menu.Popup>
+ </Menu.Positioner>
+ </Menu.Portal>
+ </Menu.Root>
)}
<Button
size="icon-xs"
diff --git a/frontend/src/documentation/components/DocumentationView.tsx b/frontend/src/documentation/components/DocumentationView.tsx
index f85970a..d05328c 100644
--- a/frontend/src/documentation/components/DocumentationView.tsx
+++ b/frontend/src/documentation/components/DocumentationView.tsx
@@ -23,18 +23,31 @@ import {
filterGroups,
filterTree,
} from '../tree'
-import { GROUP_BY_LABELS, type GroupBy, type TreeLeaf } from '../types'
+import { GROUP_BY_LABELS, type GroupBy, type TreeLeaf, type UpdatePreview } from '../types'
import { DocEditor } from './DocEditor'
import { DocTreeGroups, DocTreeItem, type TreeDnd } from './DocTree'
import { DocViewer } from './DocViewer'
import { MigrateNotesBanner } from './MigrateNotesBanner'
import { NewDocMenu } from './NewDocMenu'
import { RegenerateDocModal } from './RegenerateDocModal'
+import { UpdateFromDeviceModal } from './UpdateFromDeviceModal'
const STANDALONE = import.meta.env.VITE_STANDALONE === 'true'
const GROUP_OPTIONS = Object.keys(GROUP_BY_LABELS) as GroupBy[]
+function updateConfirmation(result: UpdatePreview): string {
+ const names = [...new Set(
+ result.changes
+ .filter((change) => change.status !== 'same')
+ .map((change) => change.name.trim())
+ .filter(Boolean),
+ )]
+ if (names.length === 0) return 'Documentation already matched the device — marked as up to date'
+ const shown = names.slice(0, 3).join(', ')
+ return `Documentation updated: ${shown}${names.length > 3 ? `, and ${names.length - 3} more` : ''}`
+}
+
/**
* The Documentation section.
*
@@ -78,6 +91,13 @@ export function DocumentationView() {
coverage,
loadCoverage,
scaffold,
+ preview,
+ previewLoading,
+ resolutions,
+ openUpdatePreview,
+ setResolution,
+ clearResolutions,
+ applyUpdate,
groupBy,
setGroupBy,
expanded,
@@ -98,7 +118,14 @@ export function DocumentationView() {
const [regenerateOpen, setRegenerateOpen] = useState(false)
const [regenerating, setRegenerating] = useState(false)
const [historyOpen, setHistoryOpen] = useState(false)
+ const [updateOpen, setUpdateOpen] = useState(false)
const [exporting, setExporting] = useState(false)
+ const updateFlow = useRef(0)
+
+ useEffect(() => {
+ updateFlow.current++
+ setUpdateOpen(false)
+ }, [openDoc?.id])
useEffect(() => {
void loadDocs()
@@ -265,6 +292,63 @@ export function DocumentationView() {
toast.success('Document regenerated — the old body is in its history')
}, [openDoc, regenerate])
+ const handleCancelUpdate = useCallback(() => {
+ updateFlow.current++
+ setUpdateOpen(false)
+ clearResolutions()
+ }, [clearResolutions])
+
+ const finishUpdate = useCallback(async (review: UpdatePreview, flow: number, docId: string) => {
+ const result = await applyUpdate()
+ const current = useDocsStore.getState()
+ if (
+ flow !== updateFlow.current ||
+ current.openDoc?.id !== docId ||
+ (current.preview !== null && current.preview.preview_id !== review.preview_id)
+ ) return
+ if (result === 'failed') {
+ toast.error('Could not apply the update')
+ return
+ }
+ if (result === 'stale') {
+ // The document moved under the preview; show it again and re-compare,
+ // so the user is never applying against a body they have not seen.
+ setUpdateOpen(true)
+ await open(docId)
+ if (flow !== updateFlow.current || useDocsStore.getState().openDoc?.id !== docId) return
+ toast.error('That preview was out of date — review the current document again')
+ await openUpdatePreview()
+ return
+ }
+ setUpdateOpen(false)
+ clearResolutions()
+ toast.success(updateConfirmation(review), {
+ action: { label: 'View history', onClick: () => setHistoryOpen(true) },
+ })
+ }, [applyUpdate, clearResolutions, open, openUpdatePreview])
+
+ // The comparison only ever opens the review. Even an update with no conflict
+ // waits for the Update button: nothing is written to a document unseen.
+ const handleUpdatePreview = useCallback(async () => {
+ if (!openDoc) return
+ const flow = ++updateFlow.current
+ const docId = openDoc.id
+ setUpdateOpen(true)
+ const result = await openUpdatePreview()
+ if (flow !== updateFlow.current || useDocsStore.getState().openDoc?.id !== docId) return
+ if (result === null) toast.error('Could not compare this document with the device')
+ }, [openDoc, openUpdatePreview])
+
+ const handleApplyUpdate = useCallback(async () => {
+ if (!openDoc || !preview) return
+ const flow = ++updateFlow.current
+ await finishUpdate(preview, flow, openDoc.id)
+ }, [finishUpdate, openDoc, preview])
+
+ // Applying the merge on a doc with an edit in flight would silently destroy
+ // the draft text it replaced; the button is hidden while editing instead.
+ const showUpdate = openDoc !== null && draft === null
+
// The rail is loaded when it is opened, and again whenever the document it is
// showing changes underneath it — a save adds a revision to the list.
const openDocId = openDoc?.id
@@ -598,6 +682,7 @@ export function DocumentationView() {
onToggleStar={() => void toggleStar(openDoc.id)}
onMarkReviewed={() => void markReviewed(openDoc.id)}
onSetTags={(tags) => void setTags(tags)}
+ onUpdateFromDevice={() => void handleUpdatePreview()}
onRegenerate={() => setRegenerateOpen(true)}
onDownload={() => downloadDoc(openDoc)}
onDelete={() => void handleDelete()}
@@ -638,6 +723,19 @@ export function DocumentationView() {
onCancel={() => setRegenerateOpen(false)}
onConfirm={() => void handleRegenerate()}
/>
+ <UpdateFromDeviceModal
+ open={showUpdate && updateOpen}
+ docTitle={openDoc?.title ?? ''}
+ preview={preview}
+ loading={previewLoading}
+ resolutions={resolutions}
+ onPreview={() => void handleUpdatePreview()}
+ onResolve={(id, item) => setResolution(id, item)}
+ onCancel={handleCancelUpdate}
+ onApply={() => void handleApplyUpdate()}
+ docs={docs}
+ devices={linkableDevices}
+ />
</div>
</div>
)
diff --git a/frontend/src/documentation/components/UpdateFromDeviceModal.tsx b/frontend/src/documentation/components/UpdateFromDeviceModal.tsx
new file mode 100644
index 0000000..22cf42f
--- /dev/null
+++ b/frontend/src/documentation/components/UpdateFromDeviceModal.tsx
@@ -0,0 +1,480 @@
+import { useCallback, useMemo, useState } from 'react'
+import { AlertTriangle, Check, Loader2, RefreshCw, X } from 'lucide-react'
+
+import { cn } from '@/lib/utils'
+import { diffLines, diffStat } from '../diff'
+
+import { Button } from '@/components/ui/button'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog'
+import { Markdown } from '../markdown/Markdown'
+import type { ReconcileChange, ResolutionItem, UpdatePreview } from '../types'
+import type { LinkableDevice, LinkableDoc } from '../wikilinks'
+
+interface Props {
+ open: boolean
+ docTitle: string
+ preview: UpdatePreview | null
+ /** The server is merging; apply and every decision are locked. */
+ loading: boolean
+ /** The conflicts the user has decided on so far, keyed by change id. */
+ resolutions: Record<string, ResolutionItem>
+ onPreview: () => void
+ /** One decision, then the merge is re-run to show its effect. */
+ onResolve: (id: string, item: ResolutionItem) => void
+ onCancel: () => void
+ onApply: () => void
+ docs: LinkableDoc[]
+ devices: LinkableDevice[]
+}
+
+/**
+ * The guided update-from-device review.
+ *
+ * The server never overwrites a body on its own: a changed device value the
+ * user never touched is applied automatically, a value both sides changed is a
+ * conflict the user settles here (keep the documentation / take the device),
+ * and the live body underneath always reflects the current decisions because
+ * it is the server's own merge. Nothing is saved until every conflict is
+ * settled and the Apply button is pressed.
+ *
+ * Each decision re-runs the merge and Update stays locked while that preview
+ * is loading, so the merge the user looks at is by construction the merge that
+ * will land.
+ */
+export function UpdateFromDeviceModal({
+ open,
+ docTitle,
+ preview,
+ loading,
+ resolutions,
+ onPreview,
+ onResolve,
+ onCancel,
+ onApply,
+ docs,
+ devices,
+}: Props) {
+ // Keep the last successful comparison mounted while a refresh is pending or
+ // has failed, so a transport error does not blank the review. `preview`, not
+ // this retained copy, remains the authority for enabling Apply.
+ const [lastPreview, setLastPreview] = useState<UpdatePreview | null>(preview)
+ const [previousPreview, setPreviousPreview] = useState(preview)
+ if (preview !== previousPreview) {
+ setPreviousPreview(preview)
+ if (preview !== null) setLastPreview(preview)
+ }
+ if (!open && lastPreview !== null) setLastPreview(null)
+ const displayedPreview = preview ?? lastPreview
+
+ // Every conflict — settled or still open — keeps a row for the whole review,
+ // so a decision can be revised after the re-preview it triggers. The section
+ // therefore descends from `changes`, never from `unresolved`.
+ const conflicts = displayedPreview
+ ? displayedPreview.changes.filter((change) => change.status === 'conflict')
+ : []
+
+ const cancel = useCallback(() => {
+ setLastPreview(null)
+ onCancel()
+ }, [onCancel])
+
+ const pending = conflicts.filter((change) => !(change.id in resolutions))
+ const hasAnythingToApply =
+ displayedPreview !== null &&
+ (displayedPreview.summary.length > 0 || displayedPreview.unresolved.length > 0 || Object.keys(resolutions).length > 0)
+ const previewReady = preview !== null
+
+ return (
+ <Dialog open={open} onOpenChange={(value) => !value && !loading && cancel()}>
+ {/* `!max-w-none`: the dialog primitive's `sm:max-w-sm` otherwise wins and
+ squeezes the side-by-side comparison into 384px. */}
+ <DialogContent className="flex max-h-[90vh] w-[95vw] !max-w-none flex-col border-border bg-[#161b22]">
+ <DialogHeader className="shrink-0">
+ <DialogTitle className="flex items-center gap-2 text-foreground">
+ <RefreshCw size={16} className="text-[var(--status-online,#39d353)]" />
+ Update "{docTitle}" from the device
+ </DialogTitle>
+ <DialogDescription className="text-xs">
+ The document is compared against the device's current facts. Nothing is saved until
+ you review it and press Update.
+ </DialogDescription>
+ </DialogHeader>
+
+ {displayedPreview === null && (
+ <div className="flex flex-1 flex-col items-center gap-3 py-10 text-center">
+ {loading ? (
+ <>
+ <Loader2 size={20} className="animate-spin text-muted-foreground" />
+ <p className="text-xs text-muted-foreground">Comparing with the device…</p>
+ </>
+ ) : (
+ <>
+ <p className="text-xs text-muted-foreground">Could not compare this document with the device.</p>
+ <Button size="sm" variant="secondary" onClick={onPreview} className="cursor-pointer">
+ Try again
+ </Button>
+ </>
+ )}
+ </div>
+ )}
+
+ {displayedPreview !== null && (
+ <div className="min-h-0 flex-1 overflow-y-auto pr-1">
+ {preview === null && !loading && (
+ <div role="alert" className="flex items-center justify-between gap-3 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive">
+ <span>Could not refresh this comparison. Review your text, then try again.</span>
+ <Button size="sm" variant="secondary" onClick={onPreview} className="shrink-0 cursor-pointer">
+ Try again
+ </Button>
+ </div>
+ )}
+ {/* What the merge decided, in the order the user will read it. */}
+ {displayedPreview.summary.length > 0 && (
+ <ul className="mt-1 space-y-1 rounded-md border border-border bg-[#0d1117]/60 px-3 py-2.5">
+ {displayedPreview.summary.map((line) => (
+ <li key={line} className="flex items-start gap-1.5 text-xs text-muted-foreground">
+ <Check size={12} className="mt-px shrink-0 text-[var(--status-online,#39d353)]" />
+ <span>{line}</span>
+ </li>
+ ))}
+ </ul>
+ )}
+
+ {conflicts.length > 0 && (
+ <section aria-label="Conflicts to resolve" className="mt-3">
+ <p className="mb-1.5 flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/70">
+ <AlertTriangle size={11} className="text-[var(--status-pending,#e3b341)]" />
+ {pending.length > 0
+ ? 'You changed this, and the device changed it too — decide which wins'
+ : 'Settled — pick a row again to revise it'}
+ </p>
+ <div className="space-y-2">
+ {conflicts.map((change) => (
+ <ConflictRow
+ key={change.id}
+ change={change}
+ onResolve={onResolve}
+ docs={docs}
+ devices={devices}
+ resolved={resolutions[change.id]}
+ />
+ ))}
+ </div>
+ </section>
+ )}
+
+ {/* The merged body, always the server's own merge with the current
+ resolutions folded in. */}
+ <section aria-label="Merged result" className="mt-3">
+ <p className="mb-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/70">
+ {hasAnythingToApply ? 'Result' : 'Nothing to change'}
+ </p>
+ {hasAnythingToApply ? (
+ <div className="max-h-72 overflow-y-auto rounded-md border border-border bg-[#0d1117]/60 px-4 py-3">
+ <Markdown
+ body={displayedPreview.proposed_body}
+ docs={docs}
+ devices={devices}
+ className="text-xs"
+ />
+ </div>
+ ) : (
+ <p className="rounded-md border border-border bg-[#0d1117]/60 px-3 py-2.5 text-xs text-muted-foreground">
+ The document already matches the device.
+ </p>
+ )}
+ </section>
+ </div>
+ )}
+
+ <DialogFooter className="shrink-0 gap-2">
+ <Button variant="ghost" onClick={cancel} disabled={loading}>
+ Cancel
+ </Button>
+ {previewReady && !hasAnythingToApply && (
+ // The body already matches, but the document still reads as
+ // drifted until the device's facts are recorded as reviewed —
+ // closing without that would leave the badge on forever.
+ <Button variant="secondary" onClick={onApply} className="cursor-pointer" disabled={loading}>
+ Mark as up to date
+ </Button>
+ )}
+ {previewReady && hasAnythingToApply && (
+ <Button
+ onClick={onApply}
+ disabled={loading || pending.length > 0}
+ className="gap-1.5 bg-[var(--status-online,#39d353)] text-[#0d1117] hover:bg-[var(--status-online,#39d353)]/90"
+ >
+ {loading ? (
+ <>
+ <Loader2 size={13} className="animate-spin" /> Working…
+ </>
+ ) : pending.length > 0 ? (
+ <>
+ <RefreshCw size={13} />
+ Resolve {pending.length} more
+ </>
+ ) : (
+ <>
+ <RefreshCw size={13} />
+ Update the document
+ </>
+ )}
+ </Button>
+ )}
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+const CHOICES: { choice: ResolutionItem['choice']; label: string }[] = [
+ { choice: 'keep', label: 'Keep actual documentation' },
+ { choice: 'device', label: 'Take new device information' },
+]
+
+/** Mark the changed run while leaving the matching context easy to scan. */
+function FieldValue({ value, other, accent }: { value: string; other: string; accent: 'document' | 'device' }) {
+ let start = 0
+ while (start < value.length && start < other.length && value[start] === other[start]) start++
+
+ let end = 0
+ while (
+ end < value.length - start &&
+ end < other.length - start &&
+ value[value.length - 1 - end] === other[other.length - 1 - end]
+ ) {
+ end++
+ }
+
+ const before = value.slice(0, start)
+ const changed = value.slice(start, value.length - end)
+ const after = value.slice(value.length - end)
+ return (
+ <p className="px-2.5 py-2 font-mono text-sm break-words text-foreground">
+ {before}
+ {changed && (
+ <mark
+ className={cn(
+ 'rounded px-0.5 text-inherit',
+ accent === 'document'
+ ? 'bg-[var(--status-pending,#e3b341)]/25'
+ : 'bg-[var(--status-online,#39d353)]/25',
+ )}
+ >
+ {changed}
+ </mark>
+ )}
+ {after}
+ {!value && <mark className="rounded bg-[var(--status-offline,#f85149)]/20 px-0.5 text-muted-foreground">removed</mark>}
+ </p>
+ )
+}
+
+function SectionValue({
+ documented,
+ device,
+ accent,
+}: {
+ documented: string
+ device: string
+ accent: 'document' | 'device'
+}) {
+ const highlightedLines = useMemo(() => {
+ let documentedLine = 1
+ let deviceLine = 1
+ const changed: number[] = []
+ diffLines(documented, device).forEach((row) => {
+ if (row.kind === 'same') {
+ documentedLine++
+ deviceLine++
+ } else if (row.kind === 'del') {
+ if (accent === 'document') changed.push(documentedLine)
+ documentedLine++
+ } else {
+ if (accent === 'device') changed.push(deviceLine)
+ deviceLine++
+ }
+ })
+ return changed
+ }, [accent, documented, device])
+
+ return (
+ <Markdown
+ body={accent === 'document' ? documented : device}
+ highlightedLines={highlightedLines}
+ highlightClassName={accent === 'document' ? 'bg-[var(--status-pending,#e3b341)]/20' : 'bg-[var(--status-online,#39d353)]/20'}
+ className="max-h-44 overflow-y-auto px-2.5 py-2 text-xs leading-relaxed"
+ />
+ )
+}
+
+/** One of the two sides of a conflict: labelled, readable, highlighted. */
+function VersionPanel({
+ label,
+ value,
+ kind,
+ otherValue,
+ accent,
+}: {
+ label: string
+ value: string
+ kind: ReconcileChange['kind']
+ otherValue: string
+ accent: 'document' | 'device'
+}) {
+ return (
+ <div
+ className={cn(
+ 'flex min-w-0 flex-col overflow-hidden rounded-lg border bg-[#0d1117]/60',
+ accent === 'document'
+ ? 'border-[var(--status-pending,#e3b341)]/40'
+ : 'border-[var(--status-online,#39d353)]/40',
+ )}
+ >
+ <p
+ className={cn(
+ 'border-b px-2.5 py-1 text-[10px] font-semibold uppercase tracking-wide',
+ accent === 'document'
+ ? 'border-[var(--status-pending,#e3b341)]/30 text-[var(--status-pending,#e3b341)]'
+ : 'border-[var(--status-online,#39d353)]/30 text-[var(--status-online,#39d353)]',
+ )}
+ >
+ {label}
+ </p>
+ {kind === 'field' ? (
+ <FieldValue value={value} other={otherValue} accent={accent} />
+ ) : (
+ <SectionValue documented={accent === 'document' ? value : otherValue} device={accent === 'device' ? value : otherValue} accent={accent} />
+ )}
+ </div>
+ )
+}
+
+/**
+ * Whether a previous value says anything worth disclosing.
+ *
+ * A document generated before baselines were recorded has its previous value
+ * rebuilt from the facts snapshot, and unknown facts come out as `—` — a whole
+ * Hardware table of dashes reads as an empty box. Headings and a table's
+ * header and separator rows are structure, not data.
+ */
+function carriesData(value: string): boolean {
+ const lines = value
+ .split('\n')
+ .map((line) => line.trim())
+ .filter((line) => line && !line.startsWith('#'))
+ const separator = lines.findIndex((line) => /^\|\s*:?-{3,}/.test(line))
+ const data = separator >= 0 ? [...lines.slice(0, Math.max(separator - 1, 0)), ...lines.slice(separator + 1)] : lines
+ return data.some((line) => line.split('|').some((cell) => cell.trim() !== '' && cell.trim() !== '—'))
+}
+
+function ConflictRow({
+ change,
+ onResolve,
+ docs,
+ devices,
+ resolved,
+}: {
+ change: ReconcileChange
+ onResolve: (id: string, item: ResolutionItem) => void
+ docs: LinkableDoc[]
+ devices: LinkableDevice[]
+ resolved?: ResolutionItem
+}) {
+ const [choice, setChoice] = useState<ResolutionItem['choice'] | null>(resolved?.choice ?? null)
+ const [previousResolved, setPreviousResolved] = useState(resolved)
+
+ // A reset (or a decision made elsewhere) must also reset this row's local
+ // selection. Adjusting state during render avoids a stale frame.
+ if (resolved !== previousResolved) {
+ setPreviousResolved(resolved)
+ setChoice(resolved?.choice ?? null)
+ }
+
+ function pick(next: ResolutionItem['choice']) {
+ setChoice(next)
+ onResolve(change.id, { id: change.id, choice: next })
+ }
+
+ const stat = useMemo(() => diffStat(diffLines(change.documented, change.device)), [change])
+
+ return (
+ <div className="rounded-md border border-border bg-[#0d1117]/60 p-2.5">
+ <div className="flex items-center gap-1.5">
+ <AlertTriangle size={13} className="shrink-0 text-[var(--status-pending,#e3b341)]" />
+ <p className="text-xs font-medium text-foreground">{change.name}</p>
+ {(stat.added > 0 || stat.removed > 0) && (
+ <span className="ml-auto rounded-full bg-muted px-1.5 py-0.5 text-[9px] text-muted-foreground">
+ {stat.added > 0 && <span className="text-[var(--status-online,#39d353)]">+{stat.added}</span>}
+ {stat.removed > 0 && <span className="ml-0.5 text-[var(--status-offline,#f85149)]">−{stat.removed}</span>}
+ </span>
+ )}
+ </div>
+
+ <div className="mt-2 grid gap-2 md:grid-cols-2">
+ <VersionPanel
+ label="Your documentation"
+ value={change.documented}
+ kind={change.kind}
+ otherValue={change.device}
+ accent="document"
+ />
+ <VersionPanel
+ label="Latest device information"
+ value={change.device}
+ kind={change.kind}
+ otherValue={change.documented}
+ accent="device"
+ />
+ </div>
+
+ {carriesData(change.previous) && change.previous !== change.documented && change.previous !== change.device && (
+ <details className="mt-2 text-xs">
+ <summary className="cursor-pointer text-muted-foreground">Show previous shared value</summary>
+ <div className="mt-1 rounded border border-border bg-muted/20 px-2.5 py-2">
+ {change.kind === 'field' ? (
+ <p className="font-mono break-words text-foreground">{change.previous}</p>
+ ) : (
+ <Markdown body={change.previous} docs={docs} devices={devices} className="text-xs" />
+ )}
+ </div>
+ </details>
+ )}
+
+ <div className="mt-2 flex flex-wrap items-center gap-x-4 gap-y-1.5 text-xs">
+ {CHOICES.map(({ choice: value, label }) => (
+ <label key={value} className="flex cursor-pointer items-center gap-1.5">
+ <input
+ type="radio"
+ name={`resolve-${change.id}`}
+ checked={choice === value}
+ onChange={() => pick(value)}
+ className="cursor-pointer accent-[var(--status-online,#39d353)]"
+ />
+ {value === 'device' && change.device ? (
+ <>
+ <RefreshCw size={11} />
+ {label}
+ </>
+ ) : value === 'device' ? (
+ <>
+ <X size={11} />
+ Remove it
+ </>
+ ) : (
+ label
+ )}
+ </label>
+ ))}
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/documentation/markdown/Markdown.tsx b/frontend/src/documentation/markdown/Markdown.tsx
index 28e1b92..4ffb746 100644
--- a/frontend/src/documentation/markdown/Markdown.tsx
+++ b/frontend/src/documentation/markdown/Markdown.tsx
@@ -3,6 +3,8 @@ import ReactMarkdown, { type Components } from 'react-markdown'
import rehypeSlug from 'rehype-slug'
import remarkGfm from 'remark-gfm'
+import { cn } from '@/lib/utils'
+
import { parseFrontmatter } from '../frontmatter'
import { MEDIA_PATH } from '../media'
import { toggleTaskAtLine } from './tasks'
@@ -26,6 +28,9 @@ export interface MarkdownProps {
onCreateFromLink?: (label: string) => void
/** Called when a task checkbox is toggled, with the rewritten body. */
onToggleTask?: (nextBody: string) => void
+ /** Source lines whose rendered block should be called out, for comparisons. */
+ highlightedLines?: readonly number[]
+ highlightClassName?: string
className?: string
}
@@ -36,46 +41,62 @@ export function Markdown({
onOpenDoc,
onCreateFromLink,
onToggleTask,
+ highlightedLines,
+ highlightClassName,
className,
}: MarkdownProps) {
const { content } = useMemo(() => parseFrontmatter(body), [body])
const components = useMemo<Components>(() => {
+ const highlighted = (
+ node?: { position?: { start?: { line?: number }; end?: { line?: number } } },
+ base?: string,
+ highlightedBase?: string,
+ ) => {
+ const start = node?.position?.start?.line
+ const end = node?.position?.end?.line ?? start
+ const intersects = start !== undefined && end !== undefined && highlightedLines?.some((line) => line >= start && line <= end)
+ return cn(base, intersects && highlightedBase, intersects && highlightClassName)
+ }
+
return {
// Every text node passes through the wiki-link splitter.
- p: ({ children }) => (
- <p className="my-3 leading-relaxed">
+ p: ({ children, node }) => (
+ <p className={highlighted(node, 'my-3 leading-relaxed', 'rounded px-1')}>
<WikiText docs={docs} devices={devices} onOpenDoc={onOpenDoc} onCreate={onCreateFromLink}>
{children}
</WikiText>
</p>
),
- li: ({ children }) => (
- <li className="my-1">
+ li: ({ children, node }) => (
+ <li className={highlighted(node, 'my-1', 'rounded px-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">
+ td: ({ children, node }) => (
+ <td className={highlighted(node, '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">
+ tr: ({ children, node }) => (
+ <tr className={highlighted(node)}>{children}</tr>
+ ),
+ h1: ({ children, node, ...props }) => (
+ <h1 {...props} className={highlighted(node, 'mt-8 mb-3 scroll-mt-20 text-2xl font-semibold first:mt-0', 'rounded px-1')}>
{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">
+ h2: ({ children, node, ...props }) => (
+ <h2 {...props} className={highlighted(node, 'mt-8 mb-3 scroll-mt-20 border-b border-border pb-1.5 text-lg font-semibold', 'rounded px-1')}>
{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">
+ h3: ({ children, node, ...props }) => (
+ <h3 {...props} className={highlighted(node, 'mt-6 mb-2 scroll-mt-20 text-sm font-semibold uppercase tracking-wide text-muted-foreground', 'rounded px-1')}>
{children}
</h3>
),
@@ -100,8 +121,8 @@ export function Markdown({
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">
+ blockquote: ({ children, node }) => (
+ <blockquote className={highlighted(node, 'my-4 border-l-2 border-primary/50 bg-muted/30 py-1 pl-4 text-muted-foreground')}>
{children}
</blockquote>
),
@@ -111,12 +132,12 @@ export function Markdown({
) : (
<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>
+ pre: ({ children, node }) => (
+ <pre className={highlighted(node, '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>,
+ ul: ({ children, node }) => <ul className={highlighted(node, 'my-3 list-disc pl-5')}>{children}</ul>,
+ ol: ({ children, node }) => <ol className={highlighted(node, '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" />
),
@@ -136,7 +157,7 @@ export function Markdown({
)
},
}
- }, [body, devices, docs, onCreateFromLink, onOpenDoc, onToggleTask])
+ }, [body, devices, docs, highlightClassName, highlightedLines, onCreateFromLink, onOpenDoc, onToggleTask])
return (
<div className={className}>
diff --git a/frontend/src/documentation/store.ts b/frontend/src/documentation/store.ts
index 3a663b8..b7ebe99 100644
--- a/frontend/src/documentation/store.ts
+++ b/frontend/src/documentation/store.ts
@@ -11,6 +11,8 @@ import type {
DocSearchResult,
DocumentSummary,
GroupBy,
+ ResolutionItem,
+ UpdatePreview,
} from './types'
/**
@@ -31,6 +33,22 @@ const STANDALONE = import.meta.env.VITE_STANDALONE === 'true'
const UI_KEY = 'homelable_docs_ui'
const DRAFT_PREFIX = 'homelable_docdraft:'
+// The update preview is re-fetched for every decision, and those requests can
+// overlap. `previewRequest` names the request currently in charge: only the
+// latest, still aimed at the still-open document, may land its answer. Anything
+// older is a merged body computed over decisions the user has already moved
+// past — landing it would silently undo the preview on screen (responses can
+// arrive out of order) or resurrect one after the review was cancelled. Every
+// invalidation — closing the document, opening another, dropping the
+// resolutions, starting an apply — bumps the counter as well, so an answer for
+// a review nobody is looking at is discarded rather than installed.
+let previewRequest = 0
+
+// The resolutions an installed preview was merged under, kept in lockstep with
+// it. `applyUpdate` refuses when the two drift apart — sending a newer set of
+// resolutions against an older preview would land a merge nobody has seen.
+let previewBinding: ResolutionItem[] = []
+
interface DraftRecord {
body: string
savedAt: number
@@ -102,6 +120,21 @@ export interface DocsState {
openDoc: Doc | null
openLoading: boolean
+ /** The update-from-device preview of the open document. Null when not comparing. */
+ preview: UpdatePreview | null
+ previewLoading: boolean
+ /** The conflicts the user has decided on so far, keyed by change id. */
+ resolutions: Record<string, ResolutionItem>
+ /** Re-run the merge against the device, folding any pending resolutions in. */
+ openUpdatePreview: () => Promise<UpdatePreview | null>
+ /** Record one decision and refresh the merged body to show its effect. */
+ setResolution: (id: string, item: ResolutionItem) => void
+ /** Drop every decision made so far (closing the review). */
+ clearResolutions: () => void
+ /** Apply the reviewed merge. 'stale' means the document moved since the
+ * preview — the flow must re-open it rather than trusting the old one. */
+ applyUpdate: () => Promise<'applied' | 'stale' | 'failed'>
+
/** The body being edited. Null when not in edit mode. */
draft: string | null
dirty: boolean
@@ -181,6 +214,20 @@ function message(error: unknown, fallback: string): string {
return typeof detail === 'string' ? detail : fallback
}
+// The resolutions an installed preview was computed with. The preview id does
+// not bind them — only the document and the live device — so apply must check
+// that the decisions it would send are exactly the ones the merged body on
+// screen was shown with. A decision made after the preview does not count;
+// its own re-preview is what makes it part of the merge.
+function sameResolutions(a: ResolutionItem[], b: ResolutionItem[]): boolean {
+ if (a.length !== b.length) return false
+ const byId = new Map(b.map((r) => [r.id, r]))
+ return a.every((r) => {
+ const other = byId.get(r.id)
+ return other?.choice === r.choice && other?.custom === r.custom
+ })
+}
+
const initialUi = readUi()
export const useDocsStore = create<DocsState>()((set, get) => ({
@@ -192,6 +239,10 @@ export const useDocsStore = create<DocsState>()((set, get) => ({
openDoc: null,
openLoading: false,
+ preview: null,
+ previewLoading: false,
+ resolutions: {},
+
draft: null,
dirty: false,
saving: false,
@@ -230,8 +281,13 @@ export const useDocsStore = create<DocsState>()((set, get) => ({
},
open: async (id) => {
+ previewRequest++
+ previewBinding = []
set({
openLoading: true,
+ preview: null,
+ previewLoading: false,
+ resolutions: {},
draft: null,
dirty: false,
pendingDraft: null,
@@ -283,9 +339,14 @@ export const useDocsStore = create<DocsState>()((set, get) => ({
return true
},
- close: () =>
+ close: () => {
+ previewRequest++
+ previewBinding = []
set({
openDoc: null,
+ preview: null,
+ previewLoading: false,
+ resolutions: {},
draft: null,
dirty: false,
pendingDraft: null,
@@ -293,7 +354,117 @@ export const useDocsStore = create<DocsState>()((set, get) => ({
revisionsLoading: false,
revisionPreview: null,
backlinks: [],
- }),
+ })
+ },
+
+ // Update-from-device keeps its merge on the server: the preview endpoint
+ // answers the same three bodies every time, with whatever the user has
+ // decided so far folded in, so the merged body they see is never a local
+ // guess — and the apply recomputes from scratch with the same resolutions,
+ // so what the modal showed last is exactly what lands.
+ openUpdatePreview: async () => {
+ const openDoc = get().openDoc
+ if (!openDoc) return null
+ const request = ++previewRequest
+ const docId = openDoc.id
+ const bindings = Object.values(get().resolutions)
+ set({ previewLoading: true })
+ try {
+ const { data } = await documentsApi.updatePreview(docId, bindings)
+ // A response only wins if nothing newer was issued and its document is
+ // still the one on screen. Out-of-order answers for older resolutions
+ // would silently roll the review back; answers for a document the user
+ // has left belong to a review nobody is looking at.
+ if (request !== previewRequest || get().openDoc?.id !== docId) return null
+ // The installed preview is bound to exactly the resolutions it was
+ // issued with — a decision made after this request means a newer one.
+ previewBinding = bindings
+ set({ preview: data, previewLoading: false })
+ return data
+ } catch (error) {
+ // The latest failure owns the screen: the merge it was trying to show is
+ // gone, so the previous preview has no business being applied either.
+ // A failure of a superseded request, by contrast, must not knock out the
+ // newer preview (or the error of one it replaced).
+ if (request !== previewRequest || get().openDoc?.id !== docId) return null
+ previewBinding = []
+ set({ preview: null, previewLoading: false, loadError: message(error, 'Could not compare this document with the device') })
+ return null
+ }
+ },
+
+ setResolution: (id, item) => {
+ set((state) => ({ resolutions: { ...state.resolutions, [id]: item } }))
+ void get().openUpdatePreview()
+ },
+
+ clearResolutions: () => {
+ previewRequest++
+ previewBinding = []
+ // Any request still in flight for the old review is now ignored, so it
+ // will never clear the loading flag itself — this has to.
+ set({ resolutions: {}, preview: null, previewLoading: false })
+ },
+
+ applyUpdate: async () => {
+ const { openDoc, preview, resolutions } = get()
+ if (!openDoc || !preview) return 'failed'
+ // Applying must never land a merge the user is not looking at: a preview
+ // still loading (the decision it reflects has no perspective yet), one
+ // with conflicts left open, or one computed over earlier decisions than
+ // the ones stored now would all destroy exactly that guarantee.
+ if (get().previewLoading) return 'failed'
+ if (preview.unresolved.length > 0) return 'failed'
+ if (!sameResolutions(Object.values(resolutions), previewBinding)) return 'failed'
+ // The review is over: any preview still in flight is about a comparison
+ // the user has stopped looking at. Bumping the counter keeps it quiet.
+ const request = ++previewRequest
+ set({ previewLoading: true })
+ try {
+ const { data } = await documentsApi.updateFromDevice(
+ openDoc.id,
+ preview.preview_id,
+ Object.values(resolutions),
+ )
+ // The body a sync replaces is what the user was reading; any draft the
+ // editor held belonged to that older body, so it goes with it.
+ const stillCurrent = request === previewRequest && get().openDoc?.id === openDoc.id
+ if (stillCurrent) previewBinding = []
+ set((state) => {
+ const docs = state.docs.map((d) => (d.id === data.id ? { ...d, ...data } : d))
+ if (!stillCurrent) return { docs }
+ return {
+ openDoc: data,
+ preview: null,
+ previewLoading: false,
+ resolutions: {},
+ draft: null,
+ dirty: false,
+ docs,
+ }
+ })
+ if (get().openDoc?.id === openDoc.id && get().revisions.length > 0) await get().loadRevisions(openDoc.id)
+ return 'applied'
+ } catch (error) {
+ const stale = (error as { response?: { status?: number } })?.response?.status === 409
+ // Navigation, cancellation, or a newer preview now owns the review.
+ // The old apply still reports its outcome to its caller, but must not
+ // overwrite that newer state when its response eventually arrives.
+ if (request !== previewRequest || get().openDoc?.id !== openDoc.id) {
+ return stale ? 'stale' : 'failed'
+ }
+ // A 409 voids the preview and the decisions that went with it: the flow
+ // re-opens the document and compares fresh, and stale choices must not
+ // ride along into a review built on a changed baseline.
+ if (stale) {
+ previewBinding = []
+ set({ preview: null, resolutions: {}, previewLoading: false, loadError: message(error, 'Could not apply the update') })
+ } else {
+ set({ previewLoading: false, loadError: message(error, 'Could not apply the update') })
+ }
+ return stale ? 'stale' : 'failed'
+ }
+ },
startEdit: () => {
const doc = get().openDoc
diff --git a/frontend/src/documentation/types.ts b/frontend/src/documentation/types.ts
index c6ab9f6..35b2bb5 100644
--- a/frontend/src/documentation/types.ts
+++ b/frontend/src/documentation/types.ts
@@ -46,11 +46,50 @@ export interface DocRevision {
id: string
document_id: string
title: string
- reason: 'edit' | 'restore' | 'import' | 'migrate' | 'scaffold' | 'regenerate' | 'mcp'
+ reason: 'edit' | 'restore' | 'import' | 'migrate' | 'scaffold' | 'regenerate' | 'mcp' | 'sync'
saved_at: string
size: number
}
+/**
+ * How update-from-device disposed of one fact or section. Mirrors
+ * `doc_reconcile.py`; the server is the single source of truth for the words.
+ */
+export type ChangeStatus = 'same' | 'auto' | 'conflict'
+
+/** How a conflict is settled. `custom` carries the user's own text. */
+export type ResolutionChoice = 'keep' | 'device' | 'custom'
+
+/** One fact or section the update preview surfaced, and its disposition. */
+export interface ReconcileChange {
+ id: string
+ name: string
+ kind: 'field' | 'section'
+ status: ChangeStatus
+ documented: string
+ device: string
+ previous: string
+ resolution?: ResolutionChoice | null
+ custom?: string | null
+}
+
+/** What the user wants for one conflict; echoed to the server. */
+export interface ResolutionItem {
+ id: string
+ choice: ResolutionChoice
+ custom?: string | null
+}
+
+/** The read-only result of an update-from-device merge. */
+export interface UpdatePreview {
+ preview_id: string
+ changes: ReconcileChange[]
+ proposed_body: string
+ summary: string[]
+ /** Conflict ids still waiting on a decision — the apply refuses while any remain. */
+ unresolved: string[]
+}
+
/** A document pointing at the open one. Inverted server-side — see the route. */
export interface DocBacklink {
doc_id: string