Selaa lähdekoodia

feat(webui): relations - browse them, and follow them to the related data

Relations were entirely absent from the web UI: the word did not appear in
webui/src at all, so five API operations had no interface and the only way to
learn that a delete was blocked was to attempt it and read a 409.

Navigation needs no new server endpoints. A relation is {parent, child,
child_field}, so "the children of this document" is the documents endpoint
filtered by child_field, and "the parent of this document" is that field's
value. Both are plain links:

  child  -> parent   #/documents?collection=<parent>&open=<value>
  parent -> children #/documents?collection=<child>&field=<child_field>&op=eq&value=<id>

That required lifting the Documents filter bar out of local state and into the
URL, which also makes any filtered view shareable and bookmarkable - it was not
before. An `open` param opens one document's editor on arrival and is then
dropped, so closing the editor does not reopen it. Changing collection closes an
open editor: it belongs to the collection being left, and leaving it open showed
one collection's document while the page read another's relations.

Child counts are deliberately not fetched. Rendering a link rather than a count
keeps opening a document to a single request however many relations exist.

Also:
- New Relations admin page: list, create and drop, with on_delete explained per
  option and a plain-language summary of what the relation will mean.
- Deleting a document now previews delete-impact first, showing which
  collections reference it and disabling the button when a restrict relation
  would block it.
- Collections gains relation enforcement, offered as Enforce / Do-not-enforce
  ACTIONS rather than a toggle: setRelationsEnforced exists but CollectionInfo
  has no field for it, so the current value cannot be read back and a switch
  would have to invent its position. The panel says so, and only appears on a
  collection that is a parent - the side the flag is read on.
- client.ts also gains deleteImpact and patchDocument, both previously missing.

packaging/devstack runs the DB and API from the release .debs in a Debian 13
container, because the Void dev host can no longer build the C++ natively:
protobuf 35 removed google/protobuf/map_field_inl.h, which the database's
generated protos include. Verified against that stack in a browser; no C++
changed, and ctest cannot run on this host.
fszontagh 1 kuukausi sitten
vanhempi
sitoutus
fbc2ec1e9b

+ 7 - 1
CLAUDE.md

@@ -20,6 +20,10 @@ SMARTBOTIC_VECTORAPI_KEY=dev ./build/src/smartbotic-vectorapi \
 
 # Web UI only
 cd webui && npm install && npm run build   # → webui/dist ; `npm run dev` for the :3000 proxy dev server
+
+# Local backend for UI work (the dev host can no longer build C++ - see gotcha)
+# packaging/devstack: DB + API from the release .debs in a Debian 13 container.
+docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svapi-devstack
 ```
 
 ## Architecture (where things live)
@@ -27,7 +31,7 @@ cd webui && npm install && npm run build   # → webui/dist ; `npm run dev` for
 - `src/` — the server. `vectorapi_core` static lib + `main.cpp`. Namespace `svapi`. Flat headers, quoted includes.
   - `db_gateway` (`qualify(project,coll)` + `DbGateway` over `smartbotic::database::Client`), `settings_store` (global settings **and per-project embedding overrides**, hot-reload, one subscribe stream for both), `project_settings` (`ProjectEmbeddingSettings` + the pure `resolveEmbedding()`), `outbound_http` (User-Agent + TLS defaults for every external call), `key_store` (API keys, hot-reload, bootstrap admin key), `collection_registry` (per-project metadata), `embeddings` (OpenAI), `auth` (sessions, bearer/cookie), `server` (ApiServer + auth helpers), `handlers/*` (one file per route group).
   - Auth model: pre-routing **authenticates** `/api/*` (401); each handler **authorizes** via `requireKey` → `requireAdmin` / `requireProjectAccess` (403). Keys are referenced by a stable **`id`** (not the secret).
-- `webui/` — React 19 + Vite + TS (strict, `erasableSyntaxOnly`) + Tailwind + Monaco. Cookie-session auth (`credentials:'include'`). Pages read `currentProject`/`admin` from `useAuthStore`; all calls go through `src/api/client.ts`. `pages/Settings.tsx` is a tab shell over `pages/settings/*` (Embeddings, Cache & performance, Access & security, Web UI are admin-only; the per-project embeddings tab is not, so `/settings` is **not** admin-gated in `App.tsx`). Shared controls live in `components/form.tsx`.
+- `webui/` — React 19 + Vite + TS (strict, `erasableSyntaxOnly`) + Tailwind + Monaco. Cookie-session auth (`credentials:'include'`). Pages read `currentProject`/`admin` from `useAuthStore`; all calls go through `src/api/client.ts`. **Documents keeps `collection`, the filter triple (`field`/`op`/`value`) and `open` in the URL**, so relation links are ordinary links and any filtered view is shareable; changing collection closes an open editor (it belongs to the collection being left). `pages/Settings.tsx` is a tab shell over `pages/settings/*` (Embeddings, Cache & performance, Access & security, Web UI are admin-only; the per-project embeddings tab is not, so `/settings` is **not** admin-gated in `App.tsx`). Shared controls live in `components/form.tsx`.
 - `api/` — `openapi.json` (3.1), `llms.txt` (llmstxt.org), `docs/` (Redoc page). Served at `/openapi.json`, `/llms.txt`, `/docs`. Shipped in the server `.deb`. **Keep these in sync when changing routes.**
 - `packaging/` — `build.sh` (`--local` + Docker trixie), `deb/create-debs.sh`, control templates, systemd unit, maintainer scripts. `docs/superpowers/` — design spec (esp. **Addendum A**) + the 3 implementation plans.
 
@@ -55,6 +59,8 @@ cd webui && npm install && npm run build   # → webui/dist ; `npm run dev` for
 - **Abseil ABI:** `smartbotic-database`/client debs must be built against the system's current Abseil; a stale build crash-loops on `libabsl_*.so.<old>`. Rebuild the DB if it won't start.
 - **Client ABI pin:** the server deb is compiled against `DB_CLIENT_VERSION` (`packaging/Dockerfile.base`, default 2.11.3-1 = what prod runs). Every 2.x client shares one SONAME, so a deb built against a newer client installs fine and only segfaults on the next restart - keep the pin equal to the deploy target, and ship a DB upgrade and a vectorapi rebuild together.
 - **The apt repo drops superseded versions on publish**, so `pkg=<old version>` is uninstallable afterwards. Old `.deb`s survive in `$DEB_REPO_DIR/dist`; `build.sh` vendors the pinned client from there into `packaging/vendor/`, and a prod rollback needs them scp'd to the target first.
+- **The Void dev host can no longer build the C++ natively.** Void moved to protobuf 35 / gRPC 1.83; protobuf 35 removed `google/protobuf/map_field_inl.h`, which the database's generated protos include, so `libsmartbotic-db-client` neither compiles nor links there (the installed `.so` still wants `libgrpc++.so.1.61`). Release builds are unaffected because they run in the Debian 13 image. For local backend work use `packaging/devstack`; `ctest` cannot run on this host.
+- **`relations_enforced` is write-only over the API.** `setRelationsEnforced` exists but the client's `CollectionInfo` carries no field for it, so nothing can read the current value back - the web UI therefore offers Enforce / Do-not-enforce as actions rather than a toggle. Fix upstream by adding it to `CollectionInfo`.
 - **Monaco** is bundled locally (`webui/src/monacoSetup.ts`) so the editor works offline — do not revert to the CDN loader.
 - systemd unit is `Type=notify`; the binary must be built with `libsystemd` (it is, when `libsystemd-dev` is present) or change to `Type=exec`.
 

+ 18 - 0
packaging/devstack/Dockerfile

@@ -0,0 +1,18 @@
+# Local dev backend: smartbotic-database + smartbotic-vectorapi from the release
+# .debs. Native builds are impossible on the Void dev host (protobuf 35 removed
+# a header the generated protos need), so the Debian 13 image is the only way to
+# run the real stack locally. The web UI is served by Vite in dev, not from here.
+FROM debian:13
+# adduser is needed by both postinst scripts; systemctl is not present in a
+# container, so a no-op shim lets the packages configure cleanly. The services
+# are started by the entrypoint instead.
+RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl adduser \
+    && rm -rf /var/lib/apt/lists/* \
+    && printf '#!/bin/sh\nexit 0\n' > /usr/bin/systemctl && chmod +x /usr/bin/systemctl
+COPY debs/ /tmp/debs/
+RUN apt-get update && apt-get install -y --no-install-recommends /tmp/debs/*.deb \
+    && rm -rf /var/lib/apt/lists/* /tmp/debs
+COPY entrypoint.sh /usr/local/bin/entrypoint.sh
+RUN chmod +x /usr/local/bin/entrypoint.sh
+EXPOSE 8080
+ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]

+ 27 - 0
packaging/devstack/README.md

@@ -0,0 +1,27 @@
+# Local dev stack (Docker)
+
+Runs `smartbotic-database` + `smartbotic-vectorapi` from release `.deb`s in a
+Debian 13 container, so the web UI can be developed against a real backend.
+
+**Why this exists:** the Void dev host cannot build the stack natively any more.
+Void moved to protobuf 35, which removed `google/protobuf/map_field_inl.h`; the
+database's generated protos include it, so `libsmartbotic-db-client` no longer
+compiles or links there. Debian 13 pins the versions the code expects.
+
+```bash
+# 1. put the .debs here (server from dist/debian13, DB + client from the deb repo)
+mkdir -p debs && cp ../../dist/debian13/smartbotic-vectorapi_*_amd64.deb \
+    "$DEB_REPO_DIR"/dist/smartbotic-database_2.11.3-1_amd64.deb \
+    "$DEB_REPO_DIR"/dist/libsmartbotic-db-client_2.11.3-1_amd64.deb debs/
+
+# 2. build and run; the admin key is whatever you seed here
+docker build -t svapi-devstack .
+docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svapi-devstack
+
+# 3. the Vite dev server already proxies /api and /ui to localhost:8080
+cd ../../webui && npm run dev      # http://localhost:3000
+```
+
+`docker logs svapi-dev` shows both services. The container has no systemd, so the
+entrypoint starts the database, waits for :9004, then execs the API; `systemctl`
+is a no-op shim purely so the packages' postinst scripts configure cleanly.

+ 13 - 0
packaging/devstack/entrypoint.sh

@@ -0,0 +1,13 @@
+#!/bin/bash
+# No systemd in the container, so both services run directly. The DB must be
+# accepting connections before vectorapi starts, or vectorapi exits.
+set -e
+mkdir -p /var/lib/smartbotic-database
+chown -R smartbotic-db:smartbotic-db /var/lib/smartbotic-database 2>/dev/null || true
+su -s /bin/bash smartbotic-db -c '/usr/bin/smartbotic-database --config /etc/smartbotic-database/config.json' &
+for i in $(seq 1 60); do
+    (exec 3<>/dev/tcp/127.0.0.1/9004) 2>/dev/null && break
+    sleep 1
+done
+sed -i 's/"bind_address": *"[^"]*"/"bind_address": "0.0.0.0"/' /etc/smartbotic-vectorapi/config.json || true
+exec /usr/bin/smartbotic-vectorapi --config /etc/smartbotic-vectorapi/config.json

+ 2 - 0
webui/src/App.tsx

@@ -11,6 +11,7 @@ import RagTester from '@/pages/RagTester'
 import Settings from '@/pages/Settings'
 import ProjectsAdmin from '@/pages/ProjectsAdmin'
 import KeysAdmin from '@/pages/KeysAdmin'
+import RelationsAdmin from '@/pages/RelationsAdmin'
 
 /// Shown while the server is being asked whether the restored session is real.
 /// Rendering the shell here is what used to flash the authenticated UI at a
@@ -72,6 +73,7 @@ export const routes: RouteObject[] = [
             children: [
               { path: 'projects', element: <ProjectsAdmin /> },
               { path: 'keys', element: <KeysAdmin /> },
+              { path: 'relations', element: <RelationsAdmin /> },
             ],
           },
         ],

+ 22 - 0
webui/src/api/client.ts

@@ -3,6 +3,7 @@ import type {
   SearchResult, ProjectStats, GlobalStats, FindResult, SettingsView,
   KeyScope, IndexDef, IndexValue, CreateIndexResult,
   ProjectEmbeddingsView, ProjectEmbeddingsPatch,
+  RelationDefinition, DeleteImpact,
 } from '@/types'
 import { ApiError } from '@/types'
 import { serverUrl } from '@/api/base'
@@ -108,6 +109,27 @@ export const api = {
   resetProjectEmbeddings: (project: string) =>
     request<{ reverted: string; had_overrides: boolean }>(`${P(project)}/settings/embeddings`, { method: 'DELETE' }),
 
+  // relations (admin)
+  listRelations: (project: string) =>
+    request<{ relations: RelationDefinition[] }>(`${P(project)}/relations`),
+  getRelation: (project: string, name: string) =>
+    request<RelationDefinition>(`${P(project)}/relations/${enc(name)}`),
+  createRelation: (project: string, rel: Omit<RelationDefinition, 'created_at' | 'updated_at'>) =>
+    request<RelationDefinition>(`${P(project)}/relations`, { method: 'POST', body: JSON.stringify(rel) }),
+  deleteRelation: (project: string, name: string) =>
+    request<{ deleted: string }>(`${P(project)}/relations/${enc(name)}`, { method: 'DELETE' }),
+  // Enforcement is read on the collection being deleted FROM, i.e. the parent.
+  setRelationsEnforced: (project: string, collection: string, enforced: boolean) =>
+    request<{ enforced: boolean }>(`${P(project)}/collections/${enc(collection)}/relations-enforced`,
+      { method: 'PUT', body: JSON.stringify({ enforced }) }),
+
+  // What a delete would affect, without deleting.
+  deleteImpact: (project: string, collection: string, id: string) =>
+    request<DeleteImpact>(`${P(project)}/collections/${enc(collection)}/documents/${enc(id)}/delete-impact`),
+  patchDocument: (project: string, collection: string, id: string, patch: Record<string, unknown>) =>
+    request<{ id: string }>(`${P(project)}/collections/${enc(collection)}/documents/${enc(id)}`,
+      { method: 'PATCH', body: JSON.stringify(patch) }),
+
   getSettings: () => request<SettingsView>('/api/v1/settings'),
   updateSettings: (patch: Partial<Omit<SettingsView, 'openai_api_key_set'> & { openai_api_key?: string }>) =>
     request<{ ok: boolean }>('/api/v1/settings', { method: 'PUT', body: JSON.stringify(patch) }),

+ 2 - 0
webui/src/components/AppShell.tsx

@@ -8,6 +8,7 @@ import {
   Settings,
   FolderKanban,
   KeyRound,
+  Share2,
   LogOut,
   BookOpen,
 } from 'lucide-react'
@@ -34,6 +35,7 @@ const mainNav: NavItem[] = [
 const adminNav: NavItem[] = [
   { to: '/projects', label: 'Projects', icon: <FolderKanban size={18} /> },
   { to: '/keys', label: 'Keys', icon: <KeyRound size={18} /> },
+  { to: '/relations', label: 'Relations', icon: <Share2 size={18} /> },
 ]
 
 function SidebarLink({ item }: { item: NavItem }) {

+ 123 - 0
webui/src/components/DeleteImpactDialog.tsx

@@ -0,0 +1,123 @@
+import { useEffect, useState } from 'react'
+import { AlertTriangle } from 'lucide-react'
+import { api } from '@/api/client'
+import { Modal } from '@/components/Modal'
+import type { DeleteImpact } from '@/types'
+
+/// Asks the server what deleting this document would affect before offering to
+/// delete it. Without this the only way to discover a restrict relation is to
+/// attempt the delete and read a 409.
+export function DeleteImpactDialog({
+  open,
+  project,
+  collection,
+  docId,
+  onConfirm,
+  onClose,
+}: {
+  open: boolean
+  project: string
+  collection: string
+  docId: string
+  onConfirm: () => void
+  onClose: () => void
+}) {
+  const [impact, setImpact] = useState<DeleteImpact | null>(null)
+  const [loading, setLoading] = useState(false)
+  const [error, setError] = useState<string | null>(null)
+
+  useEffect(() => {
+    if (!open || !docId) return
+    let cancelled = false
+    setLoading(true)
+    setImpact(null)
+    setError(null)
+    api
+      .deleteImpact(project, collection, docId)
+      .then((r) => { if (!cancelled) setImpact(r) })
+      // A preview failure must not block the delete; fall back to a plain confirm.
+      .catch((e) => { if (!cancelled) setError(e instanceof Error ? e.message : String(e)) })
+      .finally(() => { if (!cancelled) setLoading(false) })
+    return () => { cancelled = true }
+  }, [open, project, collection, docId])
+
+  const blocked = impact?.would_be_blocked === true
+  const impacts = impact?.impacts ?? []
+
+  return (
+    <Modal open={open} title="Delete document" onClose={onClose}>
+      <div className="flex flex-col gap-4">
+        {loading && <p className="text-sm text-slate-400">Checking what this would affect...</p>}
+
+        {error && (
+          <p className="text-sm text-amber-300">
+            Could not preview the impact ({error}). The delete may still fail if another document
+            references this one.
+          </p>
+        )}
+
+        {impact && impacts.length === 0 && (
+          <p className="text-sm text-slate-300">
+            Nothing references this document. Deleting it is permanent.
+          </p>
+        )}
+
+        {impacts.length > 0 && (
+          <div className="flex flex-col gap-2">
+            <p className="text-sm text-slate-300">This document is referenced by:</p>
+            <ul className="flex flex-col gap-2">
+              {impacts.map((i) => (
+                <li key={i.relation} className="rounded-md border border-slate-700 bg-slate-800/50 px-3 py-2 text-sm">
+                  <div className="flex items-center gap-2">
+                    <span className="font-mono text-slate-200">
+                      {i.child_count} {i.child_collection}
+                    </span>
+                    <span className="text-slate-500">via</span>
+                    <span className="font-mono text-slate-400">{i.child_field}</span>
+                    <span className={`ml-auto rounded px-1.5 py-0.5 text-[10px] font-medium ${
+                      i.blocks ? 'bg-amber-500/15 text-amber-300' : 'bg-slate-700/60 text-slate-300'}`}>
+                      {i.on_delete}
+                    </span>
+                  </div>
+                  {i.sample_child_ids.length > 0 && (
+                    <p className="mt-1 font-mono text-[11px] text-slate-500 truncate">
+                      e.g. {i.sample_child_ids.slice(0, 3).join(', ')}
+                    </p>
+                  )}
+                </li>
+              ))}
+            </ul>
+          </div>
+        )}
+
+        {blocked && (
+          <div className="flex items-start gap-2 rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-2">
+            <AlertTriangle size={16} className="mt-0.5 shrink-0 text-amber-300" />
+            <p className="text-xs text-amber-200">
+              The server will refuse this delete while those documents reference it. Remove or repoint
+              them first, or relax the relation's <code>on_delete</code>.
+            </p>
+          </div>
+        )}
+
+        <div className="flex items-center justify-end gap-3">
+          <button
+            onClick={onClose}
+            className="px-4 py-2 rounded-md text-sm font-medium text-slate-300 hover:text-slate-100 bg-slate-700/50 hover:bg-slate-700 transition"
+          >
+            Cancel
+          </button>
+          <button
+            onClick={() => { onConfirm(); onClose() }}
+            disabled={loading || blocked}
+            title={blocked ? 'Blocked by a restrict relation' : undefined}
+            className="px-4 py-2 rounded-md text-sm font-medium text-white bg-red-600 hover:bg-red-500 transition disabled:opacity-40 disabled:cursor-not-allowed"
+            data-testid="delete-impact-confirm"
+          >
+            Delete
+          </button>
+        </div>
+      </div>
+    </Modal>
+  )
+}

+ 109 - 0
webui/src/components/RelationLinks.tsx

@@ -0,0 +1,109 @@
+import { useQuery } from '@tanstack/react-query'
+import { Link } from 'react-router-dom'
+import { ArrowUpRight, CornerDownRight } from 'lucide-react'
+import { api } from '@/api/client'
+import type { RelationDefinition } from '@/types'
+
+/// The server returns the stored id as `_id`; a document written with an
+/// explicit id also carries it, so accept either.
+export function documentId(doc: Record<string, unknown>): string {
+  const v = doc._id ?? doc.id
+  return typeof v === 'string' ? v : ''
+}
+
+function docUrl(collection: string, params: Record<string, string>): string {
+  const qs = new URLSearchParams({ collection, ...params })
+  return `/documents?${qs.toString()}`
+}
+
+/// Both directions of every relation this collection takes part in:
+///   - as CHILD: the document's reference field points at one parent document
+///   - as PARENT: other documents point back at this one
+///
+/// Child counts are deliberately not fetched here. Rendering a link instead of
+/// a count keeps opening a document to a single request, however many relations
+/// the project defines.
+export function RelationLinks({
+  project,
+  collection,
+  doc,
+}: {
+  project: string
+  collection: string
+  doc: Record<string, unknown>
+}) {
+  const { data } = useQuery({
+    queryKey: ['relations', project],
+    queryFn: () => api.listRelations(project),
+    enabled: !!project,
+  })
+
+  const relations: RelationDefinition[] = data?.relations ?? []
+  const asChild = relations.filter((r) => r.child === collection)
+  const asParent = relations.filter((r) => r.parent === collection)
+  const id = documentId(doc)
+
+  if (asChild.length === 0 && asParent.length === 0) return null
+
+  return (
+    <div className="rounded-lg border border-slate-700 bg-slate-800/40 px-4 py-3">
+      <p className="text-xs font-medium uppercase tracking-wide text-slate-400 mb-2">Related data</p>
+      <ul className="flex flex-col gap-1.5 text-sm">
+        {asChild.map((r) => {
+          const raw = doc[r.child_field]
+          const ref = typeof raw === 'string' || typeof raw === 'number' ? String(raw) : ''
+          return (
+            <li key={`up-${r.name}`} className="flex items-center gap-2">
+              <ArrowUpRight size={14} className="shrink-0 text-slate-500" />
+              <span className="text-slate-400">
+                <code className="text-slate-300">{r.child_field}</code> references{' '}
+                <code className="text-slate-300">{r.parent}</code>
+              </span>
+              {ref ? (
+                <Link
+                  to={docUrl(r.parent, { open: ref })}
+                  className="font-mono text-indigo-300 hover:underline"
+                  data-testid="relation-parent-link"
+                >
+                  {ref}
+                </Link>
+              ) : (
+                <span className="text-xs text-slate-500">(not set)</span>
+              )}
+            </li>
+          )
+        })}
+
+        {asParent.map((r) => (
+          <li key={`down-${r.name}`} className="flex items-center gap-2">
+            <CornerDownRight size={14} className="shrink-0 text-slate-500" />
+            <span className="text-slate-400">
+              referenced by <code className="text-slate-300">{r.child}.{r.child_field}</code>
+            </span>
+            {id ? (
+              <Link
+                to={docUrl(r.child, { field: r.child_field, op: 'eq', value: id })}
+                className="text-indigo-300 hover:underline"
+                data-testid="relation-children-link"
+              >
+                show {r.child}
+              </Link>
+            ) : (
+              <span className="text-xs text-slate-500">(save the document first)</span>
+            )}
+            {r.on_delete === 'restrict' && (
+              <span className="rounded bg-amber-500/15 px-1.5 py-0.5 text-[10px] font-medium text-amber-300">
+                delete restricted
+              </span>
+            )}
+            {r.on_delete === 'cascade' && (
+              <span className="rounded bg-red-500/15 px-1.5 py-0.5 text-[10px] font-medium text-red-300">
+                delete cascades
+              </span>
+            )}
+          </li>
+        ))}
+      </ul>
+    </div>
+  )
+}

+ 77 - 0
webui/src/components/RelationsEnforcedPanel.tsx

@@ -0,0 +1,77 @@
+import { useState } from 'react'
+import { useQuery } from '@tanstack/react-query'
+import { ShieldCheck, ShieldOff } from 'lucide-react'
+import { api } from '@/api/client'
+import { useToastStore } from '@/stores/toastStore'
+import { ApiError } from '@/types'
+
+/// Relation enforcement for one collection.
+///
+/// This is an ACTION, not a toggle, and deliberately so: the database client
+/// (2.11.3) exposes setRelationsEnforced but CollectionInfo carries no
+/// relations_enforced field, so the server cannot report the current value.
+/// A switch would have to invent a position and would be wrong half the time.
+export function RelationsEnforcedPanel({
+  project,
+  collection,
+}: {
+  project: string
+  collection: string
+}) {
+  const push = useToastStore((s) => s.push)
+  const [busy, setBusy] = useState(false)
+
+  // Only meaningful when this collection is a parent in some relation - that is
+  // the side the flag is read on when a delete is issued.
+  const { data } = useQuery({
+    queryKey: ['relations', project],
+    queryFn: () => api.listRelations(project),
+    enabled: !!project,
+  })
+  const asParent = (data?.relations ?? []).filter((r) => r.parent === collection)
+  if (asParent.length === 0) return null
+
+  async function set(enforced: boolean) {
+    setBusy(true)
+    try {
+      await api.setRelationsEnforced(project, collection, enforced)
+      push(`Relation enforcement ${enforced ? 'enabled' : 'disabled'} on ${collection}.`, 'success')
+    } catch (err) {
+      push(`Could not change enforcement: ${err instanceof ApiError ? err.message : String(err)}`, 'error')
+    } finally {
+      setBusy(false)
+    }
+  }
+
+  return (
+    <div className="rounded-lg border border-slate-700/40 bg-slate-800/30 px-4 py-3">
+      <p className="text-xs font-medium uppercase tracking-wide text-slate-400">Relation enforcement</p>
+      <p className="mt-1 text-xs text-slate-500">
+        Deletes from <span className="font-mono text-slate-400">{collection}</span> are checked against{' '}
+        {asParent.length === 1
+          ? 'the relation that names it as parent'
+          : `the ${asParent.length} relations that name it as parent`}{' '}
+        ({asParent.map((r) => r.name).join(', ')}). Enforcement is read on this, the parent side - setting
+        it on the child collection has no effect.
+      </p>
+      <p className="mt-1 text-xs text-slate-500">
+        The server cannot report the current setting (the database client exposes no read for it), so these
+        buttons set it rather than showing it.
+      </p>
+      <div className="mt-2 flex items-center gap-2">
+        <button
+          type="button" disabled={busy} onClick={() => void set(true)}
+          className="inline-flex items-center gap-1.5 rounded-md border border-slate-600 px-3 py-1.5 text-xs text-slate-200 hover:bg-slate-700 disabled:opacity-50"
+        >
+          <ShieldCheck size={14} /> Enforce
+        </button>
+        <button
+          type="button" disabled={busy} onClick={() => void set(false)}
+          className="inline-flex items-center gap-1.5 rounded-md border border-slate-600 px-3 py-1.5 text-xs text-slate-200 hover:bg-slate-700 disabled:opacity-50"
+        >
+          <ShieldOff size={14} /> Do not enforce
+        </button>
+      </div>
+    </div>
+  )
+}

+ 4 - 0
webui/src/pages/Collections.tsx

@@ -11,6 +11,7 @@ import { useToastStore } from '@/stores/toastStore'
 import { Modal } from '@/components/Modal'
 import { ConfirmDialog } from '@/components/ConfirmDialog'
 import { IndexPanel } from '@/components/IndexPanel'
+import { RelationsEnforcedPanel } from '@/components/RelationsEnforcedPanel'
 import { ApiError } from '@/types'
 import type { CollectionMeta } from '@/types'
 
@@ -336,6 +337,9 @@ function CollectionDetailDrawer({ project, name, onClose }: DetailDrawerProps) {
           {/* Indexes */}
           <IndexPanel project={project} collection={data.name} />
 
+          {/* Relation enforcement (only when this collection is a parent) */}
+          <RelationsEnforcedPanel project={project} collection={data.name} />
+
           {/* Quick actions */}
           <div className="flex items-center justify-end gap-3 pt-1">
             {data.kind === 'vector' && (

+ 90 - 8
webui/src/pages/Documents.tsx

@@ -11,6 +11,8 @@ import { useToastStore } from '@/stores/toastStore'
 import { Modal } from '@/components/Modal'
 import { ConfirmDialog } from '@/components/ConfirmDialog'
 import { JsonEditor } from '@/components/JsonEditor'
+import { RelationLinks } from '@/components/RelationLinks'
+import { DeleteImpactDialog } from '@/components/DeleteImpactDialog'
 import { ApiError } from '@/types'
 import type { CollectionMeta } from '@/types'
 
@@ -194,6 +196,11 @@ interface DocEditorModalProps {
   open: boolean
   title: string
   initialJson: string
+  // Present only when editing an existing document; enables the relation links
+  // and the delete-impact preview.
+  project?: string
+  collection?: string
+  docId?: string
   onClose: () => void
   onSave: (parsed: Record<string, unknown>) => Promise<void>
   onDelete?: () => void
@@ -202,6 +209,7 @@ interface DocEditorModalProps {
 
 function DocEditorModal({
   open, title, initialJson,
+  project, collection, docId,
   onClose, onSave, onDelete, saving,
 }: DocEditorModalProps) {
   const [json, setJson] = useState(initialJson)
@@ -239,6 +247,12 @@ function DocEditorModal({
             <p className="text-xs text-red-400">Invalid JSON — fix before saving.</p>
           )}
 
+          {project && collection && docId && jsonValid && (() => {
+            let parsed: Record<string, unknown> = {}
+            try { parsed = JSON.parse(json) as Record<string, unknown> } catch { return null }
+            return <RelationLinks project={project} collection={collection} doc={parsed} />
+          })()}
+
           <div className="flex items-center justify-between pt-1">
             <div>
               {onDelete && (
@@ -271,7 +285,18 @@ function DocEditorModal({
         </div>
       </Modal>
 
-      {onDelete && (
+      {onDelete && project && collection && docId && (
+        <DeleteImpactDialog
+          open={showDelete}
+          project={project}
+          collection={collection}
+          docId={docId}
+          onConfirm={onDelete}
+          onClose={() => setShowDelete(false)}
+        />
+      )}
+
+      {onDelete && !(project && collection && docId) && (
         <ConfirmDialog
           open={showDelete}
           title="Delete Document"
@@ -412,10 +437,23 @@ export default function Documents() {
   const [searchParams, setSearchParams] = useSearchParams()
   const selectedColl = searchParams.get('collection') ?? ''
 
-  // Filter state
-  const [filterField, setFilterField] = useState('')
-  const [filterOp, setFilterOp] = useState<FilterOp>('eq')
-  const [filterValue, setFilterValue] = useState('')
+  // The filter lives in the URL, so a relation link can point straight at
+  // "the children of this document" and the view is shareable and bookmarkable.
+  const filterField = searchParams.get('field') ?? ''
+  const filterOp = (searchParams.get('op') as FilterOp) || 'eq'
+  const filterValue = searchParams.get('value') ?? ''
+  // `open` asks the page to open one document's editor on arrival.
+  const openId = searchParams.get('open') ?? ''
+
+  const setParam = (key: string, value: string) => {
+    setSearchParams((prev) => {
+      const next = new URLSearchParams(prev)
+      if (value) next.set(key, value)
+      else next.delete(key)
+      return next
+    }, { replace: true })
+  }
+
   const [limit, setLimit] = useState('50')
   const [offset, setOffset] = useState('0')
 
@@ -484,6 +522,46 @@ export default function Documents() {
     setAppliedQs(buildQueryString(filterField, filterOp, filterValue, limit, off, sf, sd))
   }
 
+  // A filter arriving in the URL (from a relation link, or a shared link) is
+  // applied on arrival. Keyed on the triple so typing in the filter bar, which
+  // also writes the URL, re-runs only when a value actually changes.
+  const urlFilterKey = `${effectiveCollection}|${filterField}|${filterOp}|${filterValue}`
+  useEffect(() => {
+    if (!effectiveCollection) return
+    if (!filterField || !filterValue) return
+    setOffset('0')
+    setAppliedQs(buildQueryString(filterField, filterOp, filterValue, limit, '0', sortField, sortDesc))
+    // eslint-disable-next-line react-hooks/exhaustive-deps
+  }, [urlFilterKey])
+
+  // Following a relation link changes the collection while the editor is open.
+  // The open document belongs to the collection being left, so close it first;
+  // declared before the `open` effect so an arriving ?open= still wins.
+  useEffect(() => {
+    setModalOpen(false)
+  }, [effectiveCollection])
+
+  // `?open=<id>` opens that document's editor once, then drops the param so
+  // closing the modal does not immediately reopen it.
+  useEffect(() => {
+    if (!openId || !currentProject || !effectiveCollection) return
+    let cancelled = false
+    void (async () => {
+      try {
+        const full = await api.getDocument(currentProject, effectiveCollection, openId)
+        if (cancelled) return
+        setModalState({ mode: 'edit', docId: openId, json: JSON.stringify(full, null, 2) })
+        setModalOpen(true)
+      } catch (err) {
+        if (!cancelled) push(`Could not open ${openId}: ${err instanceof ApiError ? err.message : String(err)}`, 'error')
+      } finally {
+        if (!cancelled) setParam('open', '')
+      }
+    })()
+    return () => { cancelled = true }
+    // eslint-disable-next-line react-hooks/exhaustive-deps
+  }, [openId, currentProject, effectiveCollection])
+
   // Toggle server-side sort by `id` from the ID column header.
   const toggleSortById = () => {
     if (sortField === 'id') applySearch({ sortDesc: !sortDesc })
@@ -500,6 +578,7 @@ export default function Documents() {
   }
 
   const handleCollectionSelect = (coll: string) => {
+    // A filter names fields of the collection being left, so drop it.
     setSearchParams(coll ? { collection: coll } : {}, { replace: true })
     setAppliedQs('')
     setOffset('0')
@@ -676,9 +755,9 @@ export default function Documents() {
           filterValue={filterValue}
           limit={limit}
           offset={offset}
-          onFieldChange={setFilterField}
-          onOpChange={setFilterOp}
-          onValueChange={setFilterValue}
+          onFieldChange={(v) => setParam('field', v)}
+          onOpChange={(v) => setParam('op', v)}
+          onValueChange={(v) => setParam('value', v)}
           onLimitChange={setLimit}
           onOffsetChange={setOffset}
           onSearch={() => applySearch()}
@@ -770,6 +849,9 @@ export default function Documents() {
         open={modalOpen}
         title={modalState.mode === 'new' ? 'New Document' : `Edit Document — ${modalState.docId}`}
         initialJson={modalState.json}
+        project={modalState.mode === 'edit' ? currentProject : undefined}
+        collection={modalState.mode === 'edit' ? effectiveCollection : undefined}
+        docId={modalState.mode === 'edit' ? modalState.docId : undefined}
         onClose={() => setModalOpen(false)}
         onSave={(parsed) => handleSave(parsed)}
         onDelete={modalState.mode === 'edit' ? () => void handleDelete() : undefined}

+ 289 - 0
webui/src/pages/RelationsAdmin.tsx

@@ -0,0 +1,289 @@
+import { useState } from 'react'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
+import { Link } from 'react-router-dom'
+import { Plus, Trash2, ArrowRight } from 'lucide-react'
+import { api } from '@/api/client'
+import { Modal } from '@/components/Modal'
+import { ConfirmDialog } from '@/components/ConfirmDialog'
+import { FormRow, inputCls, SaveButton } from '@/components/form'
+import { useAuthStore } from '@/stores/authStore'
+import { useToastStore } from '@/stores/toastStore'
+import { ApiError } from '@/types'
+import type { CollectionMeta, OnDelete, RelationDefinition } from '@/types'
+
+const ON_DELETE: { value: OnDelete; label: string; hint: string }[] = [
+  { value: 'restrict', label: 'restrict', hint: 'Block the parent delete while children reference it (default).' },
+  { value: 'cascade', label: 'cascade', hint: 'Delete the referencing children along with the parent.' },
+  { value: 'set_null', label: 'set_null', hint: 'Clear the reference field on the children.' },
+  { value: 'no_action', label: 'no_action', hint: 'Do nothing; the reference is left dangling.' },
+]
+
+const NAME_RE = /^[a-zA-Z_][a-zA-Z0-9_-]{0,62}$/
+
+// ─── create form ──────────────────────────────────────────────────────────────
+
+function NewRelationForm({
+  project,
+  collections,
+  onDone,
+  onCancel,
+}: {
+  project: string
+  collections: CollectionMeta[]
+  onDone: () => void
+  onCancel: () => void
+}) {
+  const push = useToastStore((s) => s.push)
+  const [name, setName] = useState('')
+  const [parent, setParent] = useState('')
+  const [child, setChild] = useState('')
+  const [childField, setChildField] = useState('')
+  const [onDelete, setOnDelete] = useState<OnDelete>('restrict')
+  const [validateOnWrite, setValidateOnWrite] = useState(true)
+  const [saving, setSaving] = useState(false)
+
+  async function submit(e: React.FormEvent) {
+    e.preventDefault()
+    if (!NAME_RE.test(name.trim())) {
+      push('Name must start with a letter or underscore (letters, digits, _ or -, max 63).', 'error')
+      return
+    }
+    if (!parent || !child || !childField.trim()) {
+      push('Parent, child and child field are all required.', 'error')
+      return
+    }
+    setSaving(true)
+    try {
+      await api.createRelation(project, {
+        name: name.trim(),
+        parent,
+        child,
+        child_field: childField.trim(),
+        on_delete: onDelete,
+        validate_on_write: validateOnWrite,
+      })
+      push(`Relation ${name.trim()} created.`, 'success')
+      onDone()
+    } catch (err) {
+      push(`Could not create relation: ${err instanceof ApiError ? err.message : String(err)}`, 'error')
+    } finally {
+      setSaving(false)
+    }
+  }
+
+  const hint = ON_DELETE.find((o) => o.value === onDelete)?.hint
+
+  return (
+    <form onSubmit={submit} className="flex flex-col gap-4">
+      <p className="text-sm text-slate-400">
+        Deleting a <span className="text-slate-200">parent</span> document affects{' '}
+        <span className="text-slate-200">child</span> documents whose field references it.
+      </p>
+
+      <FormRow label="Name" hint="Unique within the project.">
+        <input type="text" value={name} onChange={(e) => setName(e.target.value)}
+          placeholder="book_author" className={inputCls} autoFocus />
+      </FormRow>
+
+      <div className="grid gap-4 sm:grid-cols-2">
+        <FormRow label="Parent collection" hint="Holds the documents being referenced.">
+          <select value={parent} onChange={(e) => setParent(e.target.value)} className={inputCls}>
+            <option value="">Select...</option>
+            {collections.map((c) => <option key={c.name} value={c.name}>{c.name}</option>)}
+          </select>
+        </FormRow>
+        <FormRow label="Child collection" hint="Holds the reference.">
+          <select value={child} onChange={(e) => setChild(e.target.value)} className={inputCls}>
+            <option value="">Select...</option>
+            {collections.map((c) => <option key={c.name} value={c.name}>{c.name}</option>)}
+          </select>
+        </FormRow>
+      </div>
+
+      <FormRow label="Child field" hint="Field on the child document storing the parent's id.">
+        <input type="text" value={childField} onChange={(e) => setChildField(e.target.value)}
+          placeholder="author_id" className={inputCls} />
+      </FormRow>
+
+      <FormRow label="On delete" hint={hint}>
+        <select value={onDelete} onChange={(e) => setOnDelete(e.target.value as OnDelete)} className={inputCls}>
+          {ON_DELETE.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
+        </select>
+      </FormRow>
+
+      <FormRow label="Validate on write" hint="Reject a child write whose reference points at no parent.">
+        <label className="flex items-center gap-2 text-sm text-slate-300 cursor-pointer w-fit">
+          <input type="checkbox" checked={validateOnWrite}
+            onChange={(e) => setValidateOnWrite(e.target.checked)} className="accent-indigo-500" />
+          {validateOnWrite ? 'Enabled' : 'Disabled'}
+        </label>
+      </FormRow>
+
+      {parent && child && childField && (
+        <div className="rounded-lg border border-slate-700 bg-slate-800/40 px-4 py-3 text-xs text-slate-400">
+          <span className="text-slate-300 font-medium">Reads as:</span>{' '}
+          <code className="text-indigo-300">{child}.{childField}</code> references{' '}
+          <code className="text-indigo-300">{parent}</code>, and deleting a {parent} document is{' '}
+          <span className="text-slate-200">{onDelete}</span>.
+        </div>
+      )}
+
+      <div className="flex items-center gap-3">
+        <SaveButton saving={saving} />
+        <button type="button" onClick={onCancel}
+          className="rounded-md border border-slate-600 px-3 py-2 text-sm text-slate-300 hover:bg-slate-700">
+          Cancel
+        </button>
+      </div>
+    </form>
+  )
+}
+
+// ─── page ─────────────────────────────────────────────────────────────────────
+
+export default function RelationsAdmin() {
+  const project = useAuthStore((s) => s.currentProject)
+  const push = useToastStore((s) => s.push)
+  const queryClient = useQueryClient()
+  const [creating, setCreating] = useState(false)
+  const [pendingDelete, setPendingDelete] = useState<RelationDefinition | null>(null)
+
+  const { data, isLoading, isError, error } = useQuery({
+    queryKey: ['relations', project],
+    queryFn: () => api.listRelations(project as string),
+    enabled: !!project,
+  })
+  const { data: collectionsData } = useQuery({
+    queryKey: ['collections', project],
+    queryFn: () => api.listCollections(project as string),
+    enabled: !!project,
+  })
+
+  async function doDelete(rel: RelationDefinition) {
+    try {
+      await api.deleteRelation(project as string, rel.name)
+      await queryClient.invalidateQueries({ queryKey: ['relations', project] })
+      push(`Relation ${rel.name} dropped.`, 'success')
+    } catch (err) {
+      push(`Could not drop relation: ${err instanceof ApiError ? err.message : String(err)}`, 'error')
+    }
+  }
+
+  if (!project) return <p className="text-sm text-slate-400">Select a project first.</p>
+
+  const relations = data?.relations ?? []
+
+  return (
+    <div className="flex flex-col gap-6">
+      <div className="flex items-start justify-between">
+        <div>
+          <h1 className="text-2xl font-semibold text-slate-100">Relations</h1>
+          <p className="text-slate-400 text-sm mt-1">
+            How documents in <span className="text-slate-300">{project}</span> reference each other, and what
+            happens when a referenced document is deleted.
+          </p>
+        </div>
+        <button
+          onClick={() => setCreating(true)}
+          className="inline-flex items-center gap-2 rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-500"
+        >
+          <Plus size={16} /> New relation
+        </button>
+      </div>
+
+      {isError && (
+        <div className="rounded-xl border border-red-500/20 bg-red-500/5 px-6 py-4 text-sm text-red-400">
+          Failed to load relations: {error instanceof Error ? error.message : 'Unknown error'}
+        </div>
+      )}
+
+      {isLoading && <p className="text-sm text-slate-400">Loading...</p>}
+
+      {!isLoading && relations.length === 0 && (
+        <div className="rounded-xl border border-slate-700 bg-slate-800/30 px-6 py-8 text-center">
+          <p className="text-slate-300 text-sm">No relations in this project yet.</p>
+          <p className="text-slate-500 text-xs mt-1">
+            A relation lets you jump from a document to the ones referencing it, and protects a parent from
+            being deleted out from under its children.
+          </p>
+        </div>
+      )}
+
+      {relations.length > 0 && (
+        <div className="overflow-x-auto rounded-xl border border-slate-700">
+          <table className="w-full text-sm">
+            <thead>
+              <tr className="border-b border-slate-700/40 bg-slate-800/60 text-left text-xs uppercase tracking-wide text-slate-400">
+                <th className="px-4 py-3">Name</th>
+                <th className="px-4 py-3">Reference</th>
+                <th className="px-4 py-3">On delete</th>
+                <th className="px-4 py-3">Validate on write</th>
+                <th className="px-4 py-3"></th>
+              </tr>
+            </thead>
+            <tbody>
+              {relations.map((r) => (
+                <tr key={r.name} className="border-b border-slate-700/20 hover:bg-indigo-500/5">
+                  <td className="px-4 py-3 font-mono text-slate-200">{r.name}</td>
+                  <td className="px-4 py-3">
+                    <span className="inline-flex items-center gap-2 text-slate-300">
+                      <Link to={`/documents?collection=${encodeURIComponent(r.child)}`}
+                        className="font-mono text-indigo-300 hover:underline">
+                        {r.child}.{r.child_field}
+                      </Link>
+                      <ArrowRight size={14} className="text-slate-500" />
+                      <Link to={`/documents?collection=${encodeURIComponent(r.parent)}`}
+                        className="font-mono text-indigo-300 hover:underline">
+                        {r.parent}
+                      </Link>
+                    </span>
+                  </td>
+                  <td className="px-4 py-3">
+                    <span className={`rounded px-1.5 py-0.5 text-xs font-medium ${
+                      r.on_delete === 'restrict' ? 'bg-amber-500/15 text-amber-300'
+                      : r.on_delete === 'cascade' ? 'bg-red-500/15 text-red-300'
+                      : 'bg-slate-700/60 text-slate-300'}`}>
+                      {r.on_delete}
+                    </span>
+                  </td>
+                  <td className="px-4 py-3 text-slate-400">{r.validate_on_write ? 'yes' : 'no'}</td>
+                  <td className="px-4 py-3 text-right">
+                    <button onClick={() => setPendingDelete(r)} title="Drop relation"
+                      className="text-slate-400 hover:text-red-400">
+                      <Trash2 size={16} />
+                    </button>
+                  </td>
+                </tr>
+              ))}
+            </tbody>
+          </table>
+        </div>
+      )}
+
+      <Modal open={creating} title="New relation" onClose={() => setCreating(false)}>
+        <NewRelationForm
+          project={project}
+          collections={collectionsData?.collections ?? []}
+          onDone={async () => {
+            setCreating(false)
+            await queryClient.invalidateQueries({ queryKey: ['relations', project] })
+          }}
+          onCancel={() => setCreating(false)}
+        />
+      </Modal>
+
+      <ConfirmDialog
+        open={!!pendingDelete}
+        title={`Drop relation ${pendingDelete?.name ?? ''}?`}
+        message={
+          pendingDelete
+            ? `${pendingDelete.child}.${pendingDelete.child_field} will no longer be tied to ${pendingDelete.parent}. Documents are not changed, but deletes of ${pendingDelete.parent} documents stop being ${pendingDelete.on_delete}ed.`
+            : ''
+        }
+        confirmLabel="Drop"
+        onConfirm={() => { if (pendingDelete) void doDelete(pendingDelete) }}
+        onClose={() => setPendingDelete(null)}
+      />
+    </div>
+  )
+}

+ 32 - 0
webui/src/types/index.ts

@@ -69,6 +69,38 @@ export interface ProjectEmbeddingsPatch {
   default_embedding_model?: string | null
 }
 
+/// A relation ties a child collection's field to a parent collection's ids.
+/// Names are per-project and unqualified; the server never exposes the internal
+/// `project:` prefix.
+export type OnDelete = 'restrict' | 'cascade' | 'set_null' | 'no_action'
+
+export interface RelationDefinition {
+  name: string
+  parent: string
+  child: string
+  child_field: string
+  on_delete: OnDelete
+  validate_on_write?: boolean
+  created_at?: number
+  updated_at?: number
+}
+
+/// What deleting one document would affect, per relation pointing at it.
+export interface RelationImpact {
+  relation: string
+  child_collection: string
+  child_field: string
+  on_delete: OnDelete
+  child_count: number
+  sample_child_ids: string[]
+  blocks: boolean
+}
+
+export interface DeleteImpact {
+  would_be_blocked: boolean
+  impacts: RelationImpact[]
+}
+
 export class ApiError extends Error {
   status: number
   details?: unknown